diff --git a/.codex-tasks/template-content-coverage/PROGRESS.md b/.codex-tasks/template-content-coverage/PROGRESS.md new file mode 100644 index 0000000..d2ef96d --- /dev/null +++ b/.codex-tasks/template-content-coverage/PROGRESS.md @@ -0,0 +1,55 @@ +# Progress Log + +## Session Start + +- **Date**: 2026-09-28 +- **Task name**: `template-content-coverage` +- **Task dir**: `.codex-tasks/template-content-coverage/` +- **Spec**: `SPEC.md` +- **Plan**: `TODO.csv` (4 milestones) +- **Environment**: TypeScript / React / NestJS / Node test + +## Context Recovery Block + +- **Current milestone**: #4 — Run delivery gates and review +- **Current status**: DONE +- **Last completed**: #4 — Run delivery gates and review +- **Current artifact**: `TODO.csv` +- **Key context**: Previous task made many fields editable but omitted shared detail/success/records presentation fields and Acheng offering details. Existing changes are uncommitted and must be preserved. +- **Known issues**: Publication snapshot tests passed previously, but did not prove complete field coverage. +- **Next action**: User performs manual Admin edit, save, publish, and miniapp visual acceptance for both brands. + +## Milestone 1: Inventory rendered brand and offering fields + +- **Status**: DONE +- **What was done**: Mapped presentation and offering fields from both template WXML trees and shared detail, success, records, and inquiry pages. +- **Validation**: `rg -n 'presentation\.|item\.' packages/template-*/miniapp apps/miniapp/components/modules` → exit 0. + +## Milestone 2: Complete template editing declarations + +- **Status**: DONE +- **What was done**: Added missing brand presentation groups, per-offering food details, detail images, and nontechnical Admin labels; removed unsupported default contact and privacy claims. +- **Validation**: `pnpm validate:templates` → exit 0. + +## Milestone 3: Add comprehensive coverage regression tests + +- **Status**: DONE +- **What was done**: Added a package-discovered test that traverses page component references and verifies page presentation, hero, profile, trust, and shared offering detail bindings. Corrected one false positive from nested offering presentation access. +- **Validation**: `pnpm --filter @personal-brand/template-contract test` → 6 tests passed. + +## Milestone 4: Run delivery gates and review + +- **Status**: DONE +- **What was done**: Extended the isolated API publication test to cover success text, detail promise, and detail image; removed unsupported fallback promises; verified template compiler and fixture output; restarted the local API process so Admin sees the new manifest. +- **Validation**: API integration 38/38, `pnpm template:check`, `pnpm typecheck`, `pnpm lint`, Admin production build, `pnpm format:check`, and `git diff --check` → exit 0. +- **Known warning**: Admin's existing >500 kB vendor chunk warning remains. Owner: Admin frontend; follow-up: evaluate bundle splitting separately. + +## Final Summary + +- **Total milestones**: 4 +- **Completed**: 4 +- **Failed + recovered**: 1 test extraction false positive, corrected before delivery. +- **External unblock events**: 0 +- **Total retries**: 1 +- **Key learnings**: Renderer consumption, Admin edit declarations, and release snapshots must be verified as one contract. +- **Recommendations for future tasks**: Include the package-discovered editability test whenever a template adds a page or content field. diff --git a/.codex-tasks/template-content-coverage/SPEC.md b/.codex-tasks/template-content-coverage/SPEC.md new file mode 100644 index 0000000..94480e9 --- /dev/null +++ b/.codex-tasks/template-content-coverage/SPEC.md @@ -0,0 +1,48 @@ +# Task Specification + +## Task Shape + +- **Shape**: `single-full` + +## Goals + +- Ensure the Acheng and Linjing miniapp templates expose their displayed brand and offering content through ordinary Admin controls. +- Prevent future partial coverage by testing template render bindings against manifest editing declarations. + +## Non-Goals + +- Make structural UI labels, backend status codes, or WeChat system controls brand-editable. +- Add industry fields to the shared brand database model. + +## Constraints + +- Preserve existing uncommitted work and template visual structure. +- Changes to published miniapps require an explicit release. +- Template declarations, not template-key branches in Admin, define editing controls. + +## Environment + +- **Project root**: `/home/que01/Project/persionalBrand` +- **Language/runtime**: TypeScript, React, NestJS, WeChat miniapp JavaScript +- **Package manager**: pnpm +- **Test framework**: Node test and API integration tests +- **Build command**: `pnpm build` + +## Deliverables + +- Complete editable declarations for both templates' displayed presentation and offering details. +- Coverage tests tying rendered content to Admin bindings. +- Verified template catalog, API publication tests, type checks and production Admin build. + +## Done-When + +- [ ] Each displayed template presentation field is declared in the corresponding Admin form. +- [ ] Each material offering detail shown by either template is editable. +- [ ] No factual service promise is left solely as a fixed template string. +- [ ] Relevant automated checks pass. + +## Final Validation Command + +```bash +pnpm format:check && pnpm lint && pnpm typecheck && pnpm template:check && pnpm --filter @personal-brand/admin build +``` diff --git a/.codex-tasks/template-content-coverage/TODO.csv b/.codex-tasks/template-content-coverage/TODO.csv new file mode 100644 index 0000000..591a9ce --- /dev/null +++ b/.codex-tasks/template-content-coverage/TODO.csv @@ -0,0 +1,5 @@ +id,task,status,acceptance_criteria,validation_command,completed_at,retry_count,notes +1,Inventory rendered brand and offering fields,DONE,Two template field matrices complete,rg -n 'presentation\.|item\.' packages/template-*/miniapp apps/miniapp/components/modules,2026-09-28,0,Shared detail success records pages and both template components mapped +2,Complete template editing declarations,DONE,Admin exposes displayed brand and offering content,pnpm validate:templates,2026-09-28,0,Both manifests extended and catalog regenerated +3,Add comprehensive coverage regression tests,DONE,Rendered fields map to manifest bindings,pnpm --filter @personal-brand/template-contract test,2026-09-28,1,Test initially misclassified offering presentation then fixed; both templates pass +4,Run delivery gates and review,DONE,Relevant checks pass and diff is coherent,pnpm format:check,2026-09-28,0,API integration 38 tests template checks lint typecheck Admin build format and diff check passed; API restarted diff --git a/.codex-tasks/template-editability/PROGRESS.md b/.codex-tasks/template-editability/PROGRESS.md new file mode 100644 index 0000000..4798021 --- /dev/null +++ b/.codex-tasks/template-editability/PROGRESS.md @@ -0,0 +1,63 @@ +# Progress Log + +## Session Start + +- **Date**: 2026-09-28 +- **Task name**: `template-editability` +- **Task dir**: `.codex-tasks/template-editability/` +- **Spec**: `SPEC.md` +- **Plan**: `TODO.csv` (5 milestones) +- **Environment**: TypeScript / React / NestJS / Node test + +## Context Recovery Block + +- **Current milestone**: #5 — Run delivery checks and review diff +- **Current status**: DONE +- **Last completed**: #5 — Run delivery checks and review diff +- **Current artifact**: `TODO.csv` +- **Key context**: Acheng contains unsupported fixed food and response claims. Linjing consumes structured trust and profile configuration that normal administrators cannot edit; offering details also lack form controls. +- **Known issues**: Published workspace reads release snapshots, so save and publish must be tested separately. +- **Next action**: Ask the user to inspect editability and visual results in Admin and both compiled miniapp templates; this is acceptance, not an unimplemented code step. + +## Milestone 2: Add manifest-driven structured editors + +- **Status**: DONE +- **What was done**: Added list field declarations and plain-language list controls for brand, trust, and offering content. +- **Validation**: `pnpm --filter @personal-brand/admin typecheck` → exit 0. + +## Milestone 3: Connect both template renderers and remove false claims + +- **Status**: DONE +- **What was done**: Added Linjing editing declarations and replaced Acheng unsupported business claims with editable content or omission. +- **Validation**: `pnpm validate:templates` → exit 0. + +## Milestone 4: Add regression coverage for edit and publish behavior + +- **Status**: DONE +- **What was done**: Added binding and manifest tests plus an API integration test that edits brand, trust, and offering fields and verifies snapshot publication. +- **Validation**: `pnpm --filter @personal-brand/api test:integration` → 38 tests passed. + +## Milestone 5: Run delivery checks and review diff + +- **Status**: DONE +- **What was done**: Reviewed field-to-editor mappings, scoped brand form fields to brand bindings, documented the structured editing rule in ADR 0016, and confirmed the running Admin and API respond. +- **Validation**: `pnpm format:check`, `pnpm lint`, `pnpm typecheck`, `pnpm template:check`, `pnpm --filter @personal-brand/admin build`, `git diff --check` → exit 0. +- **Known warning**: The Admin production bundle still reports a pre-existing >500 kB chunk warning. Owner: Admin frontend; follow-up: evaluate route-level/vendor chunk splitting separately from template content editing. + +## Final Summary + +- **Total milestones**: 5 +- **Completed**: 5 +- **Failed + recovered**: 1 compiler assertion updated for the generic startup title; 1 lint and 2 formatting issues fixed. +- **External unblock events**: 0 +- **Total retries**: 3 +- **Key learnings**: A template-rendered field is not truly configurable until the ordinary Admin form can edit it and a release test proves the public snapshot changes only after publication. +- **Recommendations for future tasks**: Require every new template to document its rendered business facts and matching editor bindings during template validation. + +## Milestone 1: Audit source-to-editor coverage + +- **Status**: DONE +- **What was done**: Traced both template renderers to published workspace, admin forms, and template declarations. +- **Key decisions**: Preserve the existing snapshot contract; use template-declared plain-language editing fields instead of exposing JSON. +- **Validation**: `rg -n 'profilePresentation|trustPresentation|今日有售' packages apps` → exit 0. +- **Next step**: Milestone 2 — Add manifest-driven structured editors. diff --git a/.codex-tasks/template-editability/SPEC.md b/.codex-tasks/template-editability/SPEC.md new file mode 100644 index 0000000..345eff4 --- /dev/null +++ b/.codex-tasks/template-editability/SPEC.md @@ -0,0 +1,47 @@ +# Task Specification + +## Task Shape + +- **Shape**: `single-full` + +## Goals + +- Make material business facts shown by the Linjing and Acheng miniapp templates editable by a brand administrator, or remove unsupported claims. +- Preserve template-owned visual design while keeping content brand-scoped and release-snapshot based. + +## Non-Goals + +- Inventory, payment, or real-time opening-state management. +- New database tables or template-specific fields in the shared brand model. + +## Constraints + +- Template manifests declare template-specific editable content. +- Admin UI uses plain-language controls, never asks users to edit JSON. +- Published miniapp content changes only after a new release. + +## Environment + +- **Project root**: `/home/que01/Project/persionalBrand` +- **Language/runtime**: TypeScript, React, NestJS, WeChat miniapp JavaScript +- **Package manager**: pnpm +- **Test framework**: Node test, API integration tests +- **Build command**: `pnpm build` + +## Deliverables + +- Template declarations and admin editing controls for material content. +- Miniapp rendering without unsupported hard-coded factual claims. +- Contract, runtime, and integration regression tests. + +## Done-When + +- [ ] Both templates expose all material displayed facts through admin content controls or omit them. +- [ ] Published workspace consumes the edited snapshot and does not change before publication. +- [ ] Relevant tests, type checks, template validation, formatting, and build pass. + +## Final Validation Command + +```bash +pnpm format:check && pnpm lint && pnpm typecheck && pnpm template:check && pnpm --filter @personal-brand/admin build +``` diff --git a/.codex-tasks/template-editability/TODO.csv b/.codex-tasks/template-editability/TODO.csv new file mode 100644 index 0000000..c4bb244 --- /dev/null +++ b/.codex-tasks/template-editability/TODO.csv @@ -0,0 +1,6 @@ +id,task,status,acceptance_criteria,validation_command,completed_at,retry_count,notes +1,Audit source-to-editor coverage,DONE,Map material displayed fields and unsupported claims,rg -n 'profilePresentation|trustPresentation|今日有售' packages apps,2026-09-28,0,Acheng claims and Linjing structured content identified +2,Add manifest-driven structured editors,DONE,Brand and trust lists editable without JSON,pnpm --filter @personal-brand/admin typecheck,2026-09-28,0,Typecheck passed after api-client build +3,Connect both template renderers and remove false claims,DONE,Displayed facts come from published data or are omitted,pnpm validate:templates,2026-09-28,0,Template validation passed after catalog generation +4,Add regression coverage for edit and publish behavior,DONE,Contract and integration tests pass,pnpm --filter @personal-brand/api test:integration,2026-09-28,0,38 API integration tests passed +5,Run delivery checks and review diff,DONE,Checks pass and no unmapped material claims remain,pnpm format:check,2026-09-28,0,Format lint typecheck template checks admin build and diff check passed; manual miniapp visual acceptance pending user diff --git a/apps/admin/src/components/TemplateListField.tsx b/apps/admin/src/components/TemplateListField.tsx new file mode 100644 index 0000000..1d4ec09 --- /dev/null +++ b/apps/admin/src/components/TemplateListField.tsx @@ -0,0 +1,41 @@ +import { Button, Form, Input, Space } from "antd"; +import type { TemplateAdminField } from "@personal-brand/api-client"; + +export function TemplateListField({ + field, + name, +}: { + field: TemplateAdminField; + name: string | (string | number)[]; +}) { + return ( + + + {(rows, { add, remove }) => ( + + {rows.map((row, index) => ( + + {field.itemFields?.map((itemField) => ( + + {itemField.input === "textarea" ? : } + + ))} + + + ))} + + + )} + + + ); +} diff --git a/apps/admin/src/features/brand/PresentationEditor.tsx b/apps/admin/src/features/brand/PresentationEditor.tsx index b71caf9..0fed01b 100644 --- a/apps/admin/src/features/brand/PresentationEditor.tsx +++ b/apps/admin/src/features/brand/PresentationEditor.tsx @@ -16,6 +16,7 @@ import { useEffect, useMemo } from "react"; import type { AdminTemplateContent, TemplateAdminField } from "@personal-brand/api-client"; import { createApiClient } from "../../lib/api.js"; import { ImageUrlField } from "../../components/ImageUrlField.js"; +import { TemplateListField } from "../../components/TemplateListField.js"; import { MutationError } from "../../components/QueryState.js"; import { applyPresentationValues, @@ -62,7 +63,16 @@ export function PresentationEditor({ }: PresentationEditorProps) { const [form] = Form.useForm(); const queryClient = useQueryClient(); - const sections = templateContent?.admin.sections ?? []; + const sections = useMemo( + () => + (templateContent?.admin.sections ?? []) + .map((section) => ({ + ...section, + fields: section.fields.filter((field) => field.binding.startsWith("brand.config.")), + })) + .filter((section) => section.fields.length > 0), + [templateContent], + ); const initialValues = useMemo(() => { const values: PresentationValues = {}; for (const section of sections) { @@ -70,6 +80,7 @@ export function PresentationEditor({ values[presentationFieldName(section.key, field.key)] = readPresentationValue( config, field.binding, + field, ); } } @@ -82,7 +93,7 @@ export function PresentationEditor({ return createApiClient().updateAdminBrand({ config: nextConfig }); }, onSuccess: () => { - message.success("页面内容已保存,小程序将使用最新内容"); + message.success("页面内容已保存为草稿,发布后小程序才会更新"); void queryClient.invalidateQueries({ queryKey: ["admin-brand"] }); void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }); void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] }); @@ -125,17 +136,28 @@ export function PresentationEditor({ {section.description} {section.fields.map((field) => ( - - - {renderField(field)} - + + {field.input === "list" ? ( + + ) : ( + + {renderField(field)} + + )} ))} diff --git a/apps/admin/src/features/brand/presentation-bindings.ts b/apps/admin/src/features/brand/presentation-bindings.ts index f3560d9..2b4394c 100644 --- a/apps/admin/src/features/brand/presentation-bindings.ts +++ b/apps/admin/src/features/brand/presentation-bindings.ts @@ -1,6 +1,8 @@ export type PresentationField = { key: string; binding: string; + input?: string; + itemValueKey?: string; }; export type PresentationSection = { @@ -8,7 +10,7 @@ export type PresentationSection = { fields: PresentationField[]; }; -export type PresentationValues = Record; +export type PresentationValues = Record; function asObject(value: unknown): Record { return value && typeof value === "object" && !Array.isArray(value) @@ -17,8 +19,11 @@ function asObject(value: unknown): Record { } function safePath(binding: string): string[] | null { - if (!binding.startsWith("brand.config.")) return null; - const path = binding.slice("brand.config.".length).split("."); + const prefix = ["brand.config.", "offering.config.", "trust.config."].find((candidate) => + binding.startsWith(candidate), + ); + if (!prefix) return null; + const path = binding.slice(prefix.length).split("."); if (path.some((part) => !part || ["__proto__", "prototype", "constructor"].includes(part))) return null; return path; @@ -31,18 +36,25 @@ export function presentationFieldName(sectionKey: string, fieldKey: string): str export function readPresentationValue( config: Record | null | undefined, binding: string, -): string | number | undefined { + field?: PresentationField, +): unknown { const path = safePath(binding); if (!path) return undefined; let value: unknown = asObject(config); for (const part of path) value = asObject(value)[part]; + if (field?.input === "list") { + if (!Array.isArray(value)) return []; + return field.itemValueKey + ? (value as unknown[]).map((item) => ({ [field.itemValueKey as string]: item })) + : value; + } return typeof value === "string" || typeof value === "number" ? value : undefined; } function writePath( source: Record, path: string[], - value: string | number | null | undefined, + value: unknown, ): Record { const [head, ...tail] = path; if (!head) return source; @@ -63,11 +75,16 @@ export function applyPresentationValues( for (const field of section.fields) { const path = safePath(field.binding); if (!path) continue; - nextConfig = writePath( - nextConfig, - path, - values[presentationFieldName(section.key, field.key)], - ); + const raw = values[presentationFieldName(section.key, field.key)]; + const value = + field.input === "list" && Array.isArray(raw) + ? field.itemValueKey + ? raw + .map((item) => asObject(item)[field.itemValueKey as string]) + .filter((item) => typeof item === "string" && item.trim()) + : raw + : raw; + nextConfig = writePath(nextConfig, path, value); } } return nextConfig; diff --git a/apps/admin/src/features/services/ServicesPage.tsx b/apps/admin/src/features/services/ServicesPage.tsx index 03299d5..22f3c4a 100644 --- a/apps/admin/src/features/services/ServicesPage.tsx +++ b/apps/admin/src/features/services/ServicesPage.tsx @@ -13,11 +13,17 @@ import { message, } from "antd"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import type { Offering } from "@personal-brand/api-client"; +import type { Offering, TemplateAdminField } from "@personal-brand/api-client"; import { useState } from "react"; import { createApiClient } from "../../lib/api.js"; import { AdminPageHeader } from "../../components/AdminPageHeader.js"; import { ImageUrlField } from "../../components/ImageUrlField.js"; +import { TemplateListField } from "../../components/TemplateListField.js"; +import { + applyPresentationValues, + presentationFieldName, + readPresentationValue, +} from "../brand/presentation-bindings.js"; import { MutationError, QueryState } from "../../components/QueryState.js"; export function ServicesPage() { @@ -30,11 +36,32 @@ export function ServicesPage() { queryKey: ["admin-offerings"], queryFn: () => client.listAdminOfferings(), }); + const workspace = useQuery({ + queryKey: ["admin-workspace-offering-fields"], + queryFn: () => client.getAdminWorkspace(), + }); + const templateFields: TemplateAdminField[] = ( + workspace.data?.templateContent?.admin.sections ?? [] + ) + .filter((section) => section.target === "offering") + .flatMap((section) => + section.fields.filter((field) => field.binding.startsWith("offering.config.")), + ); const saveOffering = useMutation({ - mutationFn: (values: Record) => - editingOffering - ? client.updateAdminOffering(editingOffering.id, values) - : client.createAdminOffering(values as Omit), + mutationFn: (values: Record) => { + const fields = Object.fromEntries( + Object.entries(values).filter(([key]) => key !== "config" && !key.startsWith("offering:")), + ); + const config = applyPresentationValues( + editingOffering?.config, + [{ key: "offering", fields: templateFields }], + values, + ); + const body = { ...fields, config }; + return editingOffering + ? client.updateAdminOffering(editingOffering.id, body) + : client.createAdminOffering(body as Omit); + }, onSuccess: () => { message.success("业务提供项已保存"); setOfferingOpen(false); @@ -72,16 +99,33 @@ export function ServicesPage() { coverUrl: item.coverUrl ?? "", sortOrder: item.sortOrder, isEnabled: item.isEnabled, + ...Object.fromEntries( + templateFields.map((field) => [ + presentationFieldName("offering", field.key), + readPresentationValue(item.config, field.binding, field), + ]), + ), } - : { kind: "service", isEnabled: true, sortOrder: 0 }, + : { + kind: "service", + isEnabled: true, + sortOrder: 0, + ...Object.fromEntries( + templateFields.map((field) => [ + presentationFieldName("offering", field.key), + field.input === "list" ? [] : undefined, + ]), + ), + }, ); }; return ( { void offerings.refetch(); + void workspace.refetch(); }} > + {templateFields.map((field) => + field.input === "list" ? ( + + ) : ( + + {field.input === "textarea" ? ( + + ) : field.input === "image" ? ( + + ) : ( + + )} + + ), + )} diff --git a/apps/admin/src/features/trust-content/TrustContentPage.tsx b/apps/admin/src/features/trust-content/TrustContentPage.tsx index e7cddcd..c0800c5 100644 --- a/apps/admin/src/features/trust-content/TrustContentPage.tsx +++ b/apps/admin/src/features/trust-content/TrustContentPage.tsx @@ -14,11 +14,16 @@ import { message, } from "antd"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import type { TrustContent, TrustContentInput } from "@personal-brand/api-client"; +import type { + TemplateAdminField, + TrustContent, + TrustContentInput, +} from "@personal-brand/api-client"; import { useState } from "react"; import { createApiClient } from "../../lib/api.js"; import { AdminPageHeader } from "../../components/AdminPageHeader.js"; import { ImageUrlField } from "../../components/ImageUrlField.js"; +import { TemplateListField } from "../../components/TemplateListField.js"; import { MutationError, QueryState } from "../../components/QueryState.js"; const types = [ @@ -59,6 +64,7 @@ type TrustTypeOption = { help?: string; placeholder?: string; required?: boolean; + configFields?: TemplateAdminField[]; }; const fallbackTypes: TrustTypeOption[] = types.map(({ value, label, help }) => ({ type: value, @@ -86,7 +92,19 @@ export function TrustContentPage() { ? workspace.data.templateContent.trustContentTypes : fallbackTypes; const selectedTypeMeta = availableTypes.find((item) => item.type === selectedType); - const contentByType = new Map((query.data ?? []).map((item) => [item.type, item])); + const contentByType = new Map(); + for (const item of query.data ?? []) { + const current = contentByType.get(item.type); + const hasConfig = Object.keys(item.config ?? {}).length > 0; + const currentHasConfig = Object.keys(current?.config ?? {}).length > 0; + if ( + !current || + (item.isPublished && !current.isPublished) || + (item.isPublished === current.isPublished && hasConfig && !currentHasConfig) + ) { + contentByType.set(item.type, item); + } + } const firstMissingRequiredType = availableTypes.find((item) => item.required && !contentByType.has(item.type))?.type ?? availableTypes[0]?.type ?? @@ -121,10 +139,11 @@ export function TrustContentPage() { title: item.title, ...(item.summary ? { summary: item.summary } : {}), content: item.content, + config: item.config ?? {}, ...(item.coverUrl ? { coverUrl: item.coverUrl } : {}), isPublished: item.isPublished, } - : { type: type ?? firstMissingRequiredType, isPublished: false }, + : { type: type ?? firstMissingRequiredType, isPublished: false, config: {} }, ); }; return ( @@ -266,6 +285,21 @@ export function TrustContentPage() { placeholder={selectedTypeMeta?.placeholder ?? "例如:\n第一项内容\n第二项内容"} /> + {(!editing || contentByType.get(selectedType)?.id === editing.id) && + selectedTypeMeta?.configFields?.map((field) => + field.input === "list" ? ( + + ) : ( + + {field.input === "textarea" ? : } + + ), + )} { + const doorsBrand = await prisma.brandProfile.findUniqueOrThrow({ + where: { slug: "linjing-doors" }, + }); + const trust = await prisma.trustContent.findFirstOrThrow({ + where: { brandId: doorsBrand.id, type: "credential", isPublished: true }, + orderBy: { sortOrder: "asc" }, + }); + const offering = await prisma.offering.findFirstOrThrow({ + where: { brandId: doorsBrand.id, isEnabled: true }, + orderBy: { sortOrder: "asc" }, + }); + const adminUser = await prisma.adminUser.findUniqueOrThrow({ + where: { username: "admin" }, + select: { id: true }, + }); + const token = signIdentity({ subject: adminUser.id, brandId: doorsBrand.id, role: "admin" }); + const headers = { authorization: `Bearer ${token}` }; + const originalBrandConfig = doorsBrand.config; + const originalTrustConfig = trust.config; + const originalOfferingConfig = offering.config; + const before = JSON.parse((await request("/public/workspace?brandSlug=linjing-doors")).body); + const changedTitle = "集成测试定制首页标题"; + const changedArea = "集成测试项目地点"; + const changedIntro = "集成测试发布后联系说明"; + const changedHint = "集成测试咨询后处理说明"; + const changedDetailHero = "https://example.com/integration-detail.jpg"; + const changedStats = [{ value: "42", label: "测试成果" }]; + try { + const brandConfig = originalBrandConfig ?? {}; + const presentation = brandConfig.visualPresentation ?? {}; + const brandUpdate = await request("/admin/config/brand", { + method: "PATCH", + headers, + payload: { + config: { + homeHero: { ...brandConfig.homeHero, title: changedTitle }, + visualPresentation: { + ...presentation, + success: { ...presentation.success, intro: changedIntro }, + detail: { ...presentation.detail, inquiryHint: changedHint }, + }, + }, + }, + }); + assert.equal(brandUpdate.statusCode, 200); + const trustUpdate = await request(`/admin/config/trust-content/${trust.id}`, { + method: "PATCH", + headers, + payload: { config: { ...(trust.config ?? {}), stats: changedStats } }, + }); + assert.equal(trustUpdate.statusCode, 200); + const offeringUpdate = await request(`/admin/workspace/offerings/${offering.id}`, { + method: "PATCH", + headers, + payload: { + config: { + ...(offering.config ?? {}), + area: changedArea, + detailHero: changedDetailHero, + }, + }, + }); + assert.equal(offeringUpdate.statusCode, 200); + + const draftView = JSON.parse((await request("/public/workspace?brandSlug=linjing-doors")).body); + assert.deepEqual(draftView.brand.homeHero, before.brand.homeHero); + assert.equal( + draftView.brand.visualPresentation.success.intro, + before.brand.visualPresentation.success.intro, + ); + assert.equal( + draftView.brand.visualPresentation.detail.inquiryHint, + before.brand.visualPresentation.detail.inquiryHint, + ); + assert.deepEqual(draftView.trustPresentation.stats, before.trustPresentation.stats); + assert.equal(draftView.offerings[0].presentation.area, before.offerings[0].presentation.area); + assert.equal( + draftView.offerings[0].presentation.heroImage, + before.offerings[0].presentation.heroImage, + ); + + const publish = await request("/admin/releases/publish", { + method: "POST", + headers, + payload: { note: "集成测试模板内容编辑" }, + }); + assert.equal(publish.statusCode, 201); + const afterPublish = JSON.parse( + (await request("/public/workspace?brandSlug=linjing-doors")).body, + ); + assert.equal(afterPublish.brand.homeHero.title, changedTitle); + assert.equal(afterPublish.brand.visualPresentation.success.intro, changedIntro); + assert.equal(afterPublish.brand.visualPresentation.detail.inquiryHint, changedHint); + assert.deepEqual(afterPublish.trustPresentation.stats, changedStats); + assert.equal(afterPublish.offerings[0].presentation.area, changedArea); + assert.equal(afterPublish.offerings[0].presentation.heroImage, changedDetailHero); + } finally { + await prisma.brandProfile.update({ + where: { id: doorsBrand.id }, + data: { config: originalBrandConfig }, + }); + await prisma.trustContent.update({ + where: { id: trust.id }, + data: { config: originalTrustConfig }, + }); + await prisma.offering.update({ + where: { id: offering.id }, + data: { config: originalOfferingConfig }, + }); + const restored = await request("/admin/releases/publish", { + method: "POST", + headers, + payload: { note: "恢复集成测试模板基线" }, + }); + assert.equal(restored.statusCode, 201); + } +}); + test("admin can create and version an inquiry form", async () => { const login = await request("/admin/session/login", { method: "POST", diff --git a/apps/miniapp/components/modules/inquiry-form/inquiry-form.wxml b/apps/miniapp/components/modules/inquiry-form/inquiry-form.wxml index c2551d2..6094d8e 100644 --- a/apps/miniapp/components/modules/inquiry-form/inquiry-form.wxml +++ b/apps/miniapp/components/modules/inquiry-form/inquiry-form.wxml @@ -1 +1 @@ -{{item.label}}{{item.required ? ' *' : ''}}