Files
boss/src/app/api/v1/accounts/onboard/openai-api/route.ts

86 lines
2.8 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { requireRequestSession } from "@/lib/boss-auth";
import { getMasterIdentitySummaryFromState, readState, saveAiAccount, updateAiAccountHealth } from "@/lib/boss-data";
import { probeOpenAiApiAccount } from "@/lib/boss-master-agent";
function chooseOpenAiPrimaryAccountId(state: Awaited<ReturnType<typeof readState>>) {
return (
state.aiAccounts.find((item) => item.provider === "openai_api" && item.role === "primary")?.accountId ||
"openai-api-primary"
);
}
export async function POST(request: NextRequest) {
const session = await requireRequestSession(request);
if (!session) {
return NextResponse.json({ ok: false, message: "UNAUTHORIZED" }, { status: 401 });
}
if (session.role !== "highest_admin") {
return NextResponse.json({ ok: false, message: "FORBIDDEN" }, { status: 403 });
}
const body = (await request.json().catch(() => ({}))) as {
label?: string;
displayName?: string;
accountIdentifier?: string;
model?: string;
apiBaseUrl?: string;
apiKey?: string;
};
if (!body.displayName?.trim()) {
return NextResponse.json({ ok: false, message: "显示名称不能为空。" }, { status: 400 });
}
if (!body.apiKey?.trim()) {
return NextResponse.json({ ok: false, message: "请先填写 OpenAI API Key。" }, { status: 400 });
}
try {
const probe = await probeOpenAiApiAccount({
apiKey: body.apiKey,
model: body.model,
apiBaseUrl: body.apiBaseUrl,
});
const state = await readState();
const accountId = chooseOpenAiPrimaryAccountId(state);
const account = await saveAiAccount({
accountId,
label: body.label?.trim() || "主 GPT",
role: "primary",
provider: "openai_api",
displayName: body.displayName.trim(),
accountIdentifier: body.accountIdentifier?.trim() || undefined,
model: probe.model,
apiBaseUrl: body.apiBaseUrl,
apiKey: body.apiKey.trim(),
enabled: true,
setActive: true,
loginStatusNote: "已在手机端登录 OpenAI 平台账号,可直接作为当前主控。",
});
await updateAiAccountHealth({
accountId: account.accountId,
status: "ready",
lastError: undefined,
lastValidatedAt: new Date().toISOString(),
lastUsedAt: new Date().toISOString(),
});
const nextState = await readState();
return NextResponse.json({
ok: true,
accountId: account.accountId,
account,
activeIdentity: getMasterIdentitySummaryFromState(nextState),
requestId: probe.requestId,
message: "OpenAI 平台账号已登录,并设为当前主控。",
});
} catch (error) {
return NextResponse.json(
{ ok: false, message: error instanceof Error ? error.message : "OPENAI_ONBOARD_FAILED" },
{ status: 400 },
);
}
}