=test_update_homework_tests_and_work_log
Some checks failed
CI / build-deploy (push) Has been cancelled
Some checks failed
CI / build-deploy (push) Has been cancelled
This commit is contained in:
204
src/modules/settings/actions.ts
Normal file
204
src/modules/settings/actions.ts
Normal file
@@ -0,0 +1,204 @@
|
||||
"use server"
|
||||
|
||||
import { z } from "zod"
|
||||
import { revalidatePath } from "next/cache"
|
||||
import { createId } from "@paralleldrive/cuid2"
|
||||
import { count, desc, eq } from "drizzle-orm"
|
||||
|
||||
import { auth } from "@/auth"
|
||||
import { db } from "@/shared/db"
|
||||
import { aiProviders } from "@/shared/db/schema"
|
||||
import type { ActionState } from "@/shared/types/action-state"
|
||||
import { encryptAiApiKey, getAiErrorMessage, testAiProviderById, testAiProviderConfig } from "@/shared/lib/ai"
|
||||
|
||||
const ProviderSchema = z.enum(["zhipu", "openai", "gemini", "custom"])
|
||||
|
||||
const AiProviderFormSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
provider: ProviderSchema,
|
||||
baseUrl: z.string().url().optional().or(z.literal("")),
|
||||
model: z.string().min(1),
|
||||
apiKey: z.string().min(1).optional(),
|
||||
isDefault: z.boolean().optional(),
|
||||
})
|
||||
|
||||
const AiProviderTestSchema = AiProviderFormSchema.extend({
|
||||
apiKey: z.string().optional(),
|
||||
}).superRefine((data, ctx) => {
|
||||
if (!data.apiKey?.trim() && !data.id?.trim()) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["apiKey"],
|
||||
message: "API key is required",
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export type AiProviderSummary = {
|
||||
id: string
|
||||
provider: z.infer<typeof ProviderSchema>
|
||||
baseUrl: string | null
|
||||
model: string
|
||||
apiKeyLast4: string | null
|
||||
isDefault: boolean
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
const ensureUser = async () => {
|
||||
const session = await auth()
|
||||
const userId = String(session?.user?.id ?? "").trim()
|
||||
if (!userId) throw new Error("Unauthorized")
|
||||
return { id: userId }
|
||||
}
|
||||
|
||||
const normalizeBaseUrl = (value: string | undefined) => {
|
||||
const raw = String(value ?? "").trim()
|
||||
if (!raw.length) return null
|
||||
const trimmed = raw.replace(/\/+$/, "")
|
||||
return trimmed
|
||||
.replace(/\/v1\/chat\/completions$/i, "")
|
||||
.replace(/\/chat\/completions$/i, "")
|
||||
}
|
||||
|
||||
export async function getAiProviderSummaries(): Promise<AiProviderSummary[]> {
|
||||
await ensureUser()
|
||||
const rows = await db
|
||||
.select({
|
||||
id: aiProviders.id,
|
||||
provider: aiProviders.provider,
|
||||
baseUrl: aiProviders.baseUrl,
|
||||
model: aiProviders.model,
|
||||
apiKeyLast4: aiProviders.apiKeyLast4,
|
||||
isDefault: aiProviders.isDefault,
|
||||
updatedAt: aiProviders.updatedAt,
|
||||
})
|
||||
.from(aiProviders)
|
||||
.orderBy(desc(aiProviders.updatedAt))
|
||||
return rows
|
||||
}
|
||||
|
||||
export async function upsertAiProviderAction(
|
||||
data: z.infer<typeof AiProviderFormSchema>
|
||||
): Promise<ActionState<string>> {
|
||||
try {
|
||||
const user = await ensureUser()
|
||||
const parsed = AiProviderFormSchema.safeParse(data)
|
||||
if (!parsed.success) {
|
||||
return { success: false, message: "Invalid form data" }
|
||||
}
|
||||
|
||||
const payload = parsed.data
|
||||
const baseUrl = normalizeBaseUrl(payload.baseUrl)
|
||||
if (payload.provider !== "openai" && !baseUrl) {
|
||||
return { success: false, message: "Base URL is required for this provider" }
|
||||
}
|
||||
|
||||
const [defaultRow] = await db
|
||||
.select({ value: count() })
|
||||
.from(aiProviders)
|
||||
.where(eq(aiProviders.isDefault, true))
|
||||
const defaultCount = Number(defaultRow?.value ?? 0)
|
||||
const hasDefault = defaultCount > 0
|
||||
|
||||
if (payload.id) {
|
||||
const id = payload.id
|
||||
const [existing] = await db
|
||||
.select({
|
||||
id: aiProviders.id,
|
||||
apiKeyEncrypted: aiProviders.apiKeyEncrypted,
|
||||
apiKeyLast4: aiProviders.apiKeyLast4,
|
||||
isDefault: aiProviders.isDefault,
|
||||
})
|
||||
.from(aiProviders)
|
||||
.where(eq(aiProviders.id, id))
|
||||
.limit(1)
|
||||
if (!existing) return { success: false, message: "AI provider not found" }
|
||||
|
||||
const nextKey = payload.apiKey?.trim()
|
||||
const encrypted = nextKey ? encryptAiApiKey(nextKey) : existing.apiKeyEncrypted
|
||||
const last4 = nextKey ? nextKey.slice(-4) : existing.apiKeyLast4
|
||||
|
||||
const nextIsDefault =
|
||||
payload.isDefault === false && existing.isDefault && defaultCount <= 1 ? true : payload.isDefault ?? existing.isDefault
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
if (payload.isDefault) {
|
||||
await tx.update(aiProviders).set({ isDefault: false }).where(eq(aiProviders.isDefault, true))
|
||||
}
|
||||
await tx
|
||||
.update(aiProviders)
|
||||
.set({
|
||||
provider: payload.provider,
|
||||
baseUrl,
|
||||
model: payload.model,
|
||||
apiKeyEncrypted: encrypted,
|
||||
apiKeyLast4: last4,
|
||||
isDefault: nextIsDefault,
|
||||
updatedBy: user.id,
|
||||
})
|
||||
.where(eq(aiProviders.id, id))
|
||||
})
|
||||
|
||||
revalidatePath("/settings")
|
||||
return { success: true, message: "AI provider updated", data: id }
|
||||
}
|
||||
|
||||
if (!payload.apiKey) {
|
||||
return { success: false, message: "API key is required" }
|
||||
}
|
||||
|
||||
const id = createId()
|
||||
const encrypted = encryptAiApiKey(payload.apiKey.trim())
|
||||
const last4 = payload.apiKey.trim().slice(-4)
|
||||
const makeDefault = payload.isDefault ?? !hasDefault
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
if (makeDefault) {
|
||||
await tx.update(aiProviders).set({ isDefault: false }).where(eq(aiProviders.isDefault, true))
|
||||
}
|
||||
await tx.insert(aiProviders).values({
|
||||
id,
|
||||
provider: payload.provider,
|
||||
baseUrl,
|
||||
model: payload.model,
|
||||
apiKeyEncrypted: encrypted,
|
||||
apiKeyLast4: last4,
|
||||
isDefault: makeDefault,
|
||||
createdBy: user.id,
|
||||
updatedBy: user.id,
|
||||
})
|
||||
})
|
||||
|
||||
revalidatePath("/settings")
|
||||
return { success: true, message: "AI provider created", data: id }
|
||||
} catch {
|
||||
return { success: false, message: "Failed to save AI provider" }
|
||||
}
|
||||
}
|
||||
|
||||
export async function testAiProviderAction(
|
||||
data: z.infer<typeof AiProviderTestSchema>
|
||||
): Promise<ActionState<null>> {
|
||||
try {
|
||||
await ensureUser()
|
||||
const parsed = AiProviderTestSchema.safeParse(data)
|
||||
if (!parsed.success) {
|
||||
return { success: false, message: "Invalid form data" }
|
||||
}
|
||||
const payload = parsed.data
|
||||
const baseUrl = normalizeBaseUrl(payload.baseUrl)
|
||||
if (payload.provider !== "openai" && !baseUrl) {
|
||||
return { success: false, message: "Base URL is required for this provider" }
|
||||
}
|
||||
const model = payload.model.trim()
|
||||
const apiKey = payload.apiKey?.trim()
|
||||
if (apiKey) {
|
||||
await testAiProviderConfig({ apiKey, baseUrl: baseUrl ?? undefined, model })
|
||||
} else if (payload.id) {
|
||||
await testAiProviderById(payload.id, { baseUrl: baseUrl ?? undefined, model })
|
||||
}
|
||||
return { success: true, message: "AI connection ok", data: null }
|
||||
} catch (error) {
|
||||
return { success: false, message: getAiErrorMessage(error) }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user