import { existsSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { PrismaClient, type Prisma } from "@prisma/client"; import type { TemplatePackageManifest } from "@personal-brand/config"; import bcrypt from "bcryptjs"; import { buildBrandReleaseSnapshot } from "../src/brand-release.service.js"; import { latestTemplateVersion } from "../src/template-version-order.js"; const prisma = new PrismaClient(); const seedAssetsDirectory = path.join(path.dirname(fileURLToPath(import.meta.url)), "assets"); function seedMediaExists(url: unknown): boolean { if (typeof url !== "string" || !url) return false; if (!url.startsWith("/media/seed/")) return true; return existsSync(path.join(seedAssetsDirectory, path.basename(url))); } const runtimeImages = { doors: [ "/media/seed/doors-hero.jpg", "/media/seed/doors-yard-gate.jpg", "/media/seed/doors-room-door.jpg", ], food: [ "/media/seed/food-package-01.jpg", "/media/seed/food-package-02.jpg", "/media/seed/food-private-chef.jpg", ], personal: ["/media/seed/personal-consulting.jpg", "/media/seed/personal-advisory.jpg"], } as const; type OfferingKind = "service" | "product" | "package" | "subscription"; interface RuntimeSeedTemplate { templateKey: "personal" | "food" | "doors"; visualTemplateKey: string; brandConfig: Record; retiredOfferingNames?: string[]; offerings: Array<{ name: string; summary: string; image: string; kind: OfferingKind; priceText?: string; priceAmount?: number; config: Record; }>; trustContent: Array<{ type: string; title: string; content: string; summary?: string; config?: Record; }>; inquiryForm?: { name: string; fieldsSnapshot: Array> }; } const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTemplate> = { personal: { templateKey: "personal", visualTemplateKey: "atelier-solopreneur", brandConfig: { templateData: { designPhilosophy: "先厘清问题,再设计表达" }, title: "品牌策略顾问", slogan: "用清晰的定位与可执行的表达,让专业被看见。", phone: "13900000003", wechat: "personal-brand", studioAddress: "上海市徐汇区创意园区", heroImage: runtimeImages.personal[0], visualPresentation: { home: { proofEyebrow: "专业经验与合作成果", manifestoEyebrow: "工作原则", manifestoTitle: "先厘清问题,再设计表达", worksEyebrow: "合作方式", worksTitle: "品牌策略与顾问服务", worksAction: "查看全部 →", flowEyebrow: "合作流程", flowTitle: "从诊断到持续落地", }, offerings: { title: "合作方式", subtitle: "围绕品牌定位、表达与业务转化,选择适合当前阶段的支持。", materialLabel: "服务内容:", hardwareLabel: "合作重点:", detailAction: "查看服务详情 →", inquiryAction: "发起合作咨询", }, detail: { priceLabel: "服务参考", spaceLabel: "适合阶段", backgroundTitle: "服务背景", conceptTitle: "工作方法", craftsTitle: "交付内容", materialsTitle: "合作说明", inquiryAction: "发起合作咨询", inquiryHint: "提交信息后由主理人与您沟通。", }, profile: { phoneLabel: "联系电话", wechatLabel: "微信", addressLabel: "工作地点", callAction: "呼叫", copyAction: "复制", recordsTitle: "我的咨询记录", recordsCountUnit: "条记录", }, inquiry: { eyebrow: "COLLABORATION", title: "合作咨询", subtitle: "留下你的品牌现状与目标,主理人会尽快联系。", submitLabel: "提交合作需求", }, success: { eyebrow: "COLLABORATION", title: "已收到你的咨询", intro: "主理人会尽快与你联系。", recordsAction: "查看咨询记录", homeAction: "返回首页", }, records: { title: "我的咨询记录", createAction: "新增咨询", emptyTitle: "还没有咨询记录", emptyDescription: "提交一次咨询,开始与你的主理人沟通。", emptyAction: "开始咨询", }, }, }, offerings: [ { name: "品牌定位诊断", summary: "梳理现有表达、目标客户与业务优先级,形成清晰的下一步行动建议。", image: runtimeImages.personal[0], kind: "service", config: { categoryKey: "consulting", keywords: ["定位", "诊断", "表达"], }, }, { name: "个人品牌年度顾问", summary: "持续支持内容策略、产品表达与关键节点决策,建立长期信任资产。", image: runtimeImages.personal[1], kind: "subscription", config: { categoryKey: "advisory", keywords: ["陪跑", "内容", "转化"], }, }, ], trustContent: [ { type: "credential", title: "关于主理人", content: "专注帮助专业服务者建立可信、清晰且能带来合作的个人品牌表达。", }, { type: "process", title: "合作方法", content: "诊断现状、明确定位、搭建表达、持续复盘,让每一步都服务于真实业务。", }, ], inquiryForm: { name: "品牌合作咨询", fieldsSnapshot: [ { key: "name", label: "您的称呼", type: "text", required: true }, { key: "phone", label: "联系电话", type: "phone", required: true }, { key: "remark", label: "目前的品牌或业务问题", type: "textarea", required: true }, ], }, }, food: { templateKey: "food", visualTemplateKey: "acheng-campus-food", brandConfig: { founder: "阿成", title: "私房菜主理人", slogan: "认真做好每一顿家常饭。", phone: "", wechat: "", studioAddress: "大学城生活区东门附近", heroImage: runtimeImages.food[0], visualPresentation: { home: { proofEyebrow: "主理人信任凭证", manifestoEyebrow: "品牌坚持", manifestoTitle: "认真对待每一次托付", worksEyebrow: "今日餐品与预订", worksTitle: "套餐、聚餐与定制餐", worksAction: "查看全部 →", flowEyebrow: "预订流程", flowTitle: "从预订到取餐", }, service: { processAction: "立即预订", }, offerings: { title: "今日套餐与定制餐", subtitle: "现做套餐、聚餐预订和定制餐品。", materialLabel: "餐品说明:", hardwareLabel: "预订要点:", detailAction: "查看餐品 →", inquiryAction: "咨询 / 提前预订", }, detail: { priceLabel: "参考价格", spaceLabel: "适合场景", backgroundTitle: "餐品说明", conceptTitle: "口味与分量", craftsTitle: "制作方式", materialsTitle: "食材与搭配", inquiryAction: "咨询 / 提前预订", inquiryHint: "提交后由主理人与您确认餐品和时间。", }, profile: { phoneLabel: "联系电话", wechatLabel: "微信", addressLabel: "服务地址", callAction: "呼叫", copyAction: "复制", recordsTitle: "我的咨询记录", recordsCountUnit: "条记录", }, inquiry: { eyebrow: "CONSULTATION", title: "餐品预订与定制", subtitle: "提交信息后由主理人与您确认时间和需求。", submitLabel: "提交预订需求", }, success: { eyebrow: "CONSULTATION", title: "已收到你的预订需求", intro: "主理人会尽快与你确认。", recordsAction: "查看咨询记录", homeAction: "返回首页", }, records: { title: "我的预订记录", createAction: "新增预订", emptyTitle: "还没有预订记录", emptyDescription: "提交一次预订需求,开始确认餐品与时间。", emptyAction: "开始预订", }, }, }, offerings: [ { name: "红烧肉双拼套餐", summary: "红烧肉、时蔬、米饭", image: runtimeImages.food[0], kind: "package", priceAmount: 2800, config: { categoryKey: "set-meal", keywords: ["现做", "家常", "定制"], }, }, { name: "小炒鸡套餐", summary: "现炒鸡块、时蔬、米饭", image: runtimeImages.food[1], kind: "package", priceAmount: 3200, config: { categoryKey: "set-meal", keywords: ["现做", "家常", "定制"], }, }, { name: "家庭聚餐私厨", summary: "根据人数、地点和口味人工沟通报价", image: runtimeImages.food[2], kind: "service", config: { categoryKey: "private-chef", keywords: ["现做", "家常", "定制"], }, }, ], trustContent: [ { type: "credential", title: "食品安全与制作承诺", content: "当天采购,现做现出餐;食具每日清洁消毒,按约定标注和分装。", }, { type: "case", title: "他们都在阿成这订过餐", content: "校街舞社年度专场 · 52 人份\n信息学院科创竞赛 · 连签 5 天\n7 号楼庆功宴 · 8 人定制", }, { type: "promise", title: "回复承诺", content: "备料期 15 分钟内联系,出摊高峰 1 小时内回复。", }, ], }, doors: { templateKey: "doors", visualTemplateKey: "linjing-editorial", retiredOfferingNames: ["别墅入户大门", "院门与围合系统", "室内户内门系统"], brandConfig: { templateData: { designPhilosophy: "让门与空间建立长期、克制的关系" }, founder: "林叙安 (Lin XUAN)", title: "高端门系统建筑研造主理人", slogan: "为当代别墅空间,定制有秩序感与呼吸感的门", phone: "186-0218-9908", wechat: "LIN-ATELIER-2024", studioAddress: "上海市静安区威海路设计中心 A 座 / 杭州良渚研造工坊", avatarUrl: "/media/seed/founder-portrait.jpg", profilePresentation: { coverage: [ { title: "直派核心圈", content: "上海、杭州、宁波、苏州、无锡、南京及深圳、广州。主理人及资深装配总工亲赴现场。", }, { title: "全国其他城市私邸", content: "接受建筑设计师联合委托,安排远程 3D 激光测绘支持与专用物流直运安装。", }, ], warranty: [ "门体内部防变形航空合金骨架承诺 10 年结构质保;", "重型天地轴、进口地弹簧及磁吸五金 5 年免费维护;", "每樘门出厂前进行 5000 次启闭校正;", "原木天然肌理享有首年 2 次木蜡油保养服务。", ], }, visualPresentation: { home: { founderBadge: "亲自主理量房", proofEyebrow: "主理人工艺与信任凭证", proofTitle: "14 年,只做门与空间的关系", manifestoEyebrow: "林境门作品质宣言", manifestoTitle: "拒绝流水线拼装", worksEyebrow: "SELECTED WORKS", worksTitle: "精选门系统作品", worksAction: "查看全部 →", flowEyebrow: "全程一对一跟进", flowTitle: "主理人私享定制流程", }, offerings: { title: "作品与系统", subtitle: "每一扇门,都是建筑秩序的一部分。", materialLabel: "主材构成:", hardwareLabel: "核心五金:", detailAction: "查看工艺详案 →", inquiryAction: "咨询此类定制", }, detail: { priceLabel: "参考定制造价", spaceLabel: "适用空间", backgroundTitle: "项目背景与空间诉求", conceptTitle: "构造深化设计理念", craftsTitle: "节点工艺考究", materialsTitle: "选型物料与五金规格", inquiryAction: "预约上门测量 / 咨询此类方案", inquiryHint: "预约后由主理人进行点对点方案分析", }, profile: { phoneLabel: "专线电话", wechatLabel: "工作室微信", addressLabel: "实体工坊", callAction: "呼叫", copyAction: "复制", recordsCountUnit: "条记录", recordsTitle: "我的量房与定制咨询", recordsSubtitle: "追踪主理人出图进度与现场勘测排期", coverageTitle: "直派服务区域与履约说明", warrantyTitle: "一门一档 · 终生质保规约", }, inquiry: { eyebrow: "私人执业研造服务", title: "高端门系统定制 · 私享测量预约", subtitle: "主理人林叙安亲自沟通,72 小时内提供空间门体构想分析。", submitLabel: "提交量房与定制评估需求", }, success: { eyebrow: "PRIVATE CONSULTATION", title: "已收到你的咨询", intro: "主理人会根据你的项目资料,整理初步判断并在 1 个工作日内与你联系。", recordsAction: "查看咨询记录", homeAction: "返回首页", }, records: { title: "我的咨询记录", createAction: "+ 新增预约", emptyTitle: "还没有咨询记录", emptyDescription: "预约一次私享沟通,让我们从你的空间开始。", emptyAction: "开始咨询", }, }, heroImage: runtimeImages.doors[0], homeHero: { eyebrow: "年度落成实景 · 莫干山庄园", title: "万籁系列 · 铸铜冷锻双轴入户门", slogan: "门高 3.4m · 德国静音地轴", cta: "探索全系作品 →", }, }, offerings: [ { name: "当代铸铜木核防暴装甲门", summary: "项目位于浙北山间独栋庄园,业主需要一扇兼具当代东方仪式感与长期耐候能力的入户大门。", image: runtimeImages.doors[0], kind: "product", priceText: "¥38,000 - ¥85,000 / 樘", config: { categoryKey: "entrance-door", series: "「万籁」重型天地轴入户系统", tag: "主理人年度代表作", area: "浙江·莫干山私家山庄", detailHero: runtimeImages.doors[0], woodMaterial: "60mm 北美特级黑胡桃整板 + 航空蜂窝铝芯", hardware: "德国 dormakaba 重型地弹簧 + 自主定制实心锻铜一体式长执手", spaceType: "独栋别墅建筑主入口 / 挑高大厅玄关", keywords: ["厚重大气", "隐式天地轴", "隔音 42dB", "抗暴防撬"], details: { background: "项目位于浙北山间独栋庄园,常年多雨潮湿,且冬季山风冷峻。业主期望一扇既有古典厚重仪式感,又能抵御风雨、长久耐候的当代东方大门。", designConcept: "提炼江南屋檐与青砖比例。以暗调冷锻手工铜板包裹耐候钢核,内衬大厚度吸音绝热芯,门体内嵌隐藏式天地承重轴,推拉阻尼丝滑沉稳。", crafts: [ "无缝冷锻铜边框,经自然氧化着色", "双道三元乙丙航天级发泡密封胶条,气密性达国标 8 级", "指纹识别模组隐于天然胡桃木纹理深处", ], materialsList: [ { name: "门扇主体", spec: "航空铝蜂窝 + 防暴钢板 + 黑胡桃" }, { name: "承重结构", spec: "不锈钢重型天地偏心轴(承重 600KG)" }, { name: "五金执手", spec: "实心黄铜拉丝防指纹覆膜" }, { name: "锁具系统", spec: "C 级多向防暴机械锁芯 + 隐匿式生物辨识" }, ], }, }, }, { name: "悬挑风琴式耐候双开院门", summary: "以柚木条与耐候钢构建视线遮蔽和透光的微妙平衡,适配长期日晒雨淋的私家庭院入口。", image: runtimeImages.doors[1], kind: "product", priceText: "¥42,000 - ¥98,000 / 樘", config: { categoryKey: "garden-door", series: "「虚实」透光私家庭院门", tag: "建筑级耐候工艺", area: "上海·佘山高尔夫别墅", detailHero: runtimeImages.doors[1], woodMaterial: "深浸缅甸柚木条格栅 + 氟碳喷涂耐候钢", hardware: "意大利全隐形地埋式液压自闭器 + 静音电控锁", spaceType: "私家庭院入口 / 围墙园林玄关", keywords: ["园林意境", "格栅光影", "耐候耐蚀", "智能对讲协同"], details: { background: "庭院门直面自然日晒雨淋,普通木门易开裂变形,普通铁艺门几年内斑驳锈蚀。本案要求长期免维护的高级自然质感。", designConcept: "利用竖向错落的柚木条构建视线遮蔽与透光的微妙平衡,内部向外望去如薄纱透竹。", crafts: [ "微隙热胀冷缩结构槽设计", "隐蔽式水路导流坡口", "院墙铰链锚栓深入混凝土柱芯 300mm", ], materialsList: [ { name: "户外木种", spec: "高油脂老料缅甸柚木,经过 180 天自然风干" }, { name: "骨架型材", spec: "4mm 高强度航空铝镁合金" }, { name: "智能五金", spec: "隐藏式地下闭门轴,支持远程授权" }, ], }, }, }, { name: "通顶极窄边框实木室内门", summary: "以 2.8m - 3.2m 满高通顶系统维持私宅空间的建筑平直感,并与木作一体深化。", image: runtimeImages.doors[2], kind: "product", priceText: "¥7,800 - ¥16,000 / 樘", config: { categoryKey: "interior-door", series: "「空灵」2.8m - 3.2m 满高通顶系统", tag: "极简建筑平直感", area: "江苏·苏州金鸡湖独栋", detailHero: runtimeImages.doors[2], woodMaterial: "天然白栓木拉丝烟熏木饰面 + 磁吸阻尼降噪", hardware: "意大利 AGB 磁吸静音门锁 + 隐藏式暗铰链", spaceType: "别墅主卧套房 / 私人藏书阁 / 视听室", keywords: ["满高通顶", "磁吸静音", "极窄边框", "与木作同色"], details: { background: "室内多道门如果尺寸矮小杂乱,会切割私宅的建筑开阔感。业主希望主卧区实现门与护墙板毫无色差、绝对平齐。", designConcept: "门扇高 3.1 米一通到顶,无传统上门套与压边;内嵌双向碳纤维抗弯龙骨。", crafts: [ "门框与墙体批荡层融为一体的无框反装工艺", "磁力吸舌落锁轻无声息", "同批原木切片保证纹理与护墙板连贯", ], materialsList: [ { name: "抗弯核心", spec: "双组份碳纤维预应力防变形拉力杆" }, { name: "吸音内衬", spec: "德国均质空心桥洞力学板" }, { name: "隐形铰链", spec: "德国 KRONA 三维可调隐形铰链" }, ], }, }, }, { name: "石材及皮质背景墙一体门", summary: "将门体与背景墙材料、纹理和收口一体深化,保留私宅完整的墙面秩序。", image: "/media/seed/doors-stone-wall.jpg", kind: "product", priceText: "¥18,000 - ¥36,000 / 樘", config: { categoryKey: "stealth-door", series: "「无垠」密室及背景墙融合门", tag: "精密收口工程", area: "广东·深圳香蜜湖一号", detailHero: "/media/seed/doors-stone-wall.jpg", woodMaterial: "3mm 超薄大理石复合蜂窝板 / 进口鞍革手工双缝线", hardware: "感应式电动自开闭装置或碰珠反弹器", spaceType: "雪茄室 / 私人金库 / 地下酒窖 / 视听隐藏储物区", keywords: ["视线隐形", "超薄岩板", "毫厘对缝", "无门把设计"], details: { background: "客厅背景墙长达 9 米,中间有一道通往主人密闭酒窖的通道,突兀开门会破坏整面奢石的连贯韵律。", designConcept: "将奢石切割对纹复合于高刚性合金门扇表面,缝隙控制在 1.5mm 以内。", crafts: [ "石材水刀无应力薄切与航空蜂窝背栓复合", "脚踏地砖预埋重力复位转轴", "支持指纹电控联动隐藏灯带", ], materialsList: [ { name: "表面饰材", spec: "意大利雪山银狐超薄天然大理石" }, { name: "驱动系统", spec: "低噪步进电机伺服闭门器" }, ], }, }, }, ], trustContent: [ { type: "credential", title: "主理人的门作观", content: "国家注册高级室内建筑师,专注高定大门及私宅空间门类系统研发 14 年。拒绝建材量产拼装,以门与空间同构的建筑理念,亲自主理选材、构造深化与落地试装。", config: { stats: [ { value: "14年", label: "高端门系深化经验", sub: "历经百项严苛私宅考验" }, { value: "260+", label: "落地庄园实景案例", sub: "全实景图库,可预约探访" }, { value: "100%", label: "主理人全案跟进", sub: "量房 / 出图 / 选料 / 试装" }, { value: "10年", label: "结构主轴质保承诺", sub: "终生五金润滑维保机制" }, ], pillars: [ { icon: "tree", title: "天然厚板与古铜锻打", desc: "精选 300 年北美黑胡桃、缅甸柚木直拼大板,搭配手工冷锻紫铜及意大利防爆钢核。", }, { icon: "ruler", title: "微米级红外高精量房", desc: "德国进口 3D 空间激光扫描,精准捕捉门洞沉降公差与建筑墙体垂直度。", }, { icon: "shield", title: "隐匿式重型五金系统", desc: "自主研发三维可调静音承重铰链,单扇承载 450kg,开合轻盈安静。", }, ], serviceFlow: [ { step: "01", name: "私享沟通", desc: "厘清生活动线与风候环境" }, { step: "02", name: "上门实测", desc: "复核门洞公差与地平基准" }, { step: "03", name: "构造出图", desc: "输出结构图与材质节点方案" }, { step: "04", name: "实样工坊确认", desc: "确认木样、锻铜样与密封节点" }, { step: "05", name: "工坊试装交付", desc: "试装调试后专车直运现场" }, { step: "06", name: "终生私属维护", desc: "建立一门一档数字化档案" }, ], }, }, { type: "case", title: "别墅门系统案例", content: "围绕入户、庭院和室内空间建立完整门系统。", }, { type: "process", title: "从测量到交付", content: "现场测量、方案沟通、深化确认和落地交付。", }, ], inquiryForm: { name: "门系统方案咨询", fieldsSnapshot: [ { key: "doorType", label: "期望定制的门类型", type: "select", required: true, options: [ { label: "入户大门(防暴铸铜 / 实木)", value: "entry" }, { label: "庭院围墙门(耐候格栅 / 对开)", value: "yard" }, { label: "全屋室内门系统(通顶隐形)", value: "interior" }, { label: "背景墙一体门 / 密室门", value: "wall" }, { label: "整栋别墅门系统全案一体化", value: "whole-home" }, ], }, { key: "cityArea", label: "房屋 / 别墅所在城市与楼盘", type: "text", required: true }, { key: "projectStage", label: "当前项目阶段", type: "radio", required: true, options: [ { label: "土建结构阶段(适合预埋加固)", value: "structure" }, { label: "水电木工阶段(适合精确测距)", value: "rough-in" }, { label: "硬装收尾阶段", value: "finishing" }, { label: "旧宅门体翻新改造", value: "renovation" }, ], }, { key: "budgetRange", label: "预估门系统投资预算", type: "select", required: false, options: [ { label: "5 万 - 10 万", value: "50k-100k" }, { label: "10 万 - 20 万", value: "100k-200k" }, { label: "20 万 - 50 万(全宅全案)", value: "200k-500k" }, { label: "50 万以上(顶级孤品定制)", value: "500k-plus" }, ], }, { key: "needMeasure", label: "是否需要主理人上门现场量房", type: "radio", required: true, options: [ { label: "需要(预约排期现场勘测)", value: "yes" }, { label: "暂不需要(先发图纸在线深化评估)", value: "no" }, ], }, { key: "contactName", label: "贵姓称谓", type: "text", required: true }, { key: "contactPhone", label: "联系手机号(微信同号)", type: "tel", required: true }, { key: "specialNote", label: "空间想法或特殊需求描述", type: "textarea", required: false }, ], }, }, }; async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTemplate): Promise { // 这里只初始化明确的开发演示品牌;业务内容统一来自视觉包 sampleContent, // 新增生产模板无需添加 seed 分支,品牌样例内容仍须由管理员显式导入。 const installation = await prisma.brandTemplateInstallation.findFirst({ where: { brandId }, include: { templatePackageVersion: true }, }); const manifest = installation?.templatePackageVersion?.manifestSnapshot as unknown as TemplatePackageManifest | undefined; const packageSample = manifest?.sampleContent?.[template.templateKey]; if ( !installation?.templatePackageVersion || manifest?.visualTemplateKey !== template.visualTemplateKey || manifest.packageKey !== template.visualTemplateKey || !packageSample ) throw new Error( `Development package sample is missing for ${template.visualTemplateKey}/${template.templateKey}`, ); const offerings = packageSample.offerings.map((item) => ({ name: item.name, summary: item.summary, image: item.coverUrl ?? "", kind: item.kind as OfferingKind, priceText: item.priceText, priceAmount: item.priceAmount, config: { categoryKey: item.categoryKey, ...(item.config ?? {}) }, })); const trustContent = packageSample.trustContent; const inquiryFields = packageSample.fields; const inquiryFormName = packageSample.inquiryFormName; const seedBrandConfig = { ...(packageSample.brandConfig ?? {}), ...template.brandConfig, }; if (!inquiryFields?.length || !inquiryFormName) throw new Error("Development inquiry fixture is missing"); const existingBrand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId } }); const existingConfig = existingBrand.config && typeof existingBrand.config === "object" && !Array.isArray(existingBrand.config) ? (existingBrand.config as Record) : {}; await prisma.brandProfile.update({ where: { id: brandId }, data: { config: { ...existingConfig, ...seedBrandConfig } as Prisma.InputJsonValue, ...(existingBrand.slug === "default-brand" && !existingBrand.avatarUrl ? { avatarUrl: "/assets/owner/portrait.jpg" } : {}), }, }); for (const [sortOrder, item] of offerings.entries()) { const offering = await prisma.offering.findUnique({ where: { brandId_name: { brandId, name: item.name } }, }); const data = { kind: item.kind, coverUrl: item.image, summary: item.summary, priceText: item.priceText ?? "沟通报价", ...(item.priceAmount === undefined ? {} : { priceAmount: item.priceAmount }), sortOrder: sortOrder + 1, isEnabled: true, config: { ...item.config, media: [{ url: item.image, alt: item.name, type: "image" }], sections: [], }, }; if (offering) await prisma.offering.update({ where: { id: offering.id }, data }); else await prisma.offering.create({ data: { brandId, name: item.name, ...data } }); } if (template.retiredOfferingNames?.length) { await prisma.offering.updateMany({ where: { brandId, name: { in: template.retiredOfferingNames } }, data: { isEnabled: false }, }); } // 旧模板迁移后可能留下数组形态的 config 或失效媒体引用。开发种子只修复结构, // 不删除品牌内容,也不擅自重新启用已停用的业务提供项。 const allOfferings = await prisma.offering.findMany({ where: { brandId } }); const fallbackImage = offerings[0]?.image; if (!fallbackImage) throw new Error("Development fixture has no offering image"); for (const offering of allOfferings) { const rawConfig = offering.config; const config = rawConfig && typeof rawConfig === "object" && !Array.isArray(rawConfig) ? (rawConfig as Record) : {}; const media = config.media; const hasValidMedia = Array.isArray(media) && media.length > 0 && media.every( (entry) => entry && typeof entry === "object" && !Array.isArray(entry) && seedMediaExists((entry as Record).url), ); const hasValidCover = seedMediaExists(offering.coverUrl); const coverUrl = hasValidCover ? (offering.coverUrl as string) : fallbackImage; if (hasValidCover && hasValidMedia && !Array.isArray(rawConfig)) continue; await prisma.offering.update({ where: { id: offering.id }, data: { coverUrl, config: { ...config, ...(config.categoryKey === undefined ? { categoryKey: "custom" } : {}), ...(Array.isArray(config.keywords) ? {} : { keywords: [] }), media: [{ url: coverUrl, alt: offering.name, type: "image" }], ...(Array.isArray(config.sections) ? {} : { sections: [] }), } as Prisma.InputJsonValue, }, }); } for (const [sortOrder, item] of trustContent.entries()) { const existing = await prisma.trustContent.findFirst({ where: { brandId, type: item.type, title: item.title }, orderBy: [{ isPublished: "desc" }, { sortOrder: "asc" }], }); const { config, ...fields } = item; const data = { ...fields, brandId, sortOrder, isPublished: true, ...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }), }; if (existing) await prisma.trustContent.update({ where: { id: existing.id }, data }); else await prisma.trustContent.create({ data }); } const existingForm = await prisma.inquiryForm.findFirst({ where: { brandId, targetType: "brand" }, orderBy: { createdAt: "asc" }, }); const formData = { name: inquiryFormName, purpose: "inquiry", targetType: "brand", submissionAction: "create-inquiry", fieldsSnapshot: inquiryFields as Prisma.InputJsonValue, isEnabled: true, } as const; if (existingForm) await prisma.inquiryForm.update({ where: { id: existingForm.id }, data: formData }); else await prisma.inquiryForm.create({ data: { brandId, ...formData } }); } async function ensureSeedRelease(brandId: string, actorId: string): Promise { if (await prisma.brandRelease.findFirst({ where: { brandId } })) return; const snapshot = await buildBrandReleaseSnapshot(prisma, brandId); await prisma.brandRelease.create({ data: { brandId, version: 1, status: "published", snapshot: snapshot as unknown as Prisma.InputJsonValue, actorId, note: "seed 基线发布版本", }, }); } /** * 行业的模板台账只能有一个,且必须与品牌身份(BrandProfile.templateKey)一致。 * seed 之前只写品牌身份、不建台账,导致后台「尚未安装模板」而公开运行时已在跑该模板; * 这里按品牌身份补齐台账,让「版本与升级」「回滚」有据可依。 */ async function ensureTemplateInstallation(brandId: string): Promise { const brand = await prisma.brandProfile.findUniqueOrThrow({ where: { id: brandId }, select: { templateKey: true }, }); const template = runtimeSeedTemplates[brand.templateKey as keyof typeof runtimeSeedTemplates]; if (!template) throw new Error("Development brand has no explicit template fixture"); const visualKey = template.visualTemplateKey; const existing = await prisma.brandTemplateInstallation.findUnique({ where: { brandId }, include: { templatePackageVersion: true }, }); if (existing) { if ( existing.templateKey !== template.templateKey || !existing.templatePackageVersionId || !existing.templatePackageVersion ) throw new Error("Development brand installation does not satisfy the template contract"); return; } // 版本升级必须按 SemVer 判断最新版,导入时间只用于同版本排序。 const packageVersion = latestTemplateVersion( await prisma.templatePackageVersion.findMany({ where: { packageKey: visualKey, status: "published" }, }), ); if (!packageVersion) throw new Error(`Development brand requires a published package version: ${visualKey}`); const configSnapshot = packageVersion.manifestSnapshot as Prisma.InputJsonValue; await prisma.brandTemplateInstallation.create({ data: { brandId, templateKey: template.templateKey, templateVersion: packageVersion.version, templatePackageVersionId: packageVersion.id, contentChecksum: packageVersion.contentChecksum, configSnapshot, }, }); } async function main(): Promise { const brand = await prisma.brandProfile.upsert({ where: { id: "00000000-0000-0000-0000-000000000001" }, update: { slug: "default-brand", name: "阿成家常菜", templateKey: "food", tagline: "现做家常套餐,也为小型聚餐定制一桌热饭菜", description: "每天认真做好一顿家常饭。", hours: "周一至周六 10:30-20:00", address: "大学城生活区东门附近", deliveryNote: "目前支持部分学生宿舍楼配送,无法送达时会主动联系。", }, create: { slug: "default-brand", id: "00000000-0000-0000-0000-000000000001", name: "阿成家常菜", templateKey: "food", tagline: "现做家常套餐,也为小型聚餐定制一桌热饭菜", description: "每天认真做好一顿家常饭。", hours: "周一至周六 10:30-20:00", address: "大学城生活区东门附近", deliveryNote: "目前支持部分学生宿舍楼配送,无法送达时会主动联系。", }, }); await ensureTemplateInstallation(brand.id); await ensureRuntimeContent(brand.id, runtimeSeedTemplates.food); for (const name of ["普通套餐", "私厨", "配送", "自取", "熟客", "重点跟进"]) { await prisma.tag.upsert({ where: { brandId_name: { brandId: brand.id, name } }, update: {}, create: { brandId: brand.id, name, isPreset: true }, }); } const admin = await prisma.adminUser.upsert({ where: { username: "admin" }, update: { platformTemplateRole: "template_admin" }, create: { username: "admin", passwordHash: await bcrypt.hash(process.env.SEED_ADMIN_PASSWORD ?? "change-me-now-123", 12), displayName: "品牌管理员", platformTemplateRole: "template_admin", mustChangePassword: true, }, }); await prisma.brandMembership.upsert({ where: { adminUserId_brandId: { adminUserId: admin.id, brandId: brand.id } }, update: { isEnabled: true, role: "owner" }, create: { adminUserId: admin.id, brandId: brand.id, role: "owner" }, }); const doorsBrand = await prisma.brandProfile.upsert({ where: { id: "00000000-0000-0000-0000-000000000002" }, update: { slug: "linjing-doors", name: "林境门作", templateKey: "doors", tagline: "为别墅空间定制有秩序感的门系统", description: "从入户大门到室内户内门,提供完整的门系统设计与落地服务。", hours: "周一至周六 09:00-18:00", address: "城市设计中心 3F", contactPhone: "13800000000", contactWechat: "linjing-doors", }, create: { id: "00000000-0000-0000-0000-000000000002", slug: "linjing-doors", name: "林境门作", templateKey: "doors", tagline: "为别墅空间定制有秩序感的门系统", description: "从入户大门到室内户内门,提供完整的门系统设计与落地服务。", hours: "周一至周六 09:00-18:00", address: "城市设计中心 3F", contactPhone: "13800000000", contactWechat: "linjing-doors", }, }); await prisma.brandMembership.upsert({ where: { adminUserId_brandId: { adminUserId: admin.id, brandId: doorsBrand.id } }, update: { isEnabled: true, role: "owner" }, create: { adminUserId: admin.id, brandId: doorsBrand.id, role: "owner" }, }); await ensureTemplateInstallation(doorsBrand.id); await ensureRuntimeContent(doorsBrand.id, runtimeSeedTemplates.doors); await ensureSeedRelease(brand.id, admin.id); await ensureSeedRelease(doorsBrand.id, admin.id); } main().finally(() => prisma.$disconnect());