feat: complete user management workflow
This commit is contained in:
@@ -24,6 +24,7 @@ export default async function SettingsPage(): Promise<React.ReactElement> {
|
||||
auditLogs={data.auditLogs.slice(0, 100)}
|
||||
organizations={data.organizations}
|
||||
memberships={data.memberships}
|
||||
joinRequests={data.joinRequests}
|
||||
incidents={data.incidents}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -36,8 +36,13 @@ export async function POST(request: Request): Promise<Response> {
|
||||
password,
|
||||
organizationId: organizationId || undefined,
|
||||
});
|
||||
await setSessionCookie(created.session.id);
|
||||
return jsonSuccess("账号已创建", { account: created.account });
|
||||
if (created.session) {
|
||||
await setSessionCookie(created.session.id);
|
||||
}
|
||||
return jsonSuccess(organizationId ? "申请已提交,待机构管理员审批" : "账号已创建", {
|
||||
account: created.account,
|
||||
pendingApproval: !created.session,
|
||||
});
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : "账号创建失败";
|
||||
const status = reason === "账号已存在" ? 409 : 500;
|
||||
|
||||
91
app/api/organizations/route.ts
Normal file
91
app/api/organizations/route.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { seedOrganizationRoles } from "@/modules/core/server/permissions";
|
||||
import { organizations } from "@/modules/core/server/schema";
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readString(source: Record<string, unknown>, key: string): string {
|
||||
const value = source[key];
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function createSlug(name: string): string {
|
||||
const base = name
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "");
|
||||
|
||||
return base.length > 0 ? base : `org-${Date.now()}`;
|
||||
}
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const database = getDatabase();
|
||||
const rows = await database.select().from(organizations).where(eq(organizations.status, "active"));
|
||||
|
||||
return jsonSuccess("机构列表已加载", {
|
||||
organizations: rows.map((organization) => ({
|
||||
id: organization.id,
|
||||
name: organization.name,
|
||||
slug: organization.slug,
|
||||
status: organization.status,
|
||||
createdAt: organization.createdAt.toISOString(),
|
||||
updatedAt: organization.updatedAt.toISOString(),
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
const auth = await requirePermission("organization:manage", {
|
||||
action: "organization.create",
|
||||
targetType: "organization",
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!isRecord(body)) {
|
||||
return jsonFailure("请求数据格式无效");
|
||||
}
|
||||
|
||||
const name = readString(body, "name");
|
||||
if (!name) {
|
||||
return jsonFailure("机构名称不能为空");
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const rows = await database
|
||||
.insert(organizations)
|
||||
.values({
|
||||
name,
|
||||
slug: readString(body, "slug") || createSlug(name),
|
||||
status: "active",
|
||||
})
|
||||
.returning();
|
||||
const organization = rows[0];
|
||||
if (!organization) {
|
||||
return jsonFailure("机构创建失败", 500);
|
||||
}
|
||||
|
||||
await seedOrganizationRoles(organization.id);
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId: organization.id,
|
||||
action: "organization.create",
|
||||
targetType: "organization",
|
||||
targetId: organization.id,
|
||||
result: "success",
|
||||
reason: `创建机构:${organization.name}`,
|
||||
});
|
||||
|
||||
return jsonSuccess("机构已创建", { organization }, 201);
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
|
||||
import { jsonSuccess } from "@/modules/core/server/api";
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { hashPassword, normalizeEmail, requirePermission, toPublicAccount } from "@/modules/core/server/auth";
|
||||
import { jsonFailure, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { hasPermission } from "@/modules/core/server/permissions";
|
||||
import { accounts, memberships, organizations, roles } from "@/modules/core/server/schema";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
|
||||
@@ -28,8 +28,21 @@ export async function GET(): Promise<Response> {
|
||||
}
|
||||
|
||||
const data = await readData();
|
||||
const canReadAllAccounts = hasPermission(auth.context.permissions, "platform:manage");
|
||||
const organizationId = auth.context.organization?.id;
|
||||
const scopedAccountIds =
|
||||
organizationId && !canReadAllAccounts
|
||||
? new Set(
|
||||
data.memberships
|
||||
.filter((membership) => membership.organizationId === organizationId)
|
||||
.map((membership) => membership.accountId),
|
||||
)
|
||||
: null;
|
||||
|
||||
return jsonSuccess("账号列表已加载", {
|
||||
accounts: data.accounts.map((account) => toPublicAccount(account)),
|
||||
accounts: data.accounts
|
||||
.filter((account) => !scopedAccountIds || scopedAccountIds.has(account.id))
|
||||
.map((account) => toPublicAccount(account)),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -60,7 +73,18 @@ export async function POST(request: Request): Promise<Response> {
|
||||
|
||||
const database = getDatabase();
|
||||
const passwordHash = hashPassword(password);
|
||||
const created = await database.transaction(async (transaction) => {
|
||||
try {
|
||||
const created = await database.transaction(async (transaction) => {
|
||||
const normalizedEmail = normalizeEmail(email);
|
||||
const existingAccountRows = await transaction
|
||||
.select({ id: accounts.id })
|
||||
.from(accounts)
|
||||
.where(eq(accounts.email, normalizedEmail))
|
||||
.limit(1);
|
||||
if (existingAccountRows.length > 0) {
|
||||
throw new Error("账号已存在");
|
||||
}
|
||||
|
||||
const organizationRows = await transaction.select().from(organizations).where(eq(organizations.id, organizationId)).limit(1);
|
||||
const organization = organizationRows[0];
|
||||
if (!organization) {
|
||||
@@ -81,7 +105,7 @@ export async function POST(request: Request): Promise<Response> {
|
||||
.insert(accounts)
|
||||
.values({
|
||||
name,
|
||||
email: normalizeEmail(email),
|
||||
email: normalizedEmail,
|
||||
passwordHash: passwordHash.hash,
|
||||
passwordSalt: passwordHash.salt,
|
||||
status: "active",
|
||||
@@ -99,27 +123,31 @@ export async function POST(request: Request): Promise<Response> {
|
||||
status: "active",
|
||||
});
|
||||
|
||||
return { account, organization, role };
|
||||
});
|
||||
return { account, organization, role };
|
||||
});
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId,
|
||||
action: "account.create",
|
||||
targetType: "account",
|
||||
targetId: created.account.id,
|
||||
result: "success",
|
||||
reason: `创建机构用户:${created.account.email}`,
|
||||
});
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId,
|
||||
action: "account.create",
|
||||
targetType: "account",
|
||||
targetId: created.account.id,
|
||||
result: "success",
|
||||
reason: `创建机构用户:${created.account.email}`,
|
||||
});
|
||||
|
||||
return jsonSuccess("账号已创建", {
|
||||
account: toPublicAccount(created.account, created.role.key, {
|
||||
id: created.organization.id,
|
||||
name: created.organization.name,
|
||||
slug: created.organization.slug,
|
||||
status: created.organization.status,
|
||||
createdAt: created.organization.createdAt.toISOString(),
|
||||
updatedAt: created.organization.updatedAt.toISOString(),
|
||||
}),
|
||||
}, 201);
|
||||
return jsonSuccess("账号已创建", {
|
||||
account: toPublicAccount(created.account, created.role.key, {
|
||||
id: created.organization.id,
|
||||
name: created.organization.name,
|
||||
slug: created.organization.slug,
|
||||
status: created.organization.status,
|
||||
createdAt: created.organization.createdAt.toISOString(),
|
||||
updatedAt: created.organization.updatedAt.toISOString(),
|
||||
}),
|
||||
}, 201);
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : "账号创建失败";
|
||||
return jsonFailure(reason, reason === "账号已存在" ? 409 : 400);
|
||||
}
|
||||
}
|
||||
|
||||
146
app/api/settings/join-requests/[id]/route.ts
Normal file
146
app/api/settings/join-requests/[id]/route.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { accounts, joinRequests, memberships, roles } from "@/modules/core/server/schema";
|
||||
|
||||
type RouteContext = {
|
||||
params: Promise<{
|
||||
id: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readString(source: Record<string, unknown>, key: string): string {
|
||||
const value = source[key];
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
export async function PATCH(request: Request, context: RouteContext): Promise<Response> {
|
||||
const { id } = await context.params;
|
||||
const auth = await requirePermission("account:manage", {
|
||||
action: "joinRequest.review",
|
||||
targetType: "joinRequest",
|
||||
targetId: id,
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!isRecord(body)) {
|
||||
return jsonFailure("请求数据格式无效");
|
||||
}
|
||||
|
||||
const decision = readString(body, "decision");
|
||||
if (decision !== "approved" && decision !== "rejected") {
|
||||
return jsonFailure("审批结果无效");
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const reviewed = await database.transaction(async (transaction) => {
|
||||
const requestRows = await transaction
|
||||
.select()
|
||||
.from(joinRequests)
|
||||
.where(eq(joinRequests.id, id))
|
||||
.limit(1);
|
||||
const joinRequest = requestRows[0];
|
||||
if (!joinRequest) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const activeOrganizationId = auth.context.organization?.id;
|
||||
if (activeOrganizationId && joinRequest.organizationId !== activeOrganizationId) {
|
||||
throw new Error("不能审批其他机构的申请");
|
||||
}
|
||||
|
||||
if (joinRequest.status !== "pending") {
|
||||
throw new Error("申请已处理");
|
||||
}
|
||||
|
||||
let roleId = readString(body, "roleId");
|
||||
if (decision === "approved" && !roleId) {
|
||||
const defaultRoleRows = await transaction
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(and(eq(roles.organizationId, joinRequest.organizationId), eq(roles.key, "caregiver")))
|
||||
.limit(1);
|
||||
const defaultRole = defaultRoleRows[0];
|
||||
if (!defaultRole) {
|
||||
throw new Error("默认角色不存在");
|
||||
}
|
||||
roleId = defaultRole.id;
|
||||
}
|
||||
|
||||
if (decision === "approved") {
|
||||
const roleRows = await transaction
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(and(eq(roles.id, roleId), eq(roles.organizationId, joinRequest.organizationId)))
|
||||
.limit(1);
|
||||
const role = roleRows[0];
|
||||
if (!role) {
|
||||
throw new Error("审批角色不存在");
|
||||
}
|
||||
|
||||
await transaction
|
||||
.insert(memberships)
|
||||
.values({
|
||||
accountId: joinRequest.accountId,
|
||||
organizationId: joinRequest.organizationId,
|
||||
roleId: role.id,
|
||||
status: "active",
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [memberships.accountId, memberships.organizationId],
|
||||
set: {
|
||||
roleId: role.id,
|
||||
status: "active",
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
});
|
||||
await transaction
|
||||
.update(accounts)
|
||||
.set({ status: "active", updatedAt: new Date() })
|
||||
.where(eq(accounts.id, joinRequest.accountId));
|
||||
}
|
||||
|
||||
const updatedRows = await transaction
|
||||
.update(joinRequests)
|
||||
.set({
|
||||
status: decision,
|
||||
reviewedByAccountId: auth.context.account.id,
|
||||
reviewedAt: new Date(),
|
||||
})
|
||||
.where(eq(joinRequests.id, joinRequest.id))
|
||||
.returning();
|
||||
const updated = updatedRows[0];
|
||||
if (!updated) {
|
||||
throw new Error("申请审批失败");
|
||||
}
|
||||
|
||||
return updated;
|
||||
});
|
||||
|
||||
if (!reviewed) {
|
||||
return jsonFailure("加入申请不存在", 404);
|
||||
}
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId: reviewed.organizationId,
|
||||
action: "joinRequest.review",
|
||||
targetType: "joinRequest",
|
||||
targetId: reviewed.id,
|
||||
result: "success",
|
||||
reason: decision === "approved" ? "通过加入申请" : "拒绝加入申请",
|
||||
});
|
||||
|
||||
return jsonSuccess("加入申请已处理", { joinRequest: reviewed });
|
||||
}
|
||||
23
app/api/settings/join-requests/route.ts
Normal file
23
app/api/settings/join-requests/route.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { jsonSuccess } from "@/modules/core/server/api";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const auth = await requirePermission("account:read", {
|
||||
action: "joinRequest.list",
|
||||
targetType: "joinRequest",
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const data = await readData();
|
||||
const organizationId = auth.context.organization?.id;
|
||||
|
||||
return jsonSuccess("加入申请已加载", {
|
||||
joinRequests: organizationId
|
||||
? data.joinRequests.filter((request) => request.organizationId === organizationId)
|
||||
: data.joinRequests,
|
||||
});
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type { ApiResult } from "@/modules/core/server/api";
|
||||
import type { Organization } from "@/modules/core/types";
|
||||
|
||||
type AuthMode = "login" | "register" | "setup";
|
||||
|
||||
@@ -30,6 +31,7 @@ function AuthPanelContent({ mode }: AuthPanelProps): React.ReactElement {
|
||||
const [message, setMessage] = useState("");
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const [hasAccounts, setHasAccounts] = useState<boolean | null>(null);
|
||||
const [organizations, setOrganizations] = useState<Organization[]>([]);
|
||||
|
||||
const copy = modeCopy[mode];
|
||||
const isSetup = mode === "setup";
|
||||
@@ -39,17 +41,23 @@ function AuthPanelContent({ mode }: AuthPanelProps): React.ReactElement {
|
||||
let isMounted = true;
|
||||
|
||||
async function loadState(): Promise<void> {
|
||||
const [bootstrapResponse, sessionResponse] = await Promise.all([
|
||||
const [bootstrapResponse, sessionResponse, organizationsResponse] = await Promise.all([
|
||||
fetch("/api/auth/bootstrap"),
|
||||
fetch("/api/auth/session"),
|
||||
fetch("/api/organizations"),
|
||||
]);
|
||||
const bootstrap = (await bootstrapResponse.json()) as ApiResult<{ setupRequired: boolean }>;
|
||||
const session = (await sessionResponse.json()) as ApiResult<{ account: unknown | null }>;
|
||||
const organizationsResult = (await organizationsResponse.json()) as ApiResult<{ organizations: Organization[] }>;
|
||||
|
||||
if (!isMounted || !bootstrap.success || !session.success) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (organizationsResult.success) {
|
||||
setOrganizations(organizationsResult.organizations);
|
||||
}
|
||||
|
||||
const initialized = !bootstrap.setupRequired;
|
||||
setHasAccounts(initialized);
|
||||
|
||||
@@ -97,6 +105,7 @@ function AuthPanelContent({ mode }: AuthPanelProps): React.ReactElement {
|
||||
const email = String(formData.get("email") ?? "");
|
||||
const password = String(formData.get("password") ?? "");
|
||||
const organization = String(formData.get("organization") ?? "");
|
||||
const organizationId = String(formData.get("organizationId") ?? "");
|
||||
|
||||
const endpoint = isLogin ? "/api/auth/login" : isSetup ? "/api/auth/setup" : "/api/auth/register";
|
||||
const response = await fetch(endpoint, {
|
||||
@@ -107,9 +116,10 @@ function AuthPanelContent({ mode }: AuthPanelProps): React.ReactElement {
|
||||
email,
|
||||
password,
|
||||
organization,
|
||||
organizationId,
|
||||
}),
|
||||
});
|
||||
const result = (await response.json()) as ApiResult<{ account: unknown }>;
|
||||
const result = (await response.json()) as ApiResult<{ account: unknown; pendingApproval?: boolean }>;
|
||||
setIsPending(false);
|
||||
|
||||
if (!result.success) {
|
||||
@@ -117,6 +127,11 @@ function AuthPanelContent({ mode }: AuthPanelProps): React.ReactElement {
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.pendingApproval) {
|
||||
setMessage(result.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
router.refresh();
|
||||
router.replace(isLogin ? redirectTo : "/app/dashboard");
|
||||
}
|
||||
@@ -180,6 +195,23 @@ function AuthPanelContent({ mode }: AuthPanelProps): React.ReactElement {
|
||||
</label>
|
||||
) : null}
|
||||
|
||||
{mode === "register" && organizations.length > 0 ? (
|
||||
<label className="block space-y-2">
|
||||
<span className="text-sm font-medium">申请加入机构</span>
|
||||
<select
|
||||
className="h-11 w-full rounded-md border bg-background px-3 text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring"
|
||||
name="organizationId"
|
||||
>
|
||||
<option value="">暂不加入机构</option>
|
||||
{organizations.map((organization) => (
|
||||
<option key={organization.id} value={organization.id}>
|
||||
{organization.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
) : null}
|
||||
|
||||
{!isLogin ? (
|
||||
<label className="block space-y-2">
|
||||
<span className="text-sm font-medium">姓名</span>
|
||||
|
||||
@@ -251,7 +251,7 @@ export async function createRegistration(input: {
|
||||
email: string;
|
||||
password: string;
|
||||
organizationId?: string;
|
||||
}): Promise<{ account: PublicAccount; session: Session }> {
|
||||
}): Promise<{ account: PublicAccount; session?: Session }> {
|
||||
const database = getDatabase();
|
||||
const password = hashPassword(input.password);
|
||||
const expiresAt = new Date(Date.now() + SESSION_MAX_AGE_SECONDS * 1000);
|
||||
@@ -278,18 +278,16 @@ export async function createRegistration(input: {
|
||||
throw new Error("账号创建失败");
|
||||
}
|
||||
|
||||
const sessionRows = await transaction
|
||||
.insert(sessions)
|
||||
.values({
|
||||
accountId: account.id,
|
||||
activeOrganizationId: input.organizationId,
|
||||
expiresAt,
|
||||
})
|
||||
.returning();
|
||||
const sessionRows = input.organizationId
|
||||
? []
|
||||
: await transaction
|
||||
.insert(sessions)
|
||||
.values({
|
||||
accountId: account.id,
|
||||
expiresAt,
|
||||
})
|
||||
.returning();
|
||||
const session = sessionRows[0];
|
||||
if (!session) {
|
||||
throw new Error("会话创建失败");
|
||||
}
|
||||
|
||||
if (input.organizationId) {
|
||||
await transaction.insert(joinRequests).values({
|
||||
@@ -308,7 +306,7 @@ export async function createRegistration(input: {
|
||||
}
|
||||
|
||||
const publicAccount = toPublicAccount(created.account);
|
||||
const session = toSession(created.session);
|
||||
const session = created.session ? toSession(created.session) : undefined;
|
||||
await recordAuditLog({
|
||||
actor: publicAccount,
|
||||
organizationId: input.organizationId,
|
||||
@@ -334,7 +332,7 @@ export async function loginWithPassword(input: {
|
||||
.limit(1);
|
||||
const account = accountRows[0];
|
||||
|
||||
if (!account || account.status === "disabled" || !verifyPassword(input.password, account)) {
|
||||
if (!account || account.status !== "active" || !verifyPassword(input.password, account)) {
|
||||
throw new Error("邮箱或密码错误");
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
admissions,
|
||||
beds,
|
||||
elders,
|
||||
joinRequests,
|
||||
memberships,
|
||||
organizations,
|
||||
roles,
|
||||
@@ -14,7 +15,18 @@ import {
|
||||
sessions,
|
||||
systemIncidents,
|
||||
} from "@/modules/core/server/schema";
|
||||
import type { Account, Admission, AppData, FacilityBed, Membership, Organization, Room, Session, SystemIncident } from "@/modules/core/types";
|
||||
import type {
|
||||
Account,
|
||||
Admission,
|
||||
AppData,
|
||||
FacilityBed,
|
||||
JoinRequest,
|
||||
Membership,
|
||||
Organization,
|
||||
Room,
|
||||
Session,
|
||||
SystemIncident,
|
||||
} from "@/modules/core/types";
|
||||
import type { Elder } from "@/modules/elders/types";
|
||||
|
||||
function iso(value: Date): string {
|
||||
@@ -27,6 +39,7 @@ export async function readData(): Promise<AppData> {
|
||||
organizationRows,
|
||||
accountRows,
|
||||
membershipRows,
|
||||
joinRequestRows,
|
||||
sessionRows,
|
||||
elderRows,
|
||||
roomRows,
|
||||
@@ -38,6 +51,17 @@ export async function readData(): Promise<AppData> {
|
||||
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({
|
||||
request: joinRequests,
|
||||
accountName: accounts.name,
|
||||
accountEmail: accounts.email,
|
||||
organizationName: organizations.name,
|
||||
})
|
||||
.from(joinRequests)
|
||||
.innerJoin(accounts, eq(accounts.id, joinRequests.accountId))
|
||||
.innerJoin(organizations, eq(organizations.id, joinRequests.organizationId))
|
||||
.orderBy(desc(joinRequests.createdAt)),
|
||||
database.select().from(sessions).orderBy(desc(sessions.createdAt)),
|
||||
database.select().from(elders).orderBy(desc(elders.createdAt)),
|
||||
database.select().from(rooms).orderBy(desc(rooms.createdAt)),
|
||||
@@ -120,6 +144,20 @@ export async function readData(): Promise<AppData> {
|
||||
};
|
||||
});
|
||||
|
||||
const joinRequestsData: JoinRequest[] = joinRequestRows.map((row) => ({
|
||||
id: row.request.id,
|
||||
accountId: row.request.accountId,
|
||||
accountName: row.accountName,
|
||||
accountEmail: row.accountEmail,
|
||||
organizationId: row.request.organizationId,
|
||||
organizationName: row.organizationName,
|
||||
status: row.request.status,
|
||||
reason: row.request.reason,
|
||||
reviewedByAccountId: row.request.reviewedByAccountId ?? undefined,
|
||||
reviewedAt: row.request.reviewedAt ? iso(row.request.reviewedAt) : undefined,
|
||||
createdAt: iso(row.request.createdAt),
|
||||
}));
|
||||
|
||||
const sessionsData: Session[] = sessionRows.map((row) => ({
|
||||
id: row.id,
|
||||
accountId: row.accountId,
|
||||
@@ -204,6 +242,7 @@ export async function readData(): Promise<AppData> {
|
||||
organizations: organizationsData,
|
||||
accounts: accountsData,
|
||||
memberships: membershipsData,
|
||||
joinRequests: joinRequestsData,
|
||||
sessions: sessionsData,
|
||||
elders: eldersData,
|
||||
rooms: roomsData,
|
||||
|
||||
@@ -86,6 +86,22 @@ export type Membership = {
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type JoinRequestStatus = "pending" | "approved" | "rejected";
|
||||
|
||||
export type JoinRequest = {
|
||||
id: string;
|
||||
accountId: string;
|
||||
accountName: string;
|
||||
accountEmail: string;
|
||||
organizationId: string;
|
||||
organizationName: string;
|
||||
status: JoinRequestStatus;
|
||||
reason: string;
|
||||
reviewedByAccountId?: string;
|
||||
reviewedAt?: string;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
export type Account = {
|
||||
id: string;
|
||||
platformRoleId?: string;
|
||||
@@ -189,6 +205,7 @@ export type AppData = {
|
||||
organizations: Organization[];
|
||||
accounts: Account[];
|
||||
memberships: Membership[];
|
||||
joinRequests: JoinRequest[];
|
||||
sessions: Session[];
|
||||
elders: Elder[];
|
||||
rooms: Room[];
|
||||
|
||||
@@ -2,8 +2,17 @@ import { Activity, Building2, Server, ShieldCheck, Users } from "lucide-react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import type { AuditLog, Membership, Organization, PublicAccount, RoleDefinition, SystemIncident } from "@/modules/core/types";
|
||||
import type {
|
||||
AuditLog,
|
||||
JoinRequest,
|
||||
Membership,
|
||||
Organization,
|
||||
PublicAccount,
|
||||
RoleDefinition,
|
||||
SystemIncident,
|
||||
} from "@/modules/core/types";
|
||||
import { ROLE_LABELS } from "@/modules/core/types";
|
||||
import { UserManagementClient } from "@/modules/settings/components/UserManagementClient";
|
||||
import type { RoleId } from "@/modules/core/types";
|
||||
|
||||
type SettingsOverviewProps = {
|
||||
@@ -12,6 +21,7 @@ type SettingsOverviewProps = {
|
||||
auditLogs: AuditLog[];
|
||||
organizations: Organization[];
|
||||
memberships: Membership[];
|
||||
joinRequests: JoinRequest[];
|
||||
incidents: SystemIncident[];
|
||||
};
|
||||
|
||||
@@ -29,6 +39,7 @@ export function SettingsOverview({
|
||||
auditLogs,
|
||||
organizations,
|
||||
memberships,
|
||||
joinRequests,
|
||||
incidents,
|
||||
}: SettingsOverviewProps): React.ReactElement {
|
||||
const activeAccountCount = accounts.filter((account) => account.status === "active").length;
|
||||
@@ -171,6 +182,8 @@ export function SettingsOverview({
|
||||
</Card>
|
||||
</section>
|
||||
|
||||
<UserManagementClient organizations={organizations} roles={roles} joinRequests={joinRequests} />
|
||||
|
||||
<section className="grid gap-4 xl:grid-cols-[0.9fr_1.1fr]">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
|
||||
224
modules/settings/components/UserManagementClient.tsx
Normal file
224
modules/settings/components/UserManagementClient.tsx
Normal file
@@ -0,0 +1,224 @@
|
||||
"use client";
|
||||
|
||||
import { FormEvent, useMemo, useState } from "react";
|
||||
import { Check, Plus, X } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type { ApiResult } from "@/modules/core/server/api";
|
||||
import type { JoinRequest, Organization, RoleDefinition } from "@/modules/core/types";
|
||||
|
||||
type UserManagementClientProps = {
|
||||
organizations: Organization[];
|
||||
roles: RoleDefinition[];
|
||||
joinRequests: JoinRequest[];
|
||||
};
|
||||
|
||||
function getOrganizationRoles(roles: RoleDefinition[], organizationId: string): RoleDefinition[] {
|
||||
return roles.filter((role) => role.scope === "organization" && role.organizationId === organizationId && role.isEnabled);
|
||||
}
|
||||
|
||||
function getDefaultOrganizationId(organizations: Organization[]): string {
|
||||
return organizations[0]?.id ?? "";
|
||||
}
|
||||
|
||||
export function UserManagementClient({
|
||||
organizations,
|
||||
roles,
|
||||
joinRequests,
|
||||
}: UserManagementClientProps): React.ReactElement {
|
||||
const router = useRouter();
|
||||
const [selectedOrganizationId, setSelectedOrganizationId] = useState(() => getDefaultOrganizationId(organizations));
|
||||
const [message, setMessage] = useState("");
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
|
||||
const organizationRoles = useMemo(
|
||||
() => getOrganizationRoles(roles, selectedOrganizationId),
|
||||
[roles, selectedOrganizationId],
|
||||
);
|
||||
const pendingJoinRequests = joinRequests.filter((request) => request.status === "pending");
|
||||
|
||||
async function handleCreateAccount(event: FormEvent<HTMLFormElement>): Promise<void> {
|
||||
event.preventDefault();
|
||||
setMessage("");
|
||||
setIsPending(true);
|
||||
|
||||
const formData = new FormData(event.currentTarget);
|
||||
const response = await fetch("/api/settings/accounts", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
organizationId: String(formData.get("organizationId") ?? ""),
|
||||
roleId: String(formData.get("roleId") ?? ""),
|
||||
name: String(formData.get("name") ?? ""),
|
||||
email: String(formData.get("email") ?? ""),
|
||||
password: String(formData.get("password") ?? ""),
|
||||
}),
|
||||
});
|
||||
const result = (await response.json()) as ApiResult<{ account: unknown }>;
|
||||
setIsPending(false);
|
||||
|
||||
if (!result.success) {
|
||||
setMessage(result.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
setMessage(result.reason);
|
||||
event.currentTarget.reset();
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function reviewJoinRequest(requestId: string, decision: "approved" | "rejected", roleId: string): Promise<void> {
|
||||
setMessage("");
|
||||
setIsPending(true);
|
||||
const response = await fetch(`/api/settings/join-requests/${requestId}`, {
|
||||
method: "PATCH",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ decision, roleId }),
|
||||
});
|
||||
const result = (await response.json()) as ApiResult<{ joinRequest: unknown }>;
|
||||
setIsPending(false);
|
||||
|
||||
if (!result.success) {
|
||||
setMessage(result.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
setMessage(result.reason);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="grid gap-4 xl:grid-cols-[0.9fr_1.1fr]">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>创建机构用户</CardTitle>
|
||||
<CardDescription>管理员创建账号后立即分配到机构和角色。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form className="grid gap-3" onSubmit={handleCreateAccount}>
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">机构</span>
|
||||
<select
|
||||
className="h-11 w-full rounded-md border bg-background px-3 text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring"
|
||||
name="organizationId"
|
||||
onChange={(event) => setSelectedOrganizationId(event.target.value)}
|
||||
value={selectedOrganizationId}
|
||||
>
|
||||
{organizations.map((organization) => (
|
||||
<option key={organization.id} value={organization.id}>
|
||||
{organization.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">角色</span>
|
||||
<select
|
||||
className="h-11 w-full rounded-md border bg-background px-3 text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring"
|
||||
name="roleId"
|
||||
required
|
||||
>
|
||||
{organizationRoles.map((role) => (
|
||||
<option key={role.id} value={role.id}>
|
||||
{role.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">姓名</span>
|
||||
<Input name="name" required />
|
||||
</label>
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">邮箱</span>
|
||||
<Input name="email" required type="email" />
|
||||
</label>
|
||||
<label className="grid gap-2 text-sm">
|
||||
<span className="font-medium">初始密码</span>
|
||||
<Input minLength={6} name="password" required type="password" />
|
||||
</label>
|
||||
|
||||
<Button disabled={isPending || organizationRoles.length === 0} type="submit">
|
||||
<Plus className="size-4" aria-hidden="true" />
|
||||
创建用户
|
||||
</Button>
|
||||
</form>
|
||||
{message ? (
|
||||
<p className="mt-3 rounded-md bg-secondary px-3 py-2 text-sm text-secondary-foreground" role="status">
|
||||
{message}
|
||||
</p>
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>加入申请审批</CardTitle>
|
||||
<CardDescription>公开注册选择机构后进入这里审批。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{pendingJoinRequests.map((request) => {
|
||||
const requestRoles = getOrganizationRoles(roles, request.organizationId);
|
||||
const defaultRoleId = requestRoles.find((role) => role.key === "caregiver")?.id ?? requestRoles[0]?.id ?? "";
|
||||
|
||||
return (
|
||||
<div key={request.id} className="rounded-md border p-3">
|
||||
<div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div>
|
||||
<p className="font-medium">{request.accountName}</p>
|
||||
<p className="text-xs text-muted-foreground">{request.accountEmail}</p>
|
||||
<p className="mt-2 text-sm text-muted-foreground">{request.organizationName}</p>
|
||||
</div>
|
||||
<Badge variant="warning">待审批</Badge>
|
||||
</div>
|
||||
<div className="mt-3 grid gap-2 sm:grid-cols-[1fr_auto_auto]">
|
||||
<select
|
||||
className="h-10 w-full rounded-md border bg-background px-3 text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring"
|
||||
defaultValue={defaultRoleId}
|
||||
id={`role-${request.id}`}
|
||||
>
|
||||
{requestRoles.map((role) => (
|
||||
<option key={role.id} value={role.id}>
|
||||
{role.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Button
|
||||
disabled={isPending || !defaultRoleId}
|
||||
onClick={() => {
|
||||
const element = document.getElementById(`role-${request.id}`);
|
||||
const roleId = element instanceof HTMLSelectElement ? element.value : defaultRoleId;
|
||||
void reviewJoinRequest(request.id, "approved", roleId);
|
||||
}}
|
||||
size="sm"
|
||||
type="button"
|
||||
>
|
||||
<Check className="size-4" aria-hidden="true" />
|
||||
通过
|
||||
</Button>
|
||||
<Button
|
||||
disabled={isPending}
|
||||
onClick={() => void reviewJoinRequest(request.id, "rejected", "")}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<X className="size-4" aria-hidden="true" />
|
||||
拒绝
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{pendingJoinRequests.length === 0 ? <p className="text-sm text-muted-foreground">暂无待审批申请</p> : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user