92 lines
2.7 KiB
TypeScript
92 lines
2.7 KiB
TypeScript
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);
|
|
}
|