32 lines
1.8 KiB
TypeScript
32 lines
1.8 KiB
TypeScript
import { randomUUID } from 'crypto'
|
|
import { z } from 'zod'
|
|
import { prisma } from '@/lib/prisma'
|
|
import { DetailGeneratorError } from './access'
|
|
import { DETAIL_FONT_FAMILY, type DetailBrandProfileRecord } from './types'
|
|
|
|
const color = z.string().regex(/^#[0-9a-fA-F]{6}$/)
|
|
const schema = z.object({
|
|
name: z.string().trim().min(1).max(100), tone: z.string().max(2000),
|
|
primaryColor: color, backgroundColor: color, textColor: color,
|
|
fontFamily: z.literal(DETAIL_FONT_FAMILY), status: z.literal('draft'),
|
|
}).strict()
|
|
|
|
export async function listDetailBrandProfiles(): Promise<DetailBrandProfileRecord[]> {
|
|
return prisma.$queryRaw<DetailBrandProfileRecord[]>`SELECT id, revision, profile FROM detail_generator_brand_profiles ORDER BY name`
|
|
}
|
|
|
|
export async function saveDetailBrandProfile(value: unknown, revision: unknown): Promise<DetailBrandProfileRecord> {
|
|
const parsed = schema.safeParse(value)
|
|
if (!parsed.success) throw new DetailGeneratorError('品牌草案格式无效;品牌标志请在各项目中上传')
|
|
if (revision != null && (!Number.isSafeInteger(revision) || Number(revision) < 1)) throw new DetailGeneratorError('品牌版本无效')
|
|
const profile = parsed.data
|
|
const rows = await prisma.$queryRaw<DetailBrandProfileRecord[]>`
|
|
INSERT INTO detail_generator_brand_profiles (id, name, profile, revision)
|
|
VALUES (${randomUUID()}, ${profile.name}, ${JSON.stringify(profile)}::jsonb, 1)
|
|
ON CONFLICT (name) DO UPDATE SET profile=EXCLUDED.profile, revision=detail_generator_brand_profiles.revision+1, updated_at=NOW()
|
|
WHERE detail_generator_brand_profiles.revision=${revision == null ? -1 : Number(revision)}
|
|
RETURNING id, revision, profile`
|
|
if (!rows[0]) throw new DetailGeneratorError('品牌草案已更新,请重新载入后保存', 409, 'revision_conflict')
|
|
return rows[0]
|
|
}
|