Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d2ca528543 | ||
|
|
47a24e0d53 | ||
|
|
c78deafee3 | ||
|
|
3330b536dc | ||
|
|
07629a4596 | ||
|
|
5c6ad02f46 | ||
|
|
048c42207c | ||
|
|
67735afd45 | ||
|
|
0574a85632 | ||
|
|
18ddf125be | ||
|
|
bb0709b8cc | ||
|
|
076c6124c8 | ||
|
|
89fdfd7d83 | ||
|
|
f87b26b201 | ||
|
|
466dc66907 | ||
|
|
357f271639 | ||
|
|
f3adf7bc15 | ||
|
|
4512d2601d | ||
|
|
d0902d6568 | ||
|
|
7e1dd543fb | ||
|
|
3003e7801d | ||
|
|
567921e726 | ||
|
|
03f947e9b8 | ||
|
|
6ac2d9421b | ||
|
|
aa42e7b866 | ||
|
|
e09b56e0f3 | ||
|
|
84956b8fe2 | ||
|
|
f57c0ca0ea | ||
|
|
9c15a822e9 | ||
|
|
85f37d2eae | ||
|
|
222055595c | ||
|
|
b1d5c2b4b0 | ||
|
|
787a50369f | ||
|
|
422162e580 | ||
|
|
26bcb2b66e | ||
|
|
91322fa9a0 |
No files matched your search
@@ -0,0 +1,25 @@
|
||||
.agents
|
||||
.aws
|
||||
.claude
|
||||
.codex
|
||||
.codex-tasks
|
||||
.git
|
||||
.github
|
||||
.turbo
|
||||
.worktrees
|
||||
coverage
|
||||
dist
|
||||
pnpm-lock.yaml.bak
|
||||
docker-compose.override.yml
|
||||
docker-compose.prod.yml
|
||||
docs
|
||||
media
|
||||
node_modules
|
||||
prototype
|
||||
scripts/deploy/*.test.mjs
|
||||
.env
|
||||
.env.*
|
||||
!.env.production.example
|
||||
**/node_modules
|
||||
**/dist
|
||||
!apps/api/prisma/assets/**
|
||||
@@ -10,9 +10,10 @@ ADMIN_PORT=3000
|
||||
SESSION_SECRET=replace-with-a-long-random-value
|
||||
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
||||
SEED_ADMIN_PASSWORD=change-me-now-123
|
||||
OBJECT_STORAGE_ENDPOINT=
|
||||
OBJECT_STORAGE_BUCKET=
|
||||
OBJECT_STORAGE_ACCESS_KEY=
|
||||
OBJECT_STORAGE_SECRET_KEY=
|
||||
OBJECT_STORAGE_ENDPOINT=http://localhost:9000
|
||||
OBJECT_STORAGE_PUBLIC_URL=http://localhost:9000/personal-brand-media
|
||||
OBJECT_STORAGE_BUCKET=personal-brand-media
|
||||
OBJECT_STORAGE_ACCESS_KEY=minioadmin
|
||||
OBJECT_STORAGE_SECRET_KEY=minioadmin
|
||||
WECHAT_APP_ID=
|
||||
WECHAT_APP_SECRET=
|
||||
@@ -0,0 +1,26 @@
|
||||
NODE_ENV=production
|
||||
POSTGRES_USER=personal_brand
|
||||
POSTGRES_PASSWORD=replace-with-a-long-database-password
|
||||
POSTGRES_DB=personal_brand
|
||||
POSTGRES_PORT=5432
|
||||
|
||||
DATABASE_URL=postgresql://personal_brand:replace-with-a-long-database-password@127.0.0.1:5432/personal_brand?schema=public
|
||||
SESSION_SECRET=replace-with-at-least-32-random-characters
|
||||
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
||||
SEED_ADMIN_PASSWORD=replace-with-a-one-time-initial-password
|
||||
SEED_MODE=seed
|
||||
|
||||
API_PORT=3001
|
||||
API_PREFIX=
|
||||
|
||||
LOCAL_MEDIA_ROOT=/home/ubuntu/persional-brand/media
|
||||
LOCAL_MEDIA_BASE_URL=/media
|
||||
OBJECT_STORAGE_ENDPOINT=
|
||||
OBJECT_STORAGE_PUBLIC_URL=
|
||||
OBJECT_STORAGE_BUCKET=
|
||||
OBJECT_STORAGE_ACCESS_KEY=
|
||||
OBJECT_STORAGE_SECRET_KEY=
|
||||
OBJECT_STORAGE_REGION=us-east-1
|
||||
|
||||
WECHAT_APP_ID=
|
||||
WECHAT_APP_SECRET=
|
||||
@@ -0,0 +1,122 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
static:
|
||||
name: Static checks
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9.15.0
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm check
|
||||
- run: pnpm template:doctor
|
||||
|
||||
build:
|
||||
name: Production build
|
||||
runs-on: ubuntu-latest
|
||||
needs: [static]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9.15.0
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm build:admin:preview
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: admin-dist
|
||||
path: apps/admin/dist
|
||||
retention-days: 7
|
||||
|
||||
api:
|
||||
name: API integration
|
||||
runs-on: ubuntu-latest
|
||||
needs: [static]
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
env:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: personal_brand
|
||||
ports:
|
||||
- 5432:5432
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U postgres -d personal_brand"
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 12
|
||||
env:
|
||||
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/personal_brand
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9.15.0
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm --filter @personal-brand/api test:integration
|
||||
|
||||
browser:
|
||||
name: Browser regression
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9.15.0
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm --filter @personal-brand/taro exec playwright install --with-deps chromium
|
||||
- run: pnpm --filter @personal-brand/api test:integration
|
||||
env:
|
||||
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/personal_brand
|
||||
- name: Start API
|
||||
run: pnpm --filter @personal-brand/api start > /tmp/api.log 2>&1 &
|
||||
env:
|
||||
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/personal_brand
|
||||
NODE_ENV: development
|
||||
- name: Start mini program preview
|
||||
run: pnpm --filter @personal-brand/taro dev:h5 > /tmp/taro.log 2>&1 &
|
||||
env:
|
||||
API_BASE_URL: http://localhost:3001
|
||||
BRAND_SLUG: default-brand
|
||||
TEMPLATE_KEY: acheng-campus-food
|
||||
- name: Start admin
|
||||
run: pnpm --filter @personal-brand/admin dev > /tmp/admin.log 2>&1 &
|
||||
env:
|
||||
VITE_API_BASE_URL: /api
|
||||
VITE_DEV_API_TARGET: http://localhost:3001
|
||||
VITE_TEMPLATE_PREVIEW_URL: http://localhost:3002
|
||||
- name: Wait for services
|
||||
run: |
|
||||
curl --retry 30 --retry-delay 1 --retry-connrefused -fsS http://localhost:3001/health
|
||||
curl --retry 30 --retry-delay 1 --retry-connrefused -fsS http://localhost:3002
|
||||
curl --retry 30 --retry-delay 1 --retry-connrefused -fsS http://localhost:3000
|
||||
- run: pnpm --filter @personal-brand/taro exec playwright test --config=playwright.config.ts --reporter=line
|
||||
@@ -2,11 +2,13 @@ node_modules/
|
||||
.pnpm-store/
|
||||
.turbo/
|
||||
dist/
|
||||
packages/config/dist/
|
||||
.next/
|
||||
coverage/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.env.production
|
||||
!.env.production.example
|
||||
*.log
|
||||
.DS_Store
|
||||
apps/miniapp/miniprogram_npm/
|
||||
@@ -18,5 +20,9 @@ apps/admin/public/template-preview/
|
||||
|
||||
apps/taro/test-results/
|
||||
apps/taro/playwright-report/
|
||||
media/
|
||||
|
||||
**/.swc/
|
||||
.codex-tasks/
|
||||
docker-compose.override.yml
|
||||
.env.production
|
||||
@@ -3,3 +3,4 @@ VITE_API_BASE_URL=/api
|
||||
VITE_DEV_API_TARGET=http://localhost:3001
|
||||
ADMIN_PORT=3000
|
||||
VITE_TEMPLATE_PREVIEW_URL=http://localhost:3002
|
||||
VITE_MEDIA_PROXY_TARGET=http://localhost:9000
|
||||
@@ -3,6 +3,7 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^6.3.4",
|
||||
"@personal-brand/api-client": "workspace:*",
|
||||
"@tanstack/react-query": "^5.103.1",
|
||||
"antd": "^6.6.4",
|
||||
|
||||
@@ -1,33 +1,150 @@
|
||||
import { Image, Input, Space, Typography } from "antd";
|
||||
import { CloudUploadOutlined, DeleteOutlined, PictureOutlined } from "@ant-design/icons";
|
||||
import { Alert, Button, Image, Popconfirm, Space, Spin, Upload, message } from "antd";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { createApiClient } from "../lib/api.js";
|
||||
|
||||
interface ImageUrlFieldProps {
|
||||
id?: string;
|
||||
value?: string;
|
||||
onChange?: (value: string) => void;
|
||||
placeholder?: string;
|
||||
scope?: "brand" | "offering" | "trust";
|
||||
}
|
||||
|
||||
export function ImageUrlField({ value, onChange, placeholder }: ImageUrlFieldProps) {
|
||||
export function ImageUrlField({ id, value, onChange, placeholder, scope }: ImageUrlFieldProps) {
|
||||
const imageUrl = typeof value === "string" ? value.trim() : "";
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [storageStatus, setStorageStatus] = useState<
|
||||
"loading" | "ok" | "unavailable" | "unconfigured"
|
||||
>("loading");
|
||||
const client = useMemo(() => createApiClient(), []);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
client
|
||||
.getUploadConfig()
|
||||
.then((config) => {
|
||||
if (active) setStorageStatus(config.configured ? config.status : "unconfigured");
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) setStorageStatus("unavailable");
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [client]);
|
||||
|
||||
async function upload(file: File) {
|
||||
if (!file.type.startsWith("image/")) {
|
||||
message.error("仅支持图片文件");
|
||||
return;
|
||||
}
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
message.error("图片不能超过 10MB");
|
||||
return;
|
||||
}
|
||||
setUploading(true);
|
||||
try {
|
||||
const presign = await client.createPresignedUpload({
|
||||
fileName: file.name,
|
||||
contentType: file.type,
|
||||
...(scope ? { scope } : {}),
|
||||
});
|
||||
const response = await fetch(presign.uploadUrl, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": file.type },
|
||||
body: file,
|
||||
});
|
||||
if (!response.ok) throw new Error(`upload failed: ${response.status}`);
|
||||
onChange?.(presign.publicUrl);
|
||||
} catch {
|
||||
setStorageStatus("unavailable");
|
||||
message.error("图片上传失败,请检查对象存储后重试");
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Space direction="vertical" size={8} style={{ width: "100%" }}>
|
||||
<Input
|
||||
value={value}
|
||||
onChange={(event) => onChange?.(event.target.value)}
|
||||
placeholder={placeholder ?? "粘贴图片地址"}
|
||||
<Space direction="vertical" size={4} style={{ width: "100%" }}>
|
||||
{storageStatus !== "ok" ? (
|
||||
<Alert
|
||||
type={storageStatus === "loading" ? "info" : "warning"}
|
||||
showIcon
|
||||
message={
|
||||
storageStatus === "loading"
|
||||
? "正在检查媒体存储..."
|
||||
: storageStatus === "unconfigured"
|
||||
? "媒体存储未配置,请先设置对象存储"
|
||||
: "媒体存储不可用,请检查对象存储配置"
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
{imageUrl ? (
|
||||
<Space align="start">
|
||||
<div
|
||||
style={{
|
||||
position: "relative",
|
||||
width: "100%",
|
||||
minHeight: 140,
|
||||
borderRadius: 8,
|
||||
overflow: "hidden",
|
||||
border: "1px solid #d9d9d9",
|
||||
background: "#f5f5f5",
|
||||
}}
|
||||
>
|
||||
<Image
|
||||
src={imageUrl}
|
||||
width={96}
|
||||
height={64}
|
||||
alt={placeholder ?? "图片预览"}
|
||||
width="100%"
|
||||
height={180}
|
||||
preview
|
||||
style={{ objectFit: "cover" }}
|
||||
fallback="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="
|
||||
style={{ objectFit: "cover", borderRadius: 8, background: "#f5f5f5" }}
|
||||
/>
|
||||
<Typography.Text type="secondary">预览图</Typography.Text>
|
||||
</Space>
|
||||
<Popconfirm title="移除这张图片?" onConfirm={() => onChange?.("")}>
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
icon={<DeleteOutlined />}
|
||||
style={{ position: "absolute", top: 8, right: 8 }}
|
||||
>
|
||||
移除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</div>
|
||||
) : (
|
||||
<Upload.Dragger
|
||||
accept="image/*"
|
||||
multiple={false}
|
||||
showUploadList={false}
|
||||
disabled={uploading || storageStatus !== "ok"}
|
||||
beforeUpload={(file) => {
|
||||
if (storageStatus === "ok") void upload(file);
|
||||
return false;
|
||||
}}
|
||||
>
|
||||
<p className="ant-upload-drag-icon">{uploading ? <Spin /> : <PictureOutlined />}</p>
|
||||
<p className="ant-upload-text">{uploading ? "上传中..." : "点击或拖拽上传图片"}</p>
|
||||
<p className="ant-upload-hint">JPG、PNG、WebP 或 AVIF,最大 10MB</p>
|
||||
</Upload.Dragger>
|
||||
)}
|
||||
{storageStatus === "unavailable" ? (
|
||||
<Button
|
||||
icon={<CloudUploadOutlined />}
|
||||
onClick={() => {
|
||||
setStorageStatus("loading");
|
||||
client
|
||||
.getUploadConfig()
|
||||
.then((config) =>
|
||||
setStorageStatus(config.configured ? config.status : "unconfigured"),
|
||||
)
|
||||
.catch(() => setStorageStatus("unavailable"));
|
||||
}}
|
||||
>
|
||||
重新检查存储
|
||||
</Button>
|
||||
) : null}
|
||||
<input {...(id ? { id } : {})} type="hidden" value={imageUrl} />
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
@@ -1,95 +1,42 @@
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Col,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
Row,
|
||||
Select,
|
||||
Space,
|
||||
Switch,
|
||||
Typography,
|
||||
message,
|
||||
} from "antd";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { Alert, Button, Col, Form, Row, Space, Typography } from "antd";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import type {
|
||||
Offering,
|
||||
TemplateAdminField,
|
||||
TemplateAdminSection,
|
||||
TrustContent,
|
||||
} from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../lib/api.js";
|
||||
import { ImageUrlField } from "./ImageUrlField.js";
|
||||
import type { TemplateAdminSection } from "@personal-brand/api-client";
|
||||
import { TemplateListField } from "./TemplateListField.js";
|
||||
import { TemplateFieldRenderer } from "./TemplateFieldRenderer.js";
|
||||
import { MutationError } from "./QueryState.js";
|
||||
import {
|
||||
applyPresentationValues,
|
||||
applyStandardEntityValues,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
type PresentationValues,
|
||||
} from "../features/brand/presentation-bindings.js";
|
||||
import { presentationFieldName } from "../features/brand/presentation-bindings.js";
|
||||
import { useRecordContentEditorState } from "./record-content/useRecordContentEditorState.js";
|
||||
import type { RecordContentEditorProps, RecordContentSource } from "./record-content/types.js";
|
||||
|
||||
export type RecordContentSource = "offering" | "trust";
|
||||
export type { RecordContentEditorProps, RecordContentSource };
|
||||
|
||||
export interface RecordContentEditorProps {
|
||||
source: RecordContentSource;
|
||||
record: Offering | TrustContent;
|
||||
export function RecordContentFields({
|
||||
section,
|
||||
sectionKey = section.key,
|
||||
}: {
|
||||
section: TemplateAdminSection;
|
||||
context: "visual" | "services";
|
||||
onDraft?: (values: PresentationValues) => void;
|
||||
onSaved?: () => void;
|
||||
visualSelection?: { targetKey: string; page: string };
|
||||
}
|
||||
|
||||
function renderField(field: TemplateAdminField) {
|
||||
if (field.input === "textarea")
|
||||
return (
|
||||
<Input.TextArea
|
||||
rows={3}
|
||||
maxLength={field.maxLength}
|
||||
showCount={!!field.maxLength}
|
||||
placeholder={field.placeholder}
|
||||
/>
|
||||
);
|
||||
if (field.input === "image")
|
||||
return <ImageUrlField {...(field.placeholder ? { placeholder: field.placeholder } : {})} />;
|
||||
if (field.input === "phone") return <Input type="tel" placeholder={field.placeholder} />;
|
||||
if (field.input === "number") return <InputNumber min={0} placeholder={field.placeholder} />;
|
||||
if (field.input === "boolean") return <Switch />;
|
||||
if (field.input === "select")
|
||||
return <Select options={(field.options ?? []).map((item) => ({ ...item }))} />;
|
||||
if (field.input === "multi-select")
|
||||
return (
|
||||
<Select
|
||||
mode="multiple"
|
||||
options={(field.options ?? []).map((item) => ({ ...item }))}
|
||||
placeholder={field.placeholder}
|
||||
/>
|
||||
);
|
||||
return <Input placeholder={field.placeholder} />;
|
||||
}
|
||||
|
||||
export function RecordContentFields({ section }: { section: TemplateAdminSection }) {
|
||||
sectionKey?: string;
|
||||
}) {
|
||||
return (
|
||||
<Row gutter={16}>
|
||||
{section.fields.map((field) => (
|
||||
<Col key={field.key} xs={24} md={24}>
|
||||
{field.input === "list" ? (
|
||||
<TemplateListField field={field} name={presentationFieldName(section.key, field.key)} />
|
||||
<TemplateListField field={field} name={presentationFieldName(sectionKey, field.key)} />
|
||||
) : (
|
||||
<Form.Item
|
||||
name={presentationFieldName(section.key, field.key)}
|
||||
name={presentationFieldName(sectionKey, field.key)}
|
||||
label={field.label}
|
||||
htmlFor={presentationFieldName(sectionKey, field.key)}
|
||||
{...(field.help ? { help: field.help } : {})}
|
||||
{...(field.required
|
||||
? { rules: [{ required: true, message: `请填写${field.label}` }] }
|
||||
: {})}
|
||||
>
|
||||
{renderField(field)}
|
||||
<TemplateFieldRenderer
|
||||
field={field}
|
||||
id={presentationFieldName(sectionKey, field.key)}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
</Col>
|
||||
@@ -108,62 +55,22 @@ export function RecordContentEditor({
|
||||
visualSelection,
|
||||
}: RecordContentEditorProps) {
|
||||
const navigate = useNavigate();
|
||||
const [form] = Form.useForm<PresentationValues>();
|
||||
const queryClient = useQueryClient();
|
||||
const recordName = "name" in record ? record.name : record.title;
|
||||
const initialValues = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
section.fields.map((field) => [
|
||||
presentationFieldName(section.key, field.key),
|
||||
readPresentationValue(
|
||||
record.config,
|
||||
field.binding,
|
||||
field,
|
||||
record as unknown as Record<string, unknown>,
|
||||
),
|
||||
]),
|
||||
),
|
||||
[record, section],
|
||||
);
|
||||
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
|
||||
const save = useMutation({
|
||||
mutationFn: async (values: PresentationValues): Promise<void> => {
|
||||
const config = applyPresentationValues(record.config, [section], values);
|
||||
const standard = applyStandardEntityValues(
|
||||
record as unknown as Record<string, unknown>,
|
||||
const { form, handleValuesChange, initialValues, save, submit } = useRecordContentEditorState({
|
||||
source,
|
||||
[section],
|
||||
values,
|
||||
);
|
||||
const changed = Object.fromEntries(
|
||||
Object.entries(standard).filter(
|
||||
([key, value]) =>
|
||||
key !== "config" && value !== (record as unknown as Record<string, unknown>)[key],
|
||||
),
|
||||
);
|
||||
const client = createApiClient();
|
||||
if (source === "offering")
|
||||
await client.updateAdminOffering(record.id, { ...changed, config });
|
||||
else await client.updateAdminTrustContent(record.id, { ...changed, config });
|
||||
},
|
||||
onSuccess: () => {
|
||||
message.success("已保存内容草稿,发布后访客才会看到更新");
|
||||
onSaved?.();
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: [source === "offering" ? "admin-offerings" : "trust-content"],
|
||||
});
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
|
||||
},
|
||||
record,
|
||||
section,
|
||||
...(onDraft ? { onDraft } : {}),
|
||||
...(onSaved ? { onSaved } : {}),
|
||||
});
|
||||
|
||||
return (
|
||||
<Form
|
||||
form={form}
|
||||
layout="vertical"
|
||||
initialValues={initialValues}
|
||||
onValuesChange={(_, values) => onDraft?.(values)}
|
||||
onFinish={(values) => save.mutate(values)}
|
||||
onValuesChange={handleValuesChange}
|
||||
onFinish={submit}
|
||||
style={{ minHeight: 0, display: "flex", flexDirection: "column" }}
|
||||
>
|
||||
<Alert
|
||||
@@ -197,7 +104,7 @@ export function RecordContentEditor({
|
||||
onClick={() =>
|
||||
navigate("/admin/brand", {
|
||||
state: {
|
||||
targetKey: visualSelection?.targetKey ?? "linjing-editorial.offerings.item",
|
||||
targetKey: visualSelection?.targetKey ?? "offering.list.item",
|
||||
recordId: record.id,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { Input, InputNumber, Select, Switch } from "antd";
|
||||
import type { TemplateAdminField } from "@personal-brand/api-client";
|
||||
import { ImageUrlField } from "./ImageUrlField.js";
|
||||
|
||||
export function TemplateFieldRenderer({
|
||||
field,
|
||||
id,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
field: TemplateAdminField;
|
||||
id?: string;
|
||||
value?: unknown;
|
||||
onChange?: (value: unknown) => void;
|
||||
}) {
|
||||
if (field.input === "textarea")
|
||||
return (
|
||||
<Input.TextArea
|
||||
{...(id ? { id } : {})}
|
||||
value={typeof value === "string" ? value : ""}
|
||||
onChange={(event) => onChange?.(event.target.value)}
|
||||
rows={3}
|
||||
maxLength={field.maxLength}
|
||||
showCount={!!field.maxLength}
|
||||
placeholder={field.placeholder}
|
||||
/>
|
||||
);
|
||||
if (field.input === "image")
|
||||
return (
|
||||
<ImageUrlField
|
||||
{...(id ? { id } : {})}
|
||||
{...(field.placeholder ? { placeholder: field.placeholder } : {})}
|
||||
{...(typeof value === "string" ? { value } : {})}
|
||||
{...(onChange ? { onChange: (next: string) => onChange(next) } : {})}
|
||||
/>
|
||||
);
|
||||
if (field.input === "phone")
|
||||
return (
|
||||
<Input
|
||||
{...(id ? { id } : {})}
|
||||
type="tel"
|
||||
placeholder={field.placeholder}
|
||||
value={typeof value === "string" ? value : ""}
|
||||
onChange={(event) => onChange?.(event.target.value)}
|
||||
/>
|
||||
);
|
||||
if (field.input === "number")
|
||||
return (
|
||||
<InputNumber
|
||||
{...(id ? { id } : {})}
|
||||
value={typeof value === "number" ? value : null}
|
||||
onChange={(input) => onChange?.(input ?? undefined)}
|
||||
min={0}
|
||||
style={{ width: "100%" }}
|
||||
placeholder={field.placeholder}
|
||||
/>
|
||||
);
|
||||
if (field.input === "boolean")
|
||||
return (
|
||||
<Switch
|
||||
{...(id ? { id } : {})}
|
||||
checked={Boolean(value)}
|
||||
onChange={(checked) => onChange?.(checked)}
|
||||
/>
|
||||
);
|
||||
if (field.input === "select")
|
||||
return (
|
||||
<Select
|
||||
{...(id ? { id } : {})}
|
||||
options={(field.options ?? []).map((item) => ({ ...item }))}
|
||||
value={typeof value === "string" || typeof value === "number" ? value : undefined}
|
||||
onChange={(selected) => onChange?.(selected)}
|
||||
{...(field.placeholder ? { placeholder: field.placeholder } : {})}
|
||||
/>
|
||||
);
|
||||
if (field.input === "multi-select")
|
||||
return (
|
||||
<Select
|
||||
{...(id ? { id } : {})}
|
||||
mode="multiple"
|
||||
options={(field.options ?? []).map((item) => ({ ...item }))}
|
||||
value={Array.isArray(value) ? value.map(String) : []}
|
||||
onChange={(selected) => onChange?.(selected)}
|
||||
placeholder={field.placeholder}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<Input
|
||||
{...(id ? { id } : {})}
|
||||
value={typeof value === "string" ? value : ""}
|
||||
onChange={(event) => onChange?.(event.target.value)}
|
||||
maxLength={field.maxLength}
|
||||
placeholder={field.placeholder}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,10 @@
|
||||
import { Button, Form, Input, Space } from "antd";
|
||||
import { Button, Card, Collapse, Empty, Form, Input, Space, Typography } from "antd";
|
||||
import {
|
||||
CaretDownOutlined,
|
||||
CaretUpOutlined,
|
||||
DeleteOutlined,
|
||||
PlusOutlined,
|
||||
} from "@ant-design/icons";
|
||||
import type { TemplateAdminField } from "@personal-brand/api-client";
|
||||
|
||||
export function TemplateListField({
|
||||
@@ -22,14 +28,81 @@ export function TemplateListField({
|
||||
]}
|
||||
>
|
||||
{(rows, { add, remove, move }, { errors }) => (
|
||||
<Space direction="vertical" style={{ width: "100%" }}>
|
||||
{rows.map((row, index) => (
|
||||
<Space key={row.key} align="start" wrap>
|
||||
<Space direction="vertical" size={12} style={{ width: "100%" }}>
|
||||
{rows.length === 0 ? (
|
||||
<Empty
|
||||
image={Empty.PRESENTED_IMAGE_SIMPLE}
|
||||
description={`还没有${field.label}内容`}
|
||||
/>
|
||||
) : null}
|
||||
{rows.map((row, index) => {
|
||||
const titleField = field.itemFields?.[0];
|
||||
const primaryTitle = titleField ? (
|
||||
<Form.Item
|
||||
noStyle
|
||||
shouldUpdate={(prev: unknown, next: unknown) => {
|
||||
const previous = Array.isArray(prev)
|
||||
? (prev[row.name] as Record<string, unknown> | undefined)
|
||||
: undefined;
|
||||
const nextRow = Array.isArray(next)
|
||||
? (next[row.name] as Record<string, unknown> | undefined)
|
||||
: undefined;
|
||||
return previous?.[titleField.key] !== nextRow?.[titleField.key];
|
||||
}}
|
||||
>
|
||||
{({ getFieldValue }) => {
|
||||
const value = String(
|
||||
getFieldValue([...name, row.name, titleField.key] as const) ?? "",
|
||||
);
|
||||
return (
|
||||
<Typography.Text
|
||||
strong
|
||||
>{`${index + 1}. ${value || titleField.label}`}</Typography.Text>
|
||||
);
|
||||
}}
|
||||
</Form.Item>
|
||||
) : (
|
||||
<Typography.Text strong>{`${index + 1}. ${field.label}`}</Typography.Text>
|
||||
);
|
||||
return (
|
||||
<Card
|
||||
key={row.key}
|
||||
size="small"
|
||||
title={primaryTitle}
|
||||
extra={
|
||||
<Space size={0}>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
aria-label={`上移第 ${index + 1} 项`}
|
||||
icon={<CaretUpOutlined />}
|
||||
disabled={index === 0}
|
||||
onClick={() => move(index, index - 1)}
|
||||
/>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
aria-label={`下移第 ${index + 1} 项`}
|
||||
icon={<CaretDownOutlined />}
|
||||
disabled={index === rows.length - 1}
|
||||
onClick={() => move(index, index + 1)}
|
||||
/>
|
||||
<Button
|
||||
type="text"
|
||||
danger
|
||||
size="small"
|
||||
aria-label={`删除第 ${index + 1} 项`}
|
||||
icon={<DeleteOutlined />}
|
||||
onClick={() => remove(row.name)}
|
||||
/>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
{field.itemFields?.map((itemField) => (
|
||||
<Form.Item
|
||||
key={itemField.key}
|
||||
name={[row.name, itemField.key]}
|
||||
label={`${index + 1}. ${itemField.label}`}
|
||||
label={itemField.label}
|
||||
rules={
|
||||
itemField.required === false
|
||||
? []
|
||||
@@ -39,25 +112,29 @@ export function TemplateListField({
|
||||
{itemField.input === "textarea" ? <Input.TextArea rows={2} /> : <Input />}
|
||||
</Form.Item>
|
||||
))}
|
||||
<Button onClick={() => remove(row.name)}>删除</Button>
|
||||
<Button
|
||||
aria-label={`上移第 ${index + 1} 项`}
|
||||
disabled={index === 0}
|
||||
onClick={() => move(index, index - 1)}
|
||||
>
|
||||
上移
|
||||
</Button>
|
||||
<Button
|
||||
aria-label={`下移第 ${index + 1} 项`}
|
||||
disabled={index === rows.length - 1}
|
||||
onClick={() => move(index, index + 1)}
|
||||
>
|
||||
下移
|
||||
</Button>
|
||||
</Space>
|
||||
))}
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
{rows.length > 1 ? (
|
||||
<Collapse
|
||||
ghost
|
||||
items={[
|
||||
{
|
||||
key: "sort-help",
|
||||
label: "排序说明",
|
||||
children: (
|
||||
<Typography.Text type="secondary">
|
||||
使用每张卡片右上角的箭头调整顺序,保存后预览也会按当前顺序展示。
|
||||
</Typography.Text>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
) : null}
|
||||
<Form.ErrorList errors={errors} />
|
||||
<Button onClick={() => add()}>新增{field.label}</Button>
|
||||
<Button block icon={<PlusOutlined />} onClick={() => add()}>
|
||||
新增{field.label}
|
||||
</Button>
|
||||
</Space>
|
||||
)}
|
||||
</Form.List>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { Offering, TemplateAdminSection, TrustContent } from "@personal-brand/api-client";
|
||||
import type { PresentationValues } from "../../features/brand/presentation-bindings.js";
|
||||
|
||||
export type RecordContentSource = "offering" | "trust";
|
||||
|
||||
export interface RecordContentEditorProps {
|
||||
source: RecordContentSource;
|
||||
record: Offering | TrustContent;
|
||||
section: TemplateAdminSection;
|
||||
context: "visual" | "services";
|
||||
onDraft?: (values: PresentationValues) => void;
|
||||
onSaved?: () => void;
|
||||
visualSelection?: { targetKey: string; page: string };
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { Form, message } from "antd";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import type { TemplateAdminSection } from "@personal-brand/api-client";
|
||||
import type { Offering, TrustContent } from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import {
|
||||
applyPresentationValues,
|
||||
applyStandardEntityValues,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
type PresentationValues,
|
||||
} from "../../features/brand/presentation-bindings.js";
|
||||
import type { RecordContentSource } from "./types.js";
|
||||
|
||||
function createInitialValues(
|
||||
record: Offering | TrustContent,
|
||||
section: TemplateAdminSection,
|
||||
): PresentationValues {
|
||||
return Object.fromEntries(
|
||||
section.fields.map((field) => [
|
||||
presentationFieldName(section.key, field.key),
|
||||
readPresentationValue(
|
||||
record.config,
|
||||
field.binding,
|
||||
field,
|
||||
record as unknown as Record<string, unknown>,
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
function createChangedStandardValues(
|
||||
record: Offering | TrustContent,
|
||||
source: RecordContentSource,
|
||||
section: TemplateAdminSection,
|
||||
values: PresentationValues,
|
||||
) {
|
||||
const entity = record as unknown as Record<string, unknown>;
|
||||
const standard = applyStandardEntityValues(entity, source, [section], values);
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(standard).filter(
|
||||
([key, value]) => key !== "config" && (key in entity || value !== entity[key]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function useRecordContentEditorState({
|
||||
source,
|
||||
record,
|
||||
section,
|
||||
onDraft,
|
||||
onSaved,
|
||||
}: {
|
||||
source: RecordContentSource;
|
||||
record: Offering | TrustContent;
|
||||
section: TemplateAdminSection;
|
||||
onDraft?: ((values: PresentationValues) => void) | undefined;
|
||||
onSaved?: (() => void) | undefined;
|
||||
}) {
|
||||
const [form] = Form.useForm<PresentationValues>();
|
||||
const queryClient = useQueryClient();
|
||||
const [draftValues, setDraftValues] = useState<PresentationValues>(() =>
|
||||
createInitialValues(record, section),
|
||||
);
|
||||
const initialValues = useMemo(() => createInitialValues(record, section), [record, section]);
|
||||
|
||||
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: async (values: PresentationValues): Promise<void> => {
|
||||
const config = applyPresentationValues(record.config, [section], values);
|
||||
const changed = createChangedStandardValues(record, source, section, values);
|
||||
const client = createApiClient();
|
||||
|
||||
if (source === "offering") {
|
||||
await client.updateAdminOffering(record.id, { ...changed, config });
|
||||
} else {
|
||||
await client.updateAdminTrustContent(record.id, { ...changed, config });
|
||||
}
|
||||
},
|
||||
onSuccess: () => {
|
||||
message.success("已保存内容草稿,发布后访客才会看到更新");
|
||||
onSaved?.();
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: [source === "offering" ? "admin-offerings" : "trust-content"],
|
||||
});
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
|
||||
if (source === "offering") {
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace-offering-fields"] });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const submit = (values: PresentationValues) => {
|
||||
const currentValues = form.getFieldsValue(true) as PresentationValues;
|
||||
save.mutate({ ...draftValues, ...values, ...currentValues });
|
||||
};
|
||||
|
||||
const handleValuesChange = (_values: PresentationValues) => {
|
||||
const currentValues = form.getFieldsValue(true) as PresentationValues;
|
||||
const next = { ...draftValues, ..._values, ...currentValues };
|
||||
setDraftValues(next);
|
||||
onDraft?.(next);
|
||||
};
|
||||
|
||||
return {
|
||||
draftValues,
|
||||
form,
|
||||
handleValuesChange,
|
||||
initialValues,
|
||||
save,
|
||||
submit,
|
||||
};
|
||||
}
|
||||
@@ -48,6 +48,10 @@ export function BrandPage() {
|
||||
queryFn: () => client.getPublicTemplate(brand.data!.templateKey),
|
||||
enabled: Boolean(brand.data?.templateKey),
|
||||
});
|
||||
const templateCatalog = useQuery({
|
||||
queryKey: ["template-catalog"],
|
||||
queryFn: () => client.listPublicTemplates(),
|
||||
});
|
||||
const save = useMutation({
|
||||
mutationFn: (values: Partial<BrandProfile>) => client.updateAdminBrand(values),
|
||||
onSuccess: () => {
|
||||
@@ -112,7 +116,7 @@ export function BrandPage() {
|
||||
help="可以是个人姓名、工作室名称或品牌名。"
|
||||
rules={[{ required: true, message: "请输入品牌名称" }]}
|
||||
>
|
||||
<Input size="large" placeholder="例如:林然|品牌顾问" />
|
||||
<Input size="large" placeholder="例如:品牌主理人|品牌顾问" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="tagline"
|
||||
@@ -190,10 +194,10 @@ export function BrandPage() {
|
||||
>
|
||||
<Select
|
||||
disabled
|
||||
options={[
|
||||
{ value: "personal", label: "个人品牌" },
|
||||
{ value: "food", label: "餐饮模板" },
|
||||
]}
|
||||
options={(templateCatalog.data?.industries ?? []).map((item) => ({
|
||||
value: item.key,
|
||||
label: item.name,
|
||||
}))}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Row gutter={16}>
|
||||
@@ -201,14 +205,18 @@ export function BrandPage() {
|
||||
<Form.Item
|
||||
name="avatarUrl"
|
||||
label="头像图片地址"
|
||||
help="粘贴一张可公开访问的图片地址。"
|
||||
help="点击上传或粘贴一张可公开访问的图片地址。"
|
||||
>
|
||||
<ImageUrlField />
|
||||
<ImageUrlField scope="brand" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
<Col xs={24} md={12}>
|
||||
<Form.Item name="coverUrl" label="品牌封面图片地址" help="建议使用横向图片。">
|
||||
<ImageUrlField />
|
||||
<Form.Item
|
||||
name="coverUrl"
|
||||
label="品牌封面图片地址"
|
||||
help="点击上传,或粘贴一张横向图片地址。"
|
||||
>
|
||||
<ImageUrlField scope="brand" />
|
||||
</Form.Item>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
@@ -48,6 +48,11 @@
|
||||
0 10px 30px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
:where(.component-template-preview__canvas) {
|
||||
--taro-button-height: 11.7333333cqw;
|
||||
--taro-button-compact-height: 6.1333333cqw;
|
||||
}
|
||||
|
||||
.component-template-preview__canvas,
|
||||
.component-template-preview__canvas * {
|
||||
box-sizing: border-box;
|
||||
@@ -59,8 +64,12 @@
|
||||
}
|
||||
|
||||
:where(.component-template-preview__canvas) button {
|
||||
display: block;
|
||||
width: -webkit-fill-available;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
min-height: var(--taro-button-height);
|
||||
appearance: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
@@ -68,8 +77,7 @@
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-size: 4.8cqw;
|
||||
line-height: 2.55555556;
|
||||
line-height: 1.5;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@@ -107,7 +115,7 @@
|
||||
.component-template-preview__composite-select {
|
||||
position: absolute;
|
||||
z-index: 7;
|
||||
width: auto !important;
|
||||
width: max-content !important;
|
||||
padding: 2px 8px !important;
|
||||
border: 1px solid #1677ff !important;
|
||||
border-radius: 4px !important;
|
||||
@@ -142,3 +150,18 @@
|
||||
.component-template-preview {
|
||||
height: 100%;
|
||||
}
|
||||
.component-template-preview__overlay-host {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 5;
|
||||
pointer-events: none;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.component-template-preview__overlay-host.is-visible {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.component-template-preview__overlay-host > * {
|
||||
pointer-events: auto;
|
||||
}
|
||||
@@ -3,8 +3,6 @@ import type { RuntimeWorkspace } from "@personal-brand/api-client";
|
||||
import { Alert } from "antd";
|
||||
import { resolveTemplateRenderer } from "./component-renderers.jsx";
|
||||
import type { PreviewSelection, PreviewTarget } from "./preview-selection.js";
|
||||
import "../../../../../packages/template-acheng-campus-food/taro/style.css";
|
||||
import "../../../../../packages/template-linjing-editorial/taro/style.css";
|
||||
import "./ComponentTemplatePreview.css";
|
||||
|
||||
type PreviewProps = {
|
||||
@@ -17,6 +15,7 @@ type PreviewProps = {
|
||||
};
|
||||
|
||||
type Outline = { top: number; left: number; width: number; height: number; label: string };
|
||||
type CompositeOutline = Outline & { key: string };
|
||||
|
||||
export function ComponentTemplatePreview({
|
||||
workspace,
|
||||
@@ -28,11 +27,10 @@ export function ComponentTemplatePreview({
|
||||
}: PreviewProps) {
|
||||
const Renderer = resolveTemplateRenderer(workspace);
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
const canvas = useRef<HTMLDivElement>(null);
|
||||
const [mode, setMode] = useState<"edit" | "browse">("edit");
|
||||
const [hovered, setHovered] = useState<HTMLElement | null>(null);
|
||||
const [hoverOutline, setHoverOutline] = useState<Outline | null>(null);
|
||||
const [selectedOutline, setSelectedOutline] = useState<Outline | null>(null);
|
||||
const [compositeOutlines, setCompositeOutlines] = useState<Array<Outline & { key: string }>>([]);
|
||||
const overlay = useRef<HTMLDivElement>(null);
|
||||
const targetFor = useCallback(
|
||||
(element: Element | null): HTMLElement | null => {
|
||||
let candidate = element?.closest<HTMLElement>("[data-editor-target]");
|
||||
@@ -58,17 +56,64 @@ export function ComponentTemplatePreview({
|
||||
) ?? null
|
||||
);
|
||||
}, [selection]);
|
||||
const renderOutlines = useCallback(
|
||||
(
|
||||
host: HTMLDivElement,
|
||||
outlines: {
|
||||
hover: Outline | null;
|
||||
selected: Outline | null;
|
||||
composite: CompositeOutline[];
|
||||
},
|
||||
) => {
|
||||
host.replaceChildren();
|
||||
const position = (node: HTMLElement, outline: Outline) => {
|
||||
node.style.top = `${outline.top}px`;
|
||||
node.style.left = `${outline.left}px`;
|
||||
node.style.width = `${outline.width}px`;
|
||||
node.style.height = `${outline.height}px`;
|
||||
};
|
||||
if (outlines.hover) {
|
||||
const node = document.createElement("div");
|
||||
node.className = "component-template-preview__outline is-hovered";
|
||||
position(node, outlines.hover);
|
||||
host.append(node);
|
||||
}
|
||||
if (outlines.selected) {
|
||||
const node = document.createElement("div");
|
||||
node.className = "component-template-preview__outline is-selected";
|
||||
node.dataset.selectedTarget = selection?.targetKey ?? "";
|
||||
node.dataset.selectedRecordId = selection?.recordId ?? "";
|
||||
const label = document.createElement("span");
|
||||
label.textContent = outlines.selected.label;
|
||||
node.append(label);
|
||||
position(node, outlines.selected);
|
||||
host.append(node);
|
||||
}
|
||||
for (const outline of outlines.composite) {
|
||||
const node = document.createElement("button");
|
||||
node.type = "button";
|
||||
node.className = "component-template-preview__composite-select";
|
||||
node.textContent = `选择${outline.label}`;
|
||||
node.setAttribute("aria-label", node.textContent);
|
||||
node.onclick = () => onTargetSelected({ targetKey: outline.key });
|
||||
node.style.top = `${outline.top + 4}px`;
|
||||
node.style.left = `${outline.left + 4}px`;
|
||||
host.append(node);
|
||||
}
|
||||
},
|
||||
[onTargetSelected, selection?.recordId, selection?.targetKey],
|
||||
);
|
||||
const measure = useCallback(
|
||||
(element: HTMLElement | null): Outline | null => {
|
||||
const viewport = root.current;
|
||||
if (!element || !viewport || !viewport.contains(element)) return null;
|
||||
const host = canvas.current;
|
||||
if (!element || !host || !host.contains(element)) return null;
|
||||
const box = element.getBoundingClientRect();
|
||||
const parent = viewport.getBoundingClientRect();
|
||||
const parent = host.getBoundingClientRect();
|
||||
const target = targets.find((item) => item.key === element.dataset.editorTarget);
|
||||
if (!target || !box.width || !box.height) return null;
|
||||
return {
|
||||
top: box.top - parent.top + viewport.scrollTop,
|
||||
left: box.left - parent.left + viewport.scrollLeft,
|
||||
top: box.top - parent.top,
|
||||
left: box.left - parent.left,
|
||||
width: box.width,
|
||||
height: box.height,
|
||||
label: target.label,
|
||||
@@ -78,30 +123,35 @@ export function ComponentTemplatePreview({
|
||||
);
|
||||
useLayoutEffect(() => {
|
||||
const viewport = root.current;
|
||||
if (!viewport) return;
|
||||
const outlineHost = overlay.current;
|
||||
const host = canvas.current;
|
||||
if (!viewport || !outlineHost || !host) return;
|
||||
let frame = 0;
|
||||
const update = () => {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(() => {
|
||||
setSelectedOutline(measure(selectedElement()));
|
||||
setHoverOutline(measure(hovered));
|
||||
setCompositeOutlines(
|
||||
targets
|
||||
const nextHover = measure(hovered);
|
||||
const nextSelected = measure(selectedElement());
|
||||
const nextComposite = targets
|
||||
.filter((target) => target.composite)
|
||||
.flatMap((target) => {
|
||||
const element = viewport.querySelector<HTMLElement>(
|
||||
const element = host.querySelector<HTMLElement>(
|
||||
`[data-editor-target="${CSS.escape(target.key)}"]`,
|
||||
);
|
||||
const outline = measure(element);
|
||||
return outline ? [{ ...outline, key: target.key }] : [];
|
||||
}),
|
||||
);
|
||||
});
|
||||
renderOutlines(outlineHost, {
|
||||
hover: nextHover,
|
||||
selected: nextSelected,
|
||||
composite: nextComposite,
|
||||
});
|
||||
});
|
||||
};
|
||||
update();
|
||||
const resize = new ResizeObserver(update);
|
||||
resize.observe(viewport);
|
||||
viewport
|
||||
host
|
||||
.querySelectorAll<HTMLElement>("[data-editor-target]")
|
||||
.forEach((node) => resize.observe(node));
|
||||
window.addEventListener("resize", update);
|
||||
@@ -176,50 +226,16 @@ export function ComponentTemplatePreview({
|
||||
);
|
||||
}}
|
||||
>
|
||||
<div className="component-template-preview__canvas">
|
||||
<div ref={canvas} className="component-template-preview__canvas">
|
||||
<Renderer workspace={workspace} page={page} {...(offeringId ? { offeringId } : {})} />
|
||||
</div>
|
||||
{mode === "edit"
|
||||
? compositeOutlines.map((outline) => (
|
||||
<button
|
||||
key={outline.key}
|
||||
type="button"
|
||||
className="component-template-preview__composite-select"
|
||||
style={{ top: outline.top + 4, left: outline.left + 4 }}
|
||||
aria-label={`选择${targets.find((target) => target.key === outline.key)?.label ?? outline.label}`}
|
||||
onClick={() => onTargetSelected({ targetKey: outline.key })}
|
||||
>
|
||||
选择{targets.find((target) => target.key === outline.key)?.label ?? outline.label}
|
||||
</button>
|
||||
))
|
||||
: null}
|
||||
{mode === "edit" && hoverOutline ? (
|
||||
<div
|
||||
className="component-template-preview__outline is-hovered"
|
||||
style={{
|
||||
top: hoverOutline.top,
|
||||
left: hoverOutline.left,
|
||||
width: hoverOutline.width,
|
||||
height: hoverOutline.height,
|
||||
}}
|
||||
aria-hidden="true"
|
||||
ref={overlay}
|
||||
className={`component-template-preview__overlay-host ${
|
||||
mode === "edit" ? "is-visible" : ""
|
||||
}`}
|
||||
data-editor-overlay=""
|
||||
/>
|
||||
) : null}
|
||||
{mode === "edit" && selectedOutline ? (
|
||||
<div
|
||||
className="component-template-preview__outline is-selected"
|
||||
style={{
|
||||
top: selectedOutline.top,
|
||||
left: selectedOutline.left,
|
||||
width: selectedOutline.width,
|
||||
height: selectedOutline.height,
|
||||
}}
|
||||
data-selected-target={selection?.targetKey}
|
||||
data-selected-record-id={selection?.recordId}
|
||||
>
|
||||
<span>{selectedOutline.label}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -114,7 +114,18 @@
|
||||
}
|
||||
|
||||
.presentation-editor__inspector .ant-form-item {
|
||||
margin-bottom: 24px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.presentation-editor__inspector form > section {
|
||||
padding: 16px;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 12px;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
.presentation-editor__inspector form > section + section {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.presentation-editor__inspector form > .ant-space:last-child {
|
||||
|
||||
@@ -5,17 +5,14 @@ import {
|
||||
Col,
|
||||
Form,
|
||||
Grid,
|
||||
Input,
|
||||
InputNumber,
|
||||
Row,
|
||||
Select,
|
||||
Segmented,
|
||||
Space,
|
||||
Tag,
|
||||
Typography,
|
||||
message,
|
||||
} from "antd";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import type {
|
||||
@@ -26,9 +23,8 @@ import type {
|
||||
} from "@personal-brand/api-client";
|
||||
import type { BrandProfile } from "@personal-brand/api-client";
|
||||
import { projectBrandAliases, projectTrustPresentation } from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
||||
import { TemplateListField } from "../../components/TemplateListField.js";
|
||||
import { TemplateFieldRenderer } from "../../components/TemplateFieldRenderer.js";
|
||||
import { MutationError } from "../../components/QueryState.js";
|
||||
import { RecordContentEditor } from "../../components/RecordContentEditor.js";
|
||||
import { TemplatePreview } from "./TemplatePreview.js";
|
||||
@@ -40,17 +36,20 @@ import {
|
||||
type PreviewTarget,
|
||||
} from "./preview-selection.js";
|
||||
import {
|
||||
applyBrandPreviewValues,
|
||||
applyStandardBrandValues,
|
||||
applyStandardEntityValues,
|
||||
applyPresentationValues,
|
||||
filterSectionsForPreviewTarget,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
type PresentationValues,
|
||||
} from "./presentation-bindings.js";
|
||||
import "./PresentationEditor.css";
|
||||
import { useEditorDraft } from "./use-editor-draft.js";
|
||||
import {
|
||||
usePresentationRecordQueries,
|
||||
useBrandPresentationSections,
|
||||
useBrandSaveMutation,
|
||||
useBrandPresentationForm,
|
||||
useBrandPreviewDraft,
|
||||
} from "./presentation-editor-state.js";
|
||||
import { useRecordPreview } from "./presentation-editor-record-preview.js";
|
||||
|
||||
interface PresentationEditorProps {
|
||||
templateContent: AdminTemplateContent | null | undefined;
|
||||
@@ -118,45 +117,6 @@ function trustSection(
|
||||
};
|
||||
}
|
||||
|
||||
function renderField(field: TemplateAdminField) {
|
||||
if (field.input === "textarea")
|
||||
return (
|
||||
<Input.TextArea
|
||||
rows={3}
|
||||
maxLength={field.maxLength}
|
||||
showCount={!!field.maxLength}
|
||||
placeholder={field.placeholder}
|
||||
/>
|
||||
);
|
||||
if (field.input === "image")
|
||||
return <ImageUrlField {...(field.placeholder ? { placeholder: field.placeholder } : {})} />;
|
||||
if (field.input === "number")
|
||||
return <InputNumber style={{ width: "100%" }} placeholder={field.placeholder} />;
|
||||
if (field.input === "boolean")
|
||||
return (
|
||||
<Select
|
||||
options={[
|
||||
{ value: true, label: "是" },
|
||||
{ value: false, label: "否" },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
if (field.input === "select" || field.input === "multi-select")
|
||||
return (
|
||||
<Select
|
||||
{...(field.input === "multi-select" ? { mode: "multiple" as const } : {})}
|
||||
options={field.options ?? []}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<Input
|
||||
type={field.input === "phone" ? "tel" : "text"}
|
||||
maxLength={field.maxLength}
|
||||
placeholder={field.placeholder}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function previewTargetSource(
|
||||
section: TemplateAdminSection,
|
||||
targetKey: string,
|
||||
@@ -177,57 +137,24 @@ export function PresentationEditor({
|
||||
error,
|
||||
initialSelection,
|
||||
}: PresentationEditorProps) {
|
||||
const [form] = Form.useForm<PresentationValues>();
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const breakpoints = Grid.useBreakpoint();
|
||||
const [activePage, setActivePage] = useState<string>();
|
||||
const [selection, setSelection] = useState<PreviewSelection | undefined>(initialSelection);
|
||||
const [hasInitializedSelection, setHasInitializedSelection] = useState(Boolean(initialSelection));
|
||||
const [detailOfferingId, setDetailOfferingId] = useState<string>();
|
||||
const [recordDraft, setRecordDraft] = useState<{
|
||||
source: "offering" | "trust";
|
||||
id: string;
|
||||
values: PresentationValues;
|
||||
}>();
|
||||
const [previewConfig, setPreviewConfig] = useState(config ?? {});
|
||||
const [previewBrandValues, setPreviewBrandValues] = useState<Record<string, unknown>>({});
|
||||
const [inquiryDraft, setInquiryDraft] =
|
||||
useState<RuntimeWorkspace["inquiryForms"][number]["fields"]>();
|
||||
const [brandDirty, setBrandDirty] = useState(false);
|
||||
const guardDraft = useEditorDraft(brandDirty || !!recordDraft || !!inquiryDraft);
|
||||
const inquiryRuntime = previewWorkspace?.inquiryForms.find((item) => item.target === "brand");
|
||||
const sections = useMemo(() => {
|
||||
const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({
|
||||
...field,
|
||||
binding: field.binding ?? `brand.config.templateData.${field.key}`,
|
||||
}));
|
||||
return [
|
||||
...[...new Set(declaredTemplateFields.map((field) => field.page ?? "home"))].map((page) => ({
|
||||
key: `template-data:${page}`,
|
||||
title: "模板专属内容",
|
||||
description: "这些字段由当前小程序模板定义,保存后发布才会对外展示。",
|
||||
page,
|
||||
target: "brand" as const,
|
||||
fields: declaredTemplateFields.filter((field) => (field.page ?? "home") === page),
|
||||
})),
|
||||
...(templateContent?.admin.sections ?? []),
|
||||
].map((section) => ({
|
||||
...section,
|
||||
fields: section.fields.filter(
|
||||
(field) =>
|
||||
field.binding.startsWith("brand.config.") ||
|
||||
[
|
||||
"brand.name",
|
||||
"brand.tagline",
|
||||
"brand.avatarUrl",
|
||||
"brand.description",
|
||||
"brand.contactPhone",
|
||||
"brand.contactWechat",
|
||||
"brand.address",
|
||||
].includes(field.binding),
|
||||
),
|
||||
}));
|
||||
}, [templateContent]);
|
||||
const sections = useBrandPresentationSections(templateContent);
|
||||
const pageOptions = useMemo(() => {
|
||||
const pages = new Map<string, string>();
|
||||
for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label);
|
||||
@@ -288,22 +215,10 @@ export function PresentationEditor({
|
||||
selectedTarget?.source === "offering" || selectedTarget?.source === "trust"
|
||||
? selectedTarget.source
|
||||
: undefined;
|
||||
const offeringsQuery = useQuery({
|
||||
queryKey: ["admin-offerings"],
|
||||
queryFn: () => createApiClient().listAdminOfferings(),
|
||||
enabled: selectedRecordSource === "offering",
|
||||
});
|
||||
const trustQuery = useQuery({
|
||||
queryKey: ["trust-content"],
|
||||
queryFn: () => createApiClient().listAdminTrustContent(),
|
||||
enabled: selectedRecordSource === "trust",
|
||||
});
|
||||
const selectedRecord =
|
||||
selectedRecordSource === "offering"
|
||||
? offeringsQuery.data?.find((item) => item.id === selection?.recordId)
|
||||
: selectedRecordSource === "trust"
|
||||
? trustQuery.data?.find((item) => item.id === selection?.recordId)
|
||||
: undefined;
|
||||
const { offeringsQuery, trustQuery, selectedRecord } = usePresentationRecordQueries(
|
||||
selectedRecordSource,
|
||||
selection?.recordId,
|
||||
);
|
||||
const editableSections = filterSectionsForPreviewTarget(
|
||||
visibleSections.filter((section) =>
|
||||
section.fields.some((field) => field.binding.startsWith("brand.")),
|
||||
@@ -381,64 +296,51 @@ export function PresentationEditor({
|
||||
return item.target === selectedSection.target;
|
||||
})
|
||||
: pageLinks;
|
||||
const initialValues = useMemo(() => {
|
||||
const values: PresentationValues = {};
|
||||
for (const section of sections) {
|
||||
for (const field of section.fields) {
|
||||
values[presentationFieldName(section.key, field.key)] = readPresentationValue(
|
||||
config,
|
||||
field.binding,
|
||||
field,
|
||||
brand as unknown as Record<string, unknown>,
|
||||
);
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}, [config, sections]);
|
||||
const formState = useBrandPresentationForm({ brand, config, sections });
|
||||
const { form, initialValues } = formState;
|
||||
const save = useBrandSaveMutation({ ...formState, brand, config, sections, queryClient });
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: (values: PresentationValues) => {
|
||||
const nextConfig = applyPresentationValues(config, sections, values);
|
||||
// 页面内容编辑不提交模板选择,避免触发切换模板的权限校验。
|
||||
const contentConfig = { ...nextConfig };
|
||||
delete contentConfig.visualTemplateKey;
|
||||
const standard = applyStandardBrandValues(
|
||||
brand as unknown as Record<string, unknown>,
|
||||
sections,
|
||||
values,
|
||||
useEffect(() => {
|
||||
const initialPage =
|
||||
typeof initialSelection === "object" && "page" in initialSelection
|
||||
? String(initialSelection.page)
|
||||
: undefined;
|
||||
if (initialPage) {
|
||||
setActivePage(
|
||||
pageOptions.some((item) => item.value === initialPage)
|
||||
? initialPage
|
||||
: pageOptions[0]?.value,
|
||||
);
|
||||
const changed = Object.fromEntries(
|
||||
Object.entries(standard).filter(
|
||||
([key, value]) =>
|
||||
key !== "config" && value !== (brand as unknown as Record<string, unknown>)[key],
|
||||
return;
|
||||
}
|
||||
if (!activePage && pageOptions.length) setActivePage(pageOptions[0]?.value);
|
||||
}, [activePage, initialSelection, pageOptions]);
|
||||
useEffect(() => {
|
||||
if (hasInitializedSelection) return;
|
||||
if (!pageOptions.length) return;
|
||||
if (!initialSelection) return;
|
||||
const requestedPage =
|
||||
typeof initialSelection === "object" && "page" in initialSelection
|
||||
? String(initialSelection.page)
|
||||
: undefined;
|
||||
const resolvedPage =
|
||||
requestedPage && pageOptions.some((item) => item.value === requestedPage)
|
||||
? requestedPage
|
||||
: (pageOptions[0]?.value ?? "home");
|
||||
setSelection(
|
||||
resolvePreviewSelection(
|
||||
initialSelection.targetKey,
|
||||
initialSelection.recordId,
|
||||
visibleTargets,
|
||||
resolvedPage,
|
||||
),
|
||||
);
|
||||
return createApiClient().updateAdminBrand({
|
||||
...changed,
|
||||
config: contentConfig,
|
||||
});
|
||||
},
|
||||
onSuccess: () => {
|
||||
setBrandDirty(false);
|
||||
message.success("页面内容已保存为草稿,发布后小程序才会更新");
|
||||
window.dispatchEvent(new Event("template-preview-refresh"));
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["publication-readiness"] });
|
||||
},
|
||||
});
|
||||
|
||||
setActivePage(resolvedPage);
|
||||
setHasInitializedSelection(true);
|
||||
}, [hasInitializedSelection, initialSelection, pageOptions, selectedPage, visibleTargets]);
|
||||
useEffect(() => {
|
||||
form.setFieldsValue(initialValues);
|
||||
}, [form, initialValues]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pageOptions.some((item) => item.value === activePage))
|
||||
setActivePage(pageOptions[0]?.value);
|
||||
}, [activePage, pageOptions]);
|
||||
useEffect(() => setSelection(undefined), [selectedPage, templateContent?.displayName]);
|
||||
if (!initialSelection) setSelection(undefined);
|
||||
}, [initialSelection, selectedPage, templateContent?.displayName]);
|
||||
useEffect(() => {
|
||||
if (!selection?.recordId) return;
|
||||
const records =
|
||||
@@ -456,45 +358,16 @@ export function PresentationEditor({
|
||||
() => setRecordDraft(undefined),
|
||||
[selection?.targetKey, selection?.recordId, selectedPage],
|
||||
);
|
||||
useEffect(() => {
|
||||
setPreviewConfig(config ?? {});
|
||||
setPreviewBrandValues({});
|
||||
}, [config]);
|
||||
const previewBrand = useMemo(
|
||||
() => ({ ...brand, ...previewBrandValues, config: previewConfig }),
|
||||
[brand, previewBrandValues, previewConfig],
|
||||
);
|
||||
const handleValuesChange = useCallback(
|
||||
(changed: PresentationValues, allValues: PresentationValues) => {
|
||||
setBrandDirty(true);
|
||||
const synchronized: PresentationValues = {
|
||||
...(form.getFieldsValue(true) as PresentationValues),
|
||||
...allValues,
|
||||
};
|
||||
for (const section of sections) {
|
||||
for (const field of section.fields) {
|
||||
const name = presentationFieldName(section.key, field.key);
|
||||
if (!Object.prototype.hasOwnProperty.call(changed, name)) continue;
|
||||
for (const peer of sections) {
|
||||
for (const item of peer.fields) {
|
||||
if (item.binding === field.binding)
|
||||
synchronized[presentationFieldName(peer.key, item.key)] = changed[name];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
form.setFieldsValue(synchronized);
|
||||
const next = applyBrandPreviewValues(
|
||||
brand as unknown as Record<string, unknown>,
|
||||
const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({
|
||||
brand,
|
||||
config,
|
||||
sections,
|
||||
synchronized,
|
||||
);
|
||||
setPreviewConfig((next.config as Record<string, unknown>) ?? {});
|
||||
setPreviewBrandValues(next);
|
||||
},
|
||||
[brand, config, sections, form],
|
||||
);
|
||||
form,
|
||||
onDirty: () => setBrandDirty(true),
|
||||
});
|
||||
const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection });
|
||||
useEffect(() => resetPreview(), [config, initialValues, resetPreview]);
|
||||
const previewConfig = previewBrand.config;
|
||||
const draftWorkspace = useMemo(() => {
|
||||
if (!previewWorkspace) return undefined;
|
||||
const next: RuntimeWorkspace = {
|
||||
@@ -521,14 +394,9 @@ export function PresentationEditor({
|
||||
};
|
||||
if (!recordDraft || !selectedRecord || !recordSection || recordDraft.id !== selectedRecord.id)
|
||||
return next;
|
||||
const values = recordDraft.values;
|
||||
const config = applyPresentationValues(selectedRecord.config, [recordSection], values);
|
||||
const standard = applyStandardEntityValues(
|
||||
selectedRecord as unknown as Record<string, unknown>,
|
||||
recordDraft.source,
|
||||
[recordSection],
|
||||
values,
|
||||
);
|
||||
const config = recordPreview?.config;
|
||||
const standard = recordPreview?.standard;
|
||||
if (!config || !standard) return next;
|
||||
if (recordDraft.source === "trust") {
|
||||
next.trustItems = next.trustItems.map((item) =>
|
||||
item.id === recordDraft.id
|
||||
@@ -550,21 +418,30 @@ export function PresentationEditor({
|
||||
item.id === recordDraft.id
|
||||
? {
|
||||
...item,
|
||||
name: typeof standard.name === "string" ? standard.name : item.name,
|
||||
name:
|
||||
(recordDraft.values[presentationFieldName(recordSection.key, "name")] as string) ||
|
||||
item.name,
|
||||
summary:
|
||||
typeof standard.summary === "string"
|
||||
? standard.summary
|
||||
: typeof standard.description === "string"
|
||||
? standard.description
|
||||
: item.summary,
|
||||
priceText: typeof standard.priceText === "string" ? standard.priceText : null,
|
||||
coverUrl: typeof standard.coverUrl === "string" ? standard.coverUrl : null,
|
||||
(recordDraft.values[
|
||||
presentationFieldName(recordSection.key, "summary")
|
||||
] as string) || item.summary,
|
||||
priceText:
|
||||
(recordDraft.values[
|
||||
presentationFieldName(recordSection.key, "priceText")
|
||||
] as string) || null,
|
||||
coverUrl:
|
||||
(recordDraft.values[
|
||||
presentationFieldName(recordSection.key, "coverUrl")
|
||||
] as string) || null,
|
||||
presentation: {
|
||||
...item.presentation,
|
||||
...config,
|
||||
...(config.presentation && typeof config.presentation === "object"
|
||||
? (config.presentation as Record<string, unknown>)
|
||||
: {}),
|
||||
...(typeof config.area === "string" ? { area: config.area } : {}),
|
||||
...(typeof config.series === "string" ? { series: config.series } : {}),
|
||||
...(typeof config.spaceType === "string" ? { spaceType: config.spaceType } : {}),
|
||||
heroImage:
|
||||
typeof config.detailHero === "string"
|
||||
? config.detailHero
|
||||
@@ -573,8 +450,10 @@ export function PresentationEditor({
|
||||
: null,
|
||||
details: {
|
||||
...item.presentation.details,
|
||||
...(config.details && typeof config.details === "object"
|
||||
? (config.details as Record<string, unknown>)
|
||||
...(config.details &&
|
||||
typeof config.details === "object" &&
|
||||
"background" in config.details
|
||||
? (config.details as RuntimeWorkspace["offerings"][number]["presentation"]["details"])
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
@@ -590,6 +469,7 @@ export function PresentationEditor({
|
||||
recordDraft,
|
||||
selectedRecord,
|
||||
recordSection,
|
||||
recordPreview,
|
||||
templateContent,
|
||||
inquiryDraft,
|
||||
inquiryRuntime,
|
||||
@@ -631,8 +511,7 @@ export function PresentationEditor({
|
||||
guardDraft(() => {
|
||||
setBrandDirty(false);
|
||||
form.setFieldsValue(initialValues);
|
||||
setPreviewConfig(config ?? {});
|
||||
setPreviewBrandValues({});
|
||||
resetPreview();
|
||||
setRecordDraft(undefined);
|
||||
setInquiryDraft(undefined);
|
||||
setActivePage(value);
|
||||
@@ -648,8 +527,7 @@ export function PresentationEditor({
|
||||
guardDraft(() => {
|
||||
setBrandDirty(false);
|
||||
form.setFieldsValue(initialValues);
|
||||
setPreviewConfig(config ?? {});
|
||||
setPreviewBrandValues({});
|
||||
resetPreview();
|
||||
setRecordDraft(undefined);
|
||||
setInquiryDraft(undefined);
|
||||
setActivePage(String(value));
|
||||
@@ -946,7 +824,7 @@ export function PresentationEditor({
|
||||
}
|
||||
: {})}
|
||||
>
|
||||
{renderField(field)}
|
||||
<TemplateFieldRenderer field={field} />
|
||||
</Form.Item>
|
||||
)}
|
||||
</Col>
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { TemplatePage as FoodTemplatePage } from "../../../../../packages/template-acheng-campus-food/taro/index.tsx";
|
||||
import { TemplatePage as EditorialTemplatePage } from "../../../../../packages/template-linjing-editorial/taro/index.tsx";
|
||||
import React from "react";
|
||||
import { Inquiry } from "../../../../taro/src/components/Inquiry.tsx";
|
||||
import { Records } from "../../../../taro/src/components/Records.tsx";
|
||||
import { Success } from "../../../../taro/src/components/Success.tsx";
|
||||
import { TemplateAssetContext } from "./taro-web-components.jsx";
|
||||
|
||||
const templateRenderers = import.meta.glob("../../../../../packages/template-*/taro/index.tsx", {
|
||||
eager: true,
|
||||
});
|
||||
|
||||
function pageContent({ workspace, page }) {
|
||||
if (page === "inquiry") return <Inquiry workspace={workspace} preview />;
|
||||
if (page === "records") return <Records workspace={workspace} preview />;
|
||||
@@ -13,28 +15,22 @@ function pageContent({ workspace, page }) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function FoodPreview(props) {
|
||||
return (
|
||||
<TemplateAssetContext.Provider value="acheng-campus-food">
|
||||
<FoodTemplatePage {...props}>{pageContent(props)}</FoodTemplatePage>
|
||||
</TemplateAssetContext.Provider>
|
||||
);
|
||||
}
|
||||
function EditorialPreview(props) {
|
||||
return (
|
||||
<TemplateAssetContext.Provider value="linjing-editorial">
|
||||
<EditorialTemplatePage {...props}>{pageContent(props)}</EditorialTemplatePage>
|
||||
</TemplateAssetContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveTemplateRenderer(workspace) {
|
||||
const config = workspace?.brand?.config;
|
||||
const key =
|
||||
config && typeof config === "object" && !Array.isArray(config)
|
||||
? config.visualTemplateKey
|
||||
: undefined;
|
||||
if (key === "acheng-campus-food") return FoodPreview;
|
||||
if (key === "linjing-editorial") return EditorialPreview;
|
||||
return null;
|
||||
if (typeof key !== "string") return null;
|
||||
const suffix = `/template-${key}/taro/index.tsx`;
|
||||
const entry = Object.entries(templateRenderers).find(([path]) => path.endsWith(suffix));
|
||||
const TemplatePage = entry?.[1]?.TemplatePage;
|
||||
if (!TemplatePage) return null;
|
||||
return function TemplatePreview(props) {
|
||||
return (
|
||||
<TemplateAssetContext.Provider value={key}>
|
||||
<TemplatePage {...props}>{pageContent(props)}</TemplatePage>
|
||||
</TemplateAssetContext.Provider>
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useMemo } from "react";
|
||||
import type { Offering, TrustContent } from "@personal-brand/api-client";
|
||||
import type { TemplateAdminSection } from "@personal-brand/api-client";
|
||||
import { applyPresentationValues, applyStandardEntityValues } from "./presentation-bindings.js";
|
||||
import type { PresentationValues } from "./presentation-bindings.js";
|
||||
|
||||
export interface RecordDraft {
|
||||
source: "offering" | "trust";
|
||||
id: string;
|
||||
values: PresentationValues;
|
||||
}
|
||||
|
||||
export function useRecordPreview({
|
||||
recordDraft,
|
||||
selectedRecord,
|
||||
recordSection,
|
||||
}: {
|
||||
recordDraft?: RecordDraft | undefined;
|
||||
selectedRecord?: Offering | TrustContent | undefined;
|
||||
recordSection?: TemplateAdminSection | undefined;
|
||||
}) {
|
||||
return useMemo(() => {
|
||||
if (!recordDraft || !selectedRecord || !recordSection) return undefined;
|
||||
const config = applyPresentationValues(
|
||||
selectedRecord.config,
|
||||
[recordSection],
|
||||
recordDraft.values,
|
||||
);
|
||||
return {
|
||||
config,
|
||||
standard: applyStandardEntityValues(
|
||||
selectedRecord as unknown as Record<string, unknown>,
|
||||
recordDraft.source,
|
||||
[recordSection],
|
||||
recordDraft.values,
|
||||
),
|
||||
};
|
||||
}, [recordDraft, selectedRecord, recordSection]);
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import { Form, message } from "antd";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import type { QueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type { FormInstance } from "antd";
|
||||
import type {
|
||||
AdminTemplateContent,
|
||||
BrandProfile,
|
||||
Offering,
|
||||
TemplateAdminSection,
|
||||
TrustContent,
|
||||
} from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import {
|
||||
applyBrandPreviewValues,
|
||||
applyPresentationValues,
|
||||
applyStandardBrandValues,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
type PresentationValues,
|
||||
} from "./presentation-bindings.js";
|
||||
|
||||
const standardBrandBindings = [
|
||||
"brand.name",
|
||||
"brand.tagline",
|
||||
"brand.avatarUrl",
|
||||
"brand.description",
|
||||
"brand.contactPhone",
|
||||
"brand.contactWechat",
|
||||
"brand.address",
|
||||
] as const;
|
||||
|
||||
export interface BrandPresentationFormState {
|
||||
form: FormInstance<PresentationValues>;
|
||||
initialValues: PresentationValues;
|
||||
}
|
||||
|
||||
export function useBrandPresentationSections(
|
||||
templateContent: AdminTemplateContent | null | undefined,
|
||||
): TemplateAdminSection[] {
|
||||
return useMemo(() => {
|
||||
const declaredTemplateFields = (templateContent?.templateFields ?? []).map((field) => ({
|
||||
...field,
|
||||
binding: field.binding ?? `brand.config.templateData.${field.key}`,
|
||||
}));
|
||||
return [
|
||||
...[...new Set(declaredTemplateFields.map((field) => field.page ?? "home"))].map((page) => ({
|
||||
key: `template-data:${page}`,
|
||||
title: "模板专属内容",
|
||||
description: "这些字段由当前小程序模板定义,保存后发布才会对外展示。",
|
||||
page,
|
||||
target: "brand" as const,
|
||||
fields: declaredTemplateFields.filter((field) => (field.page ?? "home") === page),
|
||||
})),
|
||||
...(templateContent?.admin.sections ?? []),
|
||||
].map((section) => ({
|
||||
...section,
|
||||
fields: section.fields.filter(
|
||||
(field) =>
|
||||
field.binding.startsWith("brand.config.") ||
|
||||
(standardBrandBindings as readonly string[]).includes(field.binding),
|
||||
),
|
||||
}));
|
||||
}, [templateContent]);
|
||||
}
|
||||
|
||||
export function useBrandPresentationForm({
|
||||
brand,
|
||||
config,
|
||||
sections,
|
||||
}: {
|
||||
brand: BrandProfile;
|
||||
config: Record<string, unknown> | null | undefined;
|
||||
sections: TemplateAdminSection[];
|
||||
}): BrandPresentationFormState {
|
||||
const [form] = Form.useForm<PresentationValues>();
|
||||
const initialValues = useMemo(() => {
|
||||
const values: PresentationValues = {};
|
||||
for (const section of sections) {
|
||||
for (const field of section.fields) {
|
||||
values[presentationFieldName(section.key, field.key)] = readPresentationValue(
|
||||
config,
|
||||
field.binding,
|
||||
field,
|
||||
brand as unknown as Record<string, unknown>,
|
||||
);
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}, [brand, config, sections]);
|
||||
|
||||
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
|
||||
return { form, initialValues };
|
||||
}
|
||||
|
||||
interface BrandSaveMutationOptions extends BrandPresentationFormState {
|
||||
brand: BrandProfile;
|
||||
config: Record<string, unknown> | null | undefined;
|
||||
sections: TemplateAdminSection[];
|
||||
queryClient: QueryClient;
|
||||
}
|
||||
|
||||
export function useBrandSaveMutation({
|
||||
brand,
|
||||
config,
|
||||
sections,
|
||||
queryClient,
|
||||
}: BrandSaveMutationOptions) {
|
||||
return useMutation({
|
||||
mutationFn: (values: PresentationValues) => {
|
||||
const nextConfig = applyPresentationValues(config, sections, values);
|
||||
const contentConfig = { ...nextConfig };
|
||||
delete contentConfig.visualTemplateKey;
|
||||
const standard = applyStandardBrandValues(
|
||||
brand as unknown as Record<string, unknown>,
|
||||
sections,
|
||||
values,
|
||||
);
|
||||
const changed = Object.fromEntries(
|
||||
Object.entries(standard).filter(
|
||||
([key, value]) =>
|
||||
key !== "config" && value !== (brand as unknown as Record<string, unknown>)[key],
|
||||
),
|
||||
);
|
||||
return createApiClient().updateAdminBrand({ ...changed, config: contentConfig });
|
||||
},
|
||||
onSuccess: () => {
|
||||
message.success("页面内容已保存为草稿,发布后小程序才会更新");
|
||||
window.dispatchEvent(new Event("template-preview-refresh"));
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["publication-readiness"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useBrandPreviewDraft({
|
||||
brand,
|
||||
config,
|
||||
sections,
|
||||
form,
|
||||
onDirty,
|
||||
}: {
|
||||
brand: BrandProfile;
|
||||
config: Record<string, unknown> | null | undefined;
|
||||
sections: TemplateAdminSection[];
|
||||
form: BrandPresentationFormState["form"];
|
||||
onDirty: () => void;
|
||||
}) {
|
||||
const [previewConfig, setPreviewConfig] = useState(config ?? {});
|
||||
const [previewBrandValues, setPreviewBrandValues] = useState<Record<string, unknown>>({});
|
||||
|
||||
useEffect(() => {
|
||||
setPreviewConfig(config ?? {});
|
||||
setPreviewBrandValues({});
|
||||
}, [config, form]);
|
||||
|
||||
const handleValuesChange = (changed: PresentationValues, allValues: PresentationValues) => {
|
||||
onDirty();
|
||||
const synchronized: PresentationValues = {
|
||||
...(form.getFieldsValue(true) as PresentationValues),
|
||||
...allValues,
|
||||
};
|
||||
for (const section of sections) {
|
||||
for (const field of section.fields) {
|
||||
const name = presentationFieldName(section.key, field.key);
|
||||
if (!Object.prototype.hasOwnProperty.call(changed, name)) continue;
|
||||
for (const peer of sections) {
|
||||
for (const item of peer.fields) {
|
||||
if (item.binding === field.binding)
|
||||
synchronized[presentationFieldName(peer.key, item.key)] = changed[name];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
form.setFieldsValue(synchronized);
|
||||
const next = applyBrandPreviewValues(
|
||||
brand as unknown as Record<string, unknown>,
|
||||
config,
|
||||
sections,
|
||||
synchronized,
|
||||
);
|
||||
setPreviewConfig((next.config as Record<string, unknown>) ?? {});
|
||||
setPreviewBrandValues(next);
|
||||
};
|
||||
|
||||
const previewBrand = useMemo(
|
||||
() => ({ ...brand, ...previewBrandValues, config: previewConfig }),
|
||||
[brand, previewBrandValues, previewConfig],
|
||||
);
|
||||
|
||||
const resetPreview = useCallback(() => {
|
||||
setPreviewConfig(config ?? {});
|
||||
setPreviewBrandValues({});
|
||||
}, [config]);
|
||||
|
||||
return {
|
||||
previewBrand,
|
||||
handleValuesChange,
|
||||
resetPreview,
|
||||
};
|
||||
}
|
||||
|
||||
export function usePresentationRecordQueries(
|
||||
source: "offering" | "trust" | undefined,
|
||||
recordId: string | undefined,
|
||||
) {
|
||||
const offeringsQuery = useQuery({
|
||||
queryKey: ["admin-offerings"],
|
||||
queryFn: () => createApiClient().listAdminOfferings(),
|
||||
enabled: source === "offering",
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
const trustQuery = useQuery({
|
||||
queryKey: ["trust-content"],
|
||||
queryFn: () => createApiClient().listAdminTrustContent(),
|
||||
enabled: source === "trust",
|
||||
});
|
||||
const selectedRecord =
|
||||
source === "offering"
|
||||
? offeringsQuery.data?.find((item: Offering) => item.id === recordId)
|
||||
: source === "trust"
|
||||
? trustQuery.data?.find((item: TrustContent) => item.id === recordId)
|
||||
: undefined;
|
||||
return { offeringsQuery, trustQuery, selectedRecord };
|
||||
}
|
||||
@@ -1,148 +1,34 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Alert, Button, Card, Form, Input, Select, Table, Tag, message } from "antd";
|
||||
import type { CapabilityInstallation } from "@personal-brand/api-client";
|
||||
import { Card, Col, Empty, Row, Typography } from "antd";
|
||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||
import { QueryState } from "../../components/QueryState.js";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
|
||||
const statusLabels = { enabled: "已启用", disabled: "已停用", degraded: "降级" } as const;
|
||||
import { CapabilityCard } from "./components/CapabilityCard.js";
|
||||
import { useCapabilityQuery } from "./hooks/useCapabilityQueries.js";
|
||||
|
||||
export function CapabilitiesPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const query = useQuery({
|
||||
queryKey: ["admin", "capabilities"],
|
||||
queryFn: () => createApiClient().listAdminCapabilities(),
|
||||
});
|
||||
const mutation = useMutation({
|
||||
mutationFn: ({
|
||||
key,
|
||||
values,
|
||||
}: {
|
||||
key: string;
|
||||
values: {
|
||||
capabilityVersion: string;
|
||||
status: CapabilityInstallation["status"];
|
||||
configText?: string;
|
||||
};
|
||||
}) =>
|
||||
createApiClient().updateAdminCapability(key, {
|
||||
capabilityVersion: values.capabilityVersion,
|
||||
status: values.status,
|
||||
config: values.configText ? (JSON.parse(values.configText) as Record<string, unknown>) : {},
|
||||
}),
|
||||
onSuccess: () => {
|
||||
message.success("能力配置已更新");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin", "capabilities"] });
|
||||
},
|
||||
onError: (error) => message.error(error instanceof Error ? error.message : "更新失败"),
|
||||
});
|
||||
const sampleMutation = useMutation({
|
||||
mutationFn: () => createApiClient().importAdminSampleContent(),
|
||||
onSuccess: (result) => message.success(`已导入 ${result.counts.offerings} 项示例业务`),
|
||||
onError: (error) => message.error(error instanceof Error ? error.message : "导入失败"),
|
||||
});
|
||||
if (query.isLoading) return <QueryState loading />;
|
||||
if (query.isError) return <QueryState error={query.error} />;
|
||||
const items = query.data ?? [];
|
||||
return (
|
||||
<div>
|
||||
<AdminPageHeader title="能力插件" description="管理当前模板声明的业务能力及其运行状态。" />
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
message="能力状态会影响公开 Runtime Workspace;停用不会删除历史数据。"
|
||||
style={{ marginBottom: 16 }}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => sampleMutation.mutate()}
|
||||
loading={sampleMutation.isPending}
|
||||
style={{ marginBottom: 16 }}
|
||||
>
|
||||
导入门窗示例内容
|
||||
</Button>
|
||||
<Table
|
||||
rowKey="capabilityKey"
|
||||
dataSource={items}
|
||||
locale={{ emptyText: "当前还没有品牌级能力覆盖,系统将使用模板默认能力。" }}
|
||||
columns={[
|
||||
{ title: "能力", dataIndex: "capabilityKey" },
|
||||
{
|
||||
title: "来源",
|
||||
dataIndex: "source",
|
||||
render: (value: CapabilityInstallation["source"]) => (
|
||||
<Tag>{value === "brand" ? "品牌覆盖" : "模板默认"}</Tag>
|
||||
),
|
||||
},
|
||||
{ title: "版本", dataIndex: "capabilityVersion" },
|
||||
{
|
||||
title: "状态",
|
||||
dataIndex: "status",
|
||||
render: (value: CapabilityInstallation["status"]) => (
|
||||
<Tag
|
||||
color={value === "enabled" ? "green" : value === "degraded" ? "orange" : "default"}
|
||||
>
|
||||
{statusLabels[value]}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
render: (_: unknown, record: CapabilityInstallation) => (
|
||||
<CapabilityEditor
|
||||
record={record}
|
||||
loading={mutation.isPending}
|
||||
onSubmit={(values) => mutation.mutate({ key: record.capabilityKey, values })}
|
||||
/>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const query = useCapabilityQuery();
|
||||
|
||||
function CapabilityEditor({
|
||||
record,
|
||||
loading,
|
||||
onSubmit,
|
||||
}: {
|
||||
record: CapabilityInstallation;
|
||||
loading: boolean;
|
||||
onSubmit: (values: {
|
||||
capabilityVersion: string;
|
||||
status: CapabilityInstallation["status"];
|
||||
configText?: string;
|
||||
}) => void;
|
||||
}) {
|
||||
const [form] = Form.useForm();
|
||||
return (
|
||||
<Card size="small" style={{ maxWidth: 420 }}>
|
||||
<Form
|
||||
form={form}
|
||||
layout="inline"
|
||||
initialValues={{
|
||||
capabilityVersion: record.capabilityVersion,
|
||||
status: record.status,
|
||||
configText: record.config ? JSON.stringify(record.config) : "",
|
||||
}}
|
||||
onFinish={onSubmit}
|
||||
>
|
||||
<Form.Item name="capabilityVersion" rules={[{ required: true, message: "请输入版本" }]}>
|
||||
<Input placeholder="版本" style={{ width: 100 }} />
|
||||
</Form.Item>
|
||||
<Form.Item name="status">
|
||||
<Select
|
||||
options={Object.entries(statusLabels).map(([value, label]) => ({ value, label }))}
|
||||
style={{ width: 100 }}
|
||||
<QueryState loading={query.isLoading} error={query.error} onRetry={() => void query.refetch()}>
|
||||
<AdminPageHeader
|
||||
title="能力管理"
|
||||
description="以经营者视角调整模板能力的开关与展示设置;保存后进入草稿,发布后生效。"
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="configText">
|
||||
<Input placeholder="JSON 配置(可选)" style={{ width: 180 }} />
|
||||
</Form.Item>
|
||||
<Button type="primary" htmlType="submit" loading={loading}>
|
||||
保存
|
||||
</Button>
|
||||
</Form>
|
||||
{query.data?.length ? (
|
||||
<Row gutter={[16, 16]}>
|
||||
{query.data.map((capability) => (
|
||||
<Col key={capability.capabilityKey} xs={24} lg={12}>
|
||||
<CapabilityCard capability={capability} />
|
||||
</Col>
|
||||
))}
|
||||
</Row>
|
||||
) : (
|
||||
<Card>
|
||||
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前模板没有可配置能力。" />
|
||||
</Card>
|
||||
)}
|
||||
<Typography.Text type="secondary" style={{ display: "block", marginTop: 16 }}>
|
||||
技术信息仅用于排查问题,不作为运营判断依据。
|
||||
</Typography.Text>
|
||||
</QueryState>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import { Alert, Button, Card, Input, Switch, Tag, Typography } from "antd";
|
||||
import { useState } from "react";
|
||||
import { useCapabilityMutation } from "../hooks/useCapabilityQueries.js";
|
||||
import type { AdminCapability, CapabilityStatus } from "../types.js";
|
||||
import { CapabilityStatusControl, CapabilityStatusTag } from "./CapabilityStatusControl.js";
|
||||
|
||||
const sourceLabels = {
|
||||
brand: "品牌覆盖",
|
||||
template: "模板默认",
|
||||
} as const;
|
||||
|
||||
const disablePolicyLabels = {
|
||||
allowed: "该能力允许停用,保存后进入草稿。",
|
||||
disabled: "该能力为模板必需项,保存后进入草稿。",
|
||||
} as const;
|
||||
|
||||
const updatedTimeFormatter = new Intl.DateTimeFormat("zh-CN", {
|
||||
dateStyle: "short",
|
||||
timeStyle: "short",
|
||||
});
|
||||
|
||||
function readTextValue(value: unknown): string {
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
function readSwitchValue(value: unknown): boolean {
|
||||
return value === true;
|
||||
}
|
||||
|
||||
export function CapabilityCard({ capability }: { capability: AdminCapability }) {
|
||||
const [status, setStatus] = useState<CapabilityStatus>(capability.status);
|
||||
const [config, setConfig] = useState<Record<string, unknown>>(capability.config);
|
||||
const mutation = useCapabilityMutation();
|
||||
|
||||
const save = async () => {
|
||||
await mutation.mutateAsync({
|
||||
key: capability.capabilityKey,
|
||||
status,
|
||||
config,
|
||||
});
|
||||
};
|
||||
|
||||
const updateConfigValue = (key: string, value: unknown) =>
|
||||
setConfig((current) => ({ ...current, [key]: value }));
|
||||
|
||||
return (
|
||||
<Card
|
||||
title={
|
||||
<span>
|
||||
{capability.displayName ?? "未命名能力"}
|
||||
<Tag style={{ marginLeft: 8 }}>{sourceLabels[capability.source]}</Tag>
|
||||
<CapabilityStatusTag status={status} />
|
||||
</span>
|
||||
}
|
||||
extra={
|
||||
<Button type="primary" loading={mutation.isPending} onClick={() => void save()}>
|
||||
保存草稿
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{mutation.isError ? (
|
||||
<Alert
|
||||
type="error"
|
||||
showIcon
|
||||
message="保存失败,已保留当前输入"
|
||||
description={
|
||||
mutation.error instanceof Error ? mutation.error.message : "请检查网络或稍后重试"
|
||||
}
|
||||
style={{ marginBottom: 16 }}
|
||||
/>
|
||||
) : null}
|
||||
{capability.description ? (
|
||||
<Typography.Paragraph>{capability.description}</Typography.Paragraph>
|
||||
) : null}
|
||||
{capability.impact ? (
|
||||
<Typography.Paragraph type="secondary">影响:{capability.impact}</Typography.Paragraph>
|
||||
) : null}
|
||||
<div style={{ display: "grid", gap: 12 }}>
|
||||
<div>
|
||||
<Typography.Text strong>运行状态</Typography.Text>
|
||||
<div style={{ marginTop: 8 }}>
|
||||
<CapabilityStatusControl
|
||||
status={status}
|
||||
onChange={setStatus}
|
||||
disabled={mutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
<Typography.Paragraph type="secondary" style={{ marginBottom: 0 }}>
|
||||
保存后进入草稿,发布后生效。
|
||||
</Typography.Paragraph>
|
||||
{status === "disabled" && capability.disablePolicy ? (
|
||||
<Typography.Paragraph type="warning" style={{ marginBottom: 0 }}>
|
||||
{disablePolicyLabels[capability.disablePolicy]}
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
</div>
|
||||
{capability.configFields?.length ? (
|
||||
<div>
|
||||
<Typography.Text strong>能力设置</Typography.Text>
|
||||
<div style={{ display: "grid", gap: 12, marginTop: 8 }}>
|
||||
{capability.configFields.map((field) => (
|
||||
<div key={field.key}>
|
||||
<Typography.Text>{field.label}</Typography.Text>
|
||||
{field.input === "switch" ? (
|
||||
<div>
|
||||
<Switch
|
||||
checked={readSwitchValue(config[field.key])}
|
||||
disabled={mutation.isPending}
|
||||
onChange={(checked) => updateConfigValue(field.key, checked)}
|
||||
/>
|
||||
</div>
|
||||
) : field.input === "textarea" ? (
|
||||
<Input.TextArea
|
||||
rows={3}
|
||||
value={readTextValue(config[field.key])}
|
||||
disabled={mutation.isPending}
|
||||
onChange={(event) => updateConfigValue(field.key, event.target.value)}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
value={readTextValue(config[field.key])}
|
||||
disabled={mutation.isPending}
|
||||
onChange={(event) => updateConfigValue(field.key, event.target.value)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<Typography.Text type="secondary">
|
||||
{capability.source === "template"
|
||||
? "当前使用模板默认设置;修改后保存会创建品牌覆盖。"
|
||||
: "当前已创建品牌覆盖;修改后保存会更新草稿。"}
|
||||
{capability.updatedAt
|
||||
? ` 最近更新:${updatedTimeFormatter.format(new Date(capability.updatedAt))}`
|
||||
: ""}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Segmented, Space, Switch, Tag, Typography } from "antd";
|
||||
import type { CapabilityStatus } from "../types.js";
|
||||
|
||||
const statusLabels: Record<CapabilityStatus, string> = {
|
||||
enabled: "启用",
|
||||
disabled: "停用",
|
||||
degraded: "降级",
|
||||
};
|
||||
|
||||
const statusColors: Record<CapabilityStatus, string> = {
|
||||
enabled: "green",
|
||||
disabled: "default",
|
||||
degraded: "orange",
|
||||
};
|
||||
|
||||
export function CapabilityStatusTag({ status }: { status: CapabilityStatus }) {
|
||||
return <Tag color={statusColors[status]}>{statusLabels[status]}</Tag>;
|
||||
}
|
||||
|
||||
export function CapabilityStatusControl({
|
||||
status,
|
||||
onChange,
|
||||
disabled,
|
||||
}: {
|
||||
status: CapabilityStatus;
|
||||
onChange: (status: CapabilityStatus) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const isDisabled = disabled === true;
|
||||
if (status === "degraded")
|
||||
return (
|
||||
<Segmented
|
||||
value={status}
|
||||
disabled={isDisabled}
|
||||
options={[
|
||||
{ value: "degraded", label: "降级" },
|
||||
{ value: "enabled", label: "启用" },
|
||||
{ value: "disabled", label: "停用" },
|
||||
]}
|
||||
onChange={(value) => onChange(value as CapabilityStatus)}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<Space>
|
||||
<Switch
|
||||
checked={status === "enabled"}
|
||||
disabled={isDisabled}
|
||||
onChange={(checked) => onChange(checked ? "enabled" : "disabled")}
|
||||
/>
|
||||
<Typography.Text type={status === "enabled" ? "success" : "secondary"}>
|
||||
{statusLabels[status]}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { message } from "antd";
|
||||
import { createApiClient } from "../../../lib/api.js";
|
||||
import { readAdminCapability } from "../types.js";
|
||||
import type { CapabilityValues } from "../types.js";
|
||||
|
||||
export const capabilitiesQueryKey = ["admin", "capabilities"] as const;
|
||||
|
||||
export function useCapabilityQuery() {
|
||||
return useQuery({
|
||||
queryKey: capabilitiesQueryKey,
|
||||
queryFn: async () => {
|
||||
const response = await createApiClient().listAdminCapabilities();
|
||||
return response.map(readAdminCapability);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useCapabilityMutation() {
|
||||
const queryClient = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({ key, ...values }: { key: string } & CapabilityValues) =>
|
||||
createApiClient().updateAdminCapability(key, {
|
||||
...values,
|
||||
}),
|
||||
onSuccess: () => {
|
||||
message.success("能力已保存,进入草稿;发布后生效");
|
||||
void queryClient.invalidateQueries({ queryKey: capabilitiesQueryKey });
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { CapabilityInstallation } from "@personal-brand/api-client";
|
||||
|
||||
export type CapabilityStatus = CapabilityInstallation["status"];
|
||||
|
||||
export type CapabilitySource = NonNullable<CapabilityInstallation["source"]>;
|
||||
|
||||
export interface CapabilityConfigField {
|
||||
key: string;
|
||||
label: string;
|
||||
input: string;
|
||||
required: boolean;
|
||||
}
|
||||
|
||||
export interface AdminCapability {
|
||||
capabilityKey: string;
|
||||
capabilityVersion: string;
|
||||
status: CapabilityStatus;
|
||||
config: Record<string, unknown>;
|
||||
source: CapabilitySource;
|
||||
updatedAt?: string | null;
|
||||
displayName?: string | undefined;
|
||||
description?: string | undefined;
|
||||
impact?: string | undefined;
|
||||
optional?: boolean | undefined;
|
||||
disablePolicy?: "allowed" | "disabled" | undefined;
|
||||
configFields?: CapabilityConfigField[] | undefined;
|
||||
}
|
||||
|
||||
export interface CapabilityValues {
|
||||
status: CapabilityStatus;
|
||||
config: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function isCapabilitySource(value: unknown): value is CapabilitySource {
|
||||
return value === "brand" || value === "template";
|
||||
}
|
||||
|
||||
export function readAdminCapability(value: CapabilityInstallation): AdminCapability {
|
||||
const { config, source, ...rest } = value;
|
||||
return {
|
||||
...rest,
|
||||
config: config ?? {},
|
||||
source: isCapabilitySource(source) ? source : "template",
|
||||
displayName: readOptionalString(value.displayName),
|
||||
description: readOptionalString(value.description),
|
||||
impact: readOptionalString(value.impact),
|
||||
optional: typeof value.optional === "boolean" ? value.optional : undefined,
|
||||
disablePolicy:
|
||||
value.disablePolicy === "allowed" || value.disablePolicy === "disabled"
|
||||
? value.disablePolicy
|
||||
: undefined,
|
||||
configFields: Array.isArray(value.configFields)
|
||||
? value.configFields.filter(isCapabilityConfigField)
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function readOptionalString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim() ? value : undefined;
|
||||
}
|
||||
|
||||
function isCapabilityConfigField(value: {
|
||||
key: string;
|
||||
label: string;
|
||||
input: string;
|
||||
required: boolean;
|
||||
}): value is CapabilityConfigField {
|
||||
const field = value;
|
||||
return (
|
||||
typeof field.key === "string" &&
|
||||
field.key.length > 0 &&
|
||||
typeof field.label === "string" &&
|
||||
field.label.length > 0 &&
|
||||
(field.input === "text" || field.input === "textarea" || field.input === "switch")
|
||||
);
|
||||
}
|
||||
@@ -147,14 +147,16 @@ export function PublicationPage({ canManageTemplate }: { canManageTemplate: bool
|
||||
workspace.data?.installations[0]?.templateKey ??
|
||||
workspace.data?.brand?.templateKey ??
|
||||
brand.data?.templateKey ??
|
||||
"personal";
|
||||
const visuals = (catalog.data?.visuals ?? []).filter((item) =>
|
||||
item.supportedIndustryTemplates.includes(industryKey),
|
||||
catalog.data?.industries[0]?.key ??
|
||||
null;
|
||||
const visuals = (catalog.data?.visuals ?? []).filter(
|
||||
(item) =>
|
||||
typeof industryKey === "string" && item.supportedIndustryTemplates.includes(industryKey),
|
||||
);
|
||||
const visualKey =
|
||||
typeof brand.data?.config?.visualTemplateKey === "string"
|
||||
? brand.data.config.visualTemplateKey
|
||||
: "linjing-editorial";
|
||||
: (visuals[0]?.key ?? null);
|
||||
const currentRelease = releases.data?.find((item) => item.status === "published");
|
||||
const publishedHistory = (releases.data ?? []).filter(
|
||||
(item) => item.status === "published" || item.status === "superseded",
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import { Alert, Button, Form, Input, Modal, Segmented, Select, Typography } from "antd";
|
||||
import type {
|
||||
Offering,
|
||||
RuntimeWorkspace,
|
||||
TemplateAdminField,
|
||||
TemplateAdminSection,
|
||||
} from "@personal-brand/api-client";
|
||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
||||
import { RecordContentFields } from "../../components/RecordContentEditor.js";
|
||||
import { ComponentTemplatePreview } from "../brand/ComponentTemplatePreview.js";
|
||||
import type { PreviewTarget } from "../brand/preview-selection.js";
|
||||
import type { FormInstance } from "antd";
|
||||
import "./ServicesPage.css";
|
||||
|
||||
type OfferingEditorModalProps = {
|
||||
open: boolean;
|
||||
editingOffering: Offering | null;
|
||||
form: FormInstance<Record<string, unknown>>;
|
||||
previewPage: "offerings" | "detail";
|
||||
previewWorkspace: RuntimeWorkspace | undefined;
|
||||
previewTargets: Record<"offerings" | "detail", PreviewTarget[]>;
|
||||
activeTemplateFields: TemplateAdminField[];
|
||||
templateFieldSection: TemplateAdminSection;
|
||||
hasTemplateDetailCopy: boolean;
|
||||
listTarget: PreviewTarget;
|
||||
detailTarget: PreviewTarget | undefined;
|
||||
saving: boolean;
|
||||
onClose: () => void;
|
||||
onPreviewPageChange: (page: "offerings" | "detail") => void;
|
||||
onValuesChange: (values: Record<string, unknown>) => void;
|
||||
onFinish: (values: Record<string, unknown>) => void;
|
||||
onEditInBrand: () => void;
|
||||
};
|
||||
|
||||
export function OfferingEditorModal({
|
||||
open,
|
||||
editingOffering,
|
||||
form,
|
||||
previewPage,
|
||||
previewWorkspace,
|
||||
previewTargets,
|
||||
activeTemplateFields,
|
||||
templateFieldSection,
|
||||
hasTemplateDetailCopy,
|
||||
listTarget,
|
||||
detailTarget,
|
||||
saving,
|
||||
onClose,
|
||||
onPreviewPageChange,
|
||||
onValuesChange,
|
||||
onFinish,
|
||||
onEditInBrand,
|
||||
}: OfferingEditorModalProps) {
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={editingOffering ? "编辑业务提供项" : "新增业务提供项"}
|
||||
width={960}
|
||||
onCancel={onClose}
|
||||
onOk={() => form.submit()}
|
||||
confirmLoading={saving}
|
||||
>
|
||||
<div className="service-offering-editor">
|
||||
{editingOffering && previewWorkspace ? (
|
||||
<div className="service-offering-editor__preview">
|
||||
<Segmented
|
||||
className="service-offering-editor__view"
|
||||
value={previewPage}
|
||||
options={[
|
||||
{ value: "offerings", label: "列表卡片" },
|
||||
{ value: "detail", label: "详情内容" },
|
||||
]}
|
||||
onChange={onPreviewPageChange}
|
||||
/>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
message={previewPage === "offerings" ? "正在核对列表展示" : "正在核对详情展示"}
|
||||
description={
|
||||
previewPage === "offerings"
|
||||
? "右侧「列表展示」字段修改后,会实时反映在当前卡片。"
|
||||
: "右侧「详情展示」字段修改后,会实时反映在当前详情内容。"
|
||||
}
|
||||
/>
|
||||
<ComponentTemplatePreview
|
||||
workspace={previewWorkspace}
|
||||
page={previewPage}
|
||||
offeringId={editingOffering.id}
|
||||
targets={previewTargets[previewPage]}
|
||||
selection={{
|
||||
targetKey: previewPage === "offerings" ? listTarget.key : (detailTarget?.key ?? ""),
|
||||
recordId: editingOffering.id,
|
||||
}}
|
||||
onTargetSelected={() => {}}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<Form
|
||||
className="service-offering-editor__form"
|
||||
form={form}
|
||||
layout="vertical"
|
||||
onValuesChange={(_, allValues) => onValuesChange(allValues)}
|
||||
onFinish={onFinish}
|
||||
>
|
||||
<div className="service-offering-editor__form-scroll">
|
||||
<Typography.Title level={5}>基础信息</Typography.Title>
|
||||
<Form.Item name="kind" label="类型" rules={[{ required: true }]}>
|
||||
<Select
|
||||
options={[
|
||||
{ value: "service", label: "服务" },
|
||||
{ value: "product", label: "定制产品" },
|
||||
{ value: "package", label: "套餐" },
|
||||
{ value: "subscription", label: "订阅" },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="summary" label="一句话说明">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
{!hasTemplateDetailCopy ? (
|
||||
<Form.Item name="description" label="详细介绍">
|
||||
<Input.TextArea rows={5} />
|
||||
</Form.Item>
|
||||
) : null}
|
||||
<Form.Item name="priceText" label="价格展示">
|
||||
<Input placeholder="例如:按现场评估报价 / ¥ 2,800 起" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="coverUrl"
|
||||
label="封面图片地址"
|
||||
help="点击上传,或粘贴服务/产品封面图片地址。"
|
||||
>
|
||||
<ImageUrlField placeholder="粘贴服务或产品封面图片地址" scope="offering" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="sortOrder"
|
||||
label="展示顺序"
|
||||
help="数字越小越靠前,不确定时填写 0。"
|
||||
rules={[{ type: "number", min: 0, max: 9999 }]}
|
||||
>
|
||||
<Input type="number" min={0} max={9999} />
|
||||
</Form.Item>
|
||||
<Form.Item name="isEnabled" label="公开状态">
|
||||
<Select
|
||||
options={[
|
||||
{ value: true, label: "已启用" },
|
||||
{ value: false, label: "已停用" },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
{activeTemplateFields.length ? (
|
||||
<div>
|
||||
<Typography.Title level={5}>
|
||||
{previewPage === "offerings" ? "列表展示字段" : "详情展示字段"}
|
||||
</Typography.Title>
|
||||
<Typography.Paragraph type="secondary">
|
||||
这里只编辑左侧预览对应的字段;它们与小程序页面编辑的是同一份业务数据。
|
||||
</Typography.Paragraph>
|
||||
<RecordContentFields
|
||||
section={{
|
||||
...templateFieldSection,
|
||||
fields: activeTemplateFields,
|
||||
}}
|
||||
sectionKey="offering"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{editingOffering ? (
|
||||
<Button htmlType="button" onClick={onEditInBrand}>
|
||||
在小程序页面编辑
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</Form>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { Button, Popconfirm, Space, Table, Tag, Typography } from "antd";
|
||||
import type { Offering } from "@personal-brand/api-client";
|
||||
import { MutationError } from "../../components/QueryState.js";
|
||||
import type { useOfferingMutations } from "./use-offering-data.js";
|
||||
|
||||
type OfferingsTableProps = {
|
||||
pageLabel: string;
|
||||
detailSectionTitles: string[];
|
||||
items: Offering[];
|
||||
loading: boolean;
|
||||
saveError: unknown;
|
||||
toggleOffering: ReturnType<typeof useOfferingMutations>["toggleOffering"];
|
||||
deleteOffering: ReturnType<typeof useOfferingMutations>["deleteOffering"];
|
||||
onEdit: (item: Offering) => void;
|
||||
};
|
||||
|
||||
const offeringKindLabels: Record<string, string> = {
|
||||
service: "服务",
|
||||
product: "定制产品",
|
||||
package: "套餐",
|
||||
subscription: "订阅",
|
||||
};
|
||||
|
||||
export function OfferingsTable({
|
||||
pageLabel,
|
||||
detailSectionTitles,
|
||||
items,
|
||||
loading,
|
||||
saveError,
|
||||
toggleOffering,
|
||||
deleteOffering,
|
||||
onEdit,
|
||||
}: OfferingsTableProps) {
|
||||
const columns = [
|
||||
{ title: "名称", dataIndex: "name" },
|
||||
{
|
||||
title: "业务类型",
|
||||
dataIndex: "kind",
|
||||
render: (value: unknown) => <Tag>{offeringKindLabels[String(value)] ?? String(value)}</Tag>,
|
||||
},
|
||||
{ title: "价格", dataIndex: "priceText" },
|
||||
{
|
||||
title: "状态",
|
||||
dataIndex: "isEnabled",
|
||||
render: (value: boolean) => (value ? "已启用" : "已停用"),
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
render: (_: unknown, item: Offering) => (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => onEdit(item)}>
|
||||
编辑详情
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
loading={toggleOffering.isPending && toggleOffering.variables?.id === item.id}
|
||||
onClick={() => toggleOffering.mutate({ id: item.id, isEnabled: !item.isEnabled })}
|
||||
>
|
||||
{item.isEnabled ? "禁用" : "启用"}
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="确认删除这项业务提供项?"
|
||||
description="如果它已经关联咨询表单,系统会阻止删除。"
|
||||
onConfirm={() => deleteOffering.mutate(item.id)}
|
||||
okText="删除"
|
||||
cancelText="取消"
|
||||
>
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
loading={deleteOffering.isPending && deleteOffering.variables === item.id}
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<section aria-label="业务提供项列表">
|
||||
<Space wrap style={{ marginBottom: 16 }}>
|
||||
<Typography.Title level={5} style={{ margin: 0 }}>
|
||||
{pageLabel}中的内容
|
||||
</Typography.Title>
|
||||
<Tag color="blue">已启用的项目会公开展示</Tag>
|
||||
</Space>
|
||||
{detailSectionTitles.length ? (
|
||||
<Typography.Paragraph type="secondary">
|
||||
编辑单项详情时,附加字段将用于:
|
||||
{detailSectionTitles.join("、")}
|
||||
。列表中的名称、说明、价格和封面也会显示在业务展示页。
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
<Table
|
||||
scroll={{ x: 760 }}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
dataSource={items}
|
||||
columns={columns}
|
||||
/>
|
||||
{items.length === 0 && (
|
||||
<Typography.Paragraph type="secondary">
|
||||
还没有公开业务提供项。创建后,小程序服务页会优先读取这些内容。
|
||||
</Typography.Paragraph>
|
||||
)}
|
||||
<MutationError error={saveError} />
|
||||
<MutationError error={toggleOffering.error} />
|
||||
<MutationError error={deleteOffering.error} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -16,13 +16,21 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.service-offering-editor__preview > * {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.service-offering-editor__view {
|
||||
align-self: flex-start;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.service-offering-editor__preview > .component-template-preview-shell {
|
||||
flex: 1;
|
||||
flex: 1 1 0;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.service-offering-editor__preview .component-template-preview {
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
@@ -30,14 +38,35 @@
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: 72vh;
|
||||
overflow-y: auto;
|
||||
padding-right: 4px;
|
||||
}
|
||||
|
||||
.service-offering-editor__form-scroll {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
flex: none;
|
||||
max-height: 66vh;
|
||||
overflow-y: auto;
|
||||
padding: 20px 16px 24px;
|
||||
border-radius: 12px;
|
||||
background: #f8fafc;
|
||||
border: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.service-offering-editor__form-scroll > .ant-typography:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.service-offering-editor__form-scroll .ant-form-item {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.service-offering-editor__form-scroll .ant-typography h5.ant-typography {
|
||||
margin: 28px 0 4px;
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.service-offering-editor__form-scroll > .ant-typography-secondary {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.service-offering-editor__preview .ant-alert {
|
||||
|
||||
@@ -1,128 +1,46 @@
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Form,
|
||||
Input,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Segmented,
|
||||
Select,
|
||||
Space,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
message,
|
||||
} from "antd";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type {
|
||||
Offering,
|
||||
RuntimeWorkspace,
|
||||
TemplateAdminField,
|
||||
TemplateAdminSection,
|
||||
} from "@personal-brand/api-client";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||
import { ImageUrlField } from "../../components/ImageUrlField.js";
|
||||
import { RecordContentFields } from "../../components/RecordContentEditor.js";
|
||||
import { ComponentTemplatePreview } from "../brand/ComponentTemplatePreview.js";
|
||||
import type { PreviewTarget } from "../brand/preview-selection.js";
|
||||
import {
|
||||
applyPresentationValues,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
} from "../brand/presentation-bindings.js";
|
||||
import { MutationError, QueryState } from "../../components/QueryState.js";
|
||||
import { Button } from "antd";
|
||||
import type { Offering, TemplateAdminField } from "@personal-brand/api-client";
|
||||
import { useMemo } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import "./ServicesPage.css";
|
||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||
import { QueryState } from "../../components/QueryState.js";
|
||||
import { OfferingEditorModal } from "./OfferingEditorModal.js";
|
||||
import { OfferingsTable } from "./OfferingsTable.js";
|
||||
import { detailPageLabel, hasTemplateDetailCopy, offeringPageLabel } from "./offering-model.js";
|
||||
import { buildOfferingPreviewWorkspace, previewTargetsByPage } from "./offering-preview.js";
|
||||
import { useOfferingEditor } from "./use-offering-editor.js";
|
||||
import { useOfferingMutations, useOfferingQueries } from "./use-offering-data.js";
|
||||
|
||||
type PreviewPage = "offerings" | "detail";
|
||||
|
||||
export function ServicesPage() {
|
||||
const navigate = useNavigate();
|
||||
const client = createApiClient();
|
||||
const queryClient = useQueryClient();
|
||||
const [offeringForm] = Form.useForm();
|
||||
const [offeringOpen, setOfferingOpen] = useState(false);
|
||||
const [editingOffering, setEditingOffering] = useState<Offering | null>(null);
|
||||
const [previewPage, setPreviewPage] = useState<"offerings" | "detail">("detail");
|
||||
const listFieldsRef = useRef<HTMLDivElement | null>(null);
|
||||
const detailFieldsRef = useRef<HTMLDivElement | null>(null);
|
||||
const formScrollRef = useRef<HTMLDivElement | null>(null);
|
||||
const offerings = useQuery({
|
||||
queryKey: ["admin-offerings"],
|
||||
queryFn: () => client.listAdminOfferings(),
|
||||
const { offerings, workspace, previewWorkspace, templateFields, retry } = useOfferingQueries();
|
||||
const editor = useOfferingEditor(templateFields);
|
||||
const mutations = useOfferingMutations({
|
||||
editingOffering: editor.editingOffering,
|
||||
templateFields,
|
||||
onSuccess: () => {
|
||||
editor.closeOffering();
|
||||
editor.offeringForm.resetFields();
|
||||
},
|
||||
});
|
||||
const workspace = useQuery({
|
||||
queryKey: ["admin-workspace-offering-fields"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
});
|
||||
const previewWorkspace = useQuery({
|
||||
queryKey: ["admin-preview-workspace-services"],
|
||||
queryFn: () => client.getAdminPreviewWorkspace(),
|
||||
});
|
||||
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 templateFieldSection = useMemo<TemplateAdminSection>(
|
||||
() => ({
|
||||
key: "offering",
|
||||
title: "模板内容",
|
||||
description: "",
|
||||
page: "detail",
|
||||
target: "offering",
|
||||
fields: templateFields,
|
||||
}),
|
||||
[templateFields],
|
||||
);
|
||||
const offeringPageLabel =
|
||||
workspace.data?.templateContent?.navigation.find((item) => item.page === "offerings")?.label ??
|
||||
"业务展示页";
|
||||
const detailPageLabel =
|
||||
workspace.data?.templateContent?.navigation.find((item) => item.page === "detail")?.label ??
|
||||
"详情页";
|
||||
const detailSections = (workspace.data?.templateContent?.admin.sections ?? []).filter(
|
||||
(section) => section.target === "offering" && section.page === "detail",
|
||||
);
|
||||
const visualOfferingTarget = (workspace.data?.templateContent?.admin.sections ?? [])
|
||||
.filter((section) => section.target === "offering" && section.page === "offerings")
|
||||
.flatMap((section) => section.previewTargets ?? [])
|
||||
.find((target) => templateFields.some((field) => field.previewTarget === target.key)) ?? {
|
||||
key: "linjing-editorial.offerings.item",
|
||||
|
||||
const sections = workspace.data?.templateContent?.admin.sections ?? [];
|
||||
const previewTargets = useMemo(() => previewTargetsByPage(sections), [sections]);
|
||||
const listTarget = previewTargets.offerings.find((target) =>
|
||||
templateFields.some((field) => field.previewTarget === target.key),
|
||||
) ?? {
|
||||
key: "offering.list.item",
|
||||
label: "业务卡片",
|
||||
page: "offerings",
|
||||
source: "offering",
|
||||
};
|
||||
const hasTemplateDetailCopy = templateFields.some(
|
||||
(field) => field.binding === "offering.config.details.background",
|
||||
);
|
||||
const previewTargets = useMemo<Record<string, PreviewTarget[]>>(
|
||||
() =>
|
||||
["offerings", "detail"].reduce<Record<string, PreviewTarget[]>>((result, page) => {
|
||||
result[page] = (workspace.data?.templateContent?.admin.sections ?? [])
|
||||
.filter((section) => section.page === page)
|
||||
.flatMap((section) =>
|
||||
(section.previewTargets ?? []).map((target) => ({
|
||||
...target,
|
||||
page: section.page,
|
||||
source: section.fields.some(
|
||||
(field) =>
|
||||
field.binding.startsWith("offering.") && field.previewTarget === target.key,
|
||||
)
|
||||
? "offering"
|
||||
: section.target,
|
||||
})),
|
||||
);
|
||||
return result;
|
||||
}, {}),
|
||||
[workspace.data?.templateContent],
|
||||
);
|
||||
const detailTarget = previewTargets.detail.find((target) => target.source === "offering");
|
||||
const listFields = useMemo(
|
||||
() => templateFields.filter((field) => field.previewTarget === visualOfferingTarget.key),
|
||||
[templateFields, visualOfferingTarget.key],
|
||||
() => templateFields.filter((field) => field.previewTarget === listTarget.key),
|
||||
[templateFields, listTarget.key],
|
||||
);
|
||||
const detailTarget = previewTargets.detail?.find((target) => target.source === "offering");
|
||||
const detailFields = useMemo(
|
||||
() => templateFields.filter((field) => field.previewTarget === detailTarget?.key),
|
||||
[templateFields, detailTarget?.key],
|
||||
@@ -134,410 +52,85 @@ export function ServicesPage() {
|
||||
),
|
||||
[templateFields, listFields, detailFields],
|
||||
);
|
||||
useEffect(() => {
|
||||
const target = previewPage === "offerings" ? listFieldsRef.current : detailFieldsRef.current;
|
||||
if (!target || !formScrollRef.current) return;
|
||||
formScrollRef.current.scrollTo({
|
||||
top: target.offsetTop - formScrollRef.current.offsetTop - 12,
|
||||
behavior: "smooth",
|
||||
const activeTemplateFields: TemplateAdminField[] =
|
||||
editor.previewPage === "offerings"
|
||||
? [...listFields, ...otherFields.filter((field) => field.page === "offerings")]
|
||||
: [...detailFields, ...otherFields.filter((field) => field.page === "detail")];
|
||||
const previewWorkspaceDraft = useMemo(() => {
|
||||
if (!previewWorkspace.data || !editor.editingOffering) return undefined;
|
||||
return buildOfferingPreviewWorkspace({
|
||||
previewWorkspace: previewWorkspace.data,
|
||||
editingOffering: editor.editingOffering,
|
||||
templateFields,
|
||||
formValues: editor.formValues,
|
||||
});
|
||||
}, [previewPage, editingOffering?.id]);
|
||||
const previewWorkspaceDraft = useMemo<RuntimeWorkspace | undefined>(() => {
|
||||
if (!previewWorkspace.data || !editingOffering) return undefined;
|
||||
const values = offeringForm.getFieldsValue(true) as Record<string, unknown>;
|
||||
const config = applyPresentationValues(
|
||||
editingOffering.config,
|
||||
[{ key: "offering", fields: templateFields }],
|
||||
values,
|
||||
);
|
||||
const offeringValues = {
|
||||
name: values.name,
|
||||
summary: values.summary,
|
||||
description: values.description,
|
||||
priceText: values.priceText,
|
||||
coverUrl: values.coverUrl,
|
||||
};
|
||||
return {
|
||||
...previewWorkspace.data,
|
||||
offerings: previewWorkspace.data.offerings.map((item) =>
|
||||
item.id === editingOffering.id
|
||||
? {
|
||||
...item,
|
||||
name:
|
||||
typeof offeringValues.name === "string" && offeringValues.name.trim()
|
||||
? offeringValues.name
|
||||
: item.name,
|
||||
summary:
|
||||
typeof offeringValues.summary === "string" ? offeringValues.summary : item.summary,
|
||||
priceText:
|
||||
typeof offeringValues.priceText === "string"
|
||||
? offeringValues.priceText
|
||||
: item.priceText,
|
||||
coverUrl:
|
||||
typeof offeringValues.coverUrl === "string" && offeringValues.coverUrl.trim()
|
||||
? offeringValues.coverUrl
|
||||
: item.coverUrl,
|
||||
config,
|
||||
presentation: {
|
||||
...item.presentation,
|
||||
...config,
|
||||
...(config.presentation && typeof config.presentation === "object"
|
||||
? (config.presentation as Record<string, unknown>)
|
||||
: {}),
|
||||
heroImage:
|
||||
typeof config.detailHero === "string"
|
||||
? config.detailHero
|
||||
: typeof offeringValues.coverUrl === "string" && offeringValues.coverUrl.trim()
|
||||
? offeringValues.coverUrl
|
||||
: (item.coverUrl ?? null),
|
||||
}, [
|
||||
previewWorkspace.data,
|
||||
editor.editingOffering,
|
||||
templateFields,
|
||||
editor.formValues,
|
||||
editor.offeringDraftVersion,
|
||||
]);
|
||||
|
||||
const navigateToBrand = () => {
|
||||
if (!editor.editingOffering) return;
|
||||
void navigate("/admin/brand", {
|
||||
state: {
|
||||
targetKey:
|
||||
editor.previewPage === "offerings"
|
||||
? listTarget.key
|
||||
: (detailTarget?.key ?? listTarget.key),
|
||||
recordId: editor.editingOffering.id,
|
||||
},
|
||||
}
|
||||
: item,
|
||||
),
|
||||
brand: previewWorkspace.data.brand,
|
||||
};
|
||||
}, [previewWorkspace.data, editingOffering, templateFields]);
|
||||
const saveOffering = useMutation({
|
||||
mutationFn: (values: Record<string, unknown>) => {
|
||||
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<Offering, "id" | "brandId">);
|
||||
},
|
||||
onSuccess: () => {
|
||||
message.success("业务提供项已保存");
|
||||
setOfferingOpen(false);
|
||||
setEditingOffering(null);
|
||||
offeringForm.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
||||
},
|
||||
});
|
||||
const deleteOffering = useMutation({
|
||||
mutationFn: (id: string) => client.deleteAdminOffering(id),
|
||||
onSuccess: () => {
|
||||
message.success("业务提供项已删除");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
||||
},
|
||||
});
|
||||
const toggleOffering = useMutation({
|
||||
mutationFn: ({ id, isEnabled }: { id: string; isEnabled: boolean }) =>
|
||||
client.updateAdminOffering(id, { isEnabled }),
|
||||
onSuccess: () => {
|
||||
message.success("业务提供项状态已更新");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
||||
},
|
||||
});
|
||||
const beginOffering = (item?: Offering) => {
|
||||
setEditingOffering(item ?? null);
|
||||
setOfferingOpen(true);
|
||||
offeringForm.setFieldsValue(
|
||||
item
|
||||
? {
|
||||
kind: item.kind,
|
||||
name: item.name,
|
||||
summary: item.summary ?? "",
|
||||
description: item.description ?? "",
|
||||
priceText: item.priceText ?? "",
|
||||
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,
|
||||
...Object.fromEntries(
|
||||
templateFields.map((field) => [
|
||||
presentationFieldName("offering", field.key),
|
||||
field.input === "list" ? [] : undefined,
|
||||
]),
|
||||
),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<QueryState
|
||||
loading={offerings.isLoading || workspace.isLoading}
|
||||
error={offerings.error || workspace.error}
|
||||
onRetry={() => {
|
||||
void offerings.refetch();
|
||||
void workspace.refetch();
|
||||
}}
|
||||
onRetry={retry}
|
||||
>
|
||||
<AdminPageHeader
|
||||
title="小程序内容:业务展示与详情"
|
||||
description={`在「${offeringPageLabel}」管理访客能选择的服务、产品或案例;每项内容的补充资料会显示在对应的「${detailPageLabel}」。`}
|
||||
description={`在「${offeringPageLabel(workspace.data?.templateContent ?? undefined)}」管理访客能选择的服务、产品或案例;每项内容的补充资料会显示在对应的「${detailPageLabel(workspace.data?.templateContent ?? undefined)}」。`}
|
||||
extra={
|
||||
<Button type="primary" onClick={() => beginOffering()}>
|
||||
<Button type="primary" onClick={() => editor.beginOffering()}>
|
||||
新增业务提供项
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<section aria-label="业务提供项列表">
|
||||
<Space wrap style={{ marginBottom: 16 }}>
|
||||
<Typography.Title level={5} style={{ margin: 0 }}>
|
||||
{offeringPageLabel}中的内容
|
||||
</Typography.Title>
|
||||
<Tag color="blue">已启用的项目会公开展示</Tag>
|
||||
</Space>
|
||||
{detailSections.length ? (
|
||||
<Typography.Paragraph type="secondary">
|
||||
编辑单项详情时,附加字段将用于:
|
||||
{detailSections.map((section) => section.title).join("、")}
|
||||
。列表中的名称、说明、价格和封面也会显示在业务展示页。
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
<Table
|
||||
scroll={{ x: 760 }}
|
||||
rowKey="id"
|
||||
<OfferingsTable
|
||||
pageLabel={offeringPageLabel(workspace.data?.templateContent ?? undefined)}
|
||||
detailSectionTitles={sections
|
||||
.filter((section) => section.target === "offering" && section.page === "detail")
|
||||
.map((section) => section.title)}
|
||||
items={offerings.data ?? []}
|
||||
loading={offerings.isLoading}
|
||||
dataSource={offerings.data ?? []}
|
||||
columns={[
|
||||
{ title: "名称", dataIndex: "name" },
|
||||
{
|
||||
title: "业务类型",
|
||||
dataIndex: "kind",
|
||||
render: (value) => (
|
||||
<Tag>
|
||||
{(
|
||||
{
|
||||
service: "服务",
|
||||
product: "定制产品",
|
||||
package: "套餐",
|
||||
subscription: "订阅",
|
||||
} as Record<string, string>
|
||||
)[String(value)] ?? String(value)}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{ title: "价格", dataIndex: "priceText" },
|
||||
{
|
||||
title: "状态",
|
||||
dataIndex: "isEnabled",
|
||||
render: (value) => (value ? "已启用" : "已停用"),
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
render: (_: unknown, item: Offering) => (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => beginOffering(item)}>
|
||||
编辑详情
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
loading={toggleOffering.isPending && toggleOffering.variables?.id === item.id}
|
||||
onClick={() =>
|
||||
toggleOffering.mutate({ id: item.id, isEnabled: !item.isEnabled })
|
||||
}
|
||||
>
|
||||
{item.isEnabled ? "禁用" : "启用"}
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="确认删除这项业务提供项?"
|
||||
description="如果它已经关联咨询表单,系统会阻止删除。"
|
||||
onConfirm={() => deleteOffering.mutate(item.id)}
|
||||
okText="删除"
|
||||
cancelText="取消"
|
||||
>
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
loading={deleteOffering.isPending && deleteOffering.variables === item.id}
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]}
|
||||
saveError={mutations.saveOffering.error}
|
||||
toggleOffering={mutations.toggleOffering}
|
||||
deleteOffering={mutations.deleteOffering}
|
||||
onEdit={(item: Offering) => editor.beginOffering(item)}
|
||||
/>
|
||||
{offerings.data?.length === 0 && (
|
||||
<Typography.Paragraph type="secondary">
|
||||
还没有公开业务提供项。创建后,小程序服务页会优先读取这些内容。
|
||||
</Typography.Paragraph>
|
||||
)}
|
||||
<MutationError error={saveOffering.error} />
|
||||
<MutationError error={toggleOffering.error} />
|
||||
<MutationError error={deleteOffering.error} />
|
||||
</section>
|
||||
<Modal
|
||||
open={offeringOpen}
|
||||
title={editingOffering ? "编辑业务提供项" : "新增业务提供项"}
|
||||
width={960}
|
||||
onCancel={() => {
|
||||
setOfferingOpen(false);
|
||||
setEditingOffering(null);
|
||||
offeringForm.resetFields();
|
||||
}}
|
||||
onOk={() => offeringForm.submit()}
|
||||
confirmLoading={saveOffering.isPending}
|
||||
>
|
||||
<div className="service-offering-editor">
|
||||
{editingOffering && previewWorkspaceDraft ? (
|
||||
<div className="service-offering-editor__preview">
|
||||
<Segmented
|
||||
className="service-offering-editor__view"
|
||||
value={previewPage}
|
||||
options={[
|
||||
{ value: "offerings", label: "列表卡片" },
|
||||
{ value: "detail", label: "详情内容" },
|
||||
]}
|
||||
onChange={(value) => setPreviewPage(value as "offerings" | "detail")}
|
||||
<OfferingEditorModal
|
||||
open={editor.offeringOpen}
|
||||
editingOffering={editor.editingOffering}
|
||||
form={editor.offeringForm}
|
||||
previewPage={editor.previewPage}
|
||||
previewWorkspace={previewWorkspaceDraft}
|
||||
previewTargets={previewTargets}
|
||||
activeTemplateFields={activeTemplateFields}
|
||||
templateFieldSection={editor.templateFieldSection}
|
||||
hasTemplateDetailCopy={hasTemplateDetailCopy(templateFields)}
|
||||
listTarget={listTarget}
|
||||
detailTarget={detailTarget}
|
||||
saving={mutations.saveOffering.isPending}
|
||||
onClose={editor.closeOffering}
|
||||
onPreviewPageChange={(page: PreviewPage) => editor.setPreviewPage(page)}
|
||||
onValuesChange={(values) => editor.handleValuesChange(null, values)}
|
||||
onFinish={(values) => mutations.saveOffering.mutate(values)}
|
||||
onEditInBrand={navigateToBrand}
|
||||
/>
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
message={previewPage === "offerings" ? "正在核对列表展示" : "正在核对详情展示"}
|
||||
description={
|
||||
previewPage === "offerings"
|
||||
? "右侧「列表展示」字段修改后,会实时反映在当前卡片。"
|
||||
: "右侧「详情展示」字段修改后,会实时反映在当前详情内容。"
|
||||
}
|
||||
/>
|
||||
<ComponentTemplatePreview
|
||||
workspace={previewWorkspaceDraft}
|
||||
page={previewPage}
|
||||
targets={previewTargets[previewPage] ?? []}
|
||||
selection={{
|
||||
targetKey:
|
||||
previewPage === "offerings"
|
||||
? visualOfferingTarget.key
|
||||
: (detailTarget?.key ?? ""),
|
||||
recordId: editingOffering.id,
|
||||
}}
|
||||
onTargetSelected={() => {}}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<Form
|
||||
className="service-offering-editor__form"
|
||||
form={offeringForm}
|
||||
layout="vertical"
|
||||
onFinish={(values) => saveOffering.mutate(values as Record<string, unknown>)}
|
||||
>
|
||||
<div ref={formScrollRef} className="service-offering-editor__form-scroll">
|
||||
<Typography.Title level={5}>基础信息</Typography.Title>
|
||||
<Form.Item name="kind" label="类型" rules={[{ required: true }]}>
|
||||
<Select
|
||||
options={[
|
||||
{ value: "service", label: "服务" },
|
||||
{ value: "product", label: "定制产品" },
|
||||
{ value: "package", label: "套餐" },
|
||||
{ value: "subscription", label: "订阅" },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<Form.Item name="name" label="名称" rules={[{ required: true }]}>
|
||||
<Input />
|
||||
</Form.Item>
|
||||
<Form.Item name="summary" label="一句话说明">
|
||||
<Input />
|
||||
</Form.Item>
|
||||
{!hasTemplateDetailCopy ? (
|
||||
<Form.Item name="description" label="详细介绍">
|
||||
<Input.TextArea rows={5} />
|
||||
</Form.Item>
|
||||
) : null}
|
||||
<Form.Item name="priceText" label="价格展示">
|
||||
<Input placeholder="例如:按现场评估报价 / ¥ 2,800 起" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="coverUrl"
|
||||
label="封面图片地址"
|
||||
help="填写图片地址;图片上传能力将在后续媒体管理中提供。"
|
||||
>
|
||||
<ImageUrlField placeholder="粘贴服务或产品封面图片地址" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="sortOrder"
|
||||
label="展示顺序"
|
||||
help="数字越小越靠前,不确定时填写 0。"
|
||||
rules={[{ type: "number", min: 0, max: 9999 }]}
|
||||
>
|
||||
<Input type="number" min={0} max={9999} />
|
||||
</Form.Item>
|
||||
<Form.Item name="isEnabled" label="公开状态">
|
||||
<Select
|
||||
options={[
|
||||
{ value: true, label: "已启用" },
|
||||
{ value: false, label: "已停用" },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
</div>
|
||||
{templateFields.length ? (
|
||||
<>
|
||||
<Typography.Paragraph type="secondary">
|
||||
以下模板字段与左侧预览及小程序页面编辑的是同一份业务数据。
|
||||
</Typography.Paragraph>
|
||||
{listFields.length ? (
|
||||
<div ref={listFieldsRef}>
|
||||
<Typography.Title level={5}>列表展示</Typography.Title>
|
||||
<RecordContentFields
|
||||
section={{
|
||||
...templateFieldSection,
|
||||
fields: listFields,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{detailFields.length ? (
|
||||
<div ref={detailFieldsRef}>
|
||||
<Typography.Title level={5}>详情展示</Typography.Title>
|
||||
<RecordContentFields
|
||||
section={{
|
||||
...templateFieldSection,
|
||||
fields: detailFields,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{otherFields.length ? (
|
||||
<>
|
||||
<Typography.Title level={5}>其他模板内容</Typography.Title>
|
||||
<RecordContentFields
|
||||
section={{
|
||||
...templateFieldSection,
|
||||
fields: otherFields,
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
{editingOffering ? (
|
||||
<Button
|
||||
htmlType="button"
|
||||
onClick={() =>
|
||||
navigate("/admin/brand", {
|
||||
state: {
|
||||
targetKey: visualOfferingTarget.key,
|
||||
recordId: editingOffering.id,
|
||||
},
|
||||
})
|
||||
}
|
||||
>
|
||||
在小程序页面编辑
|
||||
</Button>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</Form>
|
||||
</div>
|
||||
</Modal>
|
||||
</QueryState>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type {
|
||||
AdminTemplateContent,
|
||||
Offering,
|
||||
TemplateAdminField,
|
||||
} from "@personal-brand/api-client";
|
||||
import {
|
||||
applyPresentationValues,
|
||||
presentationFieldName,
|
||||
readPresentationValue,
|
||||
} from "../brand/presentation-bindings.js";
|
||||
|
||||
export type OfferingFormValues = Record<string, unknown>;
|
||||
|
||||
export function offeringTemplateFields(
|
||||
sections: AdminTemplateContent["admin"]["sections"],
|
||||
): TemplateAdminField[] {
|
||||
return sections
|
||||
.filter((section) => section.target === "offering")
|
||||
.flatMap((section) =>
|
||||
section.fields.filter((field) => field.binding.startsWith("offering.config.")),
|
||||
);
|
||||
}
|
||||
|
||||
export function offeringDefaultFormValues(
|
||||
templateFields: TemplateAdminField[],
|
||||
): OfferingFormValues {
|
||||
return {
|
||||
kind: "service",
|
||||
isEnabled: true,
|
||||
sortOrder: 0,
|
||||
...Object.fromEntries(
|
||||
templateFields.map((field) => [
|
||||
presentationFieldName("offering", field.key),
|
||||
field.input === "list" ? [] : undefined,
|
||||
]),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function offeringEditFormValues(
|
||||
item: Offering,
|
||||
templateFields: TemplateAdminField[],
|
||||
): OfferingFormValues {
|
||||
return {
|
||||
kind: item.kind,
|
||||
name: item.name,
|
||||
summary: item.summary ?? "",
|
||||
description: item.description ?? "",
|
||||
priceText: item.priceText ?? "",
|
||||
coverUrl: item.coverUrl ?? "",
|
||||
sortOrder: item.sortOrder,
|
||||
isEnabled: item.isEnabled,
|
||||
...Object.fromEntries(
|
||||
templateFields.map((field) => {
|
||||
const value = readPresentationValue(item.config, field.binding, field);
|
||||
return [
|
||||
presentationFieldName("offering", field.key),
|
||||
value === undefined || value === null || value === ""
|
||||
? field.input === "select"
|
||||
? field.options?.[0]?.value
|
||||
: field.input === "list"
|
||||
? []
|
||||
: undefined
|
||||
: value,
|
||||
];
|
||||
}),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildOfferingRequestBody(
|
||||
values: OfferingFormValues,
|
||||
editingOffering: Offering | null,
|
||||
templateFields: TemplateAdminField[],
|
||||
): Record<string, unknown> {
|
||||
const fields = Object.fromEntries(
|
||||
Object.entries(values).filter(([key]) => key !== "config" && !key.startsWith("offering:")),
|
||||
);
|
||||
return {
|
||||
...fields,
|
||||
config: applyPresentationValues(
|
||||
editingOffering?.config,
|
||||
[{ key: "offering", fields: templateFields }],
|
||||
values,
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { AdminTemplateContent, TemplateAdminField } from "@personal-brand/api-client";
|
||||
|
||||
export function offeringPageLabel(templateContent?: AdminTemplateContent): string {
|
||||
return (
|
||||
templateContent?.navigation.find((item) => item.page === "offerings")?.label ?? "业务展示页"
|
||||
);
|
||||
}
|
||||
|
||||
export function detailPageLabel(templateContent?: AdminTemplateContent): string {
|
||||
return templateContent?.navigation.find((item) => item.page === "detail")?.label ?? "详情页";
|
||||
}
|
||||
|
||||
export function hasTemplateDetailCopy(templateFields: TemplateAdminField[]): boolean {
|
||||
return templateFields.some((field) => field.binding === "offering.config.details.background");
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import type {
|
||||
AdminTemplateContent,
|
||||
Offering,
|
||||
RuntimeWorkspace,
|
||||
TemplateAdminField,
|
||||
} from "@personal-brand/api-client";
|
||||
import type { PreviewTarget } from "../brand/preview-selection.js";
|
||||
import { applyPresentationValues } from "../brand/presentation-bindings.js";
|
||||
|
||||
export function previewTargetsByPage(
|
||||
sections: AdminTemplateContent["admin"]["sections"],
|
||||
): Record<"offerings" | "detail", PreviewTarget[]> {
|
||||
const result: Record<"offerings" | "detail", PreviewTarget[]> = {
|
||||
offerings: [],
|
||||
detail: [],
|
||||
};
|
||||
for (const page of ["offerings", "detail"] as const) {
|
||||
result[page] = sections
|
||||
.filter((section) => section.page === page)
|
||||
.flatMap((section) =>
|
||||
(section.previewTargets ?? []).map((target) => ({
|
||||
...target,
|
||||
page: section.page,
|
||||
source: section.fields.some(
|
||||
(field) => field.binding.startsWith("offering.") && field.previewTarget === target.key,
|
||||
)
|
||||
? "offering"
|
||||
: section.target,
|
||||
})),
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function buildOfferingPreviewWorkspace(options: {
|
||||
previewWorkspace: RuntimeWorkspace;
|
||||
editingOffering: Offering;
|
||||
templateFields: TemplateAdminField[];
|
||||
formValues: Record<string, unknown>;
|
||||
}): RuntimeWorkspace {
|
||||
const { previewWorkspace, editingOffering, templateFields, formValues } = options;
|
||||
const config = applyPresentationValues(
|
||||
editingOffering.config,
|
||||
[{ key: "offering", fields: templateFields }],
|
||||
formValues,
|
||||
);
|
||||
const offeringValues = {
|
||||
name: formValues.name,
|
||||
summary: formValues.summary,
|
||||
description: formValues.description,
|
||||
priceText: formValues.priceText,
|
||||
coverUrl: formValues.coverUrl,
|
||||
};
|
||||
return {
|
||||
...previewWorkspace,
|
||||
offerings: previewWorkspace.offerings.map((item) =>
|
||||
item.id === editingOffering.id
|
||||
? {
|
||||
...item,
|
||||
name:
|
||||
typeof offeringValues.name === "string" && offeringValues.name.trim()
|
||||
? offeringValues.name
|
||||
: item.name,
|
||||
summary:
|
||||
typeof offeringValues.summary === "string" ? offeringValues.summary : item.summary,
|
||||
priceText:
|
||||
typeof offeringValues.priceText === "string"
|
||||
? offeringValues.priceText
|
||||
: item.priceText,
|
||||
coverUrl:
|
||||
typeof offeringValues.coverUrl === "string" && offeringValues.coverUrl.trim()
|
||||
? offeringValues.coverUrl
|
||||
: item.coverUrl,
|
||||
config,
|
||||
presentation: {
|
||||
...item.presentation,
|
||||
...config,
|
||||
...(config.presentation && typeof config.presentation === "object"
|
||||
? (config.presentation as Record<string, unknown>)
|
||||
: {}),
|
||||
...(typeof config.area === "string" ? { area: config.area } : {}),
|
||||
...(typeof config.series === "string" ? { series: config.series } : {}),
|
||||
...(typeof config.spaceType === "string" ? { spaceType: config.spaceType } : {}),
|
||||
heroImage:
|
||||
typeof config.detailHero === "string"
|
||||
? config.detailHero
|
||||
: typeof offeringValues.coverUrl === "string" && offeringValues.coverUrl.trim()
|
||||
? offeringValues.coverUrl
|
||||
: (item.coverUrl ?? null),
|
||||
details: {
|
||||
...item.presentation.details,
|
||||
...(config.details && typeof config.details === "object"
|
||||
? {
|
||||
...item.presentation.details,
|
||||
...(config.details as Record<string, unknown>),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
}
|
||||
: item,
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { Offering } from "@personal-brand/api-client";
|
||||
import { message } from "antd";
|
||||
import { useMemo } from "react";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import {
|
||||
buildOfferingRequestBody,
|
||||
offeringTemplateFields,
|
||||
type OfferingFormValues,
|
||||
} from "./offering-form.js";
|
||||
|
||||
export function useOfferingQueries() {
|
||||
const client = createApiClient();
|
||||
const offerings = useQuery({
|
||||
queryKey: ["admin-offerings"],
|
||||
queryFn: () => client.listAdminOfferings(),
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
const workspace = useQuery({
|
||||
queryKey: ["admin-workspace-offering-fields"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
});
|
||||
const previewWorkspace = useQuery({
|
||||
queryKey: ["admin-preview-workspace-services"],
|
||||
queryFn: () => client.getAdminPreviewWorkspace(),
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
const templateFields = useMemo(
|
||||
() => offeringTemplateFields(workspace.data?.templateContent?.admin.sections ?? []),
|
||||
[workspace.data?.templateContent?.admin.sections],
|
||||
);
|
||||
return {
|
||||
offerings,
|
||||
workspace,
|
||||
previewWorkspace,
|
||||
templateFields,
|
||||
retry: () => {
|
||||
void offerings.refetch();
|
||||
void workspace.refetch();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function useOfferingMutations(options: {
|
||||
editingOffering: Offering | null;
|
||||
templateFields: ReturnType<typeof offeringTemplateFields>;
|
||||
onSuccess: () => void;
|
||||
}) {
|
||||
const client = createApiClient();
|
||||
const queryClient = useQueryClient();
|
||||
const invalidateAfterSave = () => {
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace-offering-fields"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-preview-workspace-services"] });
|
||||
};
|
||||
const saveOffering = useMutation({
|
||||
mutationFn: (values: OfferingFormValues) =>
|
||||
options.editingOffering
|
||||
? client.updateAdminOffering(
|
||||
options.editingOffering.id,
|
||||
buildOfferingRequestBody(values, options.editingOffering, options.templateFields),
|
||||
)
|
||||
: client.createAdminOffering(
|
||||
buildOfferingRequestBody(values, null, options.templateFields) as Omit<
|
||||
Offering,
|
||||
"id" | "brandId"
|
||||
>,
|
||||
),
|
||||
onSuccess: () => {
|
||||
message.success("业务提供项已保存");
|
||||
invalidateAfterSave();
|
||||
options.onSuccess();
|
||||
},
|
||||
});
|
||||
const deleteOffering = useMutation({
|
||||
mutationFn: (id: string) => client.deleteAdminOffering(id),
|
||||
onSuccess: () => {
|
||||
message.success("业务提供项已删除");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
||||
},
|
||||
});
|
||||
const toggleOffering = useMutation({
|
||||
mutationFn: ({ id, isEnabled }: { id: string; isEnabled: boolean }) =>
|
||||
client.updateAdminOffering(id, { isEnabled }),
|
||||
onSuccess: () => {
|
||||
message.success("业务提供项状态已更新");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-offerings"] });
|
||||
},
|
||||
});
|
||||
return { saveOffering, deleteOffering, toggleOffering };
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Form } from "antd";
|
||||
import { useMemo, useState } from "react";
|
||||
import type {
|
||||
Offering,
|
||||
TemplateAdminField,
|
||||
TemplateAdminSection,
|
||||
} from "@personal-brand/api-client";
|
||||
import { offeringDefaultFormValues, offeringEditFormValues } from "./offering-form.js";
|
||||
|
||||
export type OfferingPreviewPage = "offerings" | "detail";
|
||||
|
||||
export function useOfferingEditor(templateFields: TemplateAdminField[]) {
|
||||
const [offeringForm] = Form.useForm();
|
||||
const [offeringOpen, setOfferingOpen] = useState(false);
|
||||
const [editingOffering, setEditingOffering] = useState<Offering | null>(null);
|
||||
const [offeringDraftVersion, setOfferingDraftVersion] = useState(0);
|
||||
const [previewPage, setPreviewPage] = useState<OfferingPreviewPage>("detail");
|
||||
const [formValues, setFormValues] = useState<Record<string, unknown>>({});
|
||||
|
||||
const templateFieldSection = useMemo<TemplateAdminSection>(
|
||||
() => ({
|
||||
key: "offering",
|
||||
title: "模板内容",
|
||||
description: "",
|
||||
page: "detail",
|
||||
target: "offering",
|
||||
fields: templateFields,
|
||||
}),
|
||||
[templateFields],
|
||||
);
|
||||
|
||||
const beginOffering = (item?: Offering) => {
|
||||
setEditingOffering(item ?? null);
|
||||
setPreviewPage("detail");
|
||||
setOfferingOpen(true);
|
||||
offeringForm.setFieldsValue(
|
||||
item
|
||||
? offeringEditFormValues(item, templateFields)
|
||||
: offeringDefaultFormValues(templateFields),
|
||||
);
|
||||
setFormValues(offeringForm.getFieldsValue(true) as Record<string, unknown>);
|
||||
};
|
||||
|
||||
const closeOffering = () => {
|
||||
setOfferingOpen(false);
|
||||
setEditingOffering(null);
|
||||
offeringForm.resetFields();
|
||||
};
|
||||
|
||||
const handleValuesChange = (_: unknown, allValues: Record<string, unknown>) => {
|
||||
setFormValues(allValues);
|
||||
setOfferingDraftVersion((version) => version + 1);
|
||||
};
|
||||
|
||||
return {
|
||||
offeringForm,
|
||||
offeringOpen,
|
||||
editingOffering,
|
||||
previewPage,
|
||||
templateFieldSection,
|
||||
formValues,
|
||||
offeringDraftVersion,
|
||||
setPreviewPage,
|
||||
beginOffering,
|
||||
closeOffering,
|
||||
handleValuesChange,
|
||||
};
|
||||
}
|
||||
@@ -169,14 +169,14 @@ export function MembersPage() {
|
||||
label="登录账号"
|
||||
rules={[{ required: true, message: "请输入登录账号" }]}
|
||||
>
|
||||
<Input placeholder="例如:linran" />
|
||||
<Input placeholder="例如:brand-owner" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="displayName"
|
||||
label="成员姓名"
|
||||
rules={[{ required: true, message: "请输入成员姓名" }]}
|
||||
>
|
||||
<Input placeholder="例如:林然" />
|
||||
<Input placeholder="例如:品牌主理人" />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name="password"
|
||||
|
||||
@@ -1,185 +1,51 @@
|
||||
import {
|
||||
Button,
|
||||
Divider,
|
||||
Form,
|
||||
Input,
|
||||
List,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Select,
|
||||
Space,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
message,
|
||||
} from "antd";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { isTrustContentComplete } from "@personal-brand/api-client";
|
||||
import type {
|
||||
TemplateAdminField,
|
||||
TrustContent,
|
||||
TrustContentInput,
|
||||
} from "@personal-brand/api-client";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import { Button, Divider, Form, Typography } from "antd";
|
||||
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 = [
|
||||
{
|
||||
value: "schedule",
|
||||
label: "时间与服务安排",
|
||||
help: "说明你通常什么时候提供服务、接受预约或处理订单。多项内容可以分行填写。",
|
||||
},
|
||||
{
|
||||
value: "coverage",
|
||||
label: "服务范围与方式",
|
||||
help: "说明服务地点、覆盖范围、适用对象或承接边界。多项内容可以分行填写。",
|
||||
},
|
||||
{
|
||||
value: "process",
|
||||
label: "合作流程",
|
||||
help: "说明客户从提出需求到完成合作会经历哪些步骤,每行写一步。",
|
||||
},
|
||||
{
|
||||
value: "credential",
|
||||
label: "资质与专业证明",
|
||||
help: "说明资质、经验、制作标准或让客户放心的专业依据。",
|
||||
},
|
||||
{
|
||||
value: "case",
|
||||
label: "案例与客户反馈",
|
||||
help: "写代表性案例、服务结果或客户评价,多条内容可以分行填写。",
|
||||
},
|
||||
{
|
||||
value: "promise",
|
||||
label: "服务承诺与响应说明",
|
||||
help: "说明回复时间、交付承诺、售后方式或合作预期。",
|
||||
},
|
||||
];
|
||||
type TrustTypeOption = {
|
||||
type: string;
|
||||
label: string;
|
||||
adminFields: {
|
||||
title: string;
|
||||
summary: string;
|
||||
content: string;
|
||||
summaryHelp?: string;
|
||||
summaryPlaceholder?: string;
|
||||
};
|
||||
pages?: string[];
|
||||
help?: string;
|
||||
placeholder?: string;
|
||||
required?: boolean;
|
||||
configFields?: TemplateAdminField[];
|
||||
hideStandardFields?: Array<"summary" | "content">;
|
||||
maxPublishedItems?: number;
|
||||
};
|
||||
const fallbackTypes: TrustTypeOption[] = types.map(({ value, label, help }) => ({
|
||||
type: value,
|
||||
label,
|
||||
adminFields: { title: "标题", summary: "摘要", content: "详细内容" },
|
||||
help,
|
||||
}));
|
||||
import { QueryState } from "../../components/QueryState.js";
|
||||
import { TrustContentEditorModal } from "./components/TrustContentEditorModal.js";
|
||||
import { TrustContentTable } from "./components/TrustContentTable.js";
|
||||
import { TrustRequirementsList } from "./components/TrustRequirementsList.js";
|
||||
import type { TrustTypeOption } from "./domain/trust-content-domain.js";
|
||||
import {
|
||||
createTrustPageLabelResolver,
|
||||
groupTrustContentByType,
|
||||
selectTrustTypeOptions,
|
||||
} from "./domain/trust-content-domain.js";
|
||||
import { useTrustContentEditor } from "./hooks/useTrustContentEditor.js";
|
||||
import { useTrustContentQueries } from "./hooks/useTrustContentQueries.js";
|
||||
|
||||
export function TrustContentPage() {
|
||||
const client = createApiClient();
|
||||
const queryClient = useQueryClient();
|
||||
const [editing, setEditing] = useState<TrustContent | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [form] = Form.useForm<TrustContentInput>();
|
||||
const [searchParams] = useSearchParams();
|
||||
const selectedType = Form.useWatch("type", form);
|
||||
const query = useQuery({
|
||||
queryKey: ["trust-content"],
|
||||
queryFn: () => client.listAdminTrustContent(),
|
||||
const { query, workspace } = useTrustContentQueries();
|
||||
const availableTypes = selectTrustTypeOptions(workspace.data?.templateContent?.trustContentTypes);
|
||||
const pageLabel = createTrustPageLabelResolver(workspace.data?.templateContent?.navigation);
|
||||
const contentByType = groupTrustContentByType(query.data ?? []);
|
||||
const firstMissingRequiredType =
|
||||
availableTypes.find((item) => item.required && !contentByType.has(item.type))?.type ??
|
||||
availableTypes[0]?.type ??
|
||||
"credential";
|
||||
const {
|
||||
begin,
|
||||
closeEditor,
|
||||
editing,
|
||||
form: editorForm,
|
||||
open,
|
||||
remove,
|
||||
save,
|
||||
} = useTrustContentEditor({
|
||||
availableTypes,
|
||||
contentByType,
|
||||
firstMissingRequiredType,
|
||||
});
|
||||
const workspace = useQuery({
|
||||
queryKey: ["admin-workspace-trust-types"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
});
|
||||
const availableTypes: TrustTypeOption[] = workspace.data?.templateContent?.trustContentTypes
|
||||
?.length
|
||||
? workspace.data.templateContent.trustContentTypes
|
||||
: fallbackTypes;
|
||||
const pageLabel = (page: string) =>
|
||||
workspace.data?.templateContent?.navigation.find((item) => item.page === page)?.label ??
|
||||
(
|
||||
{ home: "首页", offerings: "业务展示页", detail: "详情页", profile: "主理人页" } as Record<
|
||||
string,
|
||||
string
|
||||
>
|
||||
)[page] ??
|
||||
page;
|
||||
const selectedType = Form.useWatch("type", editorForm);
|
||||
const selectedTypeMeta: TrustTypeOption | undefined = availableTypes.find(
|
||||
(item) => item.type === selectedType,
|
||||
);
|
||||
const trustPageLabels = [
|
||||
...new Set(availableTypes.flatMap((item) => item.pages ?? []).map(pageLabel)),
|
||||
];
|
||||
const trustPlacement = trustPageLabels.length
|
||||
? `小程序的${trustPageLabels.join("、")}中`
|
||||
: "小程序对应的信任展示区域中";
|
||||
const selectedTypeMeta = availableTypes.find((item) => item.type === selectedType);
|
||||
const contentByType = new Map<string, TrustContent>();
|
||||
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 ??
|
||||
"credential";
|
||||
const requestedType = searchParams.get("type");
|
||||
const save = useMutation({
|
||||
mutationFn: (values: TrustContentInput) =>
|
||||
editing
|
||||
? client.updateAdminTrustContent(editing.id, values)
|
||||
: client.createAdminTrustContent(values),
|
||||
onSuccess: () => {
|
||||
message.success("品牌内容已保存为草稿,发布后小程序才会更新");
|
||||
setOpen(false);
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
|
||||
},
|
||||
});
|
||||
const remove = useMutation({
|
||||
mutationFn: (id: string) => client.deleteAdminTrustContent(id),
|
||||
onSuccess: () => {
|
||||
message.success("品牌内容已删除");
|
||||
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
|
||||
},
|
||||
});
|
||||
const begin = (item?: TrustContent, type?: string) => {
|
||||
setEditing(item ?? null);
|
||||
setOpen(true);
|
||||
form.setFieldsValue(
|
||||
item
|
||||
? {
|
||||
type: item.type,
|
||||
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, config: {} },
|
||||
);
|
||||
};
|
||||
useEffect(() => {
|
||||
if (!requestedType || !availableTypes.some((item) => item.type === requestedType)) return;
|
||||
begin(contentByType.get(requestedType), requestedType);
|
||||
}, [requestedType, availableTypes.length]);
|
||||
|
||||
return (
|
||||
<QueryState
|
||||
loading={query.isLoading || workspace.isLoading}
|
||||
@@ -202,213 +68,34 @@ export function TrustContentPage() {
|
||||
<Typography.Paragraph type="secondary">
|
||||
标记为“发布必填”的项目需要填写完整后,才能发布小程序。
|
||||
</Typography.Paragraph>
|
||||
<List
|
||||
size="small"
|
||||
dataSource={availableTypes}
|
||||
renderItem={(item) => {
|
||||
const content = contentByType.get(item.type);
|
||||
const publishedCount = (query.data ?? []).filter(
|
||||
(record) => record.type === item.type && record.isPublished,
|
||||
).length;
|
||||
const tooMany =
|
||||
item.maxPublishedItems !== undefined && publishedCount > item.maxPublishedItems;
|
||||
const complete = Boolean(content && isTrustContentComplete(content, item) && !tooMany);
|
||||
return (
|
||||
<List.Item
|
||||
actions={[
|
||||
<Button
|
||||
key={item.type}
|
||||
type="link"
|
||||
size="small"
|
||||
onClick={() => (content ? begin(content) : begin(undefined, item.type))}
|
||||
>
|
||||
{content ? "编辑" : "新增"}
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
<Space wrap>
|
||||
<Typography.Text strong>{item.label}</Typography.Text>
|
||||
{item.required && <Tag color="orange">发布必填</Tag>}
|
||||
{(item.pages ?? []).map((page) => (
|
||||
<Tag key={page}>{pageLabel(page)}</Tag>
|
||||
))}
|
||||
<Tag color={complete ? "success" : "default"}>
|
||||
{tooMany
|
||||
? `公开内容过多(${publishedCount} 条)`
|
||||
: complete
|
||||
? "内容完整"
|
||||
: content
|
||||
? "需要完善"
|
||||
: "尚未填写"}
|
||||
</Tag>
|
||||
{item.help && <Typography.Text type="secondary">{item.help}</Typography.Text>}
|
||||
</Space>
|
||||
</List.Item>
|
||||
);
|
||||
}}
|
||||
<TrustRequirementsList
|
||||
availableTypes={availableTypes}
|
||||
contentByType={contentByType}
|
||||
items={query.data ?? []}
|
||||
onEdit={begin}
|
||||
/>
|
||||
</section>
|
||||
<Divider />
|
||||
<section aria-label="已配置的品牌内容">
|
||||
<Table
|
||||
rowKey="id"
|
||||
dataSource={query.data ?? []}
|
||||
locale={{ emptyText: "还没有品牌内容,请先按上方模板要求添加。" }}
|
||||
columns={[
|
||||
{
|
||||
title: "内容类型",
|
||||
dataIndex: "type",
|
||||
render: (value) => (
|
||||
<Tag>{availableTypes.find((item) => item.type === value)?.label ?? value}</Tag>
|
||||
),
|
||||
},
|
||||
{ title: "标题", dataIndex: "title" },
|
||||
{
|
||||
title: "内容预览",
|
||||
ellipsis: { showTitle: true },
|
||||
render: (_value: unknown, item: TrustContent) => {
|
||||
const meta = availableTypes.find((type) => type.type === item.type);
|
||||
if (meta?.hideStandardFields?.includes("content")) {
|
||||
return (
|
||||
meta.configFields
|
||||
?.flatMap((field) => {
|
||||
const value = item.config?.[field.key];
|
||||
if (Array.isArray(value))
|
||||
return value.length ? [`${field.label}:${value.length} 项`] : [];
|
||||
return typeof value === "string" && value.trim()
|
||||
? [`${field.label}:${value}`]
|
||||
: [];
|
||||
})
|
||||
.join(";") || "尚未填写区块内容"
|
||||
);
|
||||
}
|
||||
return item.summary || item.content || "未填写";
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "发布状态",
|
||||
dataIndex: "isPublished",
|
||||
render: (value) => (
|
||||
<Tag color={value ? "success" : "default"}>{value ? "随发布展示" : "草稿"}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
render: (_: unknown, item: TrustContent) => (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => begin(item)}>
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="确认删除这条信任内容?"
|
||||
description="删除后需发布品牌,才会更新小程序展示。"
|
||||
onConfirm={() => remove.mutate(item.id)}
|
||||
>
|
||||
<Button size="small" danger loading={remove.isPending}>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]}
|
||||
<TrustContentTable
|
||||
availableTypes={availableTypes}
|
||||
items={query.data ?? []}
|
||||
removeError={remove.error}
|
||||
removePending={remove.isPending}
|
||||
onEdit={(item) => begin(item)}
|
||||
onDelete={(id) => remove.mutate(id)}
|
||||
/>
|
||||
<MutationError error={remove.error} />
|
||||
</section>
|
||||
<Modal
|
||||
<TrustContentEditorModal
|
||||
availableTypes={availableTypes}
|
||||
editing={editing}
|
||||
form={editorForm}
|
||||
open={open}
|
||||
title={editing ? "编辑品牌内容" : "添加品牌内容"}
|
||||
onCancel={() => {
|
||||
setOpen(false);
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
}}
|
||||
onOk={() => form.submit()}
|
||||
confirmLoading={save.isPending}
|
||||
destroyOnClose
|
||||
>
|
||||
<Form
|
||||
form={form}
|
||||
layout="vertical"
|
||||
onFinish={(values) => save.mutate({ ...values, content: values.content ?? "" })}
|
||||
>
|
||||
<Form.Item name="type" label="内容类型" rules={[{ required: true }]}>
|
||||
<Select
|
||||
options={availableTypes.map((item) => ({ value: item.type, label: item.label }))}
|
||||
pageLabel={pageLabel}
|
||||
saveError={save.error}
|
||||
savePending={save.isPending}
|
||||
selectedTypeMeta={selectedTypeMeta}
|
||||
onCancel={closeEditor}
|
||||
onFinish={(values) => save.mutate(values)}
|
||||
/>
|
||||
</Form.Item>
|
||||
{selectedTypeMeta?.pages?.length ? (
|
||||
<Typography.Paragraph type="secondary">
|
||||
这类内容会显示在:
|
||||
{selectedTypeMeta.pages.map(pageLabel).join("、")}
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
<Form.Item
|
||||
name="title"
|
||||
label={selectedTypeMeta?.adminFields.title ?? "标题"}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<Input placeholder="例如:服务过 30+ 位独立创作者" />
|
||||
</Form.Item>
|
||||
{!selectedTypeMeta?.hideStandardFields?.includes("summary") && (
|
||||
<Form.Item
|
||||
name="summary"
|
||||
label={selectedTypeMeta?.adminFields.summary ?? "摘要"}
|
||||
help={selectedTypeMeta?.adminFields.summaryHelp}
|
||||
>
|
||||
<Input placeholder={selectedTypeMeta?.adminFields.summaryPlaceholder} />
|
||||
</Form.Item>
|
||||
)}
|
||||
{!selectedTypeMeta?.hideStandardFields?.includes("content") && (
|
||||
<Form.Item
|
||||
name="content"
|
||||
label={selectedTypeMeta?.adminFields.content ?? "详细内容"}
|
||||
help={
|
||||
selectedTypeMeta?.help ?? "每行写一项,页面会按模板样式展示。不要填写 HTML 或代码。"
|
||||
}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<Input.TextArea
|
||||
rows={8}
|
||||
showCount
|
||||
maxLength={2000}
|
||||
placeholder={selectedTypeMeta?.placeholder ?? "例如:\n第一项内容\n第二项内容"}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
{selectedTypeMeta?.configFields?.map((field) =>
|
||||
field.input === "list" ? (
|
||||
<TemplateListField key={field.key} field={field} name={["config", field.key]} />
|
||||
) : (
|
||||
<Form.Item
|
||||
key={field.key}
|
||||
name={["config", field.key]}
|
||||
label={field.label}
|
||||
help={field.help}
|
||||
rules={[{ required: field.required === true }]}
|
||||
>
|
||||
{field.input === "textarea" ? <Input.TextArea rows={3} /> : <Input />}
|
||||
</Form.Item>
|
||||
),
|
||||
)}
|
||||
<Form.Item
|
||||
name="coverUrl"
|
||||
label="配图地址"
|
||||
help="粘贴一张可公开访问的图片地址,保存前会显示预览。"
|
||||
>
|
||||
<ImageUrlField placeholder="粘贴案例或经历配图地址" />
|
||||
</Form.Item>
|
||||
<Form.Item name="isPublished" label="公开状态">
|
||||
<Select
|
||||
options={[
|
||||
{ value: true, label: "随品牌发布展示" },
|
||||
{ value: false, label: "保存为草稿" },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<MutationError error={save.error} />
|
||||
</Form>
|
||||
</Modal>
|
||||
</QueryState>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { Form, Input, Modal, Select, Typography } from "antd";
|
||||
import type { FormInstance } from "antd";
|
||||
import type { TrustContent, TrustContentInput } from "@personal-brand/api-client";
|
||||
import { ImageUrlField } from "../../../components/ImageUrlField.js";
|
||||
import { TemplateListField } from "../../../components/TemplateListField.js";
|
||||
import { MutationError } from "../../../components/QueryState.js";
|
||||
import type { TrustTypeOption } from "../domain/trust-content-domain.js";
|
||||
|
||||
export function TrustContentEditorModal({
|
||||
availableTypes,
|
||||
editing,
|
||||
form,
|
||||
open,
|
||||
pageLabel,
|
||||
saveError,
|
||||
savePending,
|
||||
selectedTypeMeta,
|
||||
onCancel,
|
||||
onFinish,
|
||||
}: {
|
||||
availableTypes: TrustTypeOption[];
|
||||
editing: TrustContent | null;
|
||||
form: FormInstance<TrustContentInput>;
|
||||
open: boolean;
|
||||
pageLabel: (page: string) => string;
|
||||
saveError: unknown;
|
||||
savePending: boolean;
|
||||
selectedTypeMeta?: TrustTypeOption | undefined;
|
||||
onCancel: () => void;
|
||||
onFinish: (values: TrustContentInput) => void;
|
||||
}) {
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={editing ? "编辑品牌内容" : "添加品牌内容"}
|
||||
onCancel={onCancel}
|
||||
onOk={() => form.submit()}
|
||||
confirmLoading={savePending}
|
||||
destroyOnClose
|
||||
>
|
||||
<Form
|
||||
form={form}
|
||||
layout="vertical"
|
||||
onFinish={(values) => onFinish({ ...values, content: values.content ?? "" })}
|
||||
>
|
||||
<Form.Item name="type" label="内容类型" rules={[{ required: true }]}>
|
||||
<Select
|
||||
options={availableTypes.map((item) => ({ value: item.type, label: item.label }))}
|
||||
/>
|
||||
</Form.Item>
|
||||
{selectedTypeMeta?.pages?.length ? (
|
||||
<Typography.Paragraph type="secondary">
|
||||
这类内容会显示在:{selectedTypeMeta.pages.map(pageLabel).join("、")}
|
||||
</Typography.Paragraph>
|
||||
) : null}
|
||||
<Form.Item
|
||||
name="title"
|
||||
label={selectedTypeMeta?.adminFields.title ?? "标题"}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<Input placeholder="例如:服务过 30+ 位独立创作者" />
|
||||
</Form.Item>
|
||||
{!selectedTypeMeta?.hideStandardFields?.includes("summary") && (
|
||||
<Form.Item
|
||||
name="summary"
|
||||
label={selectedTypeMeta?.adminFields.summary ?? "摘要"}
|
||||
help={selectedTypeMeta?.adminFields.summaryHelp}
|
||||
>
|
||||
<Input placeholder={selectedTypeMeta?.adminFields.summaryPlaceholder} />
|
||||
</Form.Item>
|
||||
)}
|
||||
{!selectedTypeMeta?.hideStandardFields?.includes("content") && (
|
||||
<Form.Item
|
||||
name="content"
|
||||
label={selectedTypeMeta?.adminFields.content ?? "详细内容"}
|
||||
help={
|
||||
selectedTypeMeta?.help ?? "每行写一项,页面会按模板样式展示。不要填写 HTML 或代码。"
|
||||
}
|
||||
rules={[{ required: true }]}
|
||||
>
|
||||
<Input.TextArea
|
||||
rows={8}
|
||||
showCount
|
||||
maxLength={2000}
|
||||
placeholder={selectedTypeMeta?.placeholder ?? "例如:\n第一项内容\n第二项内容"}
|
||||
/>
|
||||
</Form.Item>
|
||||
)}
|
||||
{selectedTypeMeta?.configFields?.map((field) =>
|
||||
field.input === "list" ? (
|
||||
<TemplateListField key={field.key} field={field} name={["config", field.key]} />
|
||||
) : (
|
||||
<Form.Item
|
||||
key={field.key}
|
||||
name={["config", field.key]}
|
||||
label={field.label}
|
||||
help={field.help}
|
||||
rules={[{ required: field.required === true }]}
|
||||
>
|
||||
{field.input === "textarea" ? <Input.TextArea rows={3} /> : <Input />}
|
||||
</Form.Item>
|
||||
),
|
||||
)}
|
||||
<Form.Item
|
||||
name="coverUrl"
|
||||
label="配图地址"
|
||||
help="粘贴一张可公开访问的图片地址,保存前会显示预览。"
|
||||
>
|
||||
<ImageUrlField placeholder="粘贴案例或经历配图地址" scope="trust" />
|
||||
</Form.Item>
|
||||
<Form.Item name="isPublished" label="公开状态">
|
||||
<Select
|
||||
options={[
|
||||
{ value: true, label: "随品牌发布展示" },
|
||||
{ value: false, label: "保存为草稿" },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
<MutationError error={saveError} />
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Button, Popconfirm, Space, Table, Tag } from "antd";
|
||||
import type { TrustContent } from "@personal-brand/api-client";
|
||||
import type { TrustTypeOption } from "../domain/trust-content-domain.js";
|
||||
import { getTrustContentPreview } from "../domain/trust-content-domain.js";
|
||||
import { MutationError } from "../../../components/QueryState.js";
|
||||
|
||||
export function TrustContentTable({
|
||||
availableTypes,
|
||||
items,
|
||||
removeError,
|
||||
removePending,
|
||||
onEdit,
|
||||
onDelete,
|
||||
}: {
|
||||
availableTypes: TrustTypeOption[];
|
||||
items: TrustContent[];
|
||||
removeError: unknown;
|
||||
removePending: boolean;
|
||||
onEdit: (item: TrustContent) => void;
|
||||
onDelete: (id: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<section aria-label="已配置的品牌内容">
|
||||
<Table
|
||||
rowKey="id"
|
||||
dataSource={items}
|
||||
locale={{ emptyText: "还没有品牌内容,请先按上方模板要求添加。" }}
|
||||
columns={[
|
||||
{
|
||||
title: "内容类型",
|
||||
dataIndex: "type",
|
||||
render: (value) => (
|
||||
<Tag>{availableTypes.find((item) => item.type === value)?.label ?? value}</Tag>
|
||||
),
|
||||
},
|
||||
{ title: "标题", dataIndex: "title" },
|
||||
{
|
||||
title: "内容预览",
|
||||
ellipsis: { showTitle: true },
|
||||
render: (_value: unknown, item: TrustContent) =>
|
||||
getTrustContentPreview(
|
||||
item,
|
||||
availableTypes.find((type) => type.type === item.type),
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "发布状态",
|
||||
dataIndex: "isPublished",
|
||||
render: (value) => (
|
||||
<Tag color={value ? "success" : "default"}>{value ? "随发布展示" : "草稿"}</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: "操作",
|
||||
render: (_: unknown, item: TrustContent) => (
|
||||
<Space>
|
||||
<Button size="small" onClick={() => onEdit(item)}>
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="确认删除这条信任内容?"
|
||||
description="删除后需发布品牌,才会更新小程序展示。"
|
||||
onConfirm={() => onDelete(item.id)}
|
||||
>
|
||||
<Button size="small" danger loading={removePending}>
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<MutationError error={removeError} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { Button, List, Space, Tag, Typography } from "antd";
|
||||
import { isTrustContentComplete } from "@personal-brand/api-client";
|
||||
import type { TrustContent } from "@personal-brand/api-client";
|
||||
import type { TrustTypeOption } from "../domain/trust-content-domain.js";
|
||||
|
||||
export function TrustRequirementsList({
|
||||
availableTypes,
|
||||
contentByType,
|
||||
items,
|
||||
onEdit,
|
||||
}: {
|
||||
availableTypes: TrustTypeOption[];
|
||||
contentByType: Map<string, TrustContent>;
|
||||
items: TrustContent[];
|
||||
onEdit: (item?: TrustContent, type?: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<List
|
||||
size="small"
|
||||
dataSource={availableTypes}
|
||||
renderItem={(item) => {
|
||||
const content = contentByType.get(item.type);
|
||||
const publishedCount = items.filter(
|
||||
(record) => record.type === item.type && record.isPublished,
|
||||
).length;
|
||||
const tooMany =
|
||||
item.maxPublishedItems !== undefined && publishedCount > item.maxPublishedItems;
|
||||
const complete = Boolean(content && isTrustContentComplete(content, item) && !tooMany);
|
||||
|
||||
return (
|
||||
<List.Item
|
||||
actions={[
|
||||
<Button
|
||||
key={item.type}
|
||||
type="link"
|
||||
size="small"
|
||||
onClick={() => (content ? onEdit(content) : onEdit(undefined, item.type))}
|
||||
>
|
||||
{content ? "编辑" : "新增"}
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
<Space wrap>
|
||||
<Typography.Text strong>{item.label}</Typography.Text>
|
||||
{item.required && <Tag color="orange">发布必填</Tag>}
|
||||
{(item.pages ?? []).map((page) => (
|
||||
<Tag key={page}>{page}</Tag>
|
||||
))}
|
||||
<Tag color={complete ? "success" : "default"}>
|
||||
{tooMany
|
||||
? `公开内容过多(${publishedCount} 条)`
|
||||
: complete
|
||||
? "内容完整"
|
||||
: content
|
||||
? "需要完善"
|
||||
: "尚未填写"}
|
||||
</Tag>
|
||||
{item.help && <Typography.Text type="secondary">{item.help}</Typography.Text>}
|
||||
</Space>
|
||||
</List.Item>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { TemplateAdminField } from "@personal-brand/api-client";
|
||||
import type { TrustContent } from "@personal-brand/api-client";
|
||||
|
||||
export type TrustTypeOption = {
|
||||
type: string;
|
||||
label: string;
|
||||
adminFields: {
|
||||
title: string;
|
||||
summary: string;
|
||||
content: string;
|
||||
summaryHelp?: string;
|
||||
summaryPlaceholder?: string;
|
||||
};
|
||||
pages?: string[];
|
||||
help?: string;
|
||||
placeholder?: string;
|
||||
required?: boolean;
|
||||
configFields?: TemplateAdminField[];
|
||||
hideStandardFields?: Array<"summary" | "content">;
|
||||
maxPublishedItems?: number;
|
||||
};
|
||||
|
||||
const fallbackTypeSeeds = [
|
||||
{
|
||||
value: "schedule",
|
||||
label: "时间与服务安排",
|
||||
help: "说明你通常什么时候提供服务、接受预约或处理订单。多项内容可以分行填写。",
|
||||
},
|
||||
{
|
||||
value: "coverage",
|
||||
label: "服务范围与方式",
|
||||
help: "说明服务地点、覆盖范围、适用对象或承接边界。多项内容可以分行填写。",
|
||||
},
|
||||
{
|
||||
value: "process",
|
||||
label: "合作流程",
|
||||
help: "说明客户从提出需求到完成合作会经历哪些步骤,每行写一步。",
|
||||
},
|
||||
{
|
||||
value: "credential",
|
||||
label: "资质与专业证明",
|
||||
help: "说明资质、经验、制作标准或让客户放心的专业依据。",
|
||||
},
|
||||
{
|
||||
value: "case",
|
||||
label: "案例与客户反馈",
|
||||
help: "写代表性案例、服务结果或客户评价,多条内容可以分行填写。",
|
||||
},
|
||||
{
|
||||
value: "promise",
|
||||
label: "服务承诺与响应说明",
|
||||
help: "说明回复时间、交付承诺、售后方式或合作预期。",
|
||||
},
|
||||
];
|
||||
|
||||
export const fallbackTrustTypes: TrustTypeOption[] = fallbackTypeSeeds.map(
|
||||
({ value, label, help }) => ({
|
||||
type: value,
|
||||
label,
|
||||
adminFields: { title: "标题", summary: "摘要", content: "详细内容" },
|
||||
help,
|
||||
}),
|
||||
);
|
||||
|
||||
const pageLabels: Record<string, string> = {
|
||||
home: "首页",
|
||||
offerings: "业务展示页",
|
||||
detail: "详情页",
|
||||
profile: "主理人页",
|
||||
};
|
||||
|
||||
export function createTrustPageLabelResolver(navigation?: Array<{ page: string; label: string }>) {
|
||||
return (page: string) =>
|
||||
navigation?.find((item) => item.page === page)?.label ?? pageLabels[page] ?? page;
|
||||
}
|
||||
|
||||
export function selectTrustTypeOptions(workspaceTypes?: TrustTypeOption[]): TrustTypeOption[] {
|
||||
return workspaceTypes?.length ? workspaceTypes : fallbackTrustTypes;
|
||||
}
|
||||
|
||||
export function groupTrustContentByType(items: TrustContent[]) {
|
||||
const contentByType = new Map<string, TrustContent>();
|
||||
|
||||
for (const item of items) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
return contentByType;
|
||||
}
|
||||
|
||||
export function getTrustContentPreview(item: TrustContent, typeMeta?: TrustTypeOption): string {
|
||||
if (typeMeta?.hideStandardFields?.includes("content")) {
|
||||
return (
|
||||
typeMeta.configFields
|
||||
?.flatMap((field) => {
|
||||
const value = item.config?.[field.key];
|
||||
if (Array.isArray(value)) {
|
||||
return value.length ? [`${field.label}:${value.length} 项`] : [];
|
||||
}
|
||||
return typeof value === "string" && value.trim() ? [`${field.label}:${value}`] : [];
|
||||
})
|
||||
.join(";") || "尚未填写区块内容"
|
||||
);
|
||||
}
|
||||
|
||||
return item.summary || item.content || "未填写";
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { Form } from "antd";
|
||||
import type { TrustContent, TrustContentInput } from "@personal-brand/api-client";
|
||||
import type { TrustTypeOption } from "../domain/trust-content-domain.js";
|
||||
import { useTrustContentMutations } from "./useTrustContentMutations.js";
|
||||
|
||||
export function useTrustContentEditor({
|
||||
availableTypes,
|
||||
contentByType,
|
||||
firstMissingRequiredType,
|
||||
}: {
|
||||
availableTypes: TrustTypeOption[];
|
||||
contentByType: Map<string, TrustContent>;
|
||||
firstMissingRequiredType: string;
|
||||
}) {
|
||||
const [editing, setEditing] = useState<TrustContent | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [form] = Form.useForm<TrustContentInput>();
|
||||
const [searchParams] = useSearchParams();
|
||||
|
||||
const closeEditor = () => {
|
||||
setOpen(false);
|
||||
setEditing(null);
|
||||
form.resetFields();
|
||||
};
|
||||
|
||||
const { save, remove } = useTrustContentMutations({ editing, closeEditor });
|
||||
|
||||
const begin = (item?: TrustContent, type?: string) => {
|
||||
setEditing(item ?? null);
|
||||
setOpen(true);
|
||||
form.setFieldsValue(
|
||||
item
|
||||
? {
|
||||
type: item.type,
|
||||
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, config: {} },
|
||||
);
|
||||
};
|
||||
|
||||
const requestedType = searchParams.get("type");
|
||||
|
||||
useEffect(() => {
|
||||
if (!requestedType || !availableTypes.some((item) => item.type === requestedType)) return;
|
||||
begin(contentByType.get(requestedType), requestedType);
|
||||
}, [requestedType, availableTypes.length]);
|
||||
|
||||
return { begin, closeEditor, editing, form, open, remove, save };
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { message } from "antd";
|
||||
import type { TrustContent, TrustContentInput } from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../../lib/api.js";
|
||||
|
||||
export function useTrustContentMutations({
|
||||
editing,
|
||||
closeEditor,
|
||||
}: {
|
||||
editing: TrustContent | null;
|
||||
closeEditor: () => void;
|
||||
}) {
|
||||
const client = createApiClient();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: (values: TrustContentInput) =>
|
||||
editing
|
||||
? client.updateAdminTrustContent(editing.id, values)
|
||||
: client.createAdminTrustContent(values),
|
||||
onSuccess: () => {
|
||||
message.success("品牌内容已保存为草稿,发布后小程序才会更新");
|
||||
closeEditor();
|
||||
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
|
||||
},
|
||||
});
|
||||
|
||||
const remove = useMutation({
|
||||
mutationFn: (id: string) => client.deleteAdminTrustContent(id),
|
||||
onSuccess: () => {
|
||||
message.success("品牌内容已删除");
|
||||
void queryClient.invalidateQueries({ queryKey: ["trust-content"] });
|
||||
},
|
||||
});
|
||||
|
||||
return { save, remove };
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { createApiClient } from "../../../lib/api.js";
|
||||
|
||||
export function useTrustContentQueries() {
|
||||
const client = createApiClient();
|
||||
|
||||
return {
|
||||
query: useQuery({
|
||||
queryKey: ["trust-content"],
|
||||
queryFn: () => client.listAdminTrustContent(),
|
||||
}),
|
||||
workspace: useQuery({
|
||||
queryKey: ["admin-workspace-trust-types"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,30 +1,25 @@
|
||||
import {
|
||||
Button,
|
||||
Card,
|
||||
Form,
|
||||
Input,
|
||||
Modal,
|
||||
Select,
|
||||
Space,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
message,
|
||||
} from "antd";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Button, Card, Form, Input, Modal, Select, Space, Table, Tag, Typography } from "antd";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import { ApiClientError } from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
import type {
|
||||
BrandFieldDefinition,
|
||||
BrandTemplateKey,
|
||||
InquiryForm,
|
||||
} from "@personal-brand/api-client";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useState } from "react";
|
||||
import {
|
||||
useWorkspaceQueries,
|
||||
useTemplateMutations,
|
||||
useFieldMutations,
|
||||
useInquiryFormMutations,
|
||||
} from "./workspace-mutations.js";
|
||||
import { supportsIndustry, type IndustryTarget } from "./workspace-templates.js";
|
||||
import { AdminPageHeader } from "../../components/AdminPageHeader.js";
|
||||
import { MutationError } from "../../components/QueryState.js";
|
||||
|
||||
const inquiryFieldTypes = [
|
||||
export const inquiryFieldTypes = [
|
||||
{ value: "text", label: "简短文字" },
|
||||
{ value: "textarea", label: "详细说明" },
|
||||
{ value: "phone", label: "联系电话" },
|
||||
@@ -36,53 +31,28 @@ const inquiryFieldTypes = [
|
||||
{ value: "multi-select", label: "多项选择" },
|
||||
];
|
||||
|
||||
function optionsToText(options: unknown): string {
|
||||
if (!Array.isArray(options)) return "";
|
||||
return options
|
||||
.map((option) => {
|
||||
if (!option || typeof option !== "object") return "";
|
||||
const label = (option as { label?: unknown }).label;
|
||||
return typeof label === "string" ? label : "";
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
export function readOptionLabel(option: unknown): string {
|
||||
const value = option as { label?: unknown } | null | undefined;
|
||||
return typeof value?.label === "string" ? value.label : "";
|
||||
}
|
||||
|
||||
function optionsFromText(value: unknown): Array<{ label: string; value: string }> {
|
||||
if (typeof value !== "string") return [];
|
||||
return value
|
||||
.split(/\r?\n|、|,/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean)
|
||||
.map((item) => ({ label: item, value: item }));
|
||||
}
|
||||
|
||||
function supportsIndustry(
|
||||
visual: { supportedIndustryTemplates?: unknown },
|
||||
industry: string,
|
||||
): boolean {
|
||||
return (
|
||||
Array.isArray(visual.supportedIndustryTemplates) &&
|
||||
visual.supportedIndustryTemplates.includes(industry)
|
||||
);
|
||||
export function normalizeOptionLabels(options: unknown): Array<{ label: string; value: string }> {
|
||||
return (Array.isArray(options) ? options : [])
|
||||
.map(readOptionLabel)
|
||||
.filter((label) => label.trim())
|
||||
.map((label) => ({ label, value: label }));
|
||||
}
|
||||
|
||||
export function WorkspacePage() {
|
||||
const navigate = useNavigate();
|
||||
const client = createApiClient();
|
||||
const queryClient = useQueryClient();
|
||||
const [fieldOpen, setFieldOpen] = useState(false);
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [editingForm, setEditingForm] = useState<InquiryForm | null>(null);
|
||||
const [visualTarget, setVisualTarget] = useState<string | null>(null);
|
||||
const [industryTarget, setIndustryTarget] = useState<{
|
||||
key: "personal" | "food" | "doors";
|
||||
name: string;
|
||||
description: string;
|
||||
capabilities: string[];
|
||||
} | null>(null);
|
||||
const [previewIndustry, setPreviewIndustry] = useState<BrandTemplateKey>("personal");
|
||||
const [previewVisual, setPreviewVisual] = useState("linjing-editorial");
|
||||
const [industryTarget, setIndustryTarget] = useState<IndustryTarget | null>(null);
|
||||
const [previewIndustry, setPreviewIndustry] = useState<BrandTemplateKey | null>(null);
|
||||
const [previewVisual, setPreviewVisual] = useState<string | null>(null);
|
||||
const [form] = Form.useForm<Record<string, unknown>>();
|
||||
const [inquiryForm] = Form.useForm<Record<string, unknown>>();
|
||||
const openNewInquiryForm = () => {
|
||||
@@ -98,126 +68,49 @@ export function WorkspacePage() {
|
||||
});
|
||||
setFormOpen(true);
|
||||
};
|
||||
const query = useQuery({
|
||||
queryKey: ["admin-workspace"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
});
|
||||
const runtimeQuery = useQuery({
|
||||
queryKey: ["public-runtime-workspace"],
|
||||
queryFn: () => client.getPublicWorkspace(),
|
||||
});
|
||||
const templateCatalog = useQuery({
|
||||
queryKey: ["template-catalog"],
|
||||
queryFn: () => client.listPublicTemplates(),
|
||||
});
|
||||
const { query, runtimeQuery, templateCatalog, forms, templatePreview } = useWorkspaceQueries();
|
||||
const previewIndustryKey =
|
||||
previewIndustry ??
|
||||
query.data?.brand.templateKey ??
|
||||
query.data?.installations[0]?.templateKey ??
|
||||
templateCatalog.data?.industries[0]?.key;
|
||||
const previewVisualKey =
|
||||
previewVisual ??
|
||||
runtimeQuery.data?.visualTemplate?.key ??
|
||||
(templateCatalog.data?.visuals ?? []).find((visual) =>
|
||||
supportsIndustry(visual, previewIndustryKey ?? ""),
|
||||
)?.key;
|
||||
const combinationPreview = useQuery({
|
||||
queryKey: ["template-combination-preview", previewIndustry, previewVisual],
|
||||
queryFn: () => client.previewPublicTemplateCombination(previewIndustry, previewVisual),
|
||||
enabled: Boolean(templateCatalog.data),
|
||||
queryKey: ["template-combination-preview", previewIndustryKey, previewVisualKey],
|
||||
queryFn: () =>
|
||||
createApiClient().previewPublicTemplateCombination(
|
||||
previewIndustryKey ?? "",
|
||||
previewVisualKey ?? "",
|
||||
),
|
||||
enabled: Boolean(templateCatalog.data && previewIndustryKey && previewVisualKey),
|
||||
});
|
||||
const compatibleVisuals = (templateCatalog.data?.visuals ?? []).filter((visual) =>
|
||||
supportsIndustry(visual, query.data?.brand?.templateKey ?? "personal"),
|
||||
supportsIndustry(visual, query.data?.brand?.templateKey ?? ""),
|
||||
);
|
||||
const visualTemplate = useMutation({
|
||||
mutationFn: (key: string) =>
|
||||
client.updateAdminBrand({
|
||||
config: { ...(runtimeQuery.data?.brand?.config ?? {}), visualTemplateKey: key },
|
||||
}),
|
||||
onSuccess: () => {
|
||||
message.success("视觉模板已切换");
|
||||
void runtimeQuery.refetch();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
|
||||
},
|
||||
const { visualTemplate, rollbackVisual, install, upgrade, rollback } = useTemplateMutations({
|
||||
runtimeConfig: runtimeQuery.data?.brand?.config ?? undefined,
|
||||
queryClient,
|
||||
});
|
||||
const visualHistory = useQuery({
|
||||
queryKey: ["visual-template-history"],
|
||||
queryFn: () => client.getAdminVisualTemplateHistory(),
|
||||
queryFn: () => createApiClient().getAdminVisualTemplateHistory(),
|
||||
});
|
||||
const rollbackVisual = useMutation({
|
||||
mutationFn: () => client.rollbackAdminVisualTemplate(),
|
||||
onSuccess: () => {
|
||||
message.success("视觉模板已回滚");
|
||||
void runtimeQuery.refetch();
|
||||
void visualHistory.refetch();
|
||||
},
|
||||
const { createField, removeField } = useFieldMutations({
|
||||
form,
|
||||
queryClient,
|
||||
onClose: () => setFieldOpen(false),
|
||||
});
|
||||
const install = useMutation({
|
||||
mutationFn: (key: "personal" | "food" | "doors") => client.installAdminTemplate(key),
|
||||
onSuccess: () => {
|
||||
message.success("模板已安装");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
},
|
||||
});
|
||||
const createField = useMutation({
|
||||
mutationFn: (values: Omit<BrandFieldDefinition, "id" | "source">) =>
|
||||
client.createAdminField(values),
|
||||
onSuccess: () => {
|
||||
message.success("字段已创建");
|
||||
setFieldOpen(false);
|
||||
form.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
},
|
||||
});
|
||||
const removeField = useMutation({
|
||||
mutationFn: (id: string) => client.deleteAdminField(id),
|
||||
onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }),
|
||||
});
|
||||
const forms = useQuery({
|
||||
queryKey: ["admin-inquiry-forms"],
|
||||
queryFn: () => client.listAdminInquiryForms(),
|
||||
});
|
||||
const templatePreview = useQuery({
|
||||
queryKey: ["admin-template-preview"],
|
||||
queryFn: () => client.getAdminTemplateUpgradePreview(),
|
||||
enabled: Boolean(query.data?.installations?.length),
|
||||
});
|
||||
const upgrade = useMutation({
|
||||
mutationFn: () => client.upgradeAdminTemplate(),
|
||||
onSuccess: () => {
|
||||
message.success("模板已升级,已有内容未被覆盖");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] });
|
||||
},
|
||||
});
|
||||
const rollback = useMutation({
|
||||
mutationFn: () => client.rollbackAdminTemplate(),
|
||||
onSuccess: () => {
|
||||
message.success("模板版本已回滚,现有内容未删除");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] });
|
||||
},
|
||||
});
|
||||
const createForm = useMutation({
|
||||
mutationFn: (values: {
|
||||
name: string;
|
||||
offeringId?: string;
|
||||
purpose?: InquiryForm["purpose"];
|
||||
targetType?: InquiryForm["targetType"];
|
||||
submissionAction?: InquiryForm["submissionAction"];
|
||||
fieldsSnapshot: unknown[];
|
||||
}) => client.createAdminInquiryForm(values),
|
||||
onSuccess: () => {
|
||||
message.success("咨询表单已创建");
|
||||
setFormOpen(false);
|
||||
inquiryForm.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-forms"] });
|
||||
},
|
||||
});
|
||||
const updateForm = useMutation({
|
||||
mutationFn: ({ id, body }: { id: string; body: Partial<InquiryForm> }) =>
|
||||
client.updateAdminInquiryForm(id, {
|
||||
...(body.name === undefined ? {} : { name: body.name }),
|
||||
...(body.offeringId == null ? {} : { offeringId: body.offeringId }),
|
||||
...(body.fieldsSnapshot === undefined ? {} : { fieldsSnapshot: body.fieldsSnapshot }),
|
||||
...(body.isEnabled === undefined ? {} : { isEnabled: body.isEnabled }),
|
||||
}),
|
||||
onSuccess: () => {
|
||||
message.success("咨询表单已更新");
|
||||
const { createForm, updateForm } = useInquiryFormMutations({
|
||||
form: inquiryForm,
|
||||
queryClient,
|
||||
onClose: () => {
|
||||
setFormOpen(false);
|
||||
setEditingForm(null);
|
||||
inquiryForm.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-forms"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
|
||||
},
|
||||
});
|
||||
if (query.isLoading) return <Card loading />;
|
||||
@@ -306,9 +199,9 @@ export function WorkspacePage() {
|
||||
<Space wrap>
|
||||
<Typography.Text strong>视觉模板</Typography.Text>
|
||||
<Select
|
||||
value={runtimeQuery.data?.visualTemplate?.key ?? "linjing-editorial"}
|
||||
value={runtimeQuery.data?.visualTemplate?.key}
|
||||
loading={visualTemplate.isPending}
|
||||
onChange={(key) => setVisualTarget(key)}
|
||||
onChange={(key) => setVisualTarget(key ?? null)}
|
||||
options={[
|
||||
...compatibleVisuals.map((visual) => ({ value: visual.key, label: visual.name })),
|
||||
]}
|
||||
@@ -475,18 +368,18 @@ export function WorkspacePage() {
|
||||
</Typography.Paragraph>
|
||||
<Space wrap>
|
||||
<Select
|
||||
value={previewIndustry}
|
||||
onChange={setPreviewIndustry}
|
||||
value={previewIndustryKey ?? null}
|
||||
onChange={(key) => setPreviewIndustry(key)}
|
||||
options={(templateCatalog.data?.industries ?? []).map((item) => ({
|
||||
value: item.key,
|
||||
label: item.name,
|
||||
}))}
|
||||
/>
|
||||
<Select
|
||||
value={previewVisual}
|
||||
onChange={setPreviewVisual}
|
||||
value={previewVisualKey ?? null}
|
||||
onChange={(key) => setPreviewVisual(key)}
|
||||
options={(templateCatalog.data?.visuals ?? [])
|
||||
.filter((item) => supportsIndustry(item, previewIndustry))
|
||||
.filter((item) => supportsIndustry(item, previewIndustryKey ?? ""))
|
||||
.map((item) => ({ value: item.key, label: item.name }))}
|
||||
/>
|
||||
</Space>
|
||||
@@ -541,11 +434,11 @@ export function WorkspacePage() {
|
||||
name: item.name,
|
||||
purpose: item.purpose,
|
||||
offeringId: item.offeringId ?? undefined,
|
||||
fieldsSnapshot: item.fieldsSnapshot.map((field) => {
|
||||
fieldsSnapshot: item.fieldsSnapshot.map((field: unknown) => {
|
||||
const value = field as Record<string, unknown>;
|
||||
return {
|
||||
...value,
|
||||
optionsText: optionsToText(value.options),
|
||||
options: normalizeOptionLabels(value.options),
|
||||
};
|
||||
}),
|
||||
});
|
||||
@@ -719,12 +612,15 @@ export function WorkspacePage() {
|
||||
fieldsSnapshot: (Array.isArray(values.fieldsSnapshot)
|
||||
? values.fieldsSnapshot
|
||||
: []
|
||||
).map((field) => {
|
||||
).map((field: unknown) => {
|
||||
const item = field as Record<string, unknown>;
|
||||
const { optionsText, ...rest } = item;
|
||||
const { options, ...rest } = item;
|
||||
const type = typeof rest.type === "string" ? rest.type : "text";
|
||||
return ["select", "radio", "multi-select"].includes(type)
|
||||
? { ...rest, options: optionsFromText(optionsText) }
|
||||
? {
|
||||
...rest,
|
||||
options: normalizeOptionLabels(options),
|
||||
}
|
||||
: rest;
|
||||
}),
|
||||
};
|
||||
@@ -824,18 +720,54 @@ export function WorkspacePage() {
|
||||
["select", "radio", "multi-select"].includes(
|
||||
String(getFieldValue(["fieldsSnapshot", name, "type"])),
|
||||
) ? (
|
||||
<Form.Item
|
||||
{...restField}
|
||||
name={[name, "optionsText"]}
|
||||
label="可选内容"
|
||||
help="每行填写一个选项,也可以用顿号分隔。"
|
||||
rules={[{ required: true, message: "请至少填写一个选项" }]}
|
||||
<Form.List
|
||||
name={[name, "options"]}
|
||||
rules={[
|
||||
{
|
||||
validator: (_, value: unknown) =>
|
||||
Array.isArray(value) &&
|
||||
value.some((option: unknown) => readOptionLabel(option).trim())
|
||||
? Promise.resolve()
|
||||
: Promise.reject(new Error("请至少添加一个选项")),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<Input.TextArea
|
||||
rows={2}
|
||||
placeholder="例如:预算内、需要沟通、暂不确定"
|
||||
/>
|
||||
{(optionFields, { add, remove }, { errors }) => (
|
||||
<>
|
||||
{optionFields.map((optionField) => (
|
||||
<Space
|
||||
key={optionField.key}
|
||||
align="center"
|
||||
style={{ display: "flex" }}
|
||||
>
|
||||
<Form.Item
|
||||
{...optionField}
|
||||
name={[optionField.name, "label"]}
|
||||
initialValue=""
|
||||
rules={[{ required: true, message: "请填写选项内容" }]}
|
||||
style={{ flex: 1, minWidth: 240, marginBottom: 8 }}
|
||||
>
|
||||
<Input placeholder="例如:预算内" />
|
||||
</Form.Item>
|
||||
<Button
|
||||
danger
|
||||
onClick={() => remove(optionField.name)}
|
||||
style={{ marginBottom: 8 }}
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
</Space>
|
||||
))}
|
||||
<Button
|
||||
onClick={() => add({ label: "", value: "" })}
|
||||
style={{ marginBottom: 8 }}
|
||||
>
|
||||
新增选项
|
||||
</Button>
|
||||
<Form.ErrorList errors={errors} />
|
||||
</>
|
||||
)}
|
||||
</Form.List>
|
||||
) : null
|
||||
}
|
||||
</Form.Item>
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { message } from "antd";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import type { FormInstance } from "antd";
|
||||
import type {
|
||||
BrandFieldDefinition,
|
||||
BrandTemplateKey,
|
||||
InquiryForm,
|
||||
} from "@personal-brand/api-client";
|
||||
import { createApiClient } from "../../lib/api.js";
|
||||
|
||||
export function useWorkspaceQueries(client = createApiClient()) {
|
||||
const query = useQuery({
|
||||
queryKey: ["admin-workspace"],
|
||||
queryFn: () => client.getAdminWorkspace(),
|
||||
});
|
||||
const runtimeQuery = useQuery({
|
||||
queryKey: ["public-runtime-workspace"],
|
||||
queryFn: () => client.getPublicWorkspace(),
|
||||
});
|
||||
const templateCatalog = useQuery({
|
||||
queryKey: ["template-catalog"],
|
||||
queryFn: () => client.listPublicTemplates(),
|
||||
});
|
||||
const forms = useQuery({
|
||||
queryKey: ["admin-inquiry-forms"],
|
||||
queryFn: () => client.listAdminInquiryForms(),
|
||||
});
|
||||
const templatePreview = useQuery({
|
||||
queryKey: ["admin-template-preview"],
|
||||
queryFn: () => client.getAdminTemplateUpgradePreview(),
|
||||
enabled: Boolean(query.data?.installations?.length),
|
||||
});
|
||||
return { query, runtimeQuery, templateCatalog, forms, templatePreview };
|
||||
}
|
||||
|
||||
interface TemplateMutationOptions {
|
||||
client?: ReturnType<typeof createApiClient>;
|
||||
runtimeConfig: Record<string, unknown> | undefined;
|
||||
queryClient: {
|
||||
invalidateQueries: (options: { queryKey: readonly unknown[] }) => Promise<void>;
|
||||
};
|
||||
}
|
||||
|
||||
export function useTemplateMutations({
|
||||
client = createApiClient(),
|
||||
runtimeConfig,
|
||||
queryClient,
|
||||
}: TemplateMutationOptions) {
|
||||
const visualTemplate = useMutation({
|
||||
mutationFn: (key: string) =>
|
||||
client.updateAdminBrand({ config: { ...(runtimeConfig ?? {}), visualTemplateKey: key } }),
|
||||
onSuccess: () => {
|
||||
message.success("视觉模板已切换");
|
||||
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-brand"] });
|
||||
},
|
||||
});
|
||||
const rollbackVisual = useMutation({
|
||||
mutationFn: () => client.rollbackAdminVisualTemplate(),
|
||||
onSuccess: () => {
|
||||
message.success("视觉模板已回滚");
|
||||
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["visual-template-history"] });
|
||||
},
|
||||
});
|
||||
const install = useMutation({
|
||||
mutationFn: (key: BrandTemplateKey) => client.installAdminTemplate(key),
|
||||
onSuccess: () => {
|
||||
message.success("模板已安装");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
},
|
||||
});
|
||||
const upgrade = useMutation({
|
||||
mutationFn: () => client.upgradeAdminTemplate(),
|
||||
onSuccess: () => {
|
||||
message.success("模板已升级,已有内容未被覆盖");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] });
|
||||
},
|
||||
});
|
||||
const rollback = useMutation({
|
||||
mutationFn: () => client.rollbackAdminTemplate(),
|
||||
onSuccess: () => {
|
||||
message.success("模板版本已回滚,现有内容未删除");
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-template-preview"] });
|
||||
},
|
||||
});
|
||||
return { visualTemplate, rollbackVisual, install, upgrade, rollback };
|
||||
}
|
||||
|
||||
interface FieldMutationOptions {
|
||||
client?: ReturnType<typeof createApiClient>;
|
||||
form: FormInstance<Record<string, unknown>>;
|
||||
queryClient: {
|
||||
invalidateQueries: (options: { queryKey: readonly unknown[] }) => Promise<void>;
|
||||
};
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function useFieldMutations({
|
||||
client = createApiClient(),
|
||||
form,
|
||||
queryClient,
|
||||
onClose,
|
||||
}: FieldMutationOptions) {
|
||||
const createField = useMutation({
|
||||
mutationFn: (values: Omit<BrandFieldDefinition, "id" | "source">) =>
|
||||
client.createAdminField(values),
|
||||
onSuccess: () => {
|
||||
message.success("字段已创建");
|
||||
onClose();
|
||||
form.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] });
|
||||
},
|
||||
});
|
||||
const removeField = useMutation({
|
||||
mutationFn: (id: string) => client.deleteAdminField(id),
|
||||
onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["admin-workspace"] }),
|
||||
});
|
||||
return { createField, removeField };
|
||||
}
|
||||
|
||||
export function useInquiryFormMutations({
|
||||
client = createApiClient(),
|
||||
form,
|
||||
queryClient,
|
||||
onClose,
|
||||
}: {
|
||||
client?: ReturnType<typeof createApiClient>;
|
||||
form: FormInstance<Record<string, unknown>>;
|
||||
queryClient: {
|
||||
invalidateQueries: (options: { queryKey: readonly unknown[] }) => Promise<void>;
|
||||
};
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const createForm = useMutation({
|
||||
mutationFn: (values: {
|
||||
name: string;
|
||||
offeringId?: string;
|
||||
purpose?: InquiryForm["purpose"];
|
||||
targetType?: InquiryForm["targetType"];
|
||||
submissionAction?: InquiryForm["submissionAction"];
|
||||
fieldsSnapshot: unknown[];
|
||||
}) => client.createAdminInquiryForm(values),
|
||||
onSuccess: () => {
|
||||
message.success("咨询表单已创建");
|
||||
onClose();
|
||||
form.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-forms"] });
|
||||
},
|
||||
});
|
||||
const updateForm = useMutation({
|
||||
mutationFn: ({ id, body }: { id: string; body: Partial<InquiryForm> }) =>
|
||||
client.updateAdminInquiryForm(id, {
|
||||
...(body.name === undefined ? {} : { name: body.name }),
|
||||
...(body.offeringId == null ? {} : { offeringId: body.offeringId }),
|
||||
...(body.fieldsSnapshot === undefined ? {} : { fieldsSnapshot: body.fieldsSnapshot }),
|
||||
...(body.isEnabled === undefined ? {} : { isEnabled: body.isEnabled }),
|
||||
}),
|
||||
onSuccess: () => {
|
||||
message.success("咨询表单已更新");
|
||||
onClose();
|
||||
form.resetFields();
|
||||
void queryClient.invalidateQueries({ queryKey: ["admin-inquiry-forms"] });
|
||||
void queryClient.invalidateQueries({ queryKey: ["public-runtime-workspace"] });
|
||||
},
|
||||
});
|
||||
return { createForm, updateForm };
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { BrandTemplateKey } from "@personal-brand/api-client";
|
||||
|
||||
export interface IndustryTarget {
|
||||
key: BrandTemplateKey;
|
||||
name: string;
|
||||
description: string;
|
||||
capabilities: string[];
|
||||
}
|
||||
|
||||
export function supportsIndustry(
|
||||
visual: { supportedIndustryTemplates?: unknown },
|
||||
industry: string,
|
||||
): boolean {
|
||||
return (
|
||||
Array.isArray(visual.supportedIndustryTemplates) &&
|
||||
visual.supportedIndustryTemplates.includes(industry)
|
||||
);
|
||||
}
|
||||
@@ -7,12 +7,14 @@ export default defineConfig({
|
||||
css: { postcss: { plugins: [templatePreviewCss()] } },
|
||||
base: process.env.VITE_APP_BASE_PATH ?? "/",
|
||||
resolve: {
|
||||
dedupe: ["react", "react-dom"],
|
||||
alias: {
|
||||
"@tarojs/components": `${process.cwd()}/src/features/brand/taro-web-components.jsx`,
|
||||
"@tarojs/taro": `${process.cwd()}/src/features/brand/taro-web-runtime.jsx`,
|
||||
},
|
||||
},
|
||||
define: {
|
||||
"process.env": "{}",
|
||||
"process.env.TARO_PLATFORM": JSON.stringify("web"),
|
||||
"process.env.TARO_ENV": JSON.stringify("h5"),
|
||||
PREVIEW_ALL_TEMPLATES: JSON.stringify(true),
|
||||
@@ -26,6 +28,19 @@ export default defineConfig({
|
||||
target: process.env.VITE_DEV_API_TARGET ?? "http://localhost:3001",
|
||||
rewrite: (path) => path.replace(/^\/api/, ""),
|
||||
},
|
||||
"/media": {
|
||||
target: process.env.VITE_MEDIA_API_TARGET ?? "http://localhost:3001",
|
||||
changeOrigin: true,
|
||||
},
|
||||
...(process.env.VITE_MEDIA_PROXY_TARGET
|
||||
? {
|
||||
[`/${(process.env.OBJECT_STORAGE_BUCKET ?? "personal-brand-media").replace(/^\/+/, "")}`]:
|
||||
{
|
||||
target: process.env.VITE_MEDIA_PROXY_TARGET,
|
||||
changeOrigin: true,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
build: { outDir: "dist" },
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
FROM node:22-alpine AS base
|
||||
ENV PNPM_HOME=/pnpm
|
||||
ENV PATH="$PNPM_HOME:$PATH"
|
||||
RUN corepack enable \
|
||||
&& apk add --no-cache openssl libc6-compat
|
||||
WORKDIR /app
|
||||
|
||||
FROM base AS build
|
||||
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json ./
|
||||
COPY tsconfig.base.json ./
|
||||
COPY packages ./packages
|
||||
COPY apps/api/package.json apps/api/package.json
|
||||
COPY apps/api/tsconfig.json apps/api/tsconfig.json
|
||||
COPY apps/api/prisma ./apps/api/prisma
|
||||
COPY apps/api/src ./apps/api/src
|
||||
RUN pnpm install --frozen-lockfile
|
||||
RUN pnpm --filter @personal-brand/config build
|
||||
RUN pnpm --filter @personal-brand/types build
|
||||
RUN pnpm --filter @personal-brand/validation build
|
||||
RUN pnpm --filter @personal-brand/api exec prisma generate
|
||||
RUN pnpm --filter @personal-brand/api build
|
||||
RUN pnpm --filter @personal-brand/api --prod deploy /out/api
|
||||
|
||||
FROM base AS runtime
|
||||
ENV NODE_ENV=production
|
||||
WORKDIR /app
|
||||
COPY --from=build /out/api ./
|
||||
COPY --from=build /app/apps/api/dist ./dist
|
||||
COPY --from=build /app/apps/api/prisma ./prisma
|
||||
COPY --from=build /app/packages/config/dist ./node_modules/@personal-brand/config/dist
|
||||
COPY --from=build /app/packages/types/dist ./node_modules/@personal-brand/types/dist
|
||||
COPY --from=build /app/packages/validation/dist ./node_modules/@personal-brand/validation/dist
|
||||
RUN mkdir -p /app/media /app/seed-media
|
||||
COPY apps/api/prisma/assets/ /app/seed-media/
|
||||
COPY docker/api-entrypoint.sh /usr/local/bin/api-entrypoint.sh
|
||||
RUN chmod +x /usr/local/bin/api-entrypoint.sh \
|
||||
&& chown -R node:node /app
|
||||
USER node
|
||||
EXPOSE 3001
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
CMD node -e "fetch('http://127.0.0.1:'+(process.env.API_PORT||3001)+'/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"
|
||||
ENTRYPOINT ["/usr/local/bin/api-entrypoint.sh"]
|
||||
CMD ["node", "dist/main.js"]
|
||||
@@ -8,7 +8,7 @@
|
||||
"lint": "eslint .",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "tsx --test test/**/*.test.ts",
|
||||
"test:integration": "pnpm build && node --env-file=.env test/run-integration.cjs",
|
||||
"test:integration": "pnpm build && node --env-file=.env test/run-integration.cjs && pnpm --filter @personal-brand/api exec tsx --test test/http.upload.test.js",
|
||||
"clean": "rimraf dist",
|
||||
"start": "node dist/main.js",
|
||||
"db:generate": "prisma generate",
|
||||
@@ -17,6 +17,10 @@
|
||||
"db:seed": "tsx prisma/seed.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.1149.0",
|
||||
"@aws-sdk/s3-request-presigner": "^3.1149.0",
|
||||
"@fastify/multipart": "^10.1.3",
|
||||
"@fastify/static": "^10.1.6",
|
||||
"@nestjs/common": "^11.0.11",
|
||||
"@nestjs/core": "^11.0.11",
|
||||
"@nestjs/platform-fastify": "^11.0.11",
|
||||
@@ -27,13 +31,13 @@
|
||||
"bcryptjs": "^2.4.3",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.1",
|
||||
"fastify": "^5.2.1",
|
||||
"fastify": "^5.11.3",
|
||||
"prisma": "^6.2.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.5",
|
||||
"prisma": "^6.2.1",
|
||||
"tsx": "^4.19.2"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 125 KiB |
|
After Width: | Height: | Size: 163 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 182 KiB |
|
After Width: | Height: | Size: 167 KiB |
|
After Width: | Height: | Size: 154 KiB |
|
After Width: | Height: | Size: 250 KiB |
|
After Width: | Height: | Size: 151 KiB |
|
After Width: | Height: | Size: 210 KiB |
@@ -0,0 +1,5 @@
|
||||
-- Normalize offering category storage: categoryKey is authoritative.
|
||||
-- Display labels are projected from the active template manifest.
|
||||
UPDATE "Offering"
|
||||
SET "config" = "config" - 'categoryLabel'
|
||||
WHERE "config" IS NOT NULL;
|
||||
@@ -0,0 +1,136 @@
|
||||
-- Replace development seed remote images with local media paths.
|
||||
UPDATE "Offering"
|
||||
SET "config" = CASE
|
||||
WHEN jsonb_typeof("config") = 'array' THEN
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
CASE
|
||||
WHEN jsonb_typeof(item->'url') = 'string' THEN
|
||||
jsonb_set(
|
||||
item,
|
||||
'{url}',
|
||||
to_jsonb(
|
||||
CASE
|
||||
WHEN item->>'url' LIKE '%1547592180-85f173990554%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN item->>'url' LIKE '%1603133872878-684f208fb84b%' THEN '/media/seed/seed-02.jpg'
|
||||
WHEN item->>'url' LIKE '%1559847844-5315695dadae%' THEN '/media/seed/seed-03.jpg'
|
||||
WHEN item->>'url' LIKE '%1513694203232-719a280e022f%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN item->>'url' LIKE '%1541123437800-1bb1317badc2%' THEN '/media/seed/seed-02.jpg'
|
||||
WHEN item->>'url' LIKE '%1505691938895-1758d7feb511%' THEN '/media/seed/seed-03.jpg'
|
||||
WHEN item->>'url' LIKE '%1600210492486-724fe5c67fb0%' THEN '/media/seed/seed-03.jpg'
|
||||
ELSE item->>'url'
|
||||
END
|
||||
)
|
||||
)
|
||||
ELSE item
|
||||
END
|
||||
)
|
||||
FROM jsonb_array_elements("config") AS item
|
||||
)
|
||||
ELSE "config"
|
||||
END
|
||||
WHERE jsonb_typeof("config") = 'array';
|
||||
|
||||
UPDATE "Offering"
|
||||
SET "config" = jsonb_set(
|
||||
"config",
|
||||
'{media}',
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
CASE
|
||||
WHEN jsonb_typeof(item->'url') = 'string' THEN
|
||||
jsonb_set(
|
||||
item,
|
||||
'{url}',
|
||||
to_jsonb(
|
||||
CASE
|
||||
WHEN item->>'url' LIKE '%1600210492486-724fe5c67fb0%' THEN '/media/seed/seed-03.jpg'
|
||||
ELSE item->>'url'
|
||||
END
|
||||
)
|
||||
)
|
||||
ELSE item
|
||||
END
|
||||
)
|
||||
FROM jsonb_array_elements("config"->'media') AS item
|
||||
)
|
||||
)
|
||||
WHERE "config" ? 'media'
|
||||
AND "config"::text LIKE '%1600210492486-724fe5c67fb0%';
|
||||
|
||||
UPDATE "Offering"
|
||||
SET "coverUrl" = '/media/seed/seed-03.jpg'
|
||||
WHERE "coverUrl" LIKE '%1600210492486-724fe5c67fb0%';
|
||||
|
||||
UPDATE "Offering"
|
||||
SET "coverUrl" = CASE
|
||||
WHEN "coverUrl" LIKE '%1547592180-85f173990554%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN "coverUrl" LIKE '%1603133872878-684f208fb84b%' THEN '/media/seed/seed-02.jpg'
|
||||
WHEN "coverUrl" LIKE '%1559847844-5315695dadae%' THEN '/media/seed/seed-03.jpg'
|
||||
WHEN "coverUrl" LIKE '%1513694203232-719a280e022f%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN "coverUrl" LIKE '%1541123437800-1bb1317badc2%' THEN '/media/seed/seed-02.jpg'
|
||||
WHEN "coverUrl" LIKE '%1505691938895-1758d7feb511%' THEN '/media/seed/seed-03.jpg'
|
||||
ELSE "coverUrl"
|
||||
END,
|
||||
"config" = CASE
|
||||
WHEN "config" ? 'media' THEN
|
||||
CASE
|
||||
WHEN jsonb_typeof("config"->'media') = 'array' THEN
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
CASE
|
||||
WHEN jsonb_typeof(item->'url') = 'string' THEN
|
||||
jsonb_set(
|
||||
item,
|
||||
'{url}',
|
||||
to_jsonb(
|
||||
CASE
|
||||
WHEN item->>'url' LIKE '%1547592180-85f173990554%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN item->>'url' LIKE '%1603133872878-684f208fb84b%' THEN '/media/seed/seed-02.jpg'
|
||||
WHEN item->>'url' LIKE '%1559847844-5315695dadae%' THEN '/media/seed/seed-03.jpg'
|
||||
WHEN item->>'url' LIKE '%1513694203232-719a280e022f%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN item->>'url' LIKE '%1541123437800-1bb1317badc2%' THEN '/media/seed/seed-02.jpg'
|
||||
WHEN item->>'url' LIKE '%1505691938895-1758d7feb511%' THEN '/media/seed/seed-03.jpg'
|
||||
ELSE item->>'url'
|
||||
END
|
||||
)
|
||||
)
|
||||
ELSE item
|
||||
END
|
||||
)
|
||||
FROM jsonb_array_elements("config"->'media') AS item
|
||||
)
|
||||
ELSE "config"->'media'
|
||||
END
|
||||
ELSE "config"
|
||||
END
|
||||
WHERE "config" IS NOT NULL;
|
||||
|
||||
UPDATE "Offering"
|
||||
SET "config" = jsonb_set(
|
||||
"config",
|
||||
'{detailHero}',
|
||||
to_jsonb(
|
||||
CASE
|
||||
WHEN "config"->>'detailHero' LIKE '%1600210492486-724fe5c67fb0%' THEN '/media/seed/seed-03.jpg'
|
||||
ELSE "config"->>'detailHero'
|
||||
END
|
||||
)
|
||||
)
|
||||
WHERE "config" ? 'detailHero';
|
||||
|
||||
UPDATE "BrandProfile"
|
||||
SET "config" = jsonb_set(
|
||||
"config",
|
||||
'{heroImage}',
|
||||
to_jsonb(
|
||||
CASE
|
||||
WHEN "config"->>'heroImage' LIKE '%1556761175-b413da4baf72%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN "config"->>'heroImage' LIKE '%1521737711867-e3b97375f902%' THEN '/media/seed/seed-02.jpg'
|
||||
WHEN "config"->>'heroImage' LIKE '%1513694203232-719a280e022f%' THEN '/media/seed/seed-01.jpg'
|
||||
WHEN "config"->>'heroImage' LIKE '%1547592180-85f173990554%' THEN '/media/seed/seed-01.jpg'
|
||||
ELSE "config"->>'heroImage'
|
||||
END
|
||||
)
|
||||
)
|
||||
WHERE "config" ? 'heroImage';
|
||||
@@ -0,0 +1,56 @@
|
||||
-- Normalize historical publication snapshots to canonical local media paths.
|
||||
UPDATE "BrandRelease"
|
||||
SET "snapshot" = replace(
|
||||
replace(
|
||||
replace(
|
||||
"snapshot"::text,
|
||||
'https://images.unsplash.com/photo-1547592180-85f173990554?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-01.jpg'
|
||||
),
|
||||
'https://images.unsplash.com/photo-1603133872878-684f208fb84b?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-02.jpg'
|
||||
),
|
||||
'https://images.unsplash.com/photo-1559847844-5315695dadae?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-03.jpg'
|
||||
)::jsonb
|
||||
WHERE "snapshot"::text LIKE '%images.unsplash.com%';
|
||||
|
||||
UPDATE "BrandRelease"
|
||||
SET "snapshot" = replace(
|
||||
replace(
|
||||
replace(
|
||||
"snapshot"::text,
|
||||
'https://images.unsplash.com/photo-1513694203232-719a280e022f?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-01.jpg'
|
||||
),
|
||||
'https://images.unsplash.com/photo-1541123437800-1bb1317badc2?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-02.jpg'
|
||||
),
|
||||
'https://images.unsplash.com/photo-1505691938895-1758d7feb511?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-03.jpg'
|
||||
)::jsonb
|
||||
WHERE "snapshot"::text LIKE '%images.unsplash.com%';
|
||||
|
||||
UPDATE "BrandRelease"
|
||||
SET "snapshot" = replace(
|
||||
replace(
|
||||
"snapshot"::text,
|
||||
'https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-03.jpg'
|
||||
),
|
||||
'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?auto=format&fit=crop&w=240&h=240&q=80',
|
||||
'/media/seed/seed-01.jpg'
|
||||
)::jsonb
|
||||
WHERE "snapshot"::text LIKE '%images.unsplash.com%';
|
||||
|
||||
UPDATE "BrandRelease"
|
||||
SET "snapshot" = replace(
|
||||
replace(
|
||||
"snapshot"::text,
|
||||
'https://images.unsplash.com/photo-1556761175-b413da4baf72?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-01.jpg'
|
||||
),
|
||||
'https://images.unsplash.com/photo-1521737711867-e3b97375f902?auto=format&fit=crop&w=1000&q=85',
|
||||
'/media/seed/seed-02.jpg'
|
||||
)::jsonb
|
||||
WHERE "snapshot"::text LIKE '%images.unsplash.com%';
|
||||
@@ -0,0 +1,2 @@
|
||||
DELETE FROM "BrandProfile"
|
||||
WHERE "slug" = 'linran-brand';
|
||||
@@ -0,0 +1,72 @@
|
||||
-- Restore collapsed seed media placeholders to their original per-role local files.
|
||||
UPDATE "Offering"
|
||||
SET "coverUrl" = CASE "coverUrl"
|
||||
WHEN '/media/seed/seed-01.jpg' THEN CASE "name"
|
||||
WHEN '红烧肉双拼套餐' THEN '/media/seed/food-package-01.jpg'
|
||||
WHEN '当代铸铜木核防暴装甲门' THEN '/media/seed/doors-hero.jpg'
|
||||
ELSE '/media/seed/personal-consulting.jpg'
|
||||
END
|
||||
WHEN '/media/seed/seed-02.jpg' THEN CASE "name"
|
||||
WHEN '小炒鸡套餐' THEN '/media/seed/food-package-02.jpg'
|
||||
WHEN '悬挑风琴式耐候双开院门' THEN '/media/seed/doors-yard-gate.jpg'
|
||||
ELSE '/media/seed/personal-advisory.jpg'
|
||||
END
|
||||
WHEN '/media/seed/seed-03.jpg' THEN CASE "name"
|
||||
WHEN '家庭聚餐私厨' THEN '/media/seed/food-private-chef.jpg'
|
||||
WHEN '通顶极窄边框实木室内门' THEN '/media/seed/doors-room-door.jpg'
|
||||
WHEN '石材及皮质背景墙一体门' THEN '/media/seed/doors-stone-wall.jpg'
|
||||
ELSE '/media/seed/personal-consulting.jpg'
|
||||
END
|
||||
END
|
||||
WHERE "coverUrl" IN ('/media/seed/seed-01.jpg', '/media/seed/seed-02.jpg', '/media/seed/seed-03.jpg');
|
||||
|
||||
UPDATE "Offering"
|
||||
SET "config" = replace(
|
||||
replace(
|
||||
replace(
|
||||
"config"::text,
|
||||
'/media/seed/seed-01.jpg',
|
||||
'/media/seed/food-package-01.jpg'
|
||||
),
|
||||
'/media/seed/seed-02.jpg',
|
||||
'/media/seed/food-package-02.jpg'
|
||||
),
|
||||
'/media/seed/seed-03.jpg',
|
||||
'/media/seed/food-private-chef.jpg'
|
||||
)::jsonb
|
||||
WHERE "config"::text LIKE '%/media/seed/seed-0%' AND "name" IN ('红烧肉双拼套餐', '小炒鸡套餐', '家庭聚餐私厨');
|
||||
|
||||
UPDATE "Offering"
|
||||
SET "config" = replace(
|
||||
replace(
|
||||
replace(
|
||||
"config"::text,
|
||||
'/media/seed/seed-01.jpg',
|
||||
'/media/seed/doors-hero.jpg'
|
||||
),
|
||||
'/media/seed/seed-02.jpg',
|
||||
'/media/seed/doors-yard-gate.jpg'
|
||||
),
|
||||
'/media/seed/seed-03.jpg',
|
||||
CASE "name"
|
||||
WHEN '通顶极窄边框实木室内门' THEN '/media/seed/doors-room-door.jpg'
|
||||
ELSE '/media/seed/doors-stone-wall.jpg'
|
||||
END
|
||||
)::jsonb
|
||||
WHERE "config"::text LIKE '%/media/seed/seed-0%' AND "name" LIKE '%门';
|
||||
|
||||
UPDATE "BrandProfile"
|
||||
SET "config" = replace(
|
||||
replace(
|
||||
replace(
|
||||
"config"::text,
|
||||
'/media/seed/seed-01.jpg',
|
||||
CASE "templateKey" WHEN 'doors' THEN '/media/seed/doors-hero.jpg' ELSE '/media/seed/personal-consulting.jpg' END
|
||||
),
|
||||
'/media/seed/seed-02.jpg',
|
||||
'/media/seed/personal-advisory.jpg'
|
||||
),
|
||||
'/media/seed/seed-03.jpg',
|
||||
'/media/seed/doors-room-door.jpg'
|
||||
)::jsonb
|
||||
WHERE "config"::text LIKE '%/media/seed/seed-0%';
|
||||
@@ -0,0 +1,32 @@
|
||||
-- Keep publication snapshots aligned with restored original seed media paths.
|
||||
UPDATE "BrandRelease"
|
||||
SET "snapshot" = replace(
|
||||
replace(
|
||||
replace(
|
||||
"snapshot"::text,
|
||||
'/media/seed/seed-01.jpg',
|
||||
'/media/seed/food-package-01.jpg'
|
||||
),
|
||||
'/media/seed/seed-02.jpg',
|
||||
'/media/seed/food-package-02.jpg'
|
||||
),
|
||||
'/media/seed/seed-03.jpg',
|
||||
'/media/seed/food-private-chef.jpg'
|
||||
)::jsonb
|
||||
WHERE "brandId" = '00000000-0000-0000-0000-000000000001';
|
||||
|
||||
UPDATE "BrandRelease"
|
||||
SET "snapshot" = replace(
|
||||
replace(
|
||||
replace(
|
||||
"snapshot"::text,
|
||||
'/media/seed/seed-01.jpg',
|
||||
'/media/seed/doors-hero.jpg'
|
||||
),
|
||||
'/media/seed/seed-02.jpg',
|
||||
'/media/seed/doors-yard-gate.jpg'
|
||||
),
|
||||
'/media/seed/seed-03.jpg',
|
||||
'/media/seed/doors-room-door.jpg'
|
||||
)::jsonb
|
||||
WHERE "brandId" = '00000000-0000-0000-0000-000000000002';
|
||||
@@ -0,0 +1,30 @@
|
||||
-- Restore non-runtime sample offerings by brand visual context.
|
||||
UPDATE "Offering" o
|
||||
SET "coverUrl" = '/media/seed/food-package-01.jpg'
|
||||
FROM "BrandProfile" b
|
||||
WHERE o."brandId" = b.id AND b.slug = 'default-brand' AND o.name IN ('家庭聚餐定制', '示例·今日套餐');
|
||||
|
||||
UPDATE "Offering" o
|
||||
SET "coverUrl" = '/media/seed/food-package-02.jpg'
|
||||
FROM "BrandProfile" b
|
||||
WHERE o."brandId" = b.id AND b.slug = 'default-brand' AND o.name IN ('示例·品牌定位咨询', '示例·聚餐定制');
|
||||
|
||||
UPDATE "Offering" o
|
||||
SET "coverUrl" = '/media/seed/doors-hero.jpg'
|
||||
FROM "BrandProfile" b
|
||||
WHERE o."brandId" = b.id AND b.slug = 'linjing-doors' AND o.name IN ('序章·入户门', '别墅入户大门');
|
||||
|
||||
UPDATE "Offering" o
|
||||
SET "coverUrl" = '/media/seed/doors-yard-gate.jpg'
|
||||
FROM "BrandProfile" b
|
||||
WHERE o."brandId" = b.id AND b.slug = 'linjing-doors' AND o.name IN ('庭院·边界门', '院门与围合系统');
|
||||
|
||||
UPDATE "Offering" o
|
||||
SET "coverUrl" = '/media/seed/doors-room-door.jpg'
|
||||
FROM "BrandProfile" b
|
||||
WHERE o."brandId" = b.id AND b.slug = 'linjing-doors' AND o.name IN ('室内户内门系统', '室内·静谧门');
|
||||
|
||||
UPDATE "Offering" o
|
||||
SET "coverUrl" = '/media/seed/doors-stone-wall.jpg'
|
||||
FROM "BrandProfile" b
|
||||
WHERE o."brandId" = b.id AND b.slug = 'linjing-doors' AND o.name = '一对一门系统设计咨询';
|
||||
@@ -1,5 +1,6 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
binaryTargets = ["linux-musl-openssl-3.0.x", "debian-openssl-3.0.x"]
|
||||
}
|
||||
|
||||
datasource db {
|
||||
|
||||
@@ -7,19 +7,16 @@ const prisma = new PrismaClient();
|
||||
|
||||
const runtimeImages = {
|
||||
doors: [
|
||||
"https://images.unsplash.com/photo-1513694203232-719a280e022f?auto=format&fit=crop&w=1000&q=85",
|
||||
"https://images.unsplash.com/photo-1541123437800-1bb1317badc2?auto=format&fit=crop&w=1000&q=85",
|
||||
"https://images.unsplash.com/photo-1505691938895-1758d7feb511?auto=format&fit=crop&w=1000&q=85",
|
||||
"/media/seed/doors-hero.jpg",
|
||||
"/media/seed/doors-yard-gate.jpg",
|
||||
"/media/seed/doors-room-door.jpg",
|
||||
],
|
||||
food: [
|
||||
"https://images.unsplash.com/photo-1547592180-85f173990554?auto=format&fit=crop&w=1000&q=85",
|
||||
"https://images.unsplash.com/photo-1603133872878-684f208fb84b?auto=format&fit=crop&w=1000&q=85",
|
||||
"https://images.unsplash.com/photo-1559847844-5315695dadae?auto=format&fit=crop&w=1000&q=85",
|
||||
],
|
||||
personal: [
|
||||
"https://images.unsplash.com/photo-1556761175-b413da4baf72?auto=format&fit=crop&w=1000&q=85",
|
||||
"https://images.unsplash.com/photo-1521737711867-e3b97375f902?auto=format&fit=crop&w=1000&q=85",
|
||||
"/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";
|
||||
@@ -53,11 +50,10 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
||||
brandConfig: {
|
||||
visualTemplateKey: "linjing-editorial",
|
||||
templateData: { designPhilosophy: "先厘清问题,再设计表达" },
|
||||
founder: "林然",
|
||||
title: "品牌策略顾问",
|
||||
slogan: "用清晰的定位与可执行的表达,让专业被看见。",
|
||||
phone: "13900000003",
|
||||
wechat: "linran-brand",
|
||||
wechat: "personal-brand",
|
||||
studioAddress: "上海市徐汇区创意园区",
|
||||
heroImage: runtimeImages.personal[0],
|
||||
visualPresentation: {
|
||||
@@ -128,7 +124,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
||||
kind: "service",
|
||||
config: {
|
||||
categoryKey: "consulting",
|
||||
categoryLabel: "策略咨询",
|
||||
keywords: ["定位", "诊断", "表达"],
|
||||
},
|
||||
},
|
||||
@@ -139,7 +134,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
||||
kind: "subscription",
|
||||
config: {
|
||||
categoryKey: "advisory",
|
||||
categoryLabel: "长期顾问",
|
||||
keywords: ["陪跑", "内容", "转化"],
|
||||
},
|
||||
},
|
||||
@@ -147,7 +141,7 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
||||
trustContent: [
|
||||
{
|
||||
type: "credential",
|
||||
title: "关于林然",
|
||||
title: "关于主理人",
|
||||
content: "专注帮助专业服务者建立可信、清晰且能带来合作的个人品牌表达。",
|
||||
},
|
||||
{
|
||||
@@ -248,7 +242,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
||||
priceAmount: 2800,
|
||||
config: {
|
||||
categoryKey: "set-meal",
|
||||
categoryLabel: "套餐",
|
||||
keywords: ["现做", "家常", "定制"],
|
||||
},
|
||||
},
|
||||
@@ -260,7 +253,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
||||
priceAmount: 3200,
|
||||
config: {
|
||||
categoryKey: "set-meal",
|
||||
categoryLabel: "套餐",
|
||||
keywords: ["现做", "家常", "定制"],
|
||||
},
|
||||
},
|
||||
@@ -271,7 +263,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
||||
kind: "service",
|
||||
config: {
|
||||
categoryKey: "private-chef",
|
||||
categoryLabel: "私厨",
|
||||
keywords: ["现做", "家常", "定制"],
|
||||
},
|
||||
},
|
||||
@@ -307,8 +298,7 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
||||
phone: "186-0218-9908",
|
||||
wechat: "LIN-ATELIER-2024",
|
||||
studioAddress: "上海市静安区威海路设计中心 A 座 / 杭州良渚研造工坊",
|
||||
avatarUrl:
|
||||
"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?auto=format&fit=crop&w=240&h=240&q=80",
|
||||
avatarUrl: "/media/seed/personal-avatar.jpg",
|
||||
profilePresentation: {
|
||||
coverage: [
|
||||
{
|
||||
@@ -410,7 +400,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
||||
priceText: "¥38,000 - ¥85,000 / 樘",
|
||||
config: {
|
||||
categoryKey: "entrance-door",
|
||||
categoryLabel: "入户大门",
|
||||
series: "「万籁」重型天地轴入户系统",
|
||||
tag: "主理人年度代表作",
|
||||
area: "浙江·莫干山私家山庄",
|
||||
@@ -446,7 +435,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
||||
priceText: "¥42,000 - ¥98,000 / 樘",
|
||||
config: {
|
||||
categoryKey: "garden-door",
|
||||
categoryLabel: "庭院围墙门",
|
||||
series: "「虚实」透光私家庭院门",
|
||||
tag: "建筑级耐候工艺",
|
||||
area: "上海·佘山高尔夫别墅",
|
||||
@@ -481,7 +469,6 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
||||
priceText: "¥7,800 - ¥16,000 / 樘",
|
||||
config: {
|
||||
categoryKey: "interior-door",
|
||||
categoryLabel: "室内户内门",
|
||||
series: "「空灵」2.8m - 3.2m 满高通顶系统",
|
||||
tag: "极简建筑平直感",
|
||||
area: "江苏·苏州金鸡湖独栋",
|
||||
@@ -510,18 +497,15 @@ const runtimeSeedTemplates: Record<"personal" | "food" | "doors", RuntimeSeedTem
|
||||
{
|
||||
name: "石材及皮质背景墙一体门",
|
||||
summary: "将门体与背景墙材料、纹理和收口一体深化,保留私宅完整的墙面秩序。",
|
||||
image:
|
||||
"https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?auto=format&fit=crop&w=1000&q=85",
|
||||
image: "/media/seed/doors-stone-wall.jpg",
|
||||
kind: "product",
|
||||
priceText: "¥18,000 - ¥36,000 / 樘",
|
||||
config: {
|
||||
categoryKey: "stealth-door",
|
||||
categoryLabel: "装饰隐形门",
|
||||
series: "「无垠」密室及背景墙融合门",
|
||||
tag: "精密收口工程",
|
||||
area: "广东·深圳香蜜湖一号",
|
||||
detailHero:
|
||||
"https://images.unsplash.com/photo-1600210492486-724fe5c67fb0?auto=format&fit=crop&w=1000&q=85",
|
||||
detailHero: "/media/seed/doors-stone-wall.jpg",
|
||||
woodMaterial: "3mm 超薄大理石复合蜂窝板 / 进口鞍革手工双缝线",
|
||||
hardware: "感应式电动自开闭装置或碰珠反弹器",
|
||||
spaceType: "雪茄室 / 私人金库 / 地下酒窖 / 视听隐藏储物区",
|
||||
@@ -729,7 +713,6 @@ async function ensureRuntimeContent(brandId: string, template: RuntimeSeedTempla
|
||||
coverUrl: image,
|
||||
config: {
|
||||
categoryKey: "custom",
|
||||
categoryLabel: "自定义业务",
|
||||
keywords: [],
|
||||
media: [{ url: image, alt: item.name, type: "image" }],
|
||||
sections: [],
|
||||
@@ -827,6 +810,7 @@ async function main(): Promise<void> {
|
||||
username: "admin",
|
||||
passwordHash: await bcrypt.hash(process.env.SEED_ADMIN_PASSWORD ?? "change-me-now-123", 12),
|
||||
displayName: "品牌管理员",
|
||||
mustChangePassword: true,
|
||||
},
|
||||
});
|
||||
await prisma.brandMembership.upsert({
|
||||
@@ -835,39 +819,6 @@ async function main(): Promise<void> {
|
||||
create: { adminUserId: admin.id, brandId: brand.id, role: "owner" },
|
||||
});
|
||||
|
||||
const personalBrand = await prisma.brandProfile.upsert({
|
||||
where: { id: "00000000-0000-0000-0000-000000000003" },
|
||||
update: {
|
||||
slug: "linran-brand",
|
||||
name: "林然品牌顾问",
|
||||
templateKey: "personal",
|
||||
tagline: "用清晰的定位与可执行的表达,让专业被看见。",
|
||||
description: "为专业服务者提供品牌定位、表达与长期顾问支持。",
|
||||
hours: "周一至周五 10:00-18:00",
|
||||
address: "上海市徐汇区创意园区",
|
||||
contactPhone: "13900000003",
|
||||
contactWechat: "linran-brand",
|
||||
},
|
||||
create: {
|
||||
id: "00000000-0000-0000-0000-000000000003",
|
||||
slug: "linran-brand",
|
||||
name: "林然品牌顾问",
|
||||
templateKey: "personal",
|
||||
tagline: "用清晰的定位与可执行的表达,让专业被看见。",
|
||||
description: "为专业服务者提供品牌定位、表达与长期顾问支持。",
|
||||
hours: "周一至周五 10:00-18:00",
|
||||
address: "上海市徐汇区创意园区",
|
||||
contactPhone: "13900000003",
|
||||
contactWechat: "linran-brand",
|
||||
},
|
||||
});
|
||||
await prisma.brandMembership.upsert({
|
||||
where: { adminUserId_brandId: { adminUserId: admin.id, brandId: personalBrand.id } },
|
||||
update: { isEnabled: true, role: "owner" },
|
||||
create: { adminUserId: admin.id, brandId: personalBrand.id, role: "owner" },
|
||||
});
|
||||
await ensureRuntimeContent(personalBrand.id, runtimeSeedTemplates.personal);
|
||||
|
||||
const doorsBrand = await prisma.brandProfile.upsert({
|
||||
where: { id: "00000000-0000-0000-0000-000000000002" },
|
||||
update: {
|
||||
@@ -901,7 +852,6 @@ async function main(): Promise<void> {
|
||||
});
|
||||
await ensureRuntimeContent(doorsBrand.id, runtimeSeedTemplates.doors);
|
||||
await ensureSeedRelease(brand.id, admin.id);
|
||||
await ensureSeedRelease(personalBrand.id, admin.id);
|
||||
await ensureSeedRelease(doorsBrand.id, admin.id);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
UnauthorizedException,
|
||||
ForbiddenException,
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
@@ -14,7 +12,6 @@ import {
|
||||
import { Prisma } from "@prisma/client";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
import { readIdentity } from "./auth.js";
|
||||
import {
|
||||
InstallTemplateDto,
|
||||
CreateOfferingDto,
|
||||
@@ -27,44 +24,32 @@ import {
|
||||
UpdateCapabilityInstallationDto,
|
||||
} from "./admin.dto.js";
|
||||
import {
|
||||
capabilityRegistry,
|
||||
capabilityMetadata,
|
||||
validateCapabilityConfig,
|
||||
capabilityPlugins,
|
||||
getBrandTemplate,
|
||||
getTemplateSampleContent,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
getDefaultVisualTemplateKey,
|
||||
resolveCapabilities,
|
||||
} from "@personal-brand/config";
|
||||
import { TemplateWorkspaceService } from "./template-workspace.service.js";
|
||||
import { validateFieldSnapshot, validateOfferingConfig } from "@personal-brand/validation";
|
||||
import { PublicWorkspaceService } from "./modules/public/public-workspace.controller.js";
|
||||
import { validateFieldSnapshot } from "@personal-brand/validation";
|
||||
import { AdminOfferingService } from "./modules/workspace/admin-offering.service.js";
|
||||
import { AdminWorkspaceService } from "./modules/workspace/admin-workspace.service.js";
|
||||
import { requireAdminIdentity } from "./modules/workspace/admin-access.identity.js";
|
||||
|
||||
@Controller("admin/workspace")
|
||||
class AdminWorkspaceController {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
private readonly publicWorkspace: PublicWorkspaceService,
|
||||
private readonly offeringService: AdminOfferingService,
|
||||
private readonly workspaceService: AdminWorkspaceService,
|
||||
) {}
|
||||
private brandId(): string {
|
||||
return process.env.DEFAULT_BRAND_ID ?? "00000000-0000-0000-0000-000000000001";
|
||||
}
|
||||
|
||||
@Get("offerings")
|
||||
async listOfferings(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const items = await this.prisma.offering.findMany({
|
||||
where: { brandId },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
});
|
||||
return items.map((item) => {
|
||||
const config = (item.config ?? {}) as Record<string, unknown>;
|
||||
return {
|
||||
...item,
|
||||
sections: config.sections ?? [],
|
||||
media: config.media ?? [],
|
||||
cta: config.cta ?? null,
|
||||
};
|
||||
});
|
||||
listOfferings(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
return this.offeringService.list(brandId);
|
||||
}
|
||||
|
||||
@Post("offerings")
|
||||
@@ -72,23 +57,8 @@ class AdminWorkspaceController {
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: CreateOfferingDto,
|
||||
): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const { config, sections, media, cta, ...fields } = body;
|
||||
const configValue = {
|
||||
...(config ?? {}),
|
||||
...(sections === undefined ? {} : { sections }),
|
||||
...(media === undefined ? {} : { media }),
|
||||
...(cta === undefined ? {} : { cta }),
|
||||
};
|
||||
const configIssues = validateOfferingConfig(configValue);
|
||||
if (configIssues.length) throw new BadRequestException("业务提供项配置无效");
|
||||
return this.prisma.offering.create({
|
||||
data: {
|
||||
...fields,
|
||||
brandId,
|
||||
config: configValue as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
return this.offeringService.create(brandId, body);
|
||||
}
|
||||
|
||||
@Patch("offerings/:id")
|
||||
@@ -97,135 +67,52 @@ class AdminWorkspaceController {
|
||||
@Param("id") id: string,
|
||||
@Body() body: UpdateOfferingDto,
|
||||
): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const item = await this.prisma.offering.findFirst({ where: { id, brandId } });
|
||||
if (!item) throw new BadRequestException("业务提供项不存在");
|
||||
const { config, sections, media, cta, ...fields } = body;
|
||||
const configValue = {
|
||||
...(config ?? {}),
|
||||
...(sections === undefined ? {} : { sections }),
|
||||
...(media === undefined ? {} : { media }),
|
||||
...(cta === undefined ? {} : { cta }),
|
||||
};
|
||||
if (validateOfferingConfig(configValue).length)
|
||||
throw new BadRequestException("业务提供项配置无效");
|
||||
return this.prisma.offering.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...fields,
|
||||
...(config === undefined &&
|
||||
sections === undefined &&
|
||||
media === undefined &&
|
||||
cta === undefined
|
||||
? {}
|
||||
: {
|
||||
config: configValue as Prisma.InputJsonValue,
|
||||
}),
|
||||
},
|
||||
});
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
return this.offeringService.update(brandId, id, body);
|
||||
}
|
||||
|
||||
@Delete("offerings/:id")
|
||||
async deleteOffering(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const item = await this.prisma.offering.findFirst({ where: { id, brandId } });
|
||||
if (!item) throw new BadRequestException("业务提供项不存在");
|
||||
const [forms, bookings, items] = await Promise.all([
|
||||
this.prisma.inquiryForm.count({ where: { offeringId: id } }),
|
||||
this.prisma.booking.count({ where: { offeringId: id } }),
|
||||
this.prisma.bookingItem.count({ where: { offeringId: id } }),
|
||||
]);
|
||||
if (forms || bookings || items)
|
||||
throw new BadRequestException("业务提供项已有业务记录,只能禁用不能删除");
|
||||
await this.prisma.offering.delete({ where: { id } });
|
||||
return { deleted: true };
|
||||
}
|
||||
private requireAdmin(request: FastifyRequest): {
|
||||
subject: string;
|
||||
brandId: string;
|
||||
role: "admin";
|
||||
} {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
let identity;
|
||||
try {
|
||||
identity = readIdentity(token);
|
||||
} catch {
|
||||
throw new UnauthorizedException("管理员登录态无效或已过期");
|
||||
}
|
||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||
return identity as { subject: string; brandId: string; role: "admin" };
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
return this.offeringService.delete(brandId, id);
|
||||
}
|
||||
@Get()
|
||||
async get(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const [brand, installations, fields, offerings, forms] = await Promise.all([
|
||||
this.prisma.brandProfile.findUnique({ where: { id: brandId } }),
|
||||
this.prisma.brandTemplateInstallation.findMany({ where: { brandId } }),
|
||||
this.prisma.brandFieldDefinition.findMany({
|
||||
where: { brandId },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
}),
|
||||
this.prisma.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
|
||||
this.prisma.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" } }),
|
||||
]);
|
||||
const config = this.jsonObject(brand?.config);
|
||||
const templateKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? "personal");
|
||||
const manifest = getTemplatePackageManifestForVisualKey(templateKey);
|
||||
return {
|
||||
brand,
|
||||
installations,
|
||||
fields,
|
||||
offerings,
|
||||
forms,
|
||||
templateContent: manifest
|
||||
? {
|
||||
displayName: manifest.displayName,
|
||||
admin: manifest.admin,
|
||||
navigation: manifest.navigation.map(({ key, label, page }) => ({ key, label, page })),
|
||||
templateFields: (manifest.templateFields ?? []).map((field) => ({
|
||||
...field,
|
||||
binding: field.binding ?? `brand.config.templateData.${field.key}`,
|
||||
})),
|
||||
assetSlots: manifest.assetSlots,
|
||||
trustContentTypes: manifest.trustContentTypes ?? [],
|
||||
}
|
||||
: null,
|
||||
};
|
||||
get(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
return this.workspaceService.get(brandId);
|
||||
}
|
||||
@Get("preview")
|
||||
async getPreviewWorkspace(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const { brandId } = this.requireAdmin(request);
|
||||
return this.publicWorkspace.getForBrandId(brandId, true);
|
||||
}
|
||||
private jsonObject(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
const { brandId } = requireAdminIdentity(request);
|
||||
return this.workspaceService.getPreview(brandId);
|
||||
}
|
||||
@Post("install")
|
||||
async install(
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: InstallTemplateDto,
|
||||
): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.templateWorkspace.install(this.requireAdmin(request).brandId, body.templateKey);
|
||||
const { brandId } = requireAdminIdentity(request);
|
||||
return this.templateWorkspace.install(brandId, body.templateKey);
|
||||
}
|
||||
|
||||
@Get("capabilities")
|
||||
async listCapabilities(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
const [templateKey, installations] = await Promise.all([
|
||||
this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
||||
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
|
||||
]);
|
||||
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
|
||||
const template = getBrandTemplate(templateKey);
|
||||
return (template ? resolveCapabilities(template.capabilities) : []).map((definition) => {
|
||||
const optionalCapabilityKeys = Object.entries(capabilityRegistry)
|
||||
.filter(([, definition]) => "optional" in definition && definition.optional)
|
||||
.map(([key]) => key);
|
||||
return [...new Set([...(template?.capabilities ?? []), ...optionalCapabilityKeys])]
|
||||
.map((key) => capabilityRegistry[key as keyof typeof capabilityRegistry])
|
||||
.filter(Boolean)
|
||||
.map((definition) => {
|
||||
const item = installed.get(definition.key);
|
||||
const metadata = capabilityMetadata(definition.key);
|
||||
return {
|
||||
id: item?.id ?? null,
|
||||
capabilityKey: definition.key,
|
||||
@@ -233,6 +120,7 @@ class AdminWorkspaceController {
|
||||
status: item?.status ?? "enabled",
|
||||
config: item?.config ?? {},
|
||||
source: item ? "brand" : "template",
|
||||
...(metadata ?? {}),
|
||||
updatedAt: item?.updatedAt ?? null,
|
||||
};
|
||||
});
|
||||
@@ -240,7 +128,7 @@ class AdminWorkspaceController {
|
||||
|
||||
@Get("sample-content/preview")
|
||||
async previewSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
||||
const sample = getTemplateSampleContent(templateKey);
|
||||
if (!sample) throw new BadRequestException("模板示例内容不存在");
|
||||
@@ -265,7 +153,7 @@ class AdminWorkspaceController {
|
||||
|
||||
@Post("sample-content/import")
|
||||
async importSampleContent(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const identity = this.requireAdmin(request);
|
||||
const identity = requireAdminIdentity(request);
|
||||
const brandId = identity.brandId;
|
||||
const templateKey = await this.templateWorkspace.getEffectiveTemplateKey(brandId);
|
||||
const sample = getTemplateSampleContent(templateKey);
|
||||
@@ -359,7 +247,7 @@ class AdminWorkspaceController {
|
||||
@Param("key") key: string,
|
||||
@Body() body: UpdateCapabilityInstallationDto,
|
||||
): Promise<unknown> {
|
||||
const identity = this.requireAdmin(request);
|
||||
const identity = requireAdminIdentity(request);
|
||||
const brandId = identity.brandId;
|
||||
const template = getBrandTemplate(
|
||||
await this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
||||
@@ -369,18 +257,25 @@ class AdminWorkspaceController {
|
||||
const existing = await this.prisma.capabilityInstallation.findUnique({
|
||||
where: { brandId_capabilityKey: { brandId, capabilityKey: key } },
|
||||
});
|
||||
const definition = capabilityRegistry[key as keyof typeof capabilityRegistry];
|
||||
if (definition && "disablePolicy" in definition && definition.disablePolicy === "disabled")
|
||||
throw new BadRequestException("核心能力不可移除");
|
||||
const configErrors = validateCapabilityConfig(key as never, body.config);
|
||||
if (configErrors === null) throw new BadRequestException("能力配置字段无效");
|
||||
if (Object.keys(configErrors).length)
|
||||
throw new BadRequestException({ message: "能力配置字段无效", errors: configErrors });
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
const installation = await tx.capabilityInstallation.upsert({
|
||||
where: { brandId_capabilityKey: { brandId, capabilityKey: key } },
|
||||
create: {
|
||||
brandId,
|
||||
capabilityKey: key,
|
||||
capabilityVersion: body.capabilityVersion,
|
||||
capabilityVersion: definition?.version ?? "1.0.0",
|
||||
status: body.status,
|
||||
config: (body.config ?? {}) as Prisma.InputJsonValue,
|
||||
},
|
||||
update: {
|
||||
capabilityVersion: body.capabilityVersion,
|
||||
...(definition ? { capabilityVersion: definition.version } : {}),
|
||||
status: body.status,
|
||||
...(body.config === undefined ? {} : { config: body.config as Prisma.InputJsonValue }),
|
||||
},
|
||||
@@ -402,20 +297,20 @@ class AdminWorkspaceController {
|
||||
|
||||
@Get("template/preview")
|
||||
async previewTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.templateWorkspace.preview(this.requireAdmin(request).brandId);
|
||||
const { brandId } = requireAdminIdentity(request);
|
||||
return this.templateWorkspace.preview(brandId);
|
||||
}
|
||||
|
||||
@Post("template/upgrade")
|
||||
async upgradeTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.templateWorkspace.upgrade(this.requireAdmin(request).brandId);
|
||||
const { brandId } = requireAdminIdentity(request);
|
||||
return this.templateWorkspace.upgrade(brandId);
|
||||
}
|
||||
|
||||
@Post("template/rollback")
|
||||
async rollbackTemplate(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
this.requireAdmin(request);
|
||||
return this.templateWorkspace.rollback(this.requireAdmin(request).brandId);
|
||||
const { brandId } = requireAdminIdentity(request);
|
||||
return this.templateWorkspace.rollback(brandId);
|
||||
}
|
||||
|
||||
@Post("fields")
|
||||
@@ -423,7 +318,7 @@ class AdminWorkspaceController {
|
||||
@Req() request: FastifyRequest,
|
||||
@Body() body: CreateFieldDefinitionDto,
|
||||
): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
return this.prisma.brandFieldDefinition.create({
|
||||
data: {
|
||||
...body,
|
||||
@@ -441,7 +336,7 @@ class AdminWorkspaceController {
|
||||
@Param("id") id: string,
|
||||
@Body() body: UpdateFieldDefinitionDto,
|
||||
): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
const item = await this.prisma.brandFieldDefinition.findFirst({
|
||||
where: { id, brandId },
|
||||
});
|
||||
@@ -459,7 +354,7 @@ class AdminWorkspaceController {
|
||||
|
||||
@Delete("fields/:id")
|
||||
async deleteField(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
const item = await this.prisma.brandFieldDefinition.findFirst({
|
||||
where: { id, brandId, source: "custom" },
|
||||
});
|
||||
@@ -470,7 +365,7 @@ class AdminWorkspaceController {
|
||||
|
||||
@Get("forms")
|
||||
listForms(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
return this.prisma.inquiryForm.findMany({
|
||||
where: { brandId },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
@@ -479,7 +374,7 @@ class AdminWorkspaceController {
|
||||
|
||||
@Get("submissions")
|
||||
listSubmissions(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
return this.prisma.inquirySubmission.findMany({
|
||||
where: { brandId },
|
||||
include: {
|
||||
@@ -496,7 +391,7 @@ class AdminWorkspaceController {
|
||||
@Param("id") id: string,
|
||||
@Body() body: UpdateInquirySubmissionDto,
|
||||
): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
const item = await this.prisma.inquirySubmission.findFirst({
|
||||
where: { id, brandId },
|
||||
});
|
||||
@@ -525,7 +420,7 @@ class AdminWorkspaceController {
|
||||
|
||||
@Post("forms")
|
||||
createForm(@Req() request: FastifyRequest, @Body() body: CreateInquiryFormDto): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
if (validateFieldSnapshot(body.fieldsSnapshot).length)
|
||||
throw new BadRequestException("咨询表单字段定义无效");
|
||||
return this.prisma.inquiryForm.create({
|
||||
@@ -544,7 +439,7 @@ class AdminWorkspaceController {
|
||||
@Param("id") id: string,
|
||||
@Body() body: UpdateInquiryFormDto,
|
||||
): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request).brandId;
|
||||
const brandId = requireAdminIdentity(request).brandId;
|
||||
const item = await this.prisma.inquiryForm.findFirst({
|
||||
where: { id, brandId },
|
||||
});
|
||||
|
||||
@@ -11,10 +11,12 @@ import {
|
||||
Max,
|
||||
Min,
|
||||
} from "class-validator";
|
||||
import { brandTemplateKeys } from "@personal-brand/config";
|
||||
import type { BrandTemplateKey } from "@personal-brand/config";
|
||||
|
||||
export class UpdateBrandDto {
|
||||
@IsOptional() @IsString() name?: string;
|
||||
@IsOptional() @IsIn(["food", "personal", "doors"]) templateKey?: "food" | "personal" | "doors";
|
||||
@IsOptional() @IsIn(brandTemplateKeys) templateKey?: BrandTemplateKey;
|
||||
@IsOptional() @IsString() tagline?: string;
|
||||
@IsOptional() @IsString() description?: string;
|
||||
@IsOptional() @IsString() avatarUrl?: string;
|
||||
@@ -101,12 +103,11 @@ export class UpdateBookingTagsDto {
|
||||
}
|
||||
|
||||
export class InstallTemplateDto {
|
||||
@IsIn(["personal", "food", "doors"])
|
||||
templateKey!: "personal" | "food" | "doors";
|
||||
@IsIn(brandTemplateKeys)
|
||||
templateKey!: BrandTemplateKey;
|
||||
}
|
||||
|
||||
export class UpdateCapabilityInstallationDto {
|
||||
@IsString() capabilityVersion!: string;
|
||||
@IsIn(["enabled", "disabled", "degraded"])
|
||||
status!: "enabled" | "disabled" | "degraded";
|
||||
@IsOptional() @IsObject() config?: Record<string, unknown>;
|
||||
|
||||
@@ -12,7 +12,11 @@ import {
|
||||
PublicWorkspaceService,
|
||||
} from "./modules/public/public-workspace.controller.js";
|
||||
import { PublicBrandContextService } from "./modules/public/public-brand-context.service.js";
|
||||
import { AdminOfferingService } from "./modules/workspace/admin-offering.service.js";
|
||||
import { AdminWorkspaceService } from "./modules/workspace/admin-workspace.service.js";
|
||||
import { AdminConfigController } from "./modules/admin/admin-config.controller.js";
|
||||
import { AdminUploadController } from "./modules/admin/admin-upload.controller.js";
|
||||
import { AdminLocalUploadController } from "./modules/admin/admin-local-upload.controller.js";
|
||||
import { PublicOfferingController } from "./modules/public/public-offering.controller.js";
|
||||
import { PublicInquiryFormController } from "./modules/public/public-inquiry-form.controller.js";
|
||||
import { CustomerInquirySubmissionController } from "./modules/customer/customer-inquiry-submission.controller.js";
|
||||
@@ -61,6 +65,8 @@ export class HealthController {
|
||||
AdminBookingController,
|
||||
AdminConfigController,
|
||||
AdminReleaseController,
|
||||
AdminUploadController,
|
||||
AdminLocalUploadController,
|
||||
],
|
||||
providers: [
|
||||
PrismaService,
|
||||
@@ -74,6 +80,8 @@ export class HealthController {
|
||||
BrandReleaseApiService,
|
||||
PublicBrandContextService,
|
||||
PublicWorkspaceService,
|
||||
AdminOfferingService,
|
||||
AdminWorkspaceService,
|
||||
],
|
||||
exports: [PrismaService, WechatAuthService],
|
||||
})
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import {
|
||||
defaultBrandTemplateKey,
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
isVisualTemplateCompatible,
|
||||
@@ -67,7 +68,7 @@ export class BrandReleaseApiService {
|
||||
const visualKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? "personal");
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? defaultBrandTemplateKey);
|
||||
const visual = getVisualTemplate(visualKey);
|
||||
const packageManifest = getTemplatePackageManifestForVisualKey(visualKey);
|
||||
const [offerings, forms, trustItems] = await Promise.all([
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import {
|
||||
defaultBrandTemplateKey,
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
getVisualTemplateManifest,
|
||||
getDefaultVisualTemplateKey,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
} from "@personal-brand/config";
|
||||
import type { TemplatePackageManifest } from "@personal-brand/config";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
|
||||
export interface BrandReleaseSnapshot {
|
||||
@@ -16,7 +18,7 @@ export interface BrandReleaseSnapshot {
|
||||
templateDefinition?: ReturnType<typeof getBrandTemplate> | null;
|
||||
visualTemplateDefinition?: ReturnType<typeof getVisualTemplate> | null;
|
||||
visualTemplateManifest?: ReturnType<typeof getVisualTemplateManifest> | null;
|
||||
templatePackageManifest?: ReturnType<typeof getTemplatePackageManifestForVisualKey> | null;
|
||||
templatePackageManifest?: TemplatePackageManifest | null;
|
||||
brand: Record<string, unknown> | null;
|
||||
installation: Record<string, unknown> | null;
|
||||
fields: unknown[];
|
||||
@@ -43,7 +45,7 @@ export async function buildBrandReleaseSnapshot(
|
||||
database.trustContent.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
|
||||
database.capabilityInstallation.findMany({ where: { brandId } }),
|
||||
]);
|
||||
const templateKey = installation?.templateKey ?? brand?.templateKey ?? "personal";
|
||||
const templateKey = installation?.templateKey ?? brand?.templateKey ?? defaultBrandTemplateKey;
|
||||
const config =
|
||||
brand?.config && typeof brand.config === "object" && !Array.isArray(brand.config)
|
||||
? (brand.config as Record<string, unknown>)
|
||||
@@ -51,7 +53,7 @@ export async function buildBrandReleaseSnapshot(
|
||||
const visualKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? "personal");
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? defaultBrandTemplateKey);
|
||||
const jsonObject = (value: object): Record<string, unknown> =>
|
||||
JSON.parse(JSON.stringify(value)) as Record<string, unknown>;
|
||||
return {
|
||||
|
||||
@@ -2,10 +2,30 @@ import "reflect-metadata";
|
||||
import { NestFactory } from "@nestjs/core";
|
||||
import type { NestFastifyApplication } from "@nestjs/platform-fastify";
|
||||
import { FastifyAdapter } from "@nestjs/platform-fastify";
|
||||
import multipart from "@fastify/multipart";
|
||||
import fastifyStatic from "@fastify/static";
|
||||
import path from "node:path";
|
||||
import { AppModule, configureApp } from "./app.module.js";
|
||||
|
||||
export async function createApp(): Promise<NestFastifyApplication> {
|
||||
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
|
||||
app
|
||||
.getHttpAdapter()
|
||||
.getInstance()
|
||||
.addContentTypeParser(
|
||||
["image/jpeg", "image/png", "image/webp", "image/avif"],
|
||||
{ parseAs: "buffer", bodyLimit: 10 * 1024 * 1024 },
|
||||
(_request: unknown, body: Buffer, done: (error: Error | null, body?: Buffer) => void) =>
|
||||
done(null, body),
|
||||
);
|
||||
await app.register(multipart);
|
||||
if (process.env.LOCAL_MEDIA_ROOT) {
|
||||
await app.register(fastifyStatic, {
|
||||
root: path.resolve(process.env.LOCAL_MEDIA_ROOT),
|
||||
prefix: "/media/",
|
||||
decorateReply: false,
|
||||
});
|
||||
}
|
||||
configureApp(app);
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
UpdateTrustContentDto,
|
||||
} from "../../admin.dto.js";
|
||||
import {
|
||||
defaultVisualTemplateKey,
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
isVisualTemplateCompatible,
|
||||
@@ -278,7 +279,7 @@ export class AdminConfigController {
|
||||
const currentKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: "linjing-editorial";
|
||||
: defaultVisualTemplateKey;
|
||||
const current = getVisualTemplate(currentKey);
|
||||
return {
|
||||
current: current
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { BadRequestException, Controller, Put, Query, Req } from "@nestjs/common";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
|
||||
const allowedExtensions = new Map([
|
||||
["image/jpeg", ".jpg"],
|
||||
["image/png", ".png"],
|
||||
["image/webp", ".webp"],
|
||||
["image/avif", ".avif"],
|
||||
]);
|
||||
|
||||
@Controller("admin/uploads")
|
||||
export class AdminLocalUploadController {
|
||||
constructor(private readonly access: AdminAccessService) {}
|
||||
|
||||
private get mediaRoot(): string {
|
||||
return path.resolve(process.env.LOCAL_MEDIA_ROOT || path.join(process.cwd(), "media"));
|
||||
}
|
||||
|
||||
@Put("local")
|
||||
async upload(
|
||||
@Req() request: FastifyRequest,
|
||||
@Query("key") key?: string,
|
||||
): Promise<{ saved: true }> {
|
||||
await this.access.requireBrand(request);
|
||||
const rawKey = key ?? (request.query as { key?: string }).key;
|
||||
const decodedKey = (rawKey ?? "").includes("%")
|
||||
? decodeURIComponent(rawKey as string)
|
||||
: (rawKey ?? "");
|
||||
if (
|
||||
!decodedKey ||
|
||||
decodedKey.includes("..") ||
|
||||
decodedKey.startsWith("/") ||
|
||||
!/^\d{4}\//.test(decodedKey)
|
||||
) {
|
||||
throw new BadRequestException("上传 key 无效");
|
||||
}
|
||||
if (!allowedExtensions.has(request.headers["content-type"] ?? "")) {
|
||||
throw new BadRequestException("仅支持图片上传");
|
||||
}
|
||||
const contentType = allowedExtensions.get(request.headers["content-type"] ?? "");
|
||||
if (!contentType || !decodedKey.endsWith(contentType)) {
|
||||
throw new BadRequestException("上传文件类型与 key 不一致");
|
||||
}
|
||||
const target = path.join(this.mediaRoot, decodedKey);
|
||||
if (!target.startsWith(path.resolve(this.mediaRoot))) {
|
||||
throw new BadRequestException("上传 key 无效");
|
||||
}
|
||||
await mkdir(path.dirname(target), { recursive: true });
|
||||
await writeFile(target, request.body as Buffer);
|
||||
return { saved: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { BadRequestException, Body, Controller, Get, Post, Req } from "@nestjs/common";
|
||||
import { HeadBucketCommand, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
|
||||
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { IsIn, IsOptional, IsString, MaxLength } from "class-validator";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
|
||||
export class PresignUploadDto {
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
fileName!: string;
|
||||
|
||||
@IsString()
|
||||
@IsIn(["image/jpeg", "image/png", "image/webp", "image/avif"])
|
||||
contentType!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(64)
|
||||
scope?: "brand" | "offering" | "trust";
|
||||
}
|
||||
|
||||
class ObjectStorage {
|
||||
private readonly client = new S3Client({
|
||||
region: process.env.OBJECT_STORAGE_REGION || "us-east-1",
|
||||
...(process.env.OBJECT_STORAGE_ENDPOINT
|
||||
? { endpoint: process.env.OBJECT_STORAGE_ENDPOINT }
|
||||
: {}),
|
||||
forcePathStyle: Boolean(process.env.OBJECT_STORAGE_ENDPOINT),
|
||||
credentials: {
|
||||
accessKeyId: process.env.OBJECT_STORAGE_ACCESS_KEY || "",
|
||||
secretAccessKey: process.env.OBJECT_STORAGE_SECRET_KEY || "",
|
||||
},
|
||||
});
|
||||
|
||||
private get bucket(): string {
|
||||
const bucket = process.env.OBJECT_STORAGE_BUCKET;
|
||||
if (!bucket) throw new BadRequestException("媒体上传尚未配置");
|
||||
return bucket;
|
||||
}
|
||||
|
||||
publicUrl(key: string): string {
|
||||
const endpoint = process.env.OBJECT_STORAGE_PUBLIC_URL?.replace(/\/$/, "");
|
||||
return endpoint ? `${endpoint}/${key}` : `/${key}`;
|
||||
}
|
||||
|
||||
get bucketName(): string {
|
||||
return this.bucket;
|
||||
}
|
||||
|
||||
async presignPut(key: string, contentType: string): Promise<string> {
|
||||
return getSignedUrl(
|
||||
this.client,
|
||||
new PutObjectCommand({ Bucket: this.bucket, Key: key, ContentType: contentType }),
|
||||
{ expiresIn: 600 },
|
||||
);
|
||||
}
|
||||
|
||||
async checkBucket(): Promise<"ok" | "unavailable"> {
|
||||
try {
|
||||
await this.client.send(new HeadBucketCommand({ Bucket: this.bucket }));
|
||||
return "ok";
|
||||
} catch {
|
||||
return "unavailable";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const allowedExtensions = new Map([
|
||||
["image/jpeg", ".jpg"],
|
||||
["image/png", ".png"],
|
||||
["image/webp", ".webp"],
|
||||
["image/avif", ".avif"],
|
||||
]);
|
||||
|
||||
@Controller("admin/uploads")
|
||||
export class AdminUploadController {
|
||||
private readonly storage = new ObjectStorage();
|
||||
|
||||
constructor(private readonly access: AdminAccessService) {}
|
||||
|
||||
private get localMediaRoot(): string {
|
||||
return path.resolve(process.env.LOCAL_MEDIA_ROOT || path.join(process.cwd(), "media"));
|
||||
}
|
||||
|
||||
private get localMediaBaseUrl(): string {
|
||||
return process.env.LOCAL_MEDIA_BASE_URL || "/media";
|
||||
}
|
||||
|
||||
@Get("config")
|
||||
async config() {
|
||||
const objectStorageConfigured = Boolean(
|
||||
process.env.OBJECT_STORAGE_BUCKET &&
|
||||
process.env.OBJECT_STORAGE_ACCESS_KEY &&
|
||||
process.env.OBJECT_STORAGE_SECRET_KEY,
|
||||
);
|
||||
const localMediaConfigured = Boolean(process.env.LOCAL_MEDIA_ROOT);
|
||||
if (localMediaConfigured) {
|
||||
return { configured: true, status: "ok", mode: "local" };
|
||||
}
|
||||
const configured = Boolean(objectStorageConfigured);
|
||||
return {
|
||||
configured,
|
||||
status: configured ? await this.storage.checkBucket() : "unconfigured",
|
||||
...(configured ? { bucket: this.storage.bucketName } : {}),
|
||||
...(configured ? { mode: "object-storage" } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@Post("presign")
|
||||
async presign(@Req() request: FastifyRequest, @Body() body: PresignUploadDto) {
|
||||
await this.access.requireBrand(request);
|
||||
const extension = allowedExtensions.get(body.contentType);
|
||||
if (!extension) throw new BadRequestException("仅支持 JPG、PNG、WebP 或 AVIF 图片");
|
||||
const cleanName = body.fileName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9._-]+/g, "-")
|
||||
.slice(-64);
|
||||
const digest = createHash("sha256")
|
||||
.update(`${body.scope ?? "brand"}:${cleanName}:${randomUUID()}`)
|
||||
.digest("hex")
|
||||
.slice(0, 16);
|
||||
const key = `${new Date().getFullYear()}/${digest}${extension}`;
|
||||
const objectStorageEnabled = Boolean(
|
||||
process.env.OBJECT_STORAGE_BUCKET &&
|
||||
process.env.OBJECT_STORAGE_ACCESS_KEY &&
|
||||
process.env.OBJECT_STORAGE_SECRET_KEY,
|
||||
);
|
||||
if (objectStorageEnabled) {
|
||||
const uploadUrl = await this.storage.presignPut(key, body.contentType);
|
||||
return { uploadUrl, key, publicUrl: this.storage.publicUrl(key) };
|
||||
}
|
||||
const target = path.join(this.localMediaRoot, key);
|
||||
await mkdir(path.dirname(target), { recursive: true });
|
||||
return {
|
||||
uploadUrl: `/admin/uploads/local?key=${encodeURIComponent(key)}`,
|
||||
key,
|
||||
publicUrl: `${this.localMediaBaseUrl}/${key}`,
|
||||
mode: "local",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,31 +1,14 @@
|
||||
import { Controller, Get, Injectable, Query } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import {
|
||||
buildBrandReleaseSnapshot,
|
||||
type BrandReleaseSnapshot,
|
||||
} from "../../brand-release.service.js";
|
||||
import { PublicBrandContextService } from "./public-brand-context.service.js";
|
||||
import type { BrandReleaseSnapshot } from "../../brand-release.service.js";
|
||||
import {
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
getVisualTemplateManifest,
|
||||
resolveCapabilities,
|
||||
capabilityPlugins,
|
||||
getDefaultVisualTemplateKey,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
} from "@personal-brand/config";
|
||||
import type {
|
||||
RuntimeInquiryField,
|
||||
RuntimeOffering,
|
||||
RuntimeTrustItem,
|
||||
RuntimeWorkspace,
|
||||
} from "@personal-brand/types";
|
||||
import { buildBrandReleaseSnapshot } from "../../brand-release.service.js";
|
||||
import {
|
||||
projectBrandAliases,
|
||||
projectOfferingDetails,
|
||||
projectTemplateData,
|
||||
projectTrustItem,
|
||||
projectTrustPresentation,
|
||||
} from "@personal-brand/types";
|
||||
assemblePublicWorkspace,
|
||||
createUnpublishedWorkspace,
|
||||
} from "./public-workspace.snapshot-assembler.js";
|
||||
|
||||
@Injectable()
|
||||
export class PublicWorkspaceService {
|
||||
@@ -38,335 +21,15 @@ export class PublicWorkspaceService {
|
||||
select: { version: true, createdAt: true, snapshot: true },
|
||||
});
|
||||
const draftSnapshot = draft ? await buildBrandReleaseSnapshot(this.prisma, brandId) : null;
|
||||
const sourceSnapshot = draftSnapshot ?? release?.snapshot;
|
||||
const releaseSnapshot = this.jsonObject(sourceSnapshot) as unknown as BrandReleaseSnapshot;
|
||||
if (!release && !draftSnapshot) {
|
||||
return {
|
||||
contractVersion: "1.0",
|
||||
schemaVersion: "1.0.0",
|
||||
publication: { status: "unpublished", version: null },
|
||||
brand: null,
|
||||
template: null,
|
||||
visualTemplate: null,
|
||||
offerings: [],
|
||||
inquiryForms: [],
|
||||
trustItems: [],
|
||||
capabilities: [],
|
||||
trustPresentation: {},
|
||||
navigation: { tabs: [] },
|
||||
plugins: [],
|
||||
theme: { colors: {} },
|
||||
};
|
||||
}
|
||||
const brandData = this.jsonObject(releaseSnapshot.brand);
|
||||
const offeringsData = this.jsonArray(releaseSnapshot.offerings).filter(
|
||||
(item) => this.jsonObject(item).isEnabled === true,
|
||||
) as Array<Record<string, unknown>>;
|
||||
const enabledOfferingIds = new Set(offeringsData.map((item) => item.id));
|
||||
const formsData = this.jsonArray(releaseSnapshot.forms).filter((item) => {
|
||||
const form = this.jsonObject(item);
|
||||
return (
|
||||
form.isEnabled === true &&
|
||||
(form.offeringId === null || enabledOfferingIds.has(form.offeringId))
|
||||
);
|
||||
if (!release && !draftSnapshot) return createUnpublishedWorkspace();
|
||||
|
||||
const sourceSnapshot = draftSnapshot ?? (release?.snapshot as BrandReleaseSnapshot | null);
|
||||
const snapshot = sourceSnapshot as BrandReleaseSnapshot;
|
||||
return assemblePublicWorkspace({
|
||||
release: release ? { version: release.version, createdAt: release.createdAt } : null,
|
||||
snapshot,
|
||||
draftSnapshot,
|
||||
});
|
||||
const trustData = this.jsonArray(releaseSnapshot.trustContents).filter(
|
||||
(item) => this.jsonObject(item).isPublished === true,
|
||||
) as Array<Record<string, unknown>>;
|
||||
const installationData = this.jsonObject(releaseSnapshot.installation);
|
||||
const templateKeyFromSnapshot =
|
||||
typeof releaseSnapshot.templateKey === "string" ? releaseSnapshot.templateKey : undefined;
|
||||
const templateKey =
|
||||
templateKeyFromSnapshot ??
|
||||
(typeof installationData.templateKey === "string"
|
||||
? installationData.templateKey
|
||||
: undefined) ??
|
||||
(typeof brandData.templateKey === "string" ? brandData.templateKey : "personal");
|
||||
const template = releaseSnapshot.templateDefinition ?? getBrandTemplate(templateKey);
|
||||
const capabilityData = this.jsonArray(releaseSnapshot.capabilities) as Array<
|
||||
Record<string, unknown>
|
||||
>;
|
||||
const runtimeCapabilities = capabilityData.length
|
||||
? capabilityData.map((item) => ({
|
||||
key: this.string(item.capabilityKey),
|
||||
version: this.string(item.capabilityVersion, "1.0.0"),
|
||||
status: this.capabilityStatus(item.status),
|
||||
config:
|
||||
item.config && typeof item.config === "object" && !Array.isArray(item.config)
|
||||
? (item.config as Record<string, unknown>)
|
||||
: {},
|
||||
}))
|
||||
: template
|
||||
? resolveCapabilities(template.capabilities).map((item) => ({
|
||||
key: item.key,
|
||||
version: item.version,
|
||||
status: "enabled" as const,
|
||||
config: {},
|
||||
}))
|
||||
: [];
|
||||
const brandConfig =
|
||||
brandData.config && typeof brandData.config === "object" && !Array.isArray(brandData.config)
|
||||
? (brandData.config as Record<string, unknown>)
|
||||
: {};
|
||||
const visualTemplateKey =
|
||||
typeof brandConfig.visualTemplateKey === "string"
|
||||
? brandConfig.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(templateKey);
|
||||
const visualTemplate =
|
||||
releaseSnapshot.visualTemplateDefinition ?? getVisualTemplate(visualTemplateKey);
|
||||
const visualTemplateManifest =
|
||||
releaseSnapshot.visualTemplateManifest ?? getVisualTemplateManifest(visualTemplateKey);
|
||||
const templatePackageManifest =
|
||||
releaseSnapshot.templatePackageManifest ??
|
||||
getTemplatePackageManifestForVisualKey(visualTemplateKey);
|
||||
// 标准 BrandProfile 字段优先,兼容旧模板仍使用的 config 字段。
|
||||
// 这样后台编辑 description/contactPhone 等标准字段后,旧模板也会立即读取新值。
|
||||
const runtimeBrand = projectBrandAliases(brandData, brandConfig);
|
||||
const declaredTemplateFields = templatePackageManifest?.templateFields ?? [];
|
||||
const templateData = projectTemplateData(
|
||||
brandConfig,
|
||||
declaredTemplateFields.map((field) => field.key),
|
||||
);
|
||||
const runtimeOfferings: RuntimeOffering[] = offeringsData.map((raw) => {
|
||||
const item = raw;
|
||||
const config = this.jsonObject(item.config);
|
||||
const sections = Array.isArray(config.sections) ? config.sections : [];
|
||||
const details = projectOfferingDetails(config);
|
||||
const media = Array.isArray(config.media)
|
||||
? config.media.flatMap((entry) => {
|
||||
const value = this.jsonObject(entry);
|
||||
return typeof value.url === "string"
|
||||
? [
|
||||
{
|
||||
url: value.url,
|
||||
alt:
|
||||
typeof value.alt === "string"
|
||||
? value.alt
|
||||
: this.string(item.name, "业务提供项"),
|
||||
type: "image" as const,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
})
|
||||
: [];
|
||||
return {
|
||||
id: this.string(item.id),
|
||||
name: this.string(item.name),
|
||||
summary: typeof item.summary === "string" ? item.summary : this.string(item.description),
|
||||
enabled: item.isEnabled !== false,
|
||||
kind: this.offeringKind(this.string(item.kind, "service")),
|
||||
coverUrl: typeof item.coverUrl === "string" ? item.coverUrl : null,
|
||||
priceText: typeof item.priceText === "string" ? item.priceText : null,
|
||||
priceAmount: typeof item.priceAmount === "number" ? item.priceAmount : null,
|
||||
schemaKey: typeof config.schemaKey === "string" ? config.schemaKey : "offering.default",
|
||||
schemaVersion: typeof config.schemaVersion === "string" ? config.schemaVersion : "1.0.0",
|
||||
presentation: {
|
||||
...Object.fromEntries(
|
||||
Object.entries(config).filter(
|
||||
([key]) =>
|
||||
![
|
||||
"schemaKey",
|
||||
"schemaVersion",
|
||||
"details",
|
||||
"sections",
|
||||
"media",
|
||||
"presentation",
|
||||
].includes(key),
|
||||
),
|
||||
),
|
||||
...this.jsonObject(config.presentation),
|
||||
categoryKey: typeof config.categoryKey === "string" ? config.categoryKey : "custom",
|
||||
categoryLabel:
|
||||
typeof config.categoryLabel === "string" ? config.categoryLabel : "业务提供项",
|
||||
heroImage:
|
||||
typeof config.detailHero === "string"
|
||||
? config.detailHero
|
||||
: typeof item.coverUrl === "string"
|
||||
? item.coverUrl
|
||||
: null,
|
||||
keywords: Array.isArray(config.keywords)
|
||||
? config.keywords.filter((keyword): keyword is string => typeof keyword === "string")
|
||||
: [],
|
||||
media,
|
||||
details: {
|
||||
background: details.background,
|
||||
designConcept: details.designConcept,
|
||||
crafts: details.crafts,
|
||||
materialsList: details.materialsList,
|
||||
},
|
||||
},
|
||||
sections: sections
|
||||
.filter((section): section is Record<string, unknown> =>
|
||||
Boolean(section && typeof section === "object"),
|
||||
)
|
||||
.map((section) => ({
|
||||
key: typeof section.key === "string" ? section.key : "section",
|
||||
type: this.sectionType(section.type),
|
||||
config: this.jsonObject(section.config),
|
||||
})),
|
||||
};
|
||||
});
|
||||
const toInquiryFields = (snapshot: Prisma.JsonValue): RuntimeInquiryField[] =>
|
||||
this.jsonArray(snapshot).flatMap((field) => {
|
||||
if (!field || typeof field !== "object") return [];
|
||||
const value = field as Record<string, unknown>;
|
||||
if (typeof value.key !== "string" || typeof value.label !== "string") return [];
|
||||
const sourceType = this.string(value.type);
|
||||
const type =
|
||||
sourceType === "phone"
|
||||
? "tel"
|
||||
: sourceType === "multi-select"
|
||||
? "checkbox"
|
||||
: [
|
||||
"text",
|
||||
"tel",
|
||||
"number",
|
||||
"select",
|
||||
"radio",
|
||||
"checkbox",
|
||||
"checkbox",
|
||||
"textarea",
|
||||
"date",
|
||||
].includes(sourceType)
|
||||
? (sourceType as RuntimeInquiryField["type"])
|
||||
: "text";
|
||||
const options = Array.isArray(value.options)
|
||||
? value.options.flatMap((option) => {
|
||||
if (typeof option === "string") return [{ label: option, value: option }];
|
||||
if (!option || typeof option !== "object") return [];
|
||||
const item = option as Record<string, unknown>;
|
||||
return typeof item.label === "string" && typeof item.value === "string"
|
||||
? [{ label: item.label, value: item.value }]
|
||||
: [];
|
||||
})
|
||||
: undefined;
|
||||
return [
|
||||
{
|
||||
key: value.key,
|
||||
label: value.label,
|
||||
type,
|
||||
required: value.required === true,
|
||||
...(options?.length ? { options } : {}),
|
||||
},
|
||||
];
|
||||
});
|
||||
const trustDeclarations = templatePackageManifest?.trustContentTypes ?? [];
|
||||
const trustItems: RuntimeTrustItem[] = trustData.flatMap((raw) => {
|
||||
const item = projectTrustItem(this.jsonObject(raw));
|
||||
return item && trustDeclarations.some((declaration) => declaration.type === item.type)
|
||||
? [item]
|
||||
: [];
|
||||
});
|
||||
const trustPresentation = projectTrustPresentation(trustItems, trustDeclarations);
|
||||
const runtimeWorkspace: RuntimeWorkspace = {
|
||||
schemaVersion: "1.0.0",
|
||||
publication: {
|
||||
status: draftSnapshot ? "draft" : "published",
|
||||
version: draftSnapshot ? null : (release?.version ?? null),
|
||||
...(!draftSnapshot && release ? { publishedAt: release.createdAt.toISOString() } : {}),
|
||||
},
|
||||
brand: runtimeBrand,
|
||||
templateData,
|
||||
navigation: {
|
||||
tabs:
|
||||
templatePackageManifest?.navigation.map((tab) => ({
|
||||
key: tab.key,
|
||||
label: tab.label,
|
||||
page: templatePackageManifest.entrypoints[tab.page] ?? tab.page,
|
||||
})) ?? [],
|
||||
},
|
||||
offerings: runtimeOfferings,
|
||||
inquiryForms: formsData.map((raw) => {
|
||||
const form = this.jsonObject(raw);
|
||||
return {
|
||||
key: this.string(form.id),
|
||||
version:
|
||||
typeof form.version === "number"
|
||||
? String(form.version)
|
||||
: this.string(form.version, "1"),
|
||||
purpose: this.formPurpose(this.string(form.purpose, "inquiry")),
|
||||
target: form.targetType === "offering" ? "offering" : "brand",
|
||||
...(typeof form.offeringId === "string" ? { targetId: form.offeringId } : {}),
|
||||
submissionAction: this.submissionAction(
|
||||
this.string(form.submissionAction, "create-inquiry"),
|
||||
),
|
||||
fields: toInquiryFields(form.fieldsSnapshot as Prisma.JsonValue),
|
||||
};
|
||||
}),
|
||||
trustItems,
|
||||
trustPresentation,
|
||||
capabilities: runtimeCapabilities,
|
||||
plugins: runtimeCapabilities
|
||||
.filter((capability) => capability.status === "enabled")
|
||||
.map((capability) => capability.key)
|
||||
.map((key) => capabilityPlugins[key as keyof typeof capabilityPlugins])
|
||||
.filter(Boolean)
|
||||
.map((plugin) => ({ ...plugin, status: "enabled" as const, config: {} })),
|
||||
theme: visualTemplate?.theme ?? {
|
||||
colors: { background: "#F7F5F1", foreground: "#252525", accent: "#8A6846" },
|
||||
},
|
||||
...(visualTemplate?.layout ? { layout: visualTemplate.layout } : {}),
|
||||
};
|
||||
const response = {
|
||||
...runtimeWorkspace,
|
||||
contractVersion: "1.0",
|
||||
brand: runtimeBrand,
|
||||
template: template
|
||||
? {
|
||||
key: template.key,
|
||||
version:
|
||||
typeof installationData.templateVersion === "string"
|
||||
? installationData.templateVersion
|
||||
: template.version,
|
||||
name: template.name,
|
||||
}
|
||||
: null,
|
||||
visualTemplate: visualTemplate
|
||||
? {
|
||||
key: visualTemplate.key,
|
||||
version: visualTemplate.version,
|
||||
name: visualTemplate.name,
|
||||
supportedIndustryTemplates: visualTemplate.supportedIndustryTemplates,
|
||||
variants: visualTemplate.variants,
|
||||
}
|
||||
: null,
|
||||
visualTemplateManifest,
|
||||
};
|
||||
return response;
|
||||
}
|
||||
private jsonObject(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
private string(value: unknown, fallback = ""): string {
|
||||
return typeof value === "string" ? value : fallback;
|
||||
}
|
||||
private capabilityStatus(value: unknown): "enabled" | "disabled" | "degraded" {
|
||||
return value === "disabled" || value === "degraded" ? value : "enabled";
|
||||
}
|
||||
private jsonArray(value: unknown): Prisma.JsonValue[] {
|
||||
return Array.isArray(value) ? (value as Prisma.JsonValue[]) : [];
|
||||
}
|
||||
private sectionType(value: unknown): RuntimeOffering["sections"][number]["type"] {
|
||||
const known = ["text", "image-list", "timeline", "faq", "specification"] as const;
|
||||
return known.includes(value as (typeof known)[number])
|
||||
? (value as (typeof known)[number])
|
||||
: "text";
|
||||
}
|
||||
private offeringKind(value: string): RuntimeOffering["kind"] {
|
||||
const known: RuntimeOffering["kind"][] = ["service", "product", "package", "subscription"];
|
||||
return known.includes(value as RuntimeOffering["kind"])
|
||||
? (value as RuntimeOffering["kind"])
|
||||
: "service";
|
||||
}
|
||||
private formPurpose(value: string): RuntimeWorkspace["inquiryForms"][number]["purpose"] {
|
||||
return value === "booking" || value === "quote-request" ? value : "inquiry";
|
||||
}
|
||||
private submissionAction(
|
||||
value: string,
|
||||
): RuntimeWorkspace["inquiryForms"][number]["submissionAction"] {
|
||||
return value === "create-booking" || value === "create-quote" ? value : "create-inquiry";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { RuntimeInquiryField, RuntimeOffering, RuntimeWorkspace } from "@personal-brand/types";
|
||||
import { projectOfferingDetails } from "@personal-brand/types";
|
||||
|
||||
export function asRecord(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
export function asArray(value: unknown): unknown[] {
|
||||
return Array.isArray(value) ? value : [];
|
||||
}
|
||||
|
||||
export function asString(value: unknown, fallback = ""): string {
|
||||
return typeof value === "string" ? value : fallback;
|
||||
}
|
||||
|
||||
export function offeringKind(value: string): RuntimeOffering["kind"] {
|
||||
const known: RuntimeOffering["kind"][] = ["service", "product", "package", "subscription"];
|
||||
return known.find((item) => item === value) ?? "service";
|
||||
}
|
||||
|
||||
export function sectionType(value: unknown): RuntimeOffering["sections"][number]["type"] {
|
||||
const known = ["text", "image-list", "timeline", "faq", "specification"] as const;
|
||||
return known.includes(value as (typeof known)[number])
|
||||
? (value as (typeof known)[number])
|
||||
: "text";
|
||||
}
|
||||
|
||||
export function capabilityStatus(value: unknown): "enabled" | "disabled" | "degraded" {
|
||||
return value === "disabled" || value === "degraded" ? value : "enabled";
|
||||
}
|
||||
|
||||
export function formPurpose(value: string): RuntimeWorkspace["inquiryForms"][number]["purpose"] {
|
||||
return value === "booking" || value === "quote-request" ? value : "inquiry";
|
||||
}
|
||||
|
||||
export function submissionAction(
|
||||
value: string,
|
||||
): RuntimeWorkspace["inquiryForms"][number]["submissionAction"] {
|
||||
return value === "create-booking" || value === "create-quote" ? value : "create-inquiry";
|
||||
}
|
||||
|
||||
export function toRuntimeOffering(
|
||||
item: Record<string, unknown>,
|
||||
categoryOptions: Map<string, string>,
|
||||
): RuntimeOffering {
|
||||
const config = asRecord(item.config);
|
||||
const sections = asArray(config.sections).filter((section): section is Record<string, unknown> =>
|
||||
Boolean(section && typeof section === "object"),
|
||||
);
|
||||
const details = projectOfferingDetails(config);
|
||||
const media = asArray(config.media).flatMap((entry) => {
|
||||
const value = asRecord(entry);
|
||||
return typeof value.url === "string"
|
||||
? [
|
||||
{
|
||||
url: value.url,
|
||||
alt: asString(value.alt, asString(item.name, "业务提供项")),
|
||||
type: "image" as const,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
});
|
||||
const categoryKey = typeof config.categoryKey === "string" ? config.categoryKey : "custom";
|
||||
return {
|
||||
id: asString(item.id),
|
||||
name: asString(item.name),
|
||||
summary: typeof item.summary === "string" ? item.summary : asString(item.description),
|
||||
enabled: item.isEnabled !== false,
|
||||
kind: offeringKind(asString(item.kind, "service")),
|
||||
coverUrl: typeof item.coverUrl === "string" ? item.coverUrl : null,
|
||||
priceText: typeof item.priceText === "string" ? item.priceText : null,
|
||||
priceAmount: typeof item.priceAmount === "number" ? item.priceAmount : null,
|
||||
schemaKey: asString(config.schemaKey, "offering.default"),
|
||||
schemaVersion: asString(config.schemaVersion, "1.0.0"),
|
||||
presentation: {
|
||||
...Object.fromEntries(
|
||||
Object.entries(config).filter(
|
||||
([key]) =>
|
||||
![
|
||||
"schemaKey",
|
||||
"schemaVersion",
|
||||
"details",
|
||||
"sections",
|
||||
"media",
|
||||
"presentation",
|
||||
].includes(key),
|
||||
),
|
||||
),
|
||||
...asRecord(config.presentation),
|
||||
categoryKey,
|
||||
categoryLabel: categoryOptions.get(categoryKey) ?? "",
|
||||
heroImage:
|
||||
typeof config.detailHero === "string"
|
||||
? config.detailHero
|
||||
: typeof item.coverUrl === "string"
|
||||
? item.coverUrl
|
||||
: null,
|
||||
keywords: asArray(config.keywords).filter(
|
||||
(keyword): keyword is string => typeof keyword === "string",
|
||||
),
|
||||
media,
|
||||
details: {
|
||||
background: details.background,
|
||||
designConcept: details.designConcept,
|
||||
crafts: details.crafts,
|
||||
materialsList: details.materialsList,
|
||||
},
|
||||
},
|
||||
sections: sections.map((section) => ({
|
||||
key: asString(section.key, "section"),
|
||||
type: sectionType(section.type),
|
||||
config: asRecord(section.config),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function toRuntimeInquiryFields(snapshot: Prisma.JsonValue): RuntimeInquiryField[] {
|
||||
return asArray(snapshot).flatMap((field) => {
|
||||
if (!field || typeof field !== "object") return [];
|
||||
const value = field as Record<string, unknown>;
|
||||
if (typeof value.key !== "string" || typeof value.label !== "string") return [];
|
||||
const sourceType = asString(value.type);
|
||||
const type =
|
||||
sourceType === "phone"
|
||||
? "tel"
|
||||
: sourceType === "multi-select"
|
||||
? "checkbox"
|
||||
: [
|
||||
"text",
|
||||
"tel",
|
||||
"number",
|
||||
"select",
|
||||
"radio",
|
||||
"checkbox",
|
||||
"checkbox",
|
||||
"textarea",
|
||||
"date",
|
||||
].includes(sourceType)
|
||||
? (sourceType as RuntimeInquiryField["type"])
|
||||
: "text";
|
||||
const options = asArray(value.options).flatMap((option) => {
|
||||
if (typeof option === "string") return [{ label: option, value: option }];
|
||||
if (!option || typeof option !== "object") return [];
|
||||
const item = option as Record<string, unknown>;
|
||||
return typeof item.label === "string" && typeof item.value === "string"
|
||||
? [{ label: item.label, value: item.value }]
|
||||
: [];
|
||||
});
|
||||
return [
|
||||
{
|
||||
key: value.key,
|
||||
label: value.label,
|
||||
type,
|
||||
required: value.required === true,
|
||||
...(options.length ? { options } : {}),
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import type { BrandReleaseSnapshot } from "../../brand-release.service.js";
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import {
|
||||
capabilityMetadata,
|
||||
capabilityPlugins,
|
||||
defaultBrandTemplateKey,
|
||||
type BrandTemplateKey,
|
||||
getBrandTemplate,
|
||||
getDefaultVisualTemplateKey,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
getVisualTemplate,
|
||||
getVisualTemplateManifest,
|
||||
resolveCapabilities,
|
||||
} from "@personal-brand/config";
|
||||
import type { RuntimeTrustItem, RuntimeWorkspace } from "@personal-brand/types";
|
||||
import {
|
||||
projectBrandAliases,
|
||||
projectTemplateData,
|
||||
projectTrustItem,
|
||||
projectTrustPresentation,
|
||||
} from "@personal-brand/types";
|
||||
import {
|
||||
asArray,
|
||||
asRecord,
|
||||
asString,
|
||||
capabilityStatus,
|
||||
formPurpose,
|
||||
submissionAction,
|
||||
toRuntimeInquiryFields,
|
||||
toRuntimeOffering,
|
||||
} from "./public-workspace.runtime-mapper.js";
|
||||
|
||||
type ReleaseMetadata = { version: number; createdAt: Date };
|
||||
|
||||
type PublicWorkspaceResponse = Omit<RuntimeWorkspace, "brand"> & {
|
||||
contractVersion: string;
|
||||
brand: Record<string, unknown> | null;
|
||||
template: {
|
||||
key: string;
|
||||
version: string;
|
||||
name: string;
|
||||
} | null;
|
||||
visualTemplate: {
|
||||
key: string;
|
||||
version: string;
|
||||
name: string;
|
||||
supportedIndustryTemplates: BrandTemplateKey[];
|
||||
variants: Record<string, string>;
|
||||
} | null;
|
||||
visualTemplateManifest: BrandReleaseSnapshot["visualTemplateManifest"];
|
||||
};
|
||||
|
||||
export function createUnpublishedWorkspace(): PublicWorkspaceResponse {
|
||||
return {
|
||||
contractVersion: "1.0",
|
||||
schemaVersion: "1.0.0",
|
||||
publication: { status: "unpublished", version: null },
|
||||
brand: null,
|
||||
template: null,
|
||||
visualTemplate: null,
|
||||
visualTemplateManifest: null,
|
||||
offerings: [],
|
||||
inquiryForms: [],
|
||||
trustItems: [],
|
||||
capabilities: [],
|
||||
trustPresentation: {},
|
||||
navigation: { tabs: [] },
|
||||
templateData: {},
|
||||
plugins: [],
|
||||
theme: { colors: {} },
|
||||
};
|
||||
}
|
||||
|
||||
export function assemblePublicWorkspace(input: {
|
||||
release: ReleaseMetadata | null;
|
||||
snapshot: BrandReleaseSnapshot;
|
||||
draftSnapshot: BrandReleaseSnapshot | null;
|
||||
}): PublicWorkspaceResponse {
|
||||
const { release, snapshot, draftSnapshot } = input;
|
||||
const releaseSnapshot = snapshot;
|
||||
const brandData = asRecord(releaseSnapshot.brand);
|
||||
const offeringsData = asArray(releaseSnapshot.offerings).filter(
|
||||
(item) => asRecord(item).isEnabled === true,
|
||||
) as Array<Record<string, unknown>>;
|
||||
const enabledOfferingIds = new Set(offeringsData.map((item) => item.id));
|
||||
const formsData = asArray(releaseSnapshot.forms).filter((item) => {
|
||||
const form = asRecord(item);
|
||||
return (
|
||||
form.isEnabled === true &&
|
||||
(form.offeringId === null || enabledOfferingIds.has(form.offeringId))
|
||||
);
|
||||
}) as Array<Record<string, unknown>>;
|
||||
const trustData = asArray(releaseSnapshot.trustContents).filter(
|
||||
(item) => asRecord(item).isPublished === true,
|
||||
) as Array<Record<string, unknown>>;
|
||||
const installationData = asRecord(releaseSnapshot.installation);
|
||||
const templateKey =
|
||||
asString(releaseSnapshot.templateKey) ||
|
||||
asString(installationData.templateKey) ||
|
||||
asString(brandData.templateKey) ||
|
||||
defaultBrandTemplateKey;
|
||||
const template = releaseSnapshot.templateDefinition ?? getBrandTemplate(templateKey);
|
||||
const capabilityData = asArray(releaseSnapshot.capabilities) as Array<Record<string, unknown>>;
|
||||
const capabilityRecord = (item: Record<string, unknown>, fallbackVersion = "1.0.0") => {
|
||||
const key = asString(item.capabilityKey) || asString(item.key);
|
||||
const metadata = capabilityMetadata(key as never);
|
||||
return {
|
||||
key,
|
||||
version: asString(item.capabilityVersion, fallbackVersion),
|
||||
status: capabilityStatus(item.status),
|
||||
config: asRecord(item.config),
|
||||
...(metadata ? { metadata: { ...metadata } } : {}),
|
||||
};
|
||||
};
|
||||
const capabilities = capabilityData.length
|
||||
? capabilityData.map((item) => capabilityRecord(item))
|
||||
: template
|
||||
? resolveCapabilities(template.capabilities).map((item) =>
|
||||
capabilityRecord({ ...item, config: {} }),
|
||||
)
|
||||
: [];
|
||||
const brandConfig = asRecord(brandData.config);
|
||||
const visualTemplateKey =
|
||||
asString(brandConfig.visualTemplateKey) || getDefaultVisualTemplateKey(templateKey);
|
||||
const visualTemplate =
|
||||
releaseSnapshot.visualTemplateDefinition ?? getVisualTemplate(visualTemplateKey);
|
||||
const visualTemplateManifest =
|
||||
releaseSnapshot.visualTemplateManifest ?? getVisualTemplateManifest(visualTemplateKey);
|
||||
const templatePackageManifest =
|
||||
releaseSnapshot.templatePackageManifest ??
|
||||
getTemplatePackageManifestForVisualKey(visualTemplateKey);
|
||||
const categoryOptions = new Map(
|
||||
(templatePackageManifest?.admin.sections ?? [])
|
||||
.filter((section) => section.target === "offering")
|
||||
.flatMap((section) => section.fields)
|
||||
.filter((field) => field.binding === "offering.config.categoryKey")
|
||||
.flatMap((field) => field.options ?? [])
|
||||
.map((option) => [option.value, option.label]),
|
||||
);
|
||||
const runtimeBrand = projectBrandAliases(brandData, brandConfig);
|
||||
const templateData = projectTemplateData(
|
||||
brandConfig,
|
||||
(templatePackageManifest?.templateFields ?? []).map((field) => field.key),
|
||||
);
|
||||
const trustDeclarations = templatePackageManifest?.trustContentTypes ?? [];
|
||||
const trustItems: RuntimeTrustItem[] = trustData.flatMap((raw) => {
|
||||
const item = projectTrustItem(asRecord(raw));
|
||||
return item && trustDeclarations.some((declaration) => declaration.type === item.type)
|
||||
? [item]
|
||||
: [];
|
||||
});
|
||||
const runtimeWorkspace: RuntimeWorkspace = {
|
||||
schemaVersion: "1.0.0",
|
||||
publication: {
|
||||
status: draftSnapshot ? "draft" : "published",
|
||||
version: draftSnapshot ? null : (release?.version ?? null),
|
||||
...(!draftSnapshot && release ? { publishedAt: release.createdAt.toISOString() } : {}),
|
||||
},
|
||||
brand: runtimeBrand,
|
||||
templateData,
|
||||
navigation: {
|
||||
tabs:
|
||||
templatePackageManifest?.navigation.map((tab) => ({
|
||||
key: tab.key,
|
||||
label: tab.label,
|
||||
page: templatePackageManifest.entrypoints[tab.page] ?? tab.page,
|
||||
})) ?? [],
|
||||
},
|
||||
offerings: offeringsData.map((item) => toRuntimeOffering(item, categoryOptions)),
|
||||
inquiryForms: formsData.map((raw) => {
|
||||
const form = asRecord(raw);
|
||||
return {
|
||||
key: asString(form.id),
|
||||
version:
|
||||
typeof form.version === "number" ? String(form.version) : asString(form.version, "1"),
|
||||
purpose: formPurpose(asString(form.purpose, "inquiry")),
|
||||
target: form.targetType === "offering" ? "offering" : "brand",
|
||||
...(typeof form.offeringId === "string" ? { targetId: form.offeringId } : {}),
|
||||
submissionAction: submissionAction(asString(form.submissionAction, "create-inquiry")),
|
||||
fields: toRuntimeInquiryFields(form.fieldsSnapshot as Prisma.JsonValue),
|
||||
};
|
||||
}),
|
||||
trustItems,
|
||||
trustPresentation: projectTrustPresentation(trustItems, trustDeclarations),
|
||||
capabilities,
|
||||
plugins: capabilities
|
||||
.filter((capability) => capability.status === "enabled")
|
||||
.map((capability) => capabilityPlugins[capability.key as keyof typeof capabilityPlugins])
|
||||
.filter(Boolean)
|
||||
.map((plugin) => ({
|
||||
...plugin,
|
||||
status: "enabled" as const,
|
||||
config: capabilities.find((capability) => capability.key === plugin.key)?.config ?? {},
|
||||
})),
|
||||
theme: visualTemplate?.theme ?? {
|
||||
colors: { background: "#F7F5F1", foreground: "#252525", accent: "#8A6846" },
|
||||
},
|
||||
...(visualTemplate?.layout ? { layout: visualTemplate.layout } : {}),
|
||||
};
|
||||
return {
|
||||
...runtimeWorkspace,
|
||||
contractVersion: "1.0",
|
||||
brand: runtimeBrand,
|
||||
template: template
|
||||
? {
|
||||
key: template.key,
|
||||
version: asString(installationData.templateVersion, template.version),
|
||||
name: template.name,
|
||||
}
|
||||
: null,
|
||||
visualTemplate: visualTemplate
|
||||
? {
|
||||
key: visualTemplate.key,
|
||||
version: visualTemplate.version,
|
||||
name: visualTemplate.name,
|
||||
supportedIndustryTemplates: [...visualTemplate.supportedIndustryTemplates],
|
||||
variants: visualTemplate.variants,
|
||||
}
|
||||
: null,
|
||||
visualTemplateManifest,
|
||||
};
|
||||
}
|
||||
@@ -2,12 +2,14 @@ import { BadRequestException, Controller, Get, Param, Query } from "@nestjs/comm
|
||||
import { PublicBrandContextService } from "./public-brand-context.service.js";
|
||||
import { BrandReleaseService } from "../../brand-release.service.js";
|
||||
import {
|
||||
brandTemplates,
|
||||
defaultBrandTemplateKey,
|
||||
defaultVisualTemplateKey,
|
||||
brandTemplateKeys,
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
isVisualTemplateCompatible,
|
||||
resolveCapabilities,
|
||||
visualTemplates,
|
||||
visualTemplateKeys,
|
||||
} from "@personal-brand/config";
|
||||
|
||||
@Controller("public")
|
||||
@@ -74,15 +76,15 @@ export class PublicTemplateController {
|
||||
@Get()
|
||||
list(): unknown {
|
||||
return {
|
||||
industries: Object.values(brandTemplates),
|
||||
visuals: Object.values(visualTemplates),
|
||||
industries: brandTemplateKeys.map((key) => getBrandTemplate(key)),
|
||||
visuals: visualTemplateKeys.map((key) => getVisualTemplate(key)),
|
||||
};
|
||||
}
|
||||
|
||||
@Get("preview")
|
||||
preview(
|
||||
@Query("industry") industry = "personal",
|
||||
@Query("visual") visual = "linjing-editorial",
|
||||
@Query("industry") industry = defaultBrandTemplateKey,
|
||||
@Query("visual") visual = defaultVisualTemplateKey,
|
||||
): unknown {
|
||||
const industryTemplate = getBrandTemplate(industry);
|
||||
const visualTemplate = getVisualTemplate(visual);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { ForbiddenException, UnauthorizedException } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
|
||||
export type AdminIdentity = {
|
||||
subject: string;
|
||||
brandId: string;
|
||||
role: "admin";
|
||||
};
|
||||
|
||||
export function requireAdminIdentity(request: FastifyRequest): AdminIdentity {
|
||||
const token = request.headers.authorization?.replace(/^Bearer\s+/i, "");
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
|
||||
let identity;
|
||||
try {
|
||||
identity = readIdentity(token);
|
||||
} catch {
|
||||
throw new UnauthorizedException("管理员登录态无效或已过期");
|
||||
}
|
||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||
return identity as AdminIdentity;
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import type { CreateOfferingDto, UpdateOfferingDto } from "../../admin.dto.js";
|
||||
import { validateOfferingConfig } from "@personal-brand/validation";
|
||||
|
||||
type OfferingConfigInput = {
|
||||
config?: CreateOfferingDto["config"] | undefined;
|
||||
sections?: CreateOfferingDto["sections"] | undefined;
|
||||
media?: CreateOfferingDto["media"] | undefined;
|
||||
cta?: CreateOfferingDto["cta"] | undefined;
|
||||
};
|
||||
|
||||
function buildOfferingConfig(body: OfferingConfigInput): Record<string, unknown> {
|
||||
const { config, sections, media, cta } = body;
|
||||
return {
|
||||
...(config ?? {}),
|
||||
...(sections === undefined ? {} : { sections }),
|
||||
...(media === undefined ? {} : { media }),
|
||||
...(cta === undefined ? {} : { cta }),
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminOfferingService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async list(brandId: string): Promise<unknown> {
|
||||
const items = await this.prisma.offering.findMany({
|
||||
where: { brandId },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
});
|
||||
return items.map((item) => {
|
||||
const config = (item.config ?? {}) as Record<string, unknown>;
|
||||
return {
|
||||
...item,
|
||||
sections: config.sections ?? [],
|
||||
media: config.media ?? [],
|
||||
cta: config.cta ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async create(brandId: string, body: CreateOfferingDto): Promise<unknown> {
|
||||
const { config, sections, media, cta, ...fields } = body;
|
||||
const configValue = buildOfferingConfig({ config, sections, media, cta });
|
||||
if (validateOfferingConfig(configValue).length) {
|
||||
throw new BadRequestException("业务提供项配置无效");
|
||||
}
|
||||
return this.prisma.offering.create({
|
||||
data: {
|
||||
...fields,
|
||||
brandId,
|
||||
config: configValue as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async update(brandId: string, id: string, body: UpdateOfferingDto): Promise<unknown> {
|
||||
const item = await this.prisma.offering.findFirst({ where: { id, brandId } });
|
||||
if (!item) throw new BadRequestException("业务提供项不存在");
|
||||
|
||||
const { config, sections, media, cta, ...fields } = body;
|
||||
const configValue = buildOfferingConfig({ config, sections, media, cta });
|
||||
if (validateOfferingConfig(configValue).length) {
|
||||
throw new BadRequestException("业务提供项配置无效");
|
||||
}
|
||||
const hasConfigInput =
|
||||
config !== undefined || sections !== undefined || media !== undefined || cta !== undefined;
|
||||
return this.prisma.offering.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...fields,
|
||||
...(hasConfigInput ? { config: configValue as Prisma.InputJsonValue } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async delete(brandId: string, id: string): Promise<unknown> {
|
||||
const item = await this.prisma.offering.findFirst({ where: { id, brandId } });
|
||||
if (!item) throw new BadRequestException("业务提供项不存在");
|
||||
|
||||
const [forms, bookings, items] = await Promise.all([
|
||||
this.prisma.inquiryForm.count({ where: { offeringId: id } }),
|
||||
this.prisma.booking.count({ where: { offeringId: id } }),
|
||||
this.prisma.bookingItem.count({ where: { offeringId: id } }),
|
||||
]);
|
||||
if (forms || bookings || items) {
|
||||
throw new BadRequestException("业务提供项已有业务记录,只能禁用不能删除");
|
||||
}
|
||||
await this.prisma.offering.delete({ where: { id } });
|
||||
return { deleted: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import {
|
||||
defaultBrandTemplateKey,
|
||||
getDefaultVisualTemplateKey,
|
||||
getTemplatePackageManifestForVisualKey,
|
||||
} from "@personal-brand/config";
|
||||
import { PublicWorkspaceService } from "../public/public-workspace.controller.js";
|
||||
|
||||
@Injectable()
|
||||
export class AdminWorkspaceService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly publicWorkspace: PublicWorkspaceService,
|
||||
) {}
|
||||
|
||||
async get(brandId: string): Promise<unknown> {
|
||||
const [brand, installations, fields, offerings, forms] = await Promise.all([
|
||||
this.prisma.brandProfile.findUnique({ where: { id: brandId } }),
|
||||
this.prisma.brandTemplateInstallation.findMany({ where: { brandId } }),
|
||||
this.prisma.brandFieldDefinition.findMany({
|
||||
where: { brandId },
|
||||
orderBy: { sortOrder: "asc" },
|
||||
}),
|
||||
this.prisma.offering.findMany({ where: { brandId }, orderBy: { sortOrder: "asc" } }),
|
||||
this.prisma.inquiryForm.findMany({ where: { brandId }, orderBy: { updatedAt: "desc" } }),
|
||||
]);
|
||||
const config = this.jsonObject(brand?.config);
|
||||
const templateKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? defaultBrandTemplateKey);
|
||||
const manifest = getTemplatePackageManifestForVisualKey(templateKey);
|
||||
|
||||
return {
|
||||
brand,
|
||||
installations,
|
||||
fields,
|
||||
offerings,
|
||||
forms,
|
||||
templateContent: manifest
|
||||
? {
|
||||
displayName: manifest.displayName,
|
||||
admin: manifest.admin,
|
||||
navigation: manifest.navigation.map(({ key, label, page }) => ({ key, label, page })),
|
||||
templateFields: (manifest.templateFields ?? []).map((field) => ({
|
||||
...field,
|
||||
binding: field.binding ?? `brand.config.templateData.${field.key}`,
|
||||
})),
|
||||
assetSlots: manifest.assetSlots,
|
||||
trustContentTypes: manifest.trustContentTypes ?? [],
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
getPreview(brandId: string): Promise<unknown> {
|
||||
return this.publicWorkspace.getForBrandId(brandId, true);
|
||||
}
|
||||
|
||||
private jsonObject(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import {
|
||||
type BrandTemplateKey,
|
||||
defaultBrandTemplateKey,
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
getVisualTemplateManifest,
|
||||
@@ -9,7 +11,6 @@ import {
|
||||
isVisualTemplateCompatible,
|
||||
} from "@personal-brand/config";
|
||||
import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.js";
|
||||
import type { BrandTemplateKey } from "@personal-brand/types";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
|
||||
@Injectable()
|
||||
@@ -27,7 +28,7 @@ export class TemplateWorkspaceService {
|
||||
const visualKey =
|
||||
typeof config.visualTemplateKey === "string"
|
||||
? config.visualTemplateKey
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? "personal");
|
||||
: getDefaultVisualTemplateKey(brand?.templateKey ?? defaultBrandTemplateKey);
|
||||
return (
|
||||
getTemplatePackageManifestForVisualKey(visualKey)?.trustContentTypes?.map(
|
||||
(item) => item.type,
|
||||
@@ -72,10 +73,12 @@ export class TemplateWorkspaceService {
|
||||
select: { templateKey: true },
|
||||
}),
|
||||
]);
|
||||
const key = installation?.templateKey ?? brand?.templateKey ?? "personal";
|
||||
return getBrandTemplate(key) ? (key as BrandTemplateKey) : "personal";
|
||||
const key =
|
||||
getBrandTemplate(installation?.templateKey ?? brand?.templateKey ?? defaultBrandTemplateKey)
|
||||
?.key ?? defaultBrandTemplateKey;
|
||||
return key;
|
||||
}
|
||||
async install(brandId: string, templateKey: "personal" | "food" | "doors") {
|
||||
async install(brandId: string, templateKey: BrandTemplateKey) {
|
||||
const template = getBrandTemplate(templateKey);
|
||||
if (!template) throw new BadRequestException("行业模板不存在");
|
||||
const [existing, brand] = await Promise.all([
|
||||
|
||||
@@ -991,6 +991,10 @@ test("health and public content are available without authentication", async ()
|
||||
assert.ok(Array.isArray(runtime.capabilities));
|
||||
assert.ok(runtime.theme.colors.background);
|
||||
assert.ok(Array.isArray(runtime.plugins));
|
||||
const inquiryPlugin = runtime.plugins.find((plugin) => plugin.key === "inquiry");
|
||||
assert.ok(inquiryPlugin);
|
||||
assert.deepEqual(inquiryPlugin.config, {});
|
||||
assert.deepEqual(inquiryPlugin.purposeBindings, ["inquiry"]);
|
||||
assert.equal(runtime.brand.founder, "阿成");
|
||||
assert.ok(runtime.offerings.every((item) => item.coverUrl));
|
||||
assert.ok(runtime.trustPresentation);
|
||||
@@ -1023,7 +1027,7 @@ test("visual template compatibility is enforced by catalog, preview, and brand s
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const compatibleSwitch = await request("/admin/config/brand", {
|
||||
method: "PATCH",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
@@ -1034,14 +1038,6 @@ test("visual template compatibility is enforced by catalog, preview, and brand s
|
||||
|
||||
test("seeded public workspaces keep personal, food, and doors brands isolated", async () => {
|
||||
const expected = [
|
||||
{
|
||||
slug: "linran-brand",
|
||||
id: "00000000-0000-0000-0000-000000000003",
|
||||
templateKey: "personal",
|
||||
founder: "林然",
|
||||
offeringKind: "service",
|
||||
categoryLabel: "策略咨询",
|
||||
},
|
||||
{
|
||||
slug: "default-brand",
|
||||
id: "00000000-0000-0000-0000-000000000001",
|
||||
@@ -1089,7 +1085,7 @@ test("seeded public workspaces keep personal, food, and doors brands isolated",
|
||||
return workspace;
|
||||
}),
|
||||
);
|
||||
assert.equal(new Set(workspaces.map((workspace) => workspace.brand.id)).size, 3);
|
||||
assert.equal(new Set(workspaces.map((workspace) => workspace.brand.id)).size, 2);
|
||||
});
|
||||
|
||||
test("public workspace uses brand-scoped capability installations and preserves status", async () => {
|
||||
@@ -1115,6 +1111,24 @@ test("public workspace uses brand-scoped capability installations and preserves
|
||||
version: "1.0.0",
|
||||
status: "disabled",
|
||||
config: { source: "integration-test" },
|
||||
metadata: {
|
||||
key: "inquiry",
|
||||
version: "1.0.0",
|
||||
displayName: "通用咨询",
|
||||
description: "接收客户的一对一合作咨询。",
|
||||
impact: "停用后所有通用咨询表单都无法提交。",
|
||||
optional: false,
|
||||
disablePolicy: "allowed",
|
||||
allowedPages: ["inquiry", "success"],
|
||||
requiredModules: ["inquiry", "records", "success-summary"],
|
||||
purposeBindings: ["inquiry"],
|
||||
entryNavigationKey: "inquiry",
|
||||
configFields: [
|
||||
{ key: "entryLabel", label: "入口文案", input: "text", required: false },
|
||||
{ key: "submitHint", label: "提交提示", input: "text", required: false },
|
||||
{ key: "disabledHint", label: "停用提示", input: "text", required: false },
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
assert.notEqual(body.capabilities[0].status, "enabled");
|
||||
@@ -1126,21 +1140,38 @@ test("public workspace uses brand-scoped capability installations and preserves
|
||||
test("admin can update declared capability status with authorization and audit", async () => {
|
||||
const unauthorized = await request("/admin/workspace/capabilities/inquiry", {
|
||||
method: "PATCH",
|
||||
payload: { capabilityVersion: "1.0.0", status: "disabled" },
|
||||
payload: { status: "disabled" },
|
||||
});
|
||||
assert.equal(unauthorized.statusCode, 401);
|
||||
const customerForbidden = await request("/admin/workspace/capabilities/inquiry", {
|
||||
method: "PATCH",
|
||||
headers: { authorization: `Bearer ${customerToken}` },
|
||||
payload: { status: "disabled" },
|
||||
});
|
||||
assert.equal(customerForbidden.statusCode, 403);
|
||||
const login = await request("/admin/session/login", {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const updated = await request("/admin/workspace/capabilities/inquiry", {
|
||||
method: "PATCH",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { capabilityVersion: "1.0.0", status: "disabled", config: { mode: "manual" } },
|
||||
payload: { status: "disabled", config: { entryLabel: "合作咨询", disabledHint: "咨询已暂停" } },
|
||||
});
|
||||
assert.equal(updated.statusCode, 200);
|
||||
assert.equal(JSON.parse(updated.body).status, "disabled");
|
||||
assert.equal(JSON.parse(updated.body).capabilityVersion, "1.0.0");
|
||||
const invalidConfig = await request("/admin/workspace/capabilities/inquiry", {
|
||||
method: "PATCH",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { status: "disabled", config: { unknown: "字段" } },
|
||||
});
|
||||
assert.equal(invalidConfig.statusCode, 400);
|
||||
const saved = await prisma.capabilityInstallation.findUnique({
|
||||
where: { brandId_capabilityKey: { brandId, capabilityKey: "inquiry" } },
|
||||
});
|
||||
assert.deepEqual(saved?.config, { entryLabel: "合作咨询", disabledHint: "咨询已暂停" });
|
||||
const audit = await prisma.capabilityAuditLog.findFirst({
|
||||
where: { brandId, capabilityKey: "inquiry" },
|
||||
orderBy: { createdAt: "desc" },
|
||||
@@ -1156,7 +1187,7 @@ test("editor membership can manage brand content but cannot change system settin
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const identity = readIdentity(token);
|
||||
const membership = await prisma.brandMembership.findUnique({
|
||||
where: { adminUserId_brandId: { adminUserId: identity.subject, brandId } },
|
||||
@@ -1195,7 +1226,7 @@ test("owner can manage brand members without removing the final owner", async ()
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const identity = readIdentity(token);
|
||||
const members = await request("/admin/brands/members", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
@@ -1281,6 +1312,8 @@ test("manually created member must change the initial password before normal use
|
||||
});
|
||||
|
||||
test("admin can install optional quote capability without industry-specific branching", async () => {
|
||||
const quoteListUser = await prisma.adminUser.findUniqueOrThrow({ where: { username: "admin" } });
|
||||
const quoteToken = signIdentity({ subject: quoteListUser.id, brandId, role: "admin" });
|
||||
const login = await request("/admin/session/login", {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
@@ -1289,13 +1322,25 @@ test("admin can install optional quote capability without industry-specific bran
|
||||
const response = await request("/admin/workspace/capabilities/quote-request", {
|
||||
method: "PATCH",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { capabilityVersion: "1.0.0", status: "enabled", config: { currency: "CNY" } },
|
||||
payload: { status: "enabled", config: { entryLabel: "获取报价", submitHint: "48 小时内回复" } },
|
||||
});
|
||||
assert.equal(response.statusCode, 200);
|
||||
assert.equal(JSON.parse(response.body).capabilityKey, "quote-request");
|
||||
assert.equal(JSON.parse(response.body).capabilityVersion, "1.0.0");
|
||||
const list = await request("/admin/workspace/capabilities", {
|
||||
headers: { authorization: `Bearer ${quoteToken}` },
|
||||
});
|
||||
assert.equal(
|
||||
JSON.parse(list.body).find((item) => item.capabilityKey === "quote-request")?.optional,
|
||||
true,
|
||||
);
|
||||
assert.equal((await publishReleaseForTests()).statusCode, 201);
|
||||
const workspace = await request("/public/workspace");
|
||||
assert.ok(JSON.parse(workspace.body).plugins.some((plugin) => plugin.key === "quote-request"));
|
||||
const quotePlugin = JSON.parse(workspace.body).plugins.find(
|
||||
(plugin) => plugin.key === "quote-request",
|
||||
);
|
||||
assert.ok(quotePlugin);
|
||||
assert.deepEqual(quotePlugin.config, { entryLabel: "获取报价", submitHint: "48 小时内回复" });
|
||||
await prisma.capabilityInstallation.deleteMany({
|
||||
where: { brandId, capabilityKey: "quote-request" },
|
||||
});
|
||||
@@ -1310,14 +1355,21 @@ test("admin capability list includes template defaults and brand overrides", asy
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const defaults = await request("/admin/workspace/capabilities", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(defaults.statusCode, 200);
|
||||
const defaultBody = JSON.parse(defaults.body);
|
||||
assert.ok(
|
||||
defaultBody.some((item) => item.capabilityKey === "inquiry" && item.source === "template"),
|
||||
defaultBody.some(
|
||||
(item) =>
|
||||
item.capabilityKey === "inquiry" &&
|
||||
item.source === "template" &&
|
||||
item.optional === false &&
|
||||
item.disablePolicy === "allowed" &&
|
||||
item.configFields?.some((field) => field.key === "entryLabel"),
|
||||
),
|
||||
);
|
||||
await prisma.capabilityInstallation.create({
|
||||
data: {
|
||||
@@ -1325,7 +1377,7 @@ test("admin capability list includes template defaults and brand overrides", asy
|
||||
capabilityKey: "inquiry",
|
||||
capabilityVersion: "1.0.0",
|
||||
status: "disabled",
|
||||
config: { mode: "manual" },
|
||||
config: { entryLabel: "品牌自定义咨询" },
|
||||
},
|
||||
});
|
||||
const overrides = await request("/admin/workspace/capabilities", {
|
||||
@@ -1334,7 +1386,7 @@ test("admin capability list includes template defaults and brand overrides", asy
|
||||
const override = JSON.parse(overrides.body).find((item) => item.capabilityKey === "inquiry");
|
||||
assert.equal(override.source, "brand");
|
||||
assert.equal(override.status, "disabled");
|
||||
assert.deepEqual(override.config, { mode: "manual" });
|
||||
assert.deepEqual(override.config, { entryLabel: "品牌自定义咨询" });
|
||||
await prisma.capabilityInstallation.deleteMany({ where: { brandId } });
|
||||
});
|
||||
|
||||
@@ -1347,7 +1399,7 @@ test("admin can install doors industry template through the shared runtime contr
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
try {
|
||||
const installed = await request("/admin/workspace/install", {
|
||||
method: "POST",
|
||||
@@ -1402,7 +1454,7 @@ test("admin can preview and import sample content idempotently", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const preview = await request("/admin/workspace/sample-content/preview", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
@@ -1482,7 +1534,7 @@ test("admin can install a template and public workspace exposes enabled configur
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const before = await request("/admin/workspace");
|
||||
assert.equal(before.statusCode, 401);
|
||||
const customerAccess = await request("/admin/workspace", {
|
||||
@@ -1633,7 +1685,7 @@ test("admin can customize workspace fields with brand isolation", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const install = await request("/admin/workspace/install", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
@@ -1685,7 +1737,7 @@ test("admin visual template selection is reflected in public runtime workspace",
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const before = await request("/public/workspace");
|
||||
assert.equal(before.statusCode, 200);
|
||||
const updated = await request("/admin/config/brand", {
|
||||
@@ -1943,7 +1995,7 @@ test("admin can create and version an inquiry form", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const offering = await prisma.offering.findFirst({ where: { brandId, isEnabled: true } });
|
||||
assert.ok(offering);
|
||||
const created = await request("/admin/workspace/forms", {
|
||||
@@ -2161,7 +2213,7 @@ test("admin rejects invalid dynamic inquiry field definitions", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const invalid = await request("/admin/workspace/forms", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
@@ -2178,7 +2230,7 @@ test("admin can manage offerings and public endpoint hides disabled offerings",
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const invalidConfig = await request("/admin/workspace/offerings", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
@@ -2207,6 +2259,20 @@ test("admin can manage offerings and public endpoint hides disabled offerings",
|
||||
});
|
||||
assert.equal(listed.statusCode, 200);
|
||||
assert.ok(JSON.parse(listed.body).some((item) => item.id === id));
|
||||
const withCategory = await request(`/admin/workspace/offerings/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { config: { categoryKey: "set-meal" } },
|
||||
});
|
||||
assert.equal(withCategory.statusCode, 200);
|
||||
const preview = await request("/admin/workspace/preview", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(preview.statusCode, 200);
|
||||
const draft = JSON.parse(preview.body);
|
||||
const previewOffering = draft.offerings.find((item) => item.id === id);
|
||||
assert.equal(previewOffering?.presentation?.categoryKey, "set-meal");
|
||||
assert.equal(previewOffering?.presentation?.categoryLabel, "套餐");
|
||||
const publicItem = await request(`/public/offerings/${id}`);
|
||||
assert.equal(publicItem.statusCode, 400);
|
||||
const publicList = await request("/public/offerings");
|
||||
@@ -2242,7 +2308,7 @@ test("offering with an inquiry form cannot be deleted", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const offering = await prisma.offering.create({
|
||||
data: { brandId, kind: "service", name: `保护测试-${Date.now()}`, description: "测试" },
|
||||
});
|
||||
@@ -2277,7 +2343,7 @@ test("seeded admin can log in and read protected booking resources", async () =>
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
assert.equal(login.statusCode, 201);
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
assert.ok(token);
|
||||
|
||||
const count = await request("/admin/bookings/unread-count", {
|
||||
@@ -2306,7 +2372,7 @@ test("admin can list and switch only enabled brand memberships", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const brands = await request("/admin/brands", {
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
@@ -2399,7 +2465,7 @@ test("disabled brand membership blocks existing admin token", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const admin = await prisma.adminUser.findUnique({ where: { username: "admin" } });
|
||||
assert.ok(admin);
|
||||
const membership = await prisma.brandMembership.findUnique({
|
||||
@@ -2541,7 +2607,7 @@ test("admin can update user-facing brand presentation without replacing other co
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
const brand = await prisma.brandProfile.findUnique({ where: { id: brandId } });
|
||||
assert.ok(brand);
|
||||
const originalConfig = brand.config;
|
||||
@@ -2577,7 +2643,7 @@ test("admin can manage trust content", async () => {
|
||||
method: "POST",
|
||||
payload: { username: "admin", password: process.env.SEED_ADMIN_PASSWORD },
|
||||
});
|
||||
const token = JSON.parse(login.body).token;
|
||||
const token = JSON.parse(login.body).data?.token ?? JSON.parse(login.body).token;
|
||||
assert.equal((await request("/admin/config/trust-content")).statusCode, 401);
|
||||
assert.equal(
|
||||
(
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
test("upload presign DTO rejects unsupported media type and oversized names", async () => {
|
||||
const { PresignUploadDto } = await import("../dist/modules/admin/admin-upload.controller.js");
|
||||
const validator = await import("class-validator");
|
||||
const invalid = new PresignUploadDto();
|
||||
invalid.fileName = "x".repeat(256);
|
||||
invalid.contentType = "application/pdf";
|
||||
const errors = await validator.validate(invalid);
|
||||
assert.ok(errors.some((error) => error.property === "fileName"));
|
||||
assert.ok(errors.some((error) => error.property === "contentType"));
|
||||
|
||||
const valid = new PresignUploadDto();
|
||||
valid.fileName = "hero.jpg";
|
||||
valid.contentType = "image/jpeg";
|
||||
assert.deepEqual(await validator.validate(valid), []);
|
||||
});
|
||||
@@ -3,3 +3,4 @@ TEMPLATE_KEY=acheng-campus-food
|
||||
BRAND_SLUG=default-brand
|
||||
API_BASE_URL=http://localhost:3001
|
||||
PREVIEW_PORT=3002
|
||||
WEAPP_APP_ID=touristappid
|
||||
@@ -31,7 +31,7 @@ TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:h5
|
||||
TEMPLATE_KEY=linjing-editorial pnpm --filter @personal-brand/taro build:weapp
|
||||
```
|
||||
|
||||
输出 `apps/taro/dist/<templateKey>/h5` 和 `weapp`。微信开发者工具导入对应 weapp 目录;正式登录需在项目配置里设置与 API 相匹配的 AppID,配置请求合法域名。默认 touristappid 仅用于浏览,不含密钥。
|
||||
输出 `apps/taro/dist/<templateKey>/h5` 和 `weapp`。微信开发者工具导入对应 weapp 目录;构建时通过 `API_BASE_URL` 设置 API 地址,通过 `WEAPP_APP_ID` 或 `TARO_APP_ID` 设置小程序 AppID,并在微信公众平台配置请求合法域名。默认 touristappid 仅用于浏览,不含密钥。
|
||||
|
||||
页面结构和样式以 React 原型为参考,当前原生小程序用于校对字段、结构化来源、认证与提交行为。模板实现位于各 package 的 `taro/`;公共请求、表单、记录和状态位于此目录。新模板须提供 manifest、Taro 实现和验收用例,不新增全局 seed。
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ import path from "node:path";
|
||||
import fs from "node:fs";
|
||||
|
||||
const root = path.resolve(__dirname, "../../..");
|
||||
const key = process.env.TEMPLATE_KEY || "acheng-campus-food";
|
||||
const previewAllTemplates = process.env.PREVIEW_ALL_TEMPLATES === "true";
|
||||
const templates = fs
|
||||
.readdirSync(path.join(root, "packages"))
|
||||
@@ -13,8 +12,12 @@ const templates = fs
|
||||
fs.existsSync(path.join(root, "packages", directory, "taro/index.tsx")) &&
|
||||
fs.existsSync(path.join(root, "packages", directory, "template.json")),
|
||||
)
|
||||
.map((directory) => directory.slice("template-".length));
|
||||
.map((directory) => directory.slice("template-".length))
|
||||
.sort();
|
||||
const key = process.env.TEMPLATE_KEY || templates[0];
|
||||
if (!key) throw new Error("No Taro template package found");
|
||||
if (!templates.includes(key)) throw new Error(`Unsupported Taro template: ${key}`);
|
||||
process.env.TARO_APP_ID ||= process.env.WEAPP_APP_ID;
|
||||
const template = path.join(root, "packages", `template-${key}`);
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(template, "template.json"), "utf8")) as {
|
||||
packageKey: string;
|
||||
@@ -58,14 +61,6 @@ export default defineConfig({
|
||||
to: `dist/template-preview/h5/assets/${templateKey}`,
|
||||
}))
|
||||
: []),
|
||||
...(process.env.TARO_ENV === "weapp"
|
||||
? [
|
||||
{
|
||||
from: path.resolve(__dirname, "../project.config.json"),
|
||||
to: `dist/${key}/weapp/project.config.json`,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(!previewAllTemplates
|
||||
? [
|
||||
{
|
||||
@@ -76,10 +71,29 @@ export default defineConfig({
|
||||
: []),
|
||||
],
|
||||
},
|
||||
mini: {},
|
||||
mini: {
|
||||
postcss: {
|
||||
htmltransform: {
|
||||
enable: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
h5: {
|
||||
publicPath: process.env.PREVIEW_PUBLIC_PATH || "/",
|
||||
router: { mode: "hash" },
|
||||
devServer: { host: "0.0.0.0", port: Number(process.env.PREVIEW_PORT || 3002) },
|
||||
devServer: {
|
||||
host: "0.0.0.0",
|
||||
port: Number(process.env.PREVIEW_PORT || 3002),
|
||||
proxy: {
|
||||
"/media": {
|
||||
target:
|
||||
process.env.MEDIA_API_TARGET ||
|
||||
(process.env.API_BASE_URL?.startsWith("http")
|
||||
? new URL(process.env.API_BASE_URL).origin
|
||||
: "http://localhost:3001"),
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -8,7 +8,7 @@
|
||||
"build:preview": "PREVIEW_ALL_TEMPLATES=true taro build --type h5",
|
||||
"build:weapp": "taro build --type weapp",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"lint": "pnpm --workspace-root exec eslint apps/taro/src apps/taro/config packages/template-acheng-campus-food/taro packages/template-linjing-editorial/taro",
|
||||
"lint": "pnpm --workspace-root exec eslint apps/taro/src apps/taro/config \"packages/template-*/taro/**/*.{ts,tsx}\"",
|
||||
"test": "node --experimental-strip-types --test test/*.test.mjs",
|
||||
"test:browser": "playwright test"
|
||||
},
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
page {
|
||||
background: #fafaf9;
|
||||
--taro-button-height: 88px;
|
||||
--taro-button-compact-height: 46px;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
@@ -13,6 +15,13 @@ button {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
min-height: var(--taro-button-height);
|
||||
text-align: center;
|
||||
appearance: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Button, Text, View } from "@tarojs/components";
|
||||
import type { ReactNode } from "react";
|
||||
import type { RuntimeWorkspace } from "@personal-brand/types";
|
||||
import { pluginByKey, pluginConfigText } from "../runtime/plugins";
|
||||
import { navigate } from "../runtime/navigation";
|
||||
|
||||
export function CapabilityAction({
|
||||
workspace,
|
||||
pluginKey,
|
||||
params,
|
||||
presentationLabel,
|
||||
fallbackLabel,
|
||||
className,
|
||||
editorTarget,
|
||||
children,
|
||||
}: {
|
||||
workspace: RuntimeWorkspace;
|
||||
pluginKey: string;
|
||||
params?: Record<string, string>;
|
||||
presentationLabel?: string;
|
||||
fallbackLabel: string;
|
||||
className?: string;
|
||||
editorTarget?: string;
|
||||
children?: ReactNode;
|
||||
}) {
|
||||
const plugin = pluginByKey(workspace, pluginKey);
|
||||
const label = pluginConfigText(plugin, "entryLabel") || presentationLabel || fallbackLabel;
|
||||
if (plugin?.status !== "enabled")
|
||||
return (
|
||||
<View className={className} data-editor-target={editorTarget}>
|
||||
<Text>{pluginConfigText(plugin, "disabledHint") || `${fallbackLabel}暂不可用`}</Text>
|
||||
</View>
|
||||
);
|
||||
return (
|
||||
<Button
|
||||
className={className}
|
||||
data-editor-target={editorTarget}
|
||||
onClick={() => navigate("inquiry", params)}
|
||||
>
|
||||
{children ?? label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import { missingField, visibleFields, presentation } from "../runtime/content";
|
||||
import type { Values } from "../runtime/content";
|
||||
import { ensureSession, request, brandSlug } from "../runtime/api";
|
||||
import { takeQuery, navigate } from "../runtime/navigation";
|
||||
import { inquiryPluginState, pluginConfigText, usableInquiryForms } from "../runtime/plugins";
|
||||
import "./forms.css";
|
||||
export function Inquiry({
|
||||
workspace,
|
||||
@@ -26,15 +27,18 @@ export function Inquiry({
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [offeringId, setOfferingId] = useState(router.params.offeringId || "");
|
||||
const forms = usableInquiryForms(workspace);
|
||||
const form: RuntimeInquiryForm | undefined =
|
||||
workspace.inquiryForms.find((form) => offeringId && form.targetId === offeringId) ||
|
||||
workspace.inquiryForms.find((form) => form.target === "brand");
|
||||
forms.find((form) => offeringId && form.targetId === offeringId) ||
|
||||
forms.find((form) => form.target === "brand");
|
||||
const [values, setValues] = useState<Values>({});
|
||||
const [error, setError] = useState("");
|
||||
const [sending, setSending] = useState(false);
|
||||
const busy = useRef(false);
|
||||
const p = presentation(workspace, "inquiry");
|
||||
const food = workspace.brand.visualTemplateKey === "acheng-campus-food";
|
||||
const inquiryPlugin = inquiryPluginState(workspace);
|
||||
const compactFieldKeys = new Set(["people", "date", "budget", "delivery"]);
|
||||
const compactForm = Boolean(form?.fields.some((field) => compactFieldKeys.has(field.key)));
|
||||
useDidShow(() => {
|
||||
const query = takeQuery("inquiry");
|
||||
if (query.offeringId) setOfferingId(query.offeringId);
|
||||
@@ -82,13 +86,18 @@ export function Inquiry({
|
||||
}
|
||||
}
|
||||
return (
|
||||
<View className={`inquiry-page ${food ? "food-inquiry" : "editorial-inquiry"}`}>
|
||||
<View className={`inquiry-page ${compactForm ? "food-inquiry" : "editorial-inquiry"}`}>
|
||||
<View className="form-intro">
|
||||
<Text className="eyebrow">{p.eyebrow}</Text>
|
||||
<Text className="form-title">{p.title || "提交咨询"}</Text>
|
||||
<Text className="form-subtitle">{p.subtitle}</Text>
|
||||
</View>
|
||||
{!form ? (
|
||||
{!inquiryPlugin.enabled && form?.purpose !== "quote-request" ? (
|
||||
<View className="records-empty">
|
||||
<Text>{inquiryPlugin.disabledHint}</Text>
|
||||
<Button onClick={() => navigate("records")}>查看咨询记录</Button>
|
||||
</View>
|
||||
) : !form ? (
|
||||
<View className="form-error">尚未配置可用的咨询表单</View>
|
||||
) : (
|
||||
<View className="inquiry-form">
|
||||
@@ -98,10 +107,10 @@ export function Inquiry({
|
||||
const value = values[field.key];
|
||||
const stringValue = typeof value === "string" ? value : "";
|
||||
const chips =
|
||||
food && field.key === "type" && ["select", "radio"].includes(field.type);
|
||||
compactForm && field.key === "type" && ["select", "radio"].includes(field.type);
|
||||
return (
|
||||
<View
|
||||
className={`form-field ${food && ["people", "date", "budget", "delivery"].includes(field.key) ? "half-field" : ""}`}
|
||||
className={`form-field ${compactForm && compactFieldKeys.has(field.key) ? "half-field" : ""}`}
|
||||
key={field.key}
|
||||
data-editor-target={preview ? `inquiry-field:${field.key}` : undefined}
|
||||
>
|
||||
@@ -196,6 +205,11 @@ export function Inquiry({
|
||||
{error}
|
||||
</View>
|
||||
)}
|
||||
{pluginConfigText(inquiryPlugin.plugin, "submitHint") && (
|
||||
<Text className="form-subtitle">
|
||||
{pluginConfigText(inquiryPlugin.plugin, "submitHint")}
|
||||
</Text>
|
||||
)}
|
||||
<Button
|
||||
className="submit-button"
|
||||
disabled={sending}
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { RuntimeWorkspace } from "@personal-brand/types";
|
||||
import { ensureSession, hasSession, request } from "../runtime/api";
|
||||
import { navigate } from "../runtime/navigation";
|
||||
import { presentation } from "../runtime/content";
|
||||
import { inquiryPluginState } from "../runtime/plugins";
|
||||
import "./forms.css";
|
||||
type RecordItem = {
|
||||
id: string;
|
||||
@@ -37,6 +38,7 @@ export function Records({
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [authenticated, setAuthenticated] = useState(preview ? false : hasSession());
|
||||
const p = presentation(workspace, "records");
|
||||
const inquiryPlugin = inquiryPluginState(workspace);
|
||||
const load = useCallback(() => {
|
||||
if (preview) return;
|
||||
if (!hasSession()) {
|
||||
@@ -58,7 +60,14 @@ export function Records({
|
||||
return (
|
||||
<View className="records-page">
|
||||
<Text className="form-title">{p.title || "我的咨询记录"}</Text>
|
||||
{inquiryPlugin.enabled ? (
|
||||
<Button onClick={() => navigate("inquiry")}>{p.createAction || "新增咨询"}</Button>
|
||||
) : (
|
||||
<View className="records-empty">
|
||||
<Text>{inquiryPlugin.disabledHint}</Text>
|
||||
<Text className="form-subtitle">暂无可发起的咨询入口</Text>
|
||||
</View>
|
||||
)}
|
||||
{loading ? (
|
||||
<View className="runtime-state">正在加载…</View>
|
||||
) : error ? (
|
||||
@@ -94,7 +103,9 @@ export function Records({
|
||||
<View className="records-empty">
|
||||
<Text>{p.emptyTitle || "还没有咨询记录"}</Text>
|
||||
<Text className="form-subtitle">{p.emptyDescription}</Text>
|
||||
{inquiryPlugin.enabled && (
|
||||
<Button onClick={() => navigate("inquiry")}>{p.emptyAction || "开始咨询"}</Button>
|
||||
)}
|
||||
</View>
|
||||
) : (
|
||||
records.map((item) => (
|
||||
|
||||
@@ -18,5 +18,5 @@ interface ImportMeta {
|
||||
glob<T = unknown>(pattern: string, options?: { eager?: boolean }): Record<string, T>;
|
||||
}
|
||||
declare module "@template" {
|
||||
export { TemplatePage } from "../../../packages/template-acheng-campus-food/taro";
|
||||
export { TemplatePage } from "./runtime/template-preview-entry";
|
||||
}
|
||||
@@ -47,9 +47,7 @@ export async function loadWorkspace() {
|
||||
const data = await request<RuntimeWorkspace>("/public/workspace");
|
||||
const editorPreview = isEditorPreview();
|
||||
if (!editorPreview && data.publication?.status !== "published") throw new Error("品牌尚未发布");
|
||||
if (!editorPreview && data.brand.visualTemplateKey !== TEMPLATE_KEY)
|
||||
throw new Error("该品牌使用其他模板,请选择匹配的模板预览地址");
|
||||
return {
|
||||
return resolveMediaUrls({
|
||||
...data,
|
||||
brand: data.brand ?? {},
|
||||
templateData: data.templateData ?? {},
|
||||
@@ -59,7 +57,22 @@ export async function loadWorkspace() {
|
||||
trustPresentation: data.trustPresentation ?? {},
|
||||
capabilities: data.capabilities ?? [],
|
||||
theme: data.theme ?? { colors: {} },
|
||||
plugins: data.plugins ?? [],
|
||||
});
|
||||
}
|
||||
|
||||
function resolveMediaUrls(workspace: RuntimeWorkspace): RuntimeWorkspace {
|
||||
const resolve = (value: unknown): unknown => {
|
||||
if (typeof value === "string") {
|
||||
return value.startsWith("/media/") ? `${API_BASE_URL.replace(/\/$/, "")}${value}` : value;
|
||||
}
|
||||
if (Array.isArray(value)) return value.map(resolve);
|
||||
if (value && typeof value === "object") {
|
||||
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, resolve(item)]));
|
||||
}
|
||||
return value;
|
||||
};
|
||||
return resolve(workspace) as RuntimeWorkspace;
|
||||
}
|
||||
export async function ensureSession() {
|
||||
if (hasSession()) return;
|
||||
|
||||