Merge pull request 'fix/react-dev-warnings' (#3) from fix/react-dev-warnings into main
Reviewed-on: #3
This commit was merged in pull request #3.
This commit is contained in:
commit
371689484e
49 files changed
+1984
-1004
No files matched your search
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"scope": "模板完成证据登记,保留命令、日志与产物哈希",
|
||||
"generatedAt": "2026-10-21T08:37:34.818Z",
|
||||
"generatedAt": "2026-10-23T06:35:59.337Z",
|
||||
"templates": {
|
||||
"acheng-campus-food": {
|
||||
"real-manifest-interaction": {
|
||||
@@ -256,5 +256,5 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"sourceTreeHash": "ba35ee9629ec5aa84b9984139a4dbabc60fb576b1178f936eb8161eb905184e7"
|
||||
"sourceTreeHash": "f39e31a1959e24c07bf60776a0d3c5f28e5745962ca004301ff304daa1430041"
|
||||
}
|
||||
@@ -9,6 +9,8 @@ API_PREFIX=
|
||||
CORS_ORIGINS=http://localhost:3000
|
||||
ADMIN_PORT=3000
|
||||
SESSION_SECRET=replace-with-a-long-random-value
|
||||
# 单实例使用 memory;多实例部署改用 postgres 并先执行数据库迁移
|
||||
CLIENT_ERROR_THROTTLE_STORE=memory
|
||||
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
||||
TEMPLATE_ARTIFACT_ROOT=/var/lib/personal-brand/template-artifacts
|
||||
SEED_ADMIN_PASSWORD=change-me-now-123
|
||||
|
||||
@@ -6,6 +6,8 @@ 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
|
||||
# 单实例使用 memory;多实例部署改用 postgres 并先执行数据库迁移
|
||||
CLIENT_ERROR_THROTTLE_STORE=memory
|
||||
DEFAULT_BRAND_ID=00000000-0000-0000-0000-000000000001
|
||||
SEED_ADMIN_PASSWORD=replace-with-a-one-time-initial-password
|
||||
SEED_MODE=skip
|
||||
|
||||
@@ -24,6 +24,9 @@ media/
|
||||
|
||||
**/.swc/
|
||||
.codex-tasks/
|
||||
!.codex-tasks/template-audit-execution/
|
||||
!.codex-tasks/template-audit-execution/raw/
|
||||
!.codex-tasks/template-audit-execution/raw/completion-evidence.json
|
||||
docker-compose.override.yml
|
||||
.env.production
|
||||
|
||||
|
||||
@@ -28,8 +28,9 @@ export function InquiryPreviewEditor({
|
||||
const record = query.data?.find((item) => item.id === runtime.key);
|
||||
const field = runtime.fields.find((item) => item.key === fieldKey);
|
||||
useEffect(() => {
|
||||
if (field) form.setFieldsValue({ ...field });
|
||||
}, [fieldKey, runtime.key, form]);
|
||||
if (!record || !field) return;
|
||||
form.setFieldsValue({ ...field });
|
||||
}, [field, fieldKey, form, record, runtime.key]);
|
||||
const update = (values: Record<string, unknown>) =>
|
||||
runtime.fields.map((item) => (item.key === fieldKey ? { ...item, ...values } : item));
|
||||
const save = useMutation({
|
||||
|
||||
@@ -1,34 +1,15 @@
|
||||
import { Alert, Button, Grid, Select, Segmented, Space, Typography } from "antd";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import type { AdminTemplateContent, RuntimeWorkspace } from "@personal-brand/api-client";
|
||||
import type { BrandProfile } from "@personal-brand/api-client";
|
||||
import { Alert, Grid, Segmented, Select, Space } from "antd";
|
||||
import type {
|
||||
AdminTemplateContent,
|
||||
BrandProfile,
|
||||
RuntimeWorkspace,
|
||||
} from "@personal-brand/api-client";
|
||||
import { StatusTag } from "../../components/StatusTag.js";
|
||||
import { RecordContentEditor } from "../../components/RecordContentEditor.js";
|
||||
import { TemplatePreview } from "./TemplatePreview.js";
|
||||
import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js";
|
||||
import {
|
||||
resolvePreviewSelection,
|
||||
previewTrustRecordId,
|
||||
type PreviewSelection,
|
||||
type PreviewTarget,
|
||||
} from "./preview-selection.js";
|
||||
import { filterSectionsForPreviewTarget } from "../../lib/presentation/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";
|
||||
import type { RecordDraft } from "./presentation-editor-record-preview.js";
|
||||
import { pageTitle, previewTargetSource, trustSection } from "./presentation-editor-helpers.js";
|
||||
import { useDraftWorkspace } from "./use-draft-workspace.js";
|
||||
import { PresentationFormPanel } from "./PresentationFormPanel.js";
|
||||
import type { PreviewSelection } from "./preview-selection.js";
|
||||
import { usePresentationEditorController } from "./presentation-editor-controller.js";
|
||||
import { PresentationEditorInspector } from "./PresentationEditorInspector.js";
|
||||
import { PresentationEditorPreview } from "./PresentationEditorPreview.js";
|
||||
|
||||
interface PresentationEditorProps {
|
||||
templateContent: AdminTemplateContent | null | undefined;
|
||||
@@ -49,254 +30,14 @@ export function PresentationEditor({
|
||||
error,
|
||||
initialSelection,
|
||||
}: PresentationEditorProps) {
|
||||
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<RecordDraft>();
|
||||
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 = useBrandPresentationSections(templateContent);
|
||||
const pageOptions = useMemo(() => {
|
||||
const pages = new Map<string, string>();
|
||||
for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label);
|
||||
for (const section of templateContent?.admin.sections ?? []) {
|
||||
const navigation = templateContent?.navigation.find((item) => item.page === section.page);
|
||||
if (!pages.has(section.page))
|
||||
pages.set(section.page, navigation?.label ?? pageTitle(section.page));
|
||||
}
|
||||
return [...pages].map(([value, label]) => ({ value, label }));
|
||||
}, [templateContent]);
|
||||
const selectedPage = pageOptions.some((item) => item.value === activePage)
|
||||
? activePage
|
||||
: pageOptions[0]?.value;
|
||||
const visibleSections = sections.filter((section) => section.page === selectedPage);
|
||||
const recordSections = useMemo(
|
||||
() =>
|
||||
(templateContent?.trustContentTypes ?? [])
|
||||
.filter((item) => item.pages?.includes(selectedPage ?? ""))
|
||||
.map((item) => trustSection(item, selectedPage ?? "home")),
|
||||
[templateContent, selectedPage],
|
||||
);
|
||||
const visibleTargets = useMemo<PreviewTarget[]>(
|
||||
() =>
|
||||
[...(templateContent?.admin.sections ?? []), ...recordSections]
|
||||
.filter(
|
||||
(section) =>
|
||||
section.page === selectedPage &&
|
||||
(selectedPage !== "detail" || section.target === "brand"),
|
||||
)
|
||||
.flatMap((section) =>
|
||||
(section.previewTargets ?? []).map((target) => ({
|
||||
...target,
|
||||
page: section.page,
|
||||
source: previewTargetSource(section, target.key),
|
||||
...(section.key.startsWith("trust:") ? { trustType: section.key.slice(6) } : {}),
|
||||
})),
|
||||
)
|
||||
.concat(
|
||||
selectedPage === "inquiry" && inquiryRuntime
|
||||
? inquiryRuntime.fields.map((field) => ({
|
||||
key: `inquiry-field:${field.key}`,
|
||||
label: field.label,
|
||||
page: "inquiry",
|
||||
source: "inquiry" as const,
|
||||
}))
|
||||
: [],
|
||||
),
|
||||
[templateContent, selectedPage, recordSections, inquiryRuntime],
|
||||
);
|
||||
const activeTarget = selection?.targetKey;
|
||||
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
|
||||
const selectedSection = [...(templateContent?.admin.sections ?? []), ...recordSections].find(
|
||||
(section) =>
|
||||
section.page === selectedPage &&
|
||||
section.previewTargets?.some((target) => target.key === selectedTarget?.key),
|
||||
);
|
||||
const selectedRecordSource =
|
||||
selectedTarget?.source === "offering" || selectedTarget?.source === "trust"
|
||||
? selectedTarget.source
|
||||
: undefined;
|
||||
const { offeringsQuery, trustQuery, selectedRecord } = usePresentationRecordQueries(
|
||||
selectedRecordSource,
|
||||
selection?.recordId,
|
||||
);
|
||||
const editableSections = filterSectionsForPreviewTarget(
|
||||
visibleSections.filter((section) =>
|
||||
section.fields.some((field) => field.binding.startsWith("brand.")),
|
||||
),
|
||||
selectedTarget?.key,
|
||||
);
|
||||
const recordSection = useMemo(
|
||||
() =>
|
||||
selectedSection && selection?.targetKey
|
||||
? {
|
||||
...selectedSection,
|
||||
fields: selectedSection.fields.filter(
|
||||
(field) => field.previewTarget === selection.targetKey,
|
||||
),
|
||||
}
|
||||
: undefined,
|
||||
[selectedSection, selection?.targetKey],
|
||||
);
|
||||
const handleTargetSelected = useCallback(
|
||||
(next?: PreviewSelection) => {
|
||||
const select = () =>
|
||||
setSelection(
|
||||
next
|
||||
? resolvePreviewSelection(
|
||||
next.targetKey,
|
||||
next.recordId,
|
||||
visibleTargets,
|
||||
selectedPage ?? "home",
|
||||
)
|
||||
: undefined,
|
||||
);
|
||||
if (recordDraft || inquiryDraft)
|
||||
guardDraft(() => {
|
||||
setInquiryDraft(undefined);
|
||||
setRecordDraft(undefined);
|
||||
select();
|
||||
});
|
||||
else select();
|
||||
},
|
||||
[visibleTargets, selectedPage, recordDraft, inquiryDraft, guardDraft],
|
||||
);
|
||||
const relatedTargets = [
|
||||
...(templateContent?.admin.sections ?? [])
|
||||
.filter((section) => section.page === selectedPage && section.target !== "brand")
|
||||
.map((section) => section.target),
|
||||
...((templateContent?.trustContentTypes ?? []).some((item) =>
|
||||
item.pages?.includes(selectedPage ?? ""),
|
||||
)
|
||||
? ["trust"]
|
||||
: []),
|
||||
];
|
||||
const pageLinks = [...new Set(relatedTargets)].flatMap((target) =>
|
||||
target === "trust"
|
||||
? (templateContent?.trustContentTypes ?? [])
|
||||
.filter((item) => item.pages?.includes(selectedPage ?? ""))
|
||||
.map((item) => ({
|
||||
target: `trust:${item.type}`,
|
||||
label: `编辑${item.label}`,
|
||||
}))
|
||||
: [
|
||||
{
|
||||
target,
|
||||
label: (
|
||||
{ offering: "管理此页展示的业务内容", inquiry: "管理此页的咨询表单" } as Record<
|
||||
string,
|
||||
string
|
||||
>
|
||||
)[target],
|
||||
},
|
||||
],
|
||||
);
|
||||
const relevantPageLinks = selectedSection
|
||||
? pageLinks.filter((item) => {
|
||||
if (item.target.startsWith("trust:")) return selectedSection.target === "trust";
|
||||
return item.target === selectedSection.target;
|
||||
})
|
||||
: pageLinks;
|
||||
const formState = useBrandPresentationForm({ brand, config, sections });
|
||||
const { form, initialValues } = formState;
|
||||
const save = useBrandSaveMutation({
|
||||
...formState,
|
||||
brand,
|
||||
config,
|
||||
sections,
|
||||
queryClient,
|
||||
onSaved: () => setBrandDirty(false),
|
||||
});
|
||||
|
||||
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,
|
||||
);
|
||||
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,
|
||||
),
|
||||
);
|
||||
setActivePage(resolvedPage);
|
||||
setHasInitializedSelection(true);
|
||||
}, [hasInitializedSelection, initialSelection, pageOptions, selectedPage, visibleTargets]);
|
||||
useEffect(() => {
|
||||
if (!initialSelection) setSelection(undefined);
|
||||
}, [initialSelection, selectedPage, templateContent?.displayName]);
|
||||
useEffect(() => {
|
||||
if (!selection?.recordId) return;
|
||||
const records =
|
||||
selectedTarget?.source === "trust"
|
||||
? previewWorkspace?.trustItems
|
||||
: previewWorkspace?.offerings;
|
||||
if (records && !records.some((item) => item.id === selection.recordId)) setSelection(undefined);
|
||||
}, [
|
||||
previewWorkspace?.offerings,
|
||||
previewWorkspace?.trustItems,
|
||||
selectedTarget?.source,
|
||||
selection,
|
||||
]);
|
||||
useEffect(
|
||||
() => setRecordDraft(undefined),
|
||||
[selection?.targetKey, selection?.recordId, selectedPage],
|
||||
);
|
||||
const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({
|
||||
brand,
|
||||
config,
|
||||
sections,
|
||||
form,
|
||||
onDirty: () => setBrandDirty(true),
|
||||
});
|
||||
const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection });
|
||||
useEffect(() => resetPreview(), [config, initialValues, resetPreview]);
|
||||
const draftWorkspace = useDraftWorkspace({
|
||||
previewWorkspace,
|
||||
previewBrand,
|
||||
inquiryRuntime,
|
||||
inquiryDraft,
|
||||
recordDraft,
|
||||
selectedRecord,
|
||||
recordSection,
|
||||
recordPreview,
|
||||
const controller = usePresentationEditorController({
|
||||
templateContent,
|
||||
previewWorkspace,
|
||||
config,
|
||||
brand,
|
||||
...(initialSelection ? { initialSelection } : {}),
|
||||
});
|
||||
const selectedDetailOfferingId =
|
||||
detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId)
|
||||
? detailOfferingId
|
||||
: draftWorkspace?.offerings[0]?.id;
|
||||
|
||||
return (
|
||||
<section className="presentation-editor" aria-labelledby="presentation-editor-title">
|
||||
@@ -324,306 +65,33 @@ export function PresentationEditor({
|
||||
{breakpoints.xs ? (
|
||||
<Select
|
||||
aria-label="选择小程序页面"
|
||||
value={selectedPage}
|
||||
options={pageOptions}
|
||||
onChange={(value) =>
|
||||
guardDraft(() => {
|
||||
setBrandDirty(false);
|
||||
form.setFieldsValue(initialValues);
|
||||
resetPreview();
|
||||
setRecordDraft(undefined);
|
||||
setInquiryDraft(undefined);
|
||||
setActivePage(value);
|
||||
})
|
||||
}
|
||||
value={controller.selectedPage ?? null}
|
||||
options={controller.pageOptions}
|
||||
onChange={controller.selectPage}
|
||||
className="admin-field-w-2xl"
|
||||
/>
|
||||
) : (
|
||||
<Segmented
|
||||
value={selectedPage}
|
||||
options={pageOptions}
|
||||
onChange={(value) =>
|
||||
guardDraft(() => {
|
||||
setBrandDirty(false);
|
||||
form.setFieldsValue(initialValues);
|
||||
resetPreview();
|
||||
setRecordDraft(undefined);
|
||||
setInquiryDraft(undefined);
|
||||
setActivePage(String(value));
|
||||
})
|
||||
}
|
||||
value={controller.selectedPage ?? null}
|
||||
options={controller.pageOptions}
|
||||
onChange={(value) => controller.selectPage(String(value))}
|
||||
/>
|
||||
)}
|
||||
</Space>
|
||||
<div className="presentation-editor__workspace">
|
||||
<div className="presentation-editor__preview">
|
||||
<h3 className="admin-section-title admin-flush">页面预览</h3>
|
||||
{selectedPage === "detail" && draftWorkspace?.offerings.length ? (
|
||||
<Select
|
||||
aria-label="选择详情页业务内容"
|
||||
className="admin-block admin-offset-bottom-sm"
|
||||
value={selectedDetailOfferingId}
|
||||
options={draftWorkspace.offerings.map((item) => ({
|
||||
value: item.id,
|
||||
label: item.name,
|
||||
}))}
|
||||
onChange={(value) => {
|
||||
setDetailOfferingId(value);
|
||||
setSelection(undefined);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<TemplatePreview
|
||||
brand={previewBrand}
|
||||
{...(draftWorkspace ? { workspace: draftWorkspace } : {})}
|
||||
page={selectedPage ?? "home"}
|
||||
{...(selectedPage === "detail" && selectedDetailOfferingId
|
||||
? { offeringId: selectedDetailOfferingId }
|
||||
: {})}
|
||||
{...(activeTarget ? { targetKey: activeTarget } : {})}
|
||||
{...(selection ? { selection } : {})}
|
||||
targets={visibleTargets}
|
||||
onTargetSelected={handleTargetSelected}
|
||||
/>
|
||||
</div>
|
||||
<aside className="presentation-editor__outline" aria-label="页面区域">
|
||||
<h3 className="admin-section-title admin-flush">页面区域</h3>
|
||||
<p className="admin-section-description">选择区域,编辑对应内容</p>
|
||||
{visibleTargets.length ? (
|
||||
<Space className="presentation-editor__regions admin-offset-top" wrap>
|
||||
{visibleTargets.map((target) => (
|
||||
<Button
|
||||
key={target.key}
|
||||
className={
|
||||
visibleTargets.some((parent) => parent.children?.includes(target.key))
|
||||
? "is-child-region"
|
||||
: ""
|
||||
}
|
||||
aria-pressed={activeTarget === target.key}
|
||||
type={activeTarget === target.key ? "primary" : "default"}
|
||||
onClick={() => {
|
||||
const recordId =
|
||||
target.source === "offering"
|
||||
? selectedPage === "detail"
|
||||
? selectedDetailOfferingId
|
||||
: draftWorkspace?.offerings[0]?.id
|
||||
: target.source === "trust"
|
||||
? previewTrustRecordId(
|
||||
draftWorkspace?.trustItems ?? [],
|
||||
target.trustType,
|
||||
)
|
||||
: undefined;
|
||||
handleTargetSelected({
|
||||
targetKey: target.key,
|
||||
...(recordId ? { recordId } : {}),
|
||||
});
|
||||
}}
|
||||
>
|
||||
{target.label}
|
||||
</Button>
|
||||
))}
|
||||
</Space>
|
||||
) : null}
|
||||
{!visibleTargets.length ? (
|
||||
<Typography.Text type="secondary">此页为动态预览</Typography.Text>
|
||||
) : null}
|
||||
</aside>
|
||||
<div className="presentation-editor__inspector">
|
||||
<h3 className="admin-section-title admin-flush">
|
||||
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
|
||||
</h3>
|
||||
<StatusTag
|
||||
tone={
|
||||
save.isError
|
||||
? "error"
|
||||
: save.isPending || brandDirty || recordDraft || inquiryDraft
|
||||
? "warning"
|
||||
: "neutral"
|
||||
}
|
||||
label={
|
||||
save.isPending
|
||||
? "正在保存"
|
||||
: save.isError
|
||||
? "保存失败,请重试"
|
||||
: brandDirty || recordDraft || inquiryDraft
|
||||
? "有未保存修改"
|
||||
: "草稿已同步"
|
||||
}
|
||||
/>
|
||||
{selectedPage === "detail" && !selectedTarget ? (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
title="详情页由所选业务内容动态生成"
|
||||
description="选择业务内容预览详情,记录内容在业务提供项中维护;公共标题和按钮文案可从左侧区域列表配置,对全部详情生效。"
|
||||
action={
|
||||
<Button
|
||||
onClick={() => {
|
||||
void navigate("/admin/services");
|
||||
}}
|
||||
>
|
||||
管理业务内容
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? (
|
||||
<InquiryPreviewEditor
|
||||
runtime={
|
||||
draftWorkspace?.inquiryForms.find((item) => item.key === inquiryRuntime.key) ??
|
||||
inquiryRuntime
|
||||
}
|
||||
fieldKey={activeTarget.slice("inquiry-field:".length)}
|
||||
onDraft={setInquiryDraft}
|
||||
onSaved={() => setInquiryDraft(undefined)}
|
||||
/>
|
||||
) : selectedTarget?.composite ? (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
title="这是一个组合区域"
|
||||
description={
|
||||
<Space wrap>
|
||||
{(selectedTarget.children ?? []).map((childKey) => {
|
||||
const child = visibleTargets.find((item) => item.key === childKey);
|
||||
if (!child) return null;
|
||||
return (
|
||||
<Button
|
||||
key={child.key}
|
||||
onClick={() => {
|
||||
const recordId =
|
||||
child.source === "offering"
|
||||
? selectedPage === "detail"
|
||||
? selectedDetailOfferingId
|
||||
: draftWorkspace?.offerings[0]?.id
|
||||
: child.source === "trust"
|
||||
? previewTrustRecordId(
|
||||
draftWorkspace?.trustItems ?? [],
|
||||
child.trustType,
|
||||
)
|
||||
: undefined;
|
||||
handleTargetSelected({
|
||||
targetKey: child.key,
|
||||
...(recordId ? { recordId } : {}),
|
||||
});
|
||||
}}
|
||||
>
|
||||
编辑{child.label}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</Space>
|
||||
}
|
||||
/>
|
||||
) : selectedRecordSource && selection?.recordId && selectedSection ? (
|
||||
selectedRecord ? (
|
||||
<RecordContentEditor
|
||||
key={`${selectedRecordSource}:${selectedRecord.id}:${selectedSection.key}`}
|
||||
source={selectedRecordSource}
|
||||
record={selectedRecord}
|
||||
section={recordSection!}
|
||||
context="visual"
|
||||
onDraft={(values) =>
|
||||
setRecordDraft({
|
||||
source: selectedRecordSource,
|
||||
id: selectedRecord.id,
|
||||
values,
|
||||
})
|
||||
}
|
||||
onSaved={() => setRecordDraft(undefined)}
|
||||
/>
|
||||
) : (
|
||||
<Alert
|
||||
type={
|
||||
(
|
||||
selectedRecordSource === "offering"
|
||||
? offeringsQuery.isError
|
||||
: trustQuery.isError
|
||||
)
|
||||
? "error"
|
||||
: "info"
|
||||
}
|
||||
title={
|
||||
(
|
||||
selectedRecordSource === "offering"
|
||||
? offeringsQuery.isError
|
||||
: trustQuery.isError
|
||||
)
|
||||
? "内容读取失败"
|
||||
: (
|
||||
selectedRecordSource === "offering"
|
||||
? offeringsQuery.isSuccess
|
||||
: trustQuery.isSuccess
|
||||
)
|
||||
? "对应内容已不存在,请重新选择页面中的区域"
|
||||
: "正在读取对应内容"
|
||||
}
|
||||
{...((
|
||||
selectedRecordSource === "offering"
|
||||
? offeringsQuery.isError
|
||||
: trustQuery.isError
|
||||
)
|
||||
? {
|
||||
action: (
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() => {
|
||||
if (selectedRecordSource === "offering")
|
||||
void offeringsQuery.refetch();
|
||||
else void trustQuery.refetch();
|
||||
}}
|
||||
>
|
||||
重试
|
||||
</Button>
|
||||
),
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
)
|
||||
) : selectedRecordSource ? (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
title="此区域尚未配置内容"
|
||||
description="创建并启用对应内容后,即可在预览中点选编辑。"
|
||||
action={
|
||||
<Button
|
||||
onClick={() =>
|
||||
guardDraft(() => {
|
||||
void navigate(
|
||||
selectedRecordSource === "trust"
|
||||
? `/admin/trust?type=${encodeURIComponent(selectedTarget?.trustType ?? "")}`
|
||||
: "/admin/services",
|
||||
);
|
||||
})
|
||||
}
|
||||
>
|
||||
配置此区域内容
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : !selectedTarget ? (
|
||||
<div className="presentation-editor__empty">
|
||||
<h3 className="admin-subhead">选择要编辑的区域</h3>
|
||||
<p className="admin-section-description">
|
||||
点击预览中的内容,或使用区域列表,查看并修改对应字段。
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<PresentationFormPanel
|
||||
form={form}
|
||||
initialValues={initialValues}
|
||||
editableSections={editableSections}
|
||||
relevantPageLinks={relevantPageLinks}
|
||||
selectedTarget={selectedTarget}
|
||||
save={{
|
||||
error: save.error,
|
||||
isPending: save.isPending,
|
||||
mutate: (values) => save.mutate(values),
|
||||
}}
|
||||
onValuesChange={handleValuesChange}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<PresentationEditorPreview
|
||||
previewBrand={controller.previewBrand}
|
||||
draftWorkspace={controller.draftWorkspace}
|
||||
selectedPage={controller.selectedPage}
|
||||
selectedDetailOfferingId={controller.selectedDetailOfferingId}
|
||||
activeTarget={controller.activeTarget}
|
||||
selection={controller.selection}
|
||||
visibleTargets={controller.visibleTargets}
|
||||
onSelectDetailOffering={controller.selectDetailOffering}
|
||||
onTargetSelected={controller.handleTargetSelected}
|
||||
onSelectPreviewTarget={controller.selectPreviewTarget}
|
||||
/>
|
||||
<PresentationEditorInspector controller={controller} />
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
import { Alert, Button, Space } from "antd";
|
||||
import { StatusTag } from "../../components/StatusTag.js";
|
||||
import { RecordContentEditor } from "../../components/RecordContentEditor.js";
|
||||
import { InquiryPreviewEditor } from "./InquiryPreviewEditor.js";
|
||||
import { PresentationFormPanel } from "./PresentationFormPanel.js";
|
||||
import { pageTitle } from "./presentation-editor-helpers.js";
|
||||
import type { PresentationEditorController } from "./presentation-editor-controller.js";
|
||||
|
||||
export function PresentationEditorInspector({
|
||||
controller,
|
||||
}: {
|
||||
controller: PresentationEditorController;
|
||||
}) {
|
||||
const {
|
||||
selectedPage,
|
||||
selectedTarget,
|
||||
activeTarget,
|
||||
selection,
|
||||
selectedSection,
|
||||
selectedRecordSource,
|
||||
selectedRecord,
|
||||
recordSection,
|
||||
editableSections,
|
||||
relevantPageLinks,
|
||||
inquiryRuntime,
|
||||
draftWorkspace,
|
||||
form,
|
||||
initialValues,
|
||||
save,
|
||||
offeringsQuery,
|
||||
trustQuery,
|
||||
recordDraft,
|
||||
inquiryDraft,
|
||||
brandDirty,
|
||||
guardDraft,
|
||||
} = controller;
|
||||
const recordQuery = selectedRecordSource === "trust" ? trustQuery : offeringsQuery;
|
||||
|
||||
return (
|
||||
<div className="presentation-editor__inspector">
|
||||
<h3 className="admin-section-title admin-flush">
|
||||
{selectedTarget?.label ?? pageTitle(selectedPage ?? "home")}
|
||||
</h3>
|
||||
<StatusTag
|
||||
tone={
|
||||
save.isError
|
||||
? "error"
|
||||
: save.isPending || brandDirty || recordDraft || inquiryDraft
|
||||
? "warning"
|
||||
: "neutral"
|
||||
}
|
||||
label={
|
||||
save.isPending
|
||||
? "正在保存"
|
||||
: save.isError
|
||||
? "保存失败,请重试"
|
||||
: brandDirty || recordDraft || inquiryDraft
|
||||
? "有未保存修改"
|
||||
: "草稿已同步"
|
||||
}
|
||||
/>
|
||||
{selectedPage === "detail" && !selectedTarget ? (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
title="详情页由所选业务内容动态生成"
|
||||
description="选择业务内容预览详情,记录内容在业务提供项中维护;公共标题和按钮文案可从左侧区域列表配置,对全部详情生效。"
|
||||
action={
|
||||
<Button
|
||||
onClick={() => {
|
||||
void controller.navigate("/admin/services");
|
||||
}}
|
||||
>
|
||||
管理业务内容
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : activeTarget?.startsWith("inquiry-field:") && inquiryRuntime ? (
|
||||
<InquiryPreviewEditor
|
||||
runtime={
|
||||
draftWorkspace?.inquiryForms.find((item) => item.key === inquiryRuntime.key) ??
|
||||
inquiryRuntime
|
||||
}
|
||||
fieldKey={activeTarget.slice("inquiry-field:".length)}
|
||||
onDraft={controller.setInquiryDraft}
|
||||
onSaved={() => controller.setInquiryDraft(undefined)}
|
||||
/>
|
||||
) : selectedTarget?.composite ? (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
title="这是一个组合区域"
|
||||
description={
|
||||
<Space wrap>
|
||||
{(selectedTarget.children ?? []).map((childKey) => {
|
||||
const child = visibleTarget(childKey, controller);
|
||||
if (!child) return null;
|
||||
return (
|
||||
<Button key={child.key} onClick={() => controller.selectPreviewTarget(child)}>
|
||||
编辑{child.label}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</Space>
|
||||
}
|
||||
/>
|
||||
) : selectedRecordSource && selection?.recordId && selectedSection ? (
|
||||
selectedRecord ? (
|
||||
<RecordContentEditor
|
||||
key={`${selectedRecordSource}:${selectedRecord.id}:${selectedSection.key}`}
|
||||
source={selectedRecordSource}
|
||||
record={selectedRecord}
|
||||
section={recordSection!}
|
||||
context="visual"
|
||||
onDraft={(values) =>
|
||||
controller.setRecordDraft({
|
||||
source: selectedRecordSource,
|
||||
id: selectedRecord.id,
|
||||
values,
|
||||
})
|
||||
}
|
||||
onSaved={() => controller.setRecordDraft(undefined)}
|
||||
/>
|
||||
) : (
|
||||
<Alert
|
||||
type={recordQuery.isError ? "error" : "info"}
|
||||
title={
|
||||
recordQuery.isError
|
||||
? "内容读取失败"
|
||||
: recordQuery.isSuccess
|
||||
? "对应内容已不存在,请重新选择页面中的区域"
|
||||
: "正在读取对应内容"
|
||||
}
|
||||
{...(recordQuery.isError
|
||||
? {
|
||||
action: (
|
||||
<Button size="small" onClick={() => void recordQuery.refetch()}>
|
||||
重试
|
||||
</Button>
|
||||
),
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
)
|
||||
) : selectedRecordSource ? (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
title="此区域尚未配置内容"
|
||||
description="创建并启用对应内容后,即可在预览中点选编辑。"
|
||||
action={
|
||||
<Button
|
||||
onClick={() =>
|
||||
guardDraft(() => {
|
||||
void controller.navigate(
|
||||
selectedRecordSource === "trust"
|
||||
? `/admin/trust?type=${encodeURIComponent(selectedTarget?.trustType ?? "")}`
|
||||
: "/admin/services",
|
||||
);
|
||||
})
|
||||
}
|
||||
>
|
||||
配置此区域内容
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
) : !selectedTarget ? (
|
||||
<div className="presentation-editor__empty">
|
||||
<h3 className="admin-subhead">选择要编辑的区域</h3>
|
||||
<p className="admin-section-description">
|
||||
点击预览中的内容,或使用区域列表,查看并修改对应字段。
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<PresentationFormPanel
|
||||
key={`${selectedPage}:${selectedTarget.key}`}
|
||||
form={form}
|
||||
initialValues={initialValues}
|
||||
editableSections={editableSections}
|
||||
relevantPageLinks={relevantPageLinks}
|
||||
selectedTarget={selectedTarget}
|
||||
save={{
|
||||
error: save.error,
|
||||
isPending: save.isPending,
|
||||
mutate: (values) => save.mutate(values),
|
||||
}}
|
||||
onValuesChange={controller.handleValuesChange}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function visibleTarget(key: string, controller: PresentationEditorController) {
|
||||
return controller.visibleTargets.find((item) => item.key === key);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Button, Select, Space, Typography } from "antd";
|
||||
import type { BrandProfile, RuntimeWorkspace } from "@personal-brand/api-client";
|
||||
import { TemplatePreview } from "./TemplatePreview.js";
|
||||
import type { PreviewSelection, PreviewTarget } from "./preview-selection.js";
|
||||
|
||||
interface PresentationEditorPreviewProps {
|
||||
previewBrand: BrandProfile;
|
||||
draftWorkspace?: RuntimeWorkspace | undefined;
|
||||
selectedPage: string | undefined;
|
||||
selectedDetailOfferingId: string | undefined;
|
||||
activeTarget: string | undefined;
|
||||
selection: PreviewSelection | undefined;
|
||||
visibleTargets: PreviewTarget[];
|
||||
onSelectDetailOffering: (id: string) => void;
|
||||
onTargetSelected: (next?: PreviewSelection) => void;
|
||||
onSelectPreviewTarget: (target: PreviewTarget) => void;
|
||||
}
|
||||
|
||||
export function PresentationEditorPreview({
|
||||
previewBrand,
|
||||
draftWorkspace,
|
||||
selectedPage,
|
||||
selectedDetailOfferingId,
|
||||
activeTarget,
|
||||
selection,
|
||||
visibleTargets,
|
||||
onSelectDetailOffering,
|
||||
onTargetSelected,
|
||||
onSelectPreviewTarget,
|
||||
}: PresentationEditorPreviewProps) {
|
||||
return (
|
||||
<>
|
||||
<div className="presentation-editor__preview">
|
||||
<h3 className="admin-section-title admin-flush">页面预览</h3>
|
||||
{selectedPage === "detail" && draftWorkspace?.offerings.length ? (
|
||||
<Select
|
||||
aria-label="选择详情页业务内容"
|
||||
className="admin-block admin-offset-bottom-sm"
|
||||
value={selectedDetailOfferingId ?? null}
|
||||
options={draftWorkspace.offerings.map((item) => ({
|
||||
value: item.id,
|
||||
label: item.name,
|
||||
}))}
|
||||
onChange={onSelectDetailOffering}
|
||||
/>
|
||||
) : null}
|
||||
<TemplatePreview
|
||||
brand={previewBrand}
|
||||
{...(draftWorkspace ? { workspace: draftWorkspace } : {})}
|
||||
page={selectedPage ?? "home"}
|
||||
{...(selectedPage === "detail" && selectedDetailOfferingId
|
||||
? { offeringId: selectedDetailOfferingId }
|
||||
: {})}
|
||||
{...(activeTarget ? { targetKey: activeTarget } : {})}
|
||||
{...(selection ? { selection } : {})}
|
||||
targets={visibleTargets}
|
||||
onTargetSelected={onTargetSelected}
|
||||
/>
|
||||
</div>
|
||||
<aside className="presentation-editor__outline" aria-label="页面区域">
|
||||
<h3 className="admin-section-title admin-flush">页面区域</h3>
|
||||
<p className="admin-section-description">选择区域,编辑对应内容</p>
|
||||
{visibleTargets.length ? (
|
||||
<Space className="presentation-editor__regions admin-offset-top" wrap>
|
||||
{visibleTargets.map((target) => (
|
||||
<Button
|
||||
key={target.key}
|
||||
className={
|
||||
visibleTargets.some((parent) => parent.children?.includes(target.key))
|
||||
? "is-child-region"
|
||||
: ""
|
||||
}
|
||||
aria-pressed={activeTarget === target.key}
|
||||
type={activeTarget === target.key ? "primary" : "default"}
|
||||
onClick={() => onSelectPreviewTarget(target)}
|
||||
>
|
||||
{target.label}
|
||||
</Button>
|
||||
))}
|
||||
</Space>
|
||||
) : null}
|
||||
{!visibleTargets.length ? (
|
||||
<Typography.Text type="secondary">此页为动态预览</Typography.Text>
|
||||
) : null}
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -146,7 +146,7 @@ export function TemplatePreview({
|
||||
<>
|
||||
{!ready && !error ? (
|
||||
<div className="template-preview__loading">
|
||||
<Spin tip="正在加载页面预览" />
|
||||
<Spin description="正在加载页面预览" />
|
||||
</div>
|
||||
) : null}
|
||||
{error ? (
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate, type NavigateFunction } from "react-router-dom";
|
||||
import type {
|
||||
AdminTemplateContent,
|
||||
BrandProfile,
|
||||
Offering,
|
||||
RuntimeWorkspace,
|
||||
TemplateAdminSection,
|
||||
TrustContent,
|
||||
} from "@personal-brand/api-client";
|
||||
import type { FormInstance } from "antd";
|
||||
import { filterSectionsForPreviewTarget } from "../../lib/presentation/presentation-bindings.js";
|
||||
import type { PresentationValues } from "../../lib/presentation/presentation-bindings.js";
|
||||
import {
|
||||
resolvePreviewSelection,
|
||||
previewTrustRecordId,
|
||||
type PreviewSelection,
|
||||
type PreviewTarget,
|
||||
} from "./preview-selection.js";
|
||||
import { useEditorDraft } from "./use-editor-draft.js";
|
||||
import {
|
||||
useBrandPresentationForm,
|
||||
useBrandPresentationSections,
|
||||
useBrandPreviewDraft,
|
||||
useBrandSaveMutation,
|
||||
usePresentationRecordQueries,
|
||||
} from "./presentation-editor-state.js";
|
||||
import { useRecordPreview, type RecordDraft } from "./presentation-editor-record-preview.js";
|
||||
import { pageTitle, previewTargetSource, trustSection } from "./presentation-editor-helpers.js";
|
||||
import { useDraftWorkspace } from "./use-draft-workspace.js";
|
||||
|
||||
export interface PresentationEditorControllerInput {
|
||||
templateContent: AdminTemplateContent | null | undefined;
|
||||
previewWorkspace?: RuntimeWorkspace | undefined;
|
||||
config: Record<string, unknown> | null | undefined;
|
||||
brand: BrandProfile;
|
||||
initialSelection?: PreviewSelection;
|
||||
}
|
||||
|
||||
export interface PresentationRecordQuery {
|
||||
isError: boolean;
|
||||
isSuccess: boolean;
|
||||
refetch: () => unknown;
|
||||
}
|
||||
|
||||
export interface PresentationEditorController {
|
||||
pageOptions: { value: string; label: string }[];
|
||||
selectedPage: string | undefined;
|
||||
visibleTargets: PreviewTarget[];
|
||||
selectedTarget: PreviewTarget | undefined;
|
||||
selectedSection: TemplateAdminSection | undefined;
|
||||
selectedRecordSource: "offering" | "trust" | undefined;
|
||||
selectedRecord: Offering | TrustContent | undefined;
|
||||
recordSection: TemplateAdminSection | undefined;
|
||||
editableSections: TemplateAdminSection[];
|
||||
relevantPageLinks: { target: string; label: string | undefined }[];
|
||||
inquiryRuntime: RuntimeWorkspace["inquiryForms"][number] | undefined;
|
||||
draftWorkspace: RuntimeWorkspace | undefined;
|
||||
previewBrand: BrandProfile;
|
||||
selectedDetailOfferingId: string | undefined;
|
||||
form: FormInstance<PresentationValues>;
|
||||
initialValues: PresentationValues;
|
||||
save: {
|
||||
error: unknown;
|
||||
isError: boolean;
|
||||
isPending: boolean;
|
||||
mutate: (values: PresentationValues) => void;
|
||||
};
|
||||
offeringsQuery: PresentationRecordQuery;
|
||||
trustQuery: PresentationRecordQuery;
|
||||
recordDraft: RecordDraft | undefined;
|
||||
inquiryDraft: RuntimeWorkspace["inquiryForms"][number]["fields"] | undefined;
|
||||
brandDirty: boolean;
|
||||
selection: PreviewSelection | undefined;
|
||||
activeTarget: string | undefined;
|
||||
guardDraft: (action: () => void) => void;
|
||||
selectPage: (page: string) => void;
|
||||
selectDetailOffering: (id: string) => void;
|
||||
selectPreviewTarget: (target: PreviewTarget) => void;
|
||||
handleTargetSelected: (next?: PreviewSelection) => void;
|
||||
setRecordDraft: (draft: RecordDraft | undefined) => void;
|
||||
setInquiryDraft: (fields: RuntimeWorkspace["inquiryForms"][number]["fields"] | undefined) => void;
|
||||
handleValuesChange: (changed: PresentationValues, allValues: PresentationValues) => void;
|
||||
navigate: NavigateFunction;
|
||||
}
|
||||
|
||||
/**
|
||||
* PresentationEditor 的状态与派生数据集中在此处。
|
||||
* 视图组件只负责渲染,避免页面组件继续膨胀。
|
||||
*/
|
||||
export function usePresentationEditorController({
|
||||
templateContent,
|
||||
previewWorkspace,
|
||||
config,
|
||||
brand,
|
||||
initialSelection,
|
||||
}: PresentationEditorControllerInput): PresentationEditorController {
|
||||
const queryClient = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
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<RecordDraft>();
|
||||
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 = useBrandPresentationSections(templateContent);
|
||||
const pageOptions = useMemo(() => {
|
||||
const pages = new Map<string, string>();
|
||||
for (const item of templateContent?.navigation ?? []) pages.set(item.page, item.label);
|
||||
for (const section of templateContent?.admin.sections ?? []) {
|
||||
const navigation = templateContent?.navigation.find((item) => item.page === section.page);
|
||||
if (!pages.has(section.page))
|
||||
pages.set(section.page, navigation?.label ?? pageTitle(section.page));
|
||||
}
|
||||
return [...pages].map(([value, label]) => ({ value, label }));
|
||||
}, [templateContent]);
|
||||
const selectedPage = pageOptions.some((item) => item.value === activePage)
|
||||
? activePage
|
||||
: pageOptions[0]?.value;
|
||||
const visibleSections = sections.filter((section) => section.page === selectedPage);
|
||||
const recordSections = useMemo(
|
||||
() =>
|
||||
(templateContent?.trustContentTypes ?? [])
|
||||
.filter((item) => item.pages?.includes(selectedPage ?? ""))
|
||||
.map((item) => trustSection(item, selectedPage ?? "home")),
|
||||
[templateContent, selectedPage],
|
||||
);
|
||||
const visibleTargets = useMemo<PreviewTarget[]>(
|
||||
() =>
|
||||
[...(templateContent?.admin.sections ?? []), ...recordSections]
|
||||
.filter(
|
||||
(section) =>
|
||||
section.page === selectedPage &&
|
||||
(selectedPage !== "detail" || section.target === "brand"),
|
||||
)
|
||||
.flatMap((section) =>
|
||||
(section.previewTargets ?? []).map((target) => ({
|
||||
...target,
|
||||
page: section.page,
|
||||
source: previewTargetSource(section, target.key),
|
||||
...(section.key.startsWith("trust:") ? { trustType: section.key.slice(6) } : {}),
|
||||
})),
|
||||
)
|
||||
.concat(
|
||||
selectedPage === "inquiry" && inquiryRuntime
|
||||
? inquiryRuntime.fields.map((field) => ({
|
||||
key: `inquiry-field:${field.key}`,
|
||||
label: field.label,
|
||||
page: "inquiry",
|
||||
source: "inquiry" as const,
|
||||
}))
|
||||
: [],
|
||||
),
|
||||
[templateContent, selectedPage, recordSections, inquiryRuntime],
|
||||
);
|
||||
const activeTarget = selection?.targetKey;
|
||||
const selectedTarget = visibleTargets.find((target) => target.key === activeTarget);
|
||||
const selectedSection = [...(templateContent?.admin.sections ?? []), ...recordSections].find(
|
||||
(section) =>
|
||||
section.page === selectedPage &&
|
||||
section.previewTargets?.some((target) => target.key === selectedTarget?.key),
|
||||
);
|
||||
const selectedRecordSource =
|
||||
selectedTarget?.source === "offering" || selectedTarget?.source === "trust"
|
||||
? selectedTarget.source
|
||||
: undefined;
|
||||
const { offeringsQuery, trustQuery, selectedRecord } = usePresentationRecordQueries(
|
||||
selectedRecordSource,
|
||||
selection?.recordId,
|
||||
);
|
||||
const editableSections = filterSectionsForPreviewTarget(
|
||||
visibleSections.filter((section) =>
|
||||
section.fields.some((field) => field.binding.startsWith("brand.")),
|
||||
),
|
||||
selectedTarget?.key,
|
||||
);
|
||||
const recordSection = useMemo(
|
||||
() =>
|
||||
selectedSection && selection?.targetKey
|
||||
? {
|
||||
...selectedSection,
|
||||
fields: selectedSection.fields.filter(
|
||||
(field) => field.previewTarget === selection.targetKey,
|
||||
),
|
||||
}
|
||||
: undefined,
|
||||
[selectedSection, selection?.targetKey],
|
||||
);
|
||||
const handleTargetSelected = useCallback(
|
||||
(next?: PreviewSelection) => {
|
||||
const select = () =>
|
||||
setSelection(
|
||||
next
|
||||
? resolvePreviewSelection(
|
||||
next.targetKey,
|
||||
next.recordId,
|
||||
visibleTargets,
|
||||
selectedPage ?? "home",
|
||||
)
|
||||
: undefined,
|
||||
);
|
||||
if (recordDraft || inquiryDraft)
|
||||
guardDraft(() => {
|
||||
setInquiryDraft(undefined);
|
||||
setRecordDraft(undefined);
|
||||
select();
|
||||
});
|
||||
else select();
|
||||
},
|
||||
[visibleTargets, selectedPage, recordDraft, inquiryDraft, guardDraft],
|
||||
);
|
||||
const relatedTargets = [
|
||||
...(templateContent?.admin.sections ?? [])
|
||||
.filter((section) => section.page === selectedPage && section.target !== "brand")
|
||||
.map((section) => section.target),
|
||||
...((templateContent?.trustContentTypes ?? []).some((item) =>
|
||||
item.pages?.includes(selectedPage ?? ""),
|
||||
)
|
||||
? ["trust"]
|
||||
: []),
|
||||
];
|
||||
const pageLinks = [...new Set(relatedTargets)].flatMap((target) =>
|
||||
target === "trust"
|
||||
? (templateContent?.trustContentTypes ?? [])
|
||||
.filter((item) => item.pages?.includes(selectedPage ?? ""))
|
||||
.map((item) => ({
|
||||
target: `trust:${item.type}`,
|
||||
label: `编辑${item.label}`,
|
||||
}))
|
||||
: [
|
||||
{
|
||||
target,
|
||||
label: (
|
||||
{ offering: "管理此页展示的业务内容", inquiry: "管理此页的咨询表单" } as Record<
|
||||
string,
|
||||
string
|
||||
>
|
||||
)[target],
|
||||
},
|
||||
],
|
||||
);
|
||||
const relevantPageLinks = selectedSection
|
||||
? pageLinks.filter((item) => {
|
||||
if (item.target.startsWith("trust:")) return selectedSection.target === "trust";
|
||||
return item.target === selectedSection.target;
|
||||
})
|
||||
: pageLinks;
|
||||
const formState = useBrandPresentationForm({ brand, config, sections });
|
||||
const { form, initialValues } = formState;
|
||||
const save = useBrandSaveMutation({
|
||||
...formState,
|
||||
brand,
|
||||
config,
|
||||
sections,
|
||||
queryClient,
|
||||
onSaved: () => setBrandDirty(false),
|
||||
});
|
||||
|
||||
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,
|
||||
);
|
||||
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,
|
||||
),
|
||||
);
|
||||
setActivePage(resolvedPage);
|
||||
setHasInitializedSelection(true);
|
||||
}, [hasInitializedSelection, initialSelection, pageOptions, selectedPage, visibleTargets]);
|
||||
useEffect(() => {
|
||||
if (!initialSelection) setSelection(undefined);
|
||||
}, [initialSelection, selectedPage, templateContent?.displayName]);
|
||||
useEffect(() => {
|
||||
if (!selection?.recordId) return;
|
||||
const records =
|
||||
selectedTarget?.source === "trust"
|
||||
? previewWorkspace?.trustItems
|
||||
: previewWorkspace?.offerings;
|
||||
if (records && !records.some((item) => item.id === selection.recordId)) setSelection(undefined);
|
||||
}, [
|
||||
previewWorkspace?.offerings,
|
||||
previewWorkspace?.trustItems,
|
||||
selectedTarget?.source,
|
||||
selection,
|
||||
]);
|
||||
useEffect(
|
||||
() => setRecordDraft(undefined),
|
||||
[selection?.targetKey, selection?.recordId, selectedPage],
|
||||
);
|
||||
const { previewBrand, handleValuesChange, resetPreview } = useBrandPreviewDraft({
|
||||
brand,
|
||||
config,
|
||||
sections,
|
||||
form,
|
||||
onDirty: () => setBrandDirty(true),
|
||||
});
|
||||
const recordPreview = useRecordPreview({ recordDraft, selectedRecord, recordSection });
|
||||
useEffect(() => resetPreview(), [config, initialValues, resetPreview]);
|
||||
const draftWorkspace = useDraftWorkspace({
|
||||
previewWorkspace,
|
||||
previewBrand,
|
||||
inquiryRuntime,
|
||||
inquiryDraft,
|
||||
recordDraft,
|
||||
selectedRecord,
|
||||
recordSection,
|
||||
recordPreview,
|
||||
templateContent,
|
||||
});
|
||||
const selectedDetailOfferingId =
|
||||
detailOfferingId && draftWorkspace?.offerings.some((item) => item.id === detailOfferingId)
|
||||
? detailOfferingId
|
||||
: draftWorkspace?.offerings[0]?.id;
|
||||
|
||||
const selectPage = useCallback(
|
||||
(page: string) => {
|
||||
guardDraft(() => {
|
||||
setBrandDirty(false);
|
||||
resetPreview();
|
||||
setRecordDraft(undefined);
|
||||
setInquiryDraft(undefined);
|
||||
setActivePage(page);
|
||||
});
|
||||
},
|
||||
[guardDraft, resetPreview],
|
||||
);
|
||||
const selectDetailOffering = useCallback((id: string) => {
|
||||
setDetailOfferingId(id);
|
||||
setSelection(undefined);
|
||||
}, []);
|
||||
const selectPreviewTarget = useCallback(
|
||||
(target: PreviewTarget) => {
|
||||
const recordId =
|
||||
target.source === "offering"
|
||||
? selectedPage === "detail"
|
||||
? selectedDetailOfferingId
|
||||
: draftWorkspace?.offerings[0]?.id
|
||||
: target.source === "trust"
|
||||
? previewTrustRecordId(draftWorkspace?.trustItems ?? [], target.trustType)
|
||||
: undefined;
|
||||
handleTargetSelected({
|
||||
targetKey: target.key,
|
||||
...(recordId ? { recordId } : {}),
|
||||
});
|
||||
},
|
||||
[handleTargetSelected, selectedPage, selectedDetailOfferingId, draftWorkspace],
|
||||
);
|
||||
|
||||
return {
|
||||
pageOptions,
|
||||
selectedPage,
|
||||
visibleTargets,
|
||||
selectedTarget,
|
||||
selectedSection,
|
||||
selectedRecordSource,
|
||||
selectedRecord,
|
||||
recordSection,
|
||||
editableSections,
|
||||
relevantPageLinks,
|
||||
inquiryRuntime,
|
||||
draftWorkspace,
|
||||
previewBrand,
|
||||
selectedDetailOfferingId,
|
||||
form,
|
||||
initialValues,
|
||||
save,
|
||||
offeringsQuery,
|
||||
trustQuery,
|
||||
recordDraft,
|
||||
inquiryDraft,
|
||||
brandDirty,
|
||||
selection,
|
||||
activeTarget,
|
||||
guardDraft,
|
||||
selectPage,
|
||||
selectDetailOffering,
|
||||
selectPreviewTarget,
|
||||
handleTargetSelected,
|
||||
setRecordDraft,
|
||||
setInquiryDraft,
|
||||
handleValuesChange,
|
||||
navigate,
|
||||
};
|
||||
}
|
||||
@@ -89,7 +89,6 @@ export function useBrandPresentationForm({
|
||||
return values;
|
||||
}, [brand, config, sections]);
|
||||
|
||||
useEffect(() => form.setFieldsValue(initialValues), [form, initialValues]);
|
||||
return { form, initialValues };
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,21 @@ const element = (tag) =>
|
||||
|
||||
export const View = element("div");
|
||||
export const Text = element("span");
|
||||
export const Button = element("button");
|
||||
export const Button = React.forwardRef(
|
||||
({ children, className, style, onClick, loading, ...props }, ref) =>
|
||||
React.createElement(
|
||||
"button",
|
||||
{
|
||||
...props,
|
||||
ref,
|
||||
className,
|
||||
style,
|
||||
onClick,
|
||||
...(loading ? { "aria-busy": "true" } : {}),
|
||||
},
|
||||
children,
|
||||
),
|
||||
);
|
||||
export const Input = React.forwardRef(({ onInput, ...props }, ref) =>
|
||||
React.createElement("input", {
|
||||
...props,
|
||||
@@ -101,16 +115,18 @@ export const Label = element("label");
|
||||
export const Image = React.forwardRef(({ mode, src, style, ...props }, ref) => {
|
||||
const key = React.useContext(TemplateAssetContext);
|
||||
const assets = React.useContext(TemplatePreviewAssetsContext);
|
||||
const normalizedSrc = typeof src === "string" ? src.trim() : "";
|
||||
if (!normalizedSrc) return null;
|
||||
return React.createElement("img", {
|
||||
...props,
|
||||
ref,
|
||||
src:
|
||||
assets && typeof src === "string" && src.startsWith("/assets/")
|
||||
assets && normalizedSrc.startsWith("/assets/")
|
||||
? // 导入包资源以 /assets 开头;本地多模板预览的 renderer 可能额外携带包 key 前缀。
|
||||
(assets[src]?.dataUrl ??
|
||||
assets[src.replace(`/assets/${key}/`, "/assets/")]?.dataUrl ??
|
||||
src)
|
||||
: resolveImageSource(src, key),
|
||||
(assets[normalizedSrc]?.dataUrl ??
|
||||
assets[normalizedSrc.replace(`/assets/${key}/`, "/assets/")]?.dataUrl ??
|
||||
normalizedSrc)
|
||||
: resolveImageSource(normalizedSrc, key),
|
||||
style: { objectFit: mode === "aspectFit" ? "contain" : "cover", ...style },
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "ClientErrorThrottleWindow" (
|
||||
"subject" TEXT NOT NULL,
|
||||
"windowStart" TIMESTAMP(3) NOT NULL,
|
||||
"count" INTEGER NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "ClientErrorThrottleWindow_pkey" PRIMARY KEY ("subject")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ClientErrorDedupe" (
|
||||
"id" TEXT NOT NULL,
|
||||
"subject" TEXT NOT NULL,
|
||||
"errorId" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "ClientErrorDedupe_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ClientErrorThrottleWindow_windowStart_idx" ON "ClientErrorThrottleWindow"("windowStart");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "ClientErrorDedupe_subject_errorId_key" ON "ClientErrorDedupe"("subject", "errorId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ClientErrorDedupe_createdAt_idx" ON "ClientErrorDedupe"("createdAt");
|
||||
@@ -468,6 +468,25 @@ model AdminUser {
|
||||
templateAuditLogs TemplatePackageAuditLog[] @relation("TemplatePackageAuditActor")
|
||||
}
|
||||
|
||||
model ClientErrorThrottleWindow {
|
||||
subject String @id
|
||||
windowStart DateTime
|
||||
count Int
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([windowStart])
|
||||
}
|
||||
|
||||
model ClientErrorDedupe {
|
||||
id String @id @default(uuid())
|
||||
subject String
|
||||
errorId String
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@unique([subject, errorId])
|
||||
@@index([createdAt])
|
||||
}
|
||||
|
||||
model TemplatePackage {
|
||||
id String @id @default(uuid())
|
||||
packageKey String @unique
|
||||
|
||||
@@ -4,16 +4,36 @@ import { PrismaService } from "./prisma.service.js";
|
||||
import { readAdminToken } from "./admin-access.identity.js";
|
||||
import { readIdentity } from "./auth.js";
|
||||
|
||||
type TokenAccess = {
|
||||
subject: string;
|
||||
brandId: string;
|
||||
mustChangePassword: boolean;
|
||||
tokenVersion: number;
|
||||
platformTemplateRole: string;
|
||||
};
|
||||
|
||||
type BrandAccess = { subject: string; brandId: string; role: string };
|
||||
|
||||
@Injectable()
|
||||
export class AdminAccessService {
|
||||
/**
|
||||
* 同一 HTTP 请求内 Guard 和 Controller 都会调用访问校验。
|
||||
* 用 WeakMap 按请求缓存结果,既避免重复查询,也不会把权限状态跨请求缓存。
|
||||
*/
|
||||
private readonly tokenAccess = new WeakMap<FastifyRequest, Promise<TokenAccess>>();
|
||||
private readonly brandAccess = new WeakMap<FastifyRequest, Promise<BrandAccess>>();
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async requireToken(request: FastifyRequest): Promise<{
|
||||
subject: string;
|
||||
brandId: string;
|
||||
mustChangePassword: boolean;
|
||||
tokenVersion: number;
|
||||
}> {
|
||||
requireToken(request: FastifyRequest): Promise<TokenAccess> {
|
||||
const cached = this.tokenAccess.get(request);
|
||||
if (cached) return cached;
|
||||
const pending = this.resolveToken(request);
|
||||
this.tokenAccess.set(request, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
private async resolveToken(request: FastifyRequest): Promise<TokenAccess> {
|
||||
const token = readAdminToken(request);
|
||||
if (!token) throw new UnauthorizedException("缺少管理员登录态");
|
||||
let identity;
|
||||
@@ -25,7 +45,12 @@ export class AdminAccessService {
|
||||
if (identity.role !== "admin") throw new ForbiddenException("无管理员权限");
|
||||
const user = await this.prisma.adminUser.findUnique({
|
||||
where: { id: identity.subject },
|
||||
select: { isEnabled: true, mustChangePassword: true, tokenVersion: true },
|
||||
select: {
|
||||
isEnabled: true,
|
||||
mustChangePassword: true,
|
||||
tokenVersion: true,
|
||||
platformTemplateRole: true,
|
||||
},
|
||||
});
|
||||
if (!user || identity.tokenVersion !== user.tokenVersion)
|
||||
throw new UnauthorizedException("管理员登录态已失效,请重新登录");
|
||||
@@ -35,12 +60,19 @@ export class AdminAccessService {
|
||||
brandId: identity.brandId,
|
||||
mustChangePassword: user.mustChangePassword,
|
||||
tokenVersion: user.tokenVersion,
|
||||
platformTemplateRole: user.platformTemplateRole,
|
||||
};
|
||||
}
|
||||
|
||||
async requireBrand(
|
||||
request: FastifyRequest,
|
||||
): Promise<{ subject: string; brandId: string; role: string }> {
|
||||
requireBrand(request: FastifyRequest): Promise<BrandAccess> {
|
||||
const cached = this.brandAccess.get(request);
|
||||
if (cached) return cached;
|
||||
const pending = this.resolveBrand(request);
|
||||
this.brandAccess.set(request, pending);
|
||||
return pending;
|
||||
}
|
||||
|
||||
private async resolveBrand(request: FastifyRequest): Promise<BrandAccess> {
|
||||
const access = await this.requireToken(request);
|
||||
if (access.mustChangePassword)
|
||||
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
||||
@@ -63,11 +95,7 @@ export class AdminAccessService {
|
||||
const access = await this.requireToken(request);
|
||||
if (access.mustChangePassword)
|
||||
throw new ForbiddenException("请先完成初始密码修改后再访问管理后台");
|
||||
const user = await this.prisma.adminUser.findUniqueOrThrow({
|
||||
where: { id: access.subject },
|
||||
select: { platformTemplateRole: true },
|
||||
});
|
||||
if (user.platformTemplateRole !== "template_admin")
|
||||
if (access.platformTemplateRole !== "template_admin")
|
||||
throw new ForbiddenException("当前账号没有模板管理权限");
|
||||
return { subject: access.subject };
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { UnauthorizedException } from "@nestjs/common";
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
import { isPlaceholderSecret } from "./runtime-config.js";
|
||||
|
||||
type Identity = {
|
||||
subject: string;
|
||||
@@ -9,9 +10,20 @@ type Identity = {
|
||||
exp: number;
|
||||
};
|
||||
|
||||
let warnedAboutPlaceholderSecret = false;
|
||||
|
||||
function secret(): string {
|
||||
const value = process.env.SESSION_SECRET;
|
||||
if (!value || value.length < 32) throw new UnauthorizedException("服务端会话密钥未正确配置");
|
||||
if (isPlaceholderSecret(value)) {
|
||||
// 生产环境已在启动时 fail fast;这里保留二次防线,避免绕过 createApp 的调用方签发弱 token。
|
||||
if (process.env.NODE_ENV === "production")
|
||||
throw new UnauthorizedException("服务端会话密钥未正确配置");
|
||||
if (!warnedAboutPlaceholderSecret) {
|
||||
warnedAboutPlaceholderSecret = true;
|
||||
console.warn("[api] SESSION_SECRET 仍是示例占位符,仅可用于本地开发");
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,8 +6,10 @@ import multipart from "@fastify/multipart";
|
||||
import fastifyStatic from "@fastify/static";
|
||||
import path from "node:path";
|
||||
import { AppModule, configureApp } from "./app.module.js";
|
||||
import { assertProductionSecret } from "./runtime-config.js";
|
||||
|
||||
export async function createApp(): Promise<NestFastifyApplication> {
|
||||
assertProductionSecret(process.env.SESSION_SECRET);
|
||||
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter());
|
||||
app
|
||||
.getHttpAdapter()
|
||||
|
||||
@@ -1,22 +1,12 @@
|
||||
import { AdminBrand } from "../../admin-auth.decorators.js";
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
} from "@nestjs/common";
|
||||
import { Body, Controller, Get, Param, Post, Query, Req } from "@nestjs/common";
|
||||
import { Transform } from "class-transformer";
|
||||
import type { TransformFnParams } from "class-transformer";
|
||||
import { BookingStatus } from "@prisma/client";
|
||||
import { IsBoolean, IsEnum, IsOptional, IsString } from "class-validator";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { AdminAccessService } from "../../admin-access.service.js";
|
||||
import { BookingService } from "../../booking.service.js";
|
||||
import { readIdentity } from "../../auth.js";
|
||||
import { UpdateBookingStatusDto, UpdateBookingTagsDto, CreateTagDto } from "../../admin.dto.js";
|
||||
|
||||
class AdminBookingQueryDto {
|
||||
@@ -35,67 +25,67 @@ class AdminBookingQueryDto {
|
||||
@AdminBrand()
|
||||
@Controller("admin/bookings")
|
||||
export class AdminBookingController {
|
||||
constructor(private readonly bookings: BookingService) {}
|
||||
constructor(
|
||||
private readonly access: AdminAccessService,
|
||||
private readonly bookings: BookingService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
list(@Req() request: FastifyRequest, @Query() query: AdminBookingQueryDto): Promise<unknown> {
|
||||
const brandId = this.requireAdmin(request);
|
||||
async list(
|
||||
@Req() request: FastifyRequest,
|
||||
@Query() query: AdminBookingQueryDto,
|
||||
): Promise<unknown> {
|
||||
const { brandId } = await this.access.requireBrand(request);
|
||||
return this.bookings.listForAdmin(brandId, query);
|
||||
}
|
||||
|
||||
@Get("unread-count")
|
||||
unreadCount(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
return this.bookings.unreadCountForAdmin(this.requireAdmin(request));
|
||||
async unreadCount(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const { brandId } = await this.access.requireBrand(request);
|
||||
return this.bookings.unreadCountForAdmin(brandId);
|
||||
}
|
||||
|
||||
@Get(":id")
|
||||
detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||
return this.bookings.getForAdmin(this.requireAdmin(request), id);
|
||||
async detail(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||
const { brandId } = await this.access.requireBrand(request);
|
||||
return this.bookings.getForAdmin(brandId, id);
|
||||
}
|
||||
|
||||
@Post(":id/status")
|
||||
update(
|
||||
async update(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("id") id: string,
|
||||
@Body() body: UpdateBookingStatusDto,
|
||||
): Promise<unknown> {
|
||||
return this.bookings.updateStatus(this.requireAdmin(request), id, body.status, body.adminNote);
|
||||
const { brandId } = await this.access.requireBrand(request);
|
||||
return this.bookings.updateStatus(brandId, id, body.status, body.adminNote);
|
||||
}
|
||||
|
||||
@Post(":id/read")
|
||||
markRead(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||
return this.bookings.markRead(this.requireAdmin(request), id);
|
||||
async markRead(@Req() request: FastifyRequest, @Param("id") id: string): Promise<unknown> {
|
||||
const { brandId } = await this.access.requireBrand(request);
|
||||
return this.bookings.markRead(brandId, id);
|
||||
}
|
||||
|
||||
@Post(":id/tags")
|
||||
updateTags(
|
||||
async updateTags(
|
||||
@Req() request: FastifyRequest,
|
||||
@Param("id") id: string,
|
||||
@Body() body: UpdateBookingTagsDto,
|
||||
): Promise<unknown> {
|
||||
return this.bookings.updateTags(this.requireAdmin(request), id, body.tagIds);
|
||||
const { brandId } = await this.access.requireBrand(request);
|
||||
return this.bookings.updateTags(brandId, id, body.tagIds);
|
||||
}
|
||||
|
||||
@Get("tags")
|
||||
listTags(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
return this.bookings.listTags(this.requireAdmin(request));
|
||||
async listTags(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const { brandId } = await this.access.requireBrand(request);
|
||||
return this.bookings.listTags(brandId);
|
||||
}
|
||||
|
||||
@Post("tags")
|
||||
createTag(@Req() request: FastifyRequest, @Body() body: CreateTagDto): Promise<unknown> {
|
||||
return this.bookings.createTag(this.requireAdmin(request), body.name);
|
||||
}
|
||||
|
||||
private requireAdmin(request: FastifyRequest): string {
|
||||
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.brandId;
|
||||
async createTag(@Req() request: FastifyRequest, @Body() body: CreateTagDto): Promise<unknown> {
|
||||
const { brandId } = await this.access.requireBrand(request);
|
||||
return this.bookings.createTag(brandId, body.name);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { HttpException, Injectable } from "@nestjs/common";
|
||||
import { Inject, Injectable } from "@nestjs/common";
|
||||
import {
|
||||
CLIENT_ERROR_THROTTLE_STORE,
|
||||
type ClientErrorThrottleStore,
|
||||
} from "./client-error-throttle.store.js";
|
||||
|
||||
const RATE_WINDOW_MS = 60_000;
|
||||
const RATE_LIMIT = 10;
|
||||
const DEDUPE_TTL_MS = 10 * 60_000;
|
||||
const DEDUPE_CAPACITY = 500;
|
||||
const LOG_STACK_LIMIT = 4000;
|
||||
|
||||
export interface ClientErrorReport {
|
||||
@@ -22,27 +22,16 @@ export interface ClientErrorReceipt {
|
||||
duplicate: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台渲染异常去重与限流。
|
||||
* 当前生产为单实例 PM2,因此使用进程内窗口;扩成多实例前需要换成共享存储。
|
||||
*/
|
||||
@Injectable()
|
||||
export class AdminClientErrorService {
|
||||
private readonly recentErrorIds = new Map<string, number>();
|
||||
private readonly windows = new Map<string, number[]>();
|
||||
constructor(
|
||||
@Inject(CLIENT_ERROR_THROTTLE_STORE)
|
||||
private readonly throttle: ClientErrorThrottleStore,
|
||||
) {}
|
||||
|
||||
record(report: ClientErrorReport): ClientErrorReceipt {
|
||||
const now = Date.now();
|
||||
this.prune(now);
|
||||
|
||||
const dedupeKey = `${report.subject}:${report.errorId}`;
|
||||
if (this.recentErrorIds.has(dedupeKey)) {
|
||||
return { received: true, duplicate: true };
|
||||
}
|
||||
|
||||
this.assertWithinRate(report.subject, now);
|
||||
this.recentErrorIds.set(dedupeKey, now);
|
||||
this.trimDedupe();
|
||||
async record(report: ClientErrorReport): Promise<ClientErrorReceipt> {
|
||||
const result = await this.throttle.record(report);
|
||||
if (result.duplicate) return { received: true, duplicate: true };
|
||||
|
||||
console.error("admin client error", {
|
||||
errorId: report.errorId,
|
||||
@@ -57,35 +46,4 @@ export class AdminClientErrorService {
|
||||
|
||||
return { received: true, duplicate: false };
|
||||
}
|
||||
|
||||
private assertWithinRate(subject: string, now: number): void {
|
||||
const recent = (this.windows.get(subject) ?? []).filter(
|
||||
(timestamp) => now - timestamp < RATE_WINDOW_MS,
|
||||
);
|
||||
if (recent.length >= RATE_LIMIT) {
|
||||
this.windows.set(subject, recent);
|
||||
throw new HttpException("客户端错误上报过于频繁,请稍后再试", 429);
|
||||
}
|
||||
recent.push(now);
|
||||
this.windows.set(subject, recent);
|
||||
}
|
||||
|
||||
private prune(now: number): void {
|
||||
for (const [key, timestamp] of this.recentErrorIds) {
|
||||
if (now - timestamp >= DEDUPE_TTL_MS) this.recentErrorIds.delete(key);
|
||||
}
|
||||
for (const [subject, timestamps] of this.windows) {
|
||||
const recent = timestamps.filter((timestamp) => now - timestamp < RATE_WINDOW_MS);
|
||||
if (recent.length === 0) this.windows.delete(subject);
|
||||
else this.windows.set(subject, recent);
|
||||
}
|
||||
}
|
||||
|
||||
private trimDedupe(): void {
|
||||
while (this.recentErrorIds.size > DEDUPE_CAPACITY) {
|
||||
const oldest = this.recentErrorIds.keys().next();
|
||||
if (oldest.done) return;
|
||||
this.recentErrorIds.delete(oldest.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
UpdateBrandPresentationDto,
|
||||
UpdateTrustContentDto,
|
||||
} from "../../admin.dto.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { TrustContentService } from "../../template/trust-content.service.js";
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
|
||||
|
||||
@@ -15,7 +15,7 @@ import { AdminBrandConfigService } from "./admin-brand-config.service.js";
|
||||
@Controller("admin/config")
|
||||
export class AdminConfigController {
|
||||
constructor(
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
private readonly trustContent: TrustContentService,
|
||||
private readonly brandConfig: AdminBrandConfigService,
|
||||
) {}
|
||||
@Get("brand")
|
||||
@@ -42,7 +42,7 @@ export class AdminConfigController {
|
||||
@Get("trust-content")
|
||||
listTrustContent(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
return this.templateWorkspace.listTrustContent(identity.brandId);
|
||||
return this.trustContent.listTrustContent(identity.brandId);
|
||||
}
|
||||
@Post("trust-content")
|
||||
createTrustContent(
|
||||
@@ -50,7 +50,7 @@ export class AdminConfigController {
|
||||
@Body() body: CreateTrustContentDto,
|
||||
): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
return this.templateWorkspace.createTrustContent(identity.brandId, body);
|
||||
return this.trustContent.createTrustContent(identity.brandId, body);
|
||||
}
|
||||
@Patch("trust-content/:id")
|
||||
updateTrustContent(
|
||||
@@ -59,7 +59,7 @@ export class AdminConfigController {
|
||||
@Body() body: UpdateTrustContentDto,
|
||||
): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
return this.templateWorkspace.updateTrustContent(identity.brandId, id, body);
|
||||
return this.trustContent.updateTrustContent(identity.brandId, id, body);
|
||||
}
|
||||
@Delete("trust-content/:id")
|
||||
async deleteTrustContent(
|
||||
@@ -67,6 +67,6 @@ export class AdminConfigController {
|
||||
@Param("id") id: string,
|
||||
): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
return this.templateWorkspace.deleteTrustContent(identity.brandId, id);
|
||||
return this.trustContent.deleteTrustContent(identity.brandId, id);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import { InfrastructureModule } from "../infrastructure.module.js";
|
||||
import { AdminBookingController } from "./admin-booking.controller.js";
|
||||
import { AdminClientErrorController } from "./admin-client-error.controller.js";
|
||||
import { AdminClientErrorService } from "./admin-client-error.service.js";
|
||||
import { createClientErrorThrottleStore } from "./client-error-throttle.factory.js";
|
||||
import { CLIENT_ERROR_THROTTLE_STORE } from "./client-error-throttle.store.js";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { AdminBrandConfigService } from "./admin-brand-config.service.js";
|
||||
import { AdminConfigController } from "./admin-config.controller.js";
|
||||
import { AdminLocalUploadController } from "./admin-local-upload.controller.js";
|
||||
@@ -47,6 +50,11 @@ import { AdminTemplatePreviewAssetsService } from "./admin-template-preview-asse
|
||||
AdminTemplatePreviewService,
|
||||
AdminTemplatePreviewAssetsService,
|
||||
TemplateOperationMetricsService,
|
||||
{
|
||||
provide: CLIENT_ERROR_THROTTLE_STORE,
|
||||
useFactory: (prisma: PrismaService) => createClientErrorThrottleStore(prisma),
|
||||
inject: [PrismaService],
|
||||
},
|
||||
AdminClientErrorService,
|
||||
],
|
||||
})
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { PrismaService } from "../../prisma.service.js";
|
||||
import { PostgresClientErrorThrottleStore } from "./client-error-throttle.postgres.store.js";
|
||||
import {
|
||||
MemoryClientErrorThrottleStore,
|
||||
type ClientErrorThrottleStore,
|
||||
} from "./client-error-throttle.store.js";
|
||||
|
||||
export function createClientErrorThrottleStore(
|
||||
prisma: PrismaService,
|
||||
mode = process.env.CLIENT_ERROR_THROTTLE_STORE ?? "memory",
|
||||
): ClientErrorThrottleStore {
|
||||
switch (mode) {
|
||||
case "memory":
|
||||
return new MemoryClientErrorThrottleStore();
|
||||
case "postgres":
|
||||
return new PostgresClientErrorThrottleStore(prisma);
|
||||
default:
|
||||
throw new Error(`Unsupported CLIENT_ERROR_THROTTLE_STORE: ${mode}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { HttpException } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import type { PrismaService } from "../../prisma.service.js";
|
||||
import {
|
||||
CLIENT_ERROR_DEDUPE_TTL_MS,
|
||||
CLIENT_ERROR_RATE_LIMIT,
|
||||
CLIENT_ERROR_RATE_WINDOW_MS,
|
||||
type ClientErrorThrottleReport,
|
||||
type ClientErrorThrottleResult,
|
||||
type ClientErrorThrottleStore,
|
||||
} from "./client-error-throttle.store.js";
|
||||
|
||||
/**
|
||||
* 多实例部署使用的共享存储实现。
|
||||
* 去重与限流在同一事务中执行:限流拒绝时不会留下已去重标记。
|
||||
*/
|
||||
export class PostgresClientErrorThrottleStore implements ClientErrorThrottleStore {
|
||||
private lastCleanupAt = 0;
|
||||
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async record(
|
||||
report: ClientErrorThrottleReport,
|
||||
now = Date.now(),
|
||||
): Promise<ClientErrorThrottleResult> {
|
||||
const cutoff = new Date(now - CLIENT_ERROR_DEDUPE_TTL_MS);
|
||||
const windowStart = new Date(
|
||||
Math.floor(now / CLIENT_ERROR_RATE_WINDOW_MS) * CLIENT_ERROR_RATE_WINDOW_MS,
|
||||
);
|
||||
const recordedAt = new Date(now);
|
||||
let duplicate = false;
|
||||
|
||||
await this.prisma.$transaction(async (transaction) => {
|
||||
const inserted = await transaction.$queryRaw<Array<{ id: string }>>(Prisma.sql`
|
||||
INSERT INTO "ClientErrorDedupe" ("id", "subject", "errorId", "createdAt")
|
||||
VALUES (${randomUUID()}, ${report.subject}, ${report.errorId}, ${recordedAt})
|
||||
ON CONFLICT ("subject", "errorId") DO UPDATE SET
|
||||
"createdAt" = EXCLUDED."createdAt"
|
||||
WHERE "ClientErrorDedupe"."createdAt" < ${cutoff}
|
||||
RETURNING "id"
|
||||
`);
|
||||
if (!inserted.length) {
|
||||
duplicate = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const rows = await transaction.$queryRaw<Array<{ count: number }>>(Prisma.sql`
|
||||
INSERT INTO "ClientErrorThrottleWindow" ("subject", "windowStart", "count", "updatedAt")
|
||||
VALUES (${report.subject}, ${windowStart}, 1, ${recordedAt})
|
||||
ON CONFLICT ("subject") DO UPDATE SET
|
||||
"count" = CASE
|
||||
WHEN EXCLUDED."windowStart" > "ClientErrorThrottleWindow"."windowStart"
|
||||
THEN 1
|
||||
WHEN EXCLUDED."windowStart" = "ClientErrorThrottleWindow"."windowStart"
|
||||
THEN LEAST("ClientErrorThrottleWindow"."count" + 1, ${CLIENT_ERROR_RATE_LIMIT + 1})
|
||||
ELSE "ClientErrorThrottleWindow"."count"
|
||||
END,
|
||||
"windowStart" = GREATEST(
|
||||
"ClientErrorThrottleWindow"."windowStart",
|
||||
EXCLUDED."windowStart"
|
||||
),
|
||||
"updatedAt" = EXCLUDED."updatedAt"
|
||||
RETURNING "count"
|
||||
`);
|
||||
if (Number(rows[0]?.count ?? 1) > CLIENT_ERROR_RATE_LIMIT) {
|
||||
throw new HttpException("客户端错误上报过于频繁,请稍后再试", 429);
|
||||
}
|
||||
});
|
||||
|
||||
await this.cleanupIfNeeded(cutoff, windowStart, now);
|
||||
return { duplicate };
|
||||
}
|
||||
|
||||
private async cleanupIfNeeded(cutoff: Date, windowStart: Date, now: number): Promise<void> {
|
||||
if (now - this.lastCleanupAt < CLIENT_ERROR_RATE_WINDOW_MS) return;
|
||||
this.lastCleanupAt = now;
|
||||
try {
|
||||
await Promise.all([
|
||||
this.prisma.clientErrorDedupe.deleteMany({ where: { createdAt: { lt: cutoff } } }),
|
||||
this.prisma.clientErrorThrottleWindow.deleteMany({
|
||||
where: {
|
||||
windowStart: {
|
||||
lt: new Date(windowStart.getTime() - CLIENT_ERROR_RATE_WINDOW_MS),
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
} catch (error) {
|
||||
// 清理失败不能影响诊断上报本身,下一分钟会再次尝试。
|
||||
console.warn("[api] client error throttle cleanup failed", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { HttpException } from "@nestjs/common";
|
||||
|
||||
export const CLIENT_ERROR_RATE_WINDOW_MS = 60_000;
|
||||
export const CLIENT_ERROR_RATE_LIMIT = 10;
|
||||
export const CLIENT_ERROR_DEDUPE_TTL_MS = 10 * 60_000;
|
||||
export const CLIENT_ERROR_DEDUPE_CAPACITY = 500;
|
||||
export const CLIENT_ERROR_THROTTLE_STORE = Symbol("CLIENT_ERROR_THROTTLE_STORE");
|
||||
|
||||
export interface ClientErrorThrottleReport {
|
||||
subject: string;
|
||||
errorId: string;
|
||||
}
|
||||
|
||||
export interface ClientErrorThrottleResult {
|
||||
duplicate: boolean;
|
||||
}
|
||||
|
||||
export interface ClientErrorThrottleStore {
|
||||
record(report: ClientErrorThrottleReport, now?: number): Promise<ClientErrorThrottleResult>;
|
||||
}
|
||||
|
||||
/** 单实例部署使用的进程内实现;多实例必须切换为共享存储。 */
|
||||
export class MemoryClientErrorThrottleStore implements ClientErrorThrottleStore {
|
||||
private readonly recentErrorIds = new Map<string, number>();
|
||||
private readonly windows = new Map<string, number[]>();
|
||||
|
||||
record(report: ClientErrorThrottleReport, now = Date.now()): Promise<ClientErrorThrottleResult> {
|
||||
this.prune(now);
|
||||
|
||||
const dedupeKey = `${report.subject}:${report.errorId}`;
|
||||
if (this.recentErrorIds.has(dedupeKey)) return Promise.resolve({ duplicate: true });
|
||||
|
||||
this.assertWithinRate(report.subject, now);
|
||||
this.recentErrorIds.set(dedupeKey, now);
|
||||
this.trimDedupe();
|
||||
return Promise.resolve({ duplicate: false });
|
||||
}
|
||||
|
||||
private assertWithinRate(subject: string, now: number): void {
|
||||
const recent = (this.windows.get(subject) ?? []).filter(
|
||||
(timestamp) => now - timestamp < CLIENT_ERROR_RATE_WINDOW_MS,
|
||||
);
|
||||
if (recent.length >= CLIENT_ERROR_RATE_LIMIT) {
|
||||
this.windows.set(subject, recent);
|
||||
throw new HttpException("客户端错误上报过于频繁,请稍后再试", 429);
|
||||
}
|
||||
recent.push(now);
|
||||
this.windows.set(subject, recent);
|
||||
}
|
||||
|
||||
private prune(now: number): void {
|
||||
for (const [key, timestamp] of this.recentErrorIds) {
|
||||
if (now - timestamp >= CLIENT_ERROR_DEDUPE_TTL_MS) this.recentErrorIds.delete(key);
|
||||
}
|
||||
for (const [subject, timestamps] of this.windows) {
|
||||
const recent = timestamps.filter(
|
||||
(timestamp) => now - timestamp < CLIENT_ERROR_RATE_WINDOW_MS,
|
||||
);
|
||||
if (recent.length === 0) this.windows.delete(subject);
|
||||
else this.windows.set(subject, recent);
|
||||
}
|
||||
}
|
||||
|
||||
private trimDedupe(): void {
|
||||
while (this.recentErrorIds.size > CLIENT_ERROR_DEDUPE_CAPACITY) {
|
||||
const oldest = this.recentErrorIds.keys().next();
|
||||
if (oldest.done) return;
|
||||
this.recentErrorIds.delete(oldest.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@ import { AdminMembershipGuard } from "../admin-membership.guard.js";
|
||||
import { BrandReleaseApiService } from "../brand-release-api.service.js";
|
||||
import { BrandReleaseService } from "../brand-release.service.js";
|
||||
import { PrismaService } from "../prisma.service.js";
|
||||
import { TemplateWorkspaceService } from "../template-workspace.service.js";
|
||||
import { PageSchemeService } from "../template/page-scheme.service.js";
|
||||
import { TemplateInstallationService } from "../template/template-installation.service.js";
|
||||
import { TrustContentService } from "../template/trust-content.service.js";
|
||||
import { WechatAuthService } from "../wechat-auth.js";
|
||||
|
||||
@Module({
|
||||
@@ -15,7 +17,9 @@ import { WechatAuthService } from "../wechat-auth.js";
|
||||
AdminMembershipGuard,
|
||||
BrandReleaseService,
|
||||
BrandReleaseApiService,
|
||||
TemplateWorkspaceService,
|
||||
PageSchemeService,
|
||||
TemplateInstallationService,
|
||||
TrustContentService,
|
||||
],
|
||||
exports: [
|
||||
PrismaService,
|
||||
@@ -24,7 +28,9 @@ import { WechatAuthService } from "../wechat-auth.js";
|
||||
AdminMembershipGuard,
|
||||
BrandReleaseService,
|
||||
BrandReleaseApiService,
|
||||
TemplateWorkspaceService,
|
||||
PageSchemeService,
|
||||
TemplateInstallationService,
|
||||
TrustContentService,
|
||||
],
|
||||
})
|
||||
export class InfrastructureModule {}
|
||||
@@ -14,7 +14,8 @@ import type {
|
||||
CreateBrandMemberDto,
|
||||
UpdateBrandMemberDto,
|
||||
} from "../../admin.dto.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { PageSchemeService } from "../../template/page-scheme.service.js";
|
||||
import { TemplateInstallationService } from "../../template/template-installation.service.js";
|
||||
|
||||
type AdminIdentity = { subject: string; brandId: string; tokenVersion?: number };
|
||||
|
||||
@@ -22,11 +23,12 @@ type AdminIdentity = { subject: string; brandId: string; tokenVersion?: number }
|
||||
export class TenantService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
private readonly pageSchemes: PageSchemeService,
|
||||
private readonly templateInstallations: TemplateInstallationService,
|
||||
) {}
|
||||
|
||||
async getCreationOptions() {
|
||||
const catalog = await this.templateWorkspace.getPageSchemeCatalog();
|
||||
const catalog = await this.pageSchemes.getPageSchemeCatalog();
|
||||
// 创建品牌只应从每个页面方案的最新已发布版本开始;旧版本仍可在页面方案页显式切换。
|
||||
return {
|
||||
...catalog,
|
||||
@@ -40,7 +42,7 @@ export class TenantService {
|
||||
const name = body.name.trim();
|
||||
const slug = body.slug.trim();
|
||||
if (!name || !slug) throw new BadRequestException("品牌名称和小程序地址标识不能为空");
|
||||
const packageVersion = await this.templateWorkspace.resolveInstallablePackageVersion(
|
||||
const packageVersion = await this.templateInstallations.resolveInstallablePackageVersion(
|
||||
body.businessType,
|
||||
body.templatePackageVersionId,
|
||||
);
|
||||
|
||||
@@ -2,24 +2,28 @@ import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
||||
import { Body, Controller, Get, Post, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { RollbackTemplateDto, UpgradeTemplateDto } from "../../admin.dto.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { PageSchemeService } from "../../template/page-scheme.service.js";
|
||||
import { TemplateInstallationService } from "../../template/template-installation.service.js";
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
|
||||
@AdminBrand()
|
||||
@Controller("admin/workspace")
|
||||
class AdminTemplateController {
|
||||
constructor(private readonly templateWorkspace: TemplateWorkspaceService) {}
|
||||
constructor(
|
||||
private readonly pageSchemes: PageSchemeService,
|
||||
private readonly templateInstallations: TemplateInstallationService,
|
||||
) {}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Get("template/options")
|
||||
options(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
return this.templateWorkspace.getPageSchemeOptions(requireAdminIdentity(request).brandId);
|
||||
return this.pageSchemes.getPageSchemeOptions(requireAdminIdentity(request).brandId);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@Get("template/preview")
|
||||
preview(@Req() request: FastifyRequest): Promise<unknown> {
|
||||
return this.templateWorkspace.preview(requireAdminIdentity(request).brandId);
|
||||
return this.templateInstallations.preview(requireAdminIdentity(request).brandId);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@@ -30,7 +34,7 @@ class AdminTemplateController {
|
||||
): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||
return this.templateWorkspace.upgrade(identity.brandId, body, identity.subject, requestId);
|
||||
return this.templateInstallations.upgrade(identity.brandId, body, identity.subject, requestId);
|
||||
}
|
||||
|
||||
@AdminRoles(["owner", "admin", "platform-admin"])
|
||||
@@ -41,7 +45,7 @@ class AdminTemplateController {
|
||||
): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||
return this.templateWorkspace.rollback(identity.brandId, identity.subject, body, requestId);
|
||||
return this.templateInstallations.rollback(identity.brandId, identity.subject, body, requestId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,19 +8,19 @@ import {
|
||||
validateCapabilityConfig,
|
||||
} from "@personal-brand/config";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { TemplateInstallationService } from "../../template/template-installation.service.js";
|
||||
import type { UpdateCapabilityInstallationDto } from "../../admin.dto.js";
|
||||
|
||||
@Injectable()
|
||||
export class AdminWorkspaceCapabilitiesService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
private readonly templateInstallations: TemplateInstallationService,
|
||||
) {}
|
||||
|
||||
async list(brandId: string) {
|
||||
const [templateKey, installations] = await Promise.all([
|
||||
this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
||||
this.templateInstallations.getEffectiveTemplateKey(brandId),
|
||||
this.prisma.capabilityInstallation.findMany({ where: { brandId } }),
|
||||
]);
|
||||
const installed = new Map(installations.map((item) => [item.capabilityKey, item]));
|
||||
@@ -54,7 +54,7 @@ export class AdminWorkspaceCapabilitiesService {
|
||||
body: UpdateCapabilityInstallationDto,
|
||||
) {
|
||||
const template = getBrandTemplate(
|
||||
await this.templateWorkspace.getEffectiveTemplateKey(brandId),
|
||||
await this.templateInstallations.getEffectiveTemplateKey(brandId),
|
||||
);
|
||||
if (!template?.capabilities.includes(key as never) && !(key in capabilityPlugins))
|
||||
throw new BadRequestException("能力未被当前模板声明");
|
||||
|
||||
@@ -2,7 +2,7 @@ import { AdminBrand, AdminRoles } from "../../admin-auth.decorators.js";
|
||||
import { Controller, Get, Post, Body, Req } from "@nestjs/common";
|
||||
import type { FastifyRequest } from "fastify";
|
||||
import { InstallTemplateDto, SelectTemplateVersionDto } from "../../admin.dto.js";
|
||||
import { TemplateWorkspaceService } from "../../template-workspace.service.js";
|
||||
import { TemplateInstallationService } from "../../template/template-installation.service.js";
|
||||
import { requireAdminIdentity } from "../../admin-access.identity.js";
|
||||
import { AdminWorkspaceService } from "./admin-workspace.service.js";
|
||||
|
||||
@@ -11,7 +11,7 @@ import { AdminWorkspaceService } from "./admin-workspace.service.js";
|
||||
class AdminWorkspacePreviewController {
|
||||
constructor(
|
||||
private readonly workspaceService: AdminWorkspaceService,
|
||||
private readonly templateWorkspace: TemplateWorkspaceService,
|
||||
private readonly templateInstallations: TemplateInstallationService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@@ -32,7 +32,7 @@ class AdminWorkspacePreviewController {
|
||||
): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||
return this.templateWorkspace.install(
|
||||
return this.templateInstallations.install(
|
||||
identity.brandId,
|
||||
body.templateKey,
|
||||
body.templatePackageVersionId,
|
||||
@@ -49,7 +49,7 @@ class AdminWorkspacePreviewController {
|
||||
): Promise<unknown> {
|
||||
const identity = requireAdminIdentity(request);
|
||||
const requestId = request.headers["x-request-id"]?.toString() ?? request.id;
|
||||
return this.templateWorkspace.selectVersion(
|
||||
return this.templateInstallations.selectVersion(
|
||||
identity.brandId,
|
||||
body,
|
||||
identity.subject,
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
const PLACEHOLDER_PATTERN = /(replace-with|change-me|changeme|^your[-_ ]|example|placeholder)/i;
|
||||
|
||||
/** 判断值是否仍是仓库示例中的占位符,而不是真实随机密钥。 */
|
||||
export function isPlaceholderSecret(value: string): boolean {
|
||||
return PLACEHOLDER_PATTERN.test(value.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* 生产环境启动前的快速失败校验。
|
||||
* 本地开发允许占位符,避免示例 `.env` 阻塞调试;生产环境必须使用真实随机值。
|
||||
*/
|
||||
export function assertProductionSecret(
|
||||
value: string | undefined,
|
||||
nodeEnv: string | undefined = process.env.NODE_ENV,
|
||||
): void {
|
||||
if (nodeEnv !== "production") return;
|
||||
const secret = value?.trim() ?? "";
|
||||
if (secret.length < 32) throw new Error("SESSION_SECRET 必须是至少 32 位的随机值");
|
||||
if (isPlaceholderSecret(secret)) throw new Error("SESSION_SECRET 不能使用示例占位符");
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import type { TemplatePackageVersion } from "@prisma/client";
|
||||
|
||||
export function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
export function manifestRecords(value: unknown): Record<string, unknown>[] {
|
||||
return Array.isArray(value)
|
||||
? value.filter((item): item is Record<string, unknown> =>
|
||||
Boolean(item && typeof item === "object" && !Array.isArray(item)),
|
||||
)
|
||||
: [];
|
||||
}
|
||||
|
||||
export function stringList(value: unknown): string[] {
|
||||
return Array.isArray(value)
|
||||
? value.filter((item): item is string => typeof item === "string")
|
||||
: [];
|
||||
}
|
||||
|
||||
export function hasBindingValue(config: Record<string, unknown>, binding: unknown): boolean {
|
||||
if (typeof binding !== "string" || !binding.startsWith("brand.config.")) return false;
|
||||
const value = binding
|
||||
.slice("brand.config.".length)
|
||||
.split(".")
|
||||
.reduce<unknown>((current, key) => record(current)[key], config);
|
||||
return value !== undefined && value !== null && value !== "";
|
||||
}
|
||||
|
||||
export function compareRecords(current: Record<string, unknown>, target: Record<string, unknown>) {
|
||||
const currentKeys = Object.keys(current);
|
||||
const targetKeys = Object.keys(target);
|
||||
return {
|
||||
added: targetKeys
|
||||
.filter((key) => !(key in current))
|
||||
.map((key) => ({ key, target: target[key] })),
|
||||
removed: currentKeys
|
||||
.filter((key) => !(key in target))
|
||||
.map((key) => ({ key, current: current[key] })),
|
||||
changed: targetKeys
|
||||
.filter(
|
||||
(key) => key in current && JSON.stringify(current[key]) !== JSON.stringify(target[key]),
|
||||
)
|
||||
.map((key) => ({ key, current: current[key], target: target[key] })),
|
||||
};
|
||||
}
|
||||
|
||||
export function compareKeyedRecords(
|
||||
current: Record<string, unknown>[],
|
||||
target: Record<string, unknown>[],
|
||||
) {
|
||||
const currentByKey = new Map(
|
||||
current
|
||||
.filter((item) => typeof item.key === "string")
|
||||
.map((item) => [item.key as string, item]),
|
||||
);
|
||||
const targetByKey = new Map(
|
||||
target.filter((item) => typeof item.key === "string").map((item) => [item.key as string, item]),
|
||||
);
|
||||
return {
|
||||
added: [...targetByKey].filter(([key]) => !currentByKey.has(key)).map(([, item]) => item),
|
||||
removed: [...currentByKey].filter(([key]) => !targetByKey.has(key)).map(([, item]) => item),
|
||||
changed: [...targetByKey].flatMap(([key, item]) => {
|
||||
const previous = currentByKey.get(key);
|
||||
return previous && JSON.stringify(previous) !== JSON.stringify(item)
|
||||
? [{ key, current: previous, target: item }]
|
||||
: [];
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export function compareFiles(
|
||||
current: Record<string, unknown>[],
|
||||
target: Record<string, unknown>[],
|
||||
) {
|
||||
const currentByPath = new Map(
|
||||
current
|
||||
.filter((item) => typeof item.path === "string")
|
||||
.map((item) => [item.path as string, item]),
|
||||
);
|
||||
const targetByPath = new Map(
|
||||
target
|
||||
.filter((item) => typeof item.path === "string")
|
||||
.map((item) => [item.path as string, item]),
|
||||
);
|
||||
const available = currentByPath.size > 0 && targetByPath.size > 0;
|
||||
return {
|
||||
available,
|
||||
...(available
|
||||
? {
|
||||
added: [...targetByPath]
|
||||
.filter(([path]) => !currentByPath.has(path))
|
||||
.map(([, item]) => item),
|
||||
removed: [...currentByPath]
|
||||
.filter(([path]) => !targetByPath.has(path))
|
||||
.map(([, item]) => item),
|
||||
changed: [...targetByPath].flatMap(([path, item]) => {
|
||||
const previous = currentByPath.get(path);
|
||||
return previous && previous.sha256 !== item.sha256
|
||||
? [{ path, current: previous, target: item }]
|
||||
: [];
|
||||
}),
|
||||
}
|
||||
: { reason: "版本验证报告未包含完整文件清单" }),
|
||||
};
|
||||
}
|
||||
|
||||
export function readPackageFiles(
|
||||
version: Pick<TemplatePackageVersion, "validationReport">,
|
||||
): Record<string, unknown>[] {
|
||||
return manifestRecords(record(version.validationReport).files);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import {
|
||||
type BrandTemplateKey,
|
||||
brandTemplateKeys,
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
getVisualTemplateManifest,
|
||||
isVisualTemplateCompatible,
|
||||
validateTemplatePackageManifest,
|
||||
} from "@personal-brand/config";
|
||||
import { PrismaService } from "../prisma.service.js";
|
||||
import { compareTemplateVersions } from "../template-version-order.js";
|
||||
import { record } from "./manifest-diff.helpers.js";
|
||||
|
||||
@Injectable()
|
||||
export class PageSchemeService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getPageSchemeCatalog() {
|
||||
const versions = await this.prisma.templatePackageVersion.findMany({
|
||||
where: { status: "published" },
|
||||
orderBy: [{ importedAt: "desc" }, { createdAt: "desc" }],
|
||||
});
|
||||
const candidates = versions.flatMap((version) => {
|
||||
const manifest = record(version.manifestSnapshot);
|
||||
const visualTemplateKey = manifest.visualTemplateKey;
|
||||
if (
|
||||
manifest.packageKey !== version.packageKey ||
|
||||
manifest.version !== version.version ||
|
||||
typeof visualTemplateKey !== "string" ||
|
||||
visualTemplateKey !== version.packageKey
|
||||
)
|
||||
return [];
|
||||
const visualTemplate = getVisualTemplate(visualTemplateKey);
|
||||
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
|
||||
if (!visualTemplate || !visualManifest) return [];
|
||||
const supportedBusinessTypes = Array.isArray(manifest.supportedIndustryTemplates)
|
||||
? manifest.supportedIndustryTemplates.filter(
|
||||
(value): value is BrandTemplateKey =>
|
||||
typeof value === "string" &&
|
||||
brandTemplateKeys.includes(value) &&
|
||||
Boolean(getBrandTemplate(value)),
|
||||
)
|
||||
: [];
|
||||
if (
|
||||
supportedBusinessTypes.length === 0 ||
|
||||
supportedBusinessTypes.some(
|
||||
(businessType) => !isVisualTemplateCompatible(visualTemplate, businessType),
|
||||
) ||
|
||||
validateTemplatePackageManifest(manifest).length > 0
|
||||
)
|
||||
return [];
|
||||
return [
|
||||
{
|
||||
templatePackageVersionId: version.id,
|
||||
packageKey: version.packageKey,
|
||||
name: version.displayName,
|
||||
description: visualManifest.description,
|
||||
version: version.version,
|
||||
supportedBusinessTypes,
|
||||
},
|
||||
];
|
||||
});
|
||||
const latestByPackage = new Map<string, string>();
|
||||
for (const candidate of candidates) {
|
||||
const latestVersion = latestByPackage.get(candidate.packageKey);
|
||||
if (!latestVersion || compareTemplateVersions(candidate.version, latestVersion) > 0) {
|
||||
latestByPackage.set(candidate.packageKey, candidate.version);
|
||||
}
|
||||
}
|
||||
const pageSchemes = candidates.map(({ packageKey, ...candidate }) => ({
|
||||
...candidate,
|
||||
isLatestForPackage: latestByPackage.get(packageKey) === candidate.version,
|
||||
}));
|
||||
|
||||
return {
|
||||
businesses: brandTemplateKeys.map((key) => {
|
||||
const template = getBrandTemplate(key);
|
||||
if (!template) throw new BadRequestException("业务类型配置不完整");
|
||||
return { key, name: template.name, description: template.description };
|
||||
}),
|
||||
pageSchemes,
|
||||
};
|
||||
}
|
||||
|
||||
async getPageSchemeOptions(brandId: string) {
|
||||
const brand = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { templateKey: true },
|
||||
});
|
||||
const template = brand ? getBrandTemplate(brand.templateKey) : undefined;
|
||||
if (!brand || !template) throw new BadRequestException("品牌业务类型无效");
|
||||
const catalog = await this.getPageSchemeCatalog();
|
||||
return {
|
||||
business: {
|
||||
key: template.key,
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
},
|
||||
pageSchemes: catalog.pageSchemes.filter((scheme) =>
|
||||
scheme.supportedBusinessTypes.includes(template.key),
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
+15
-258
@@ -3,7 +3,6 @@ import type { TemplatePackageVersion } from "@prisma/client";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import {
|
||||
type BrandTemplateKey,
|
||||
brandTemplateKeys,
|
||||
getBrandTemplate,
|
||||
getVisualTemplate,
|
||||
getVisualTemplateManifest,
|
||||
@@ -11,157 +10,25 @@ import {
|
||||
validateTemplatePackageManifest,
|
||||
} from "@personal-brand/config";
|
||||
import type { TemplatePackageManifest } from "@personal-brand/config";
|
||||
import type { CreateTrustContentDto, UpdateTrustContentDto } from "./admin.dto.js";
|
||||
import type { RollbackTemplateDto, UpgradeTemplateDto } from "./admin.dto.js";
|
||||
import { PrismaService } from "./prisma.service.js";
|
||||
import { recordTemplateOperationFailure } from "./modules/admin/template-operation-failure.js";
|
||||
import { compareTemplateVersions, latestTemplateVersion } from "./template-version-order.js";
|
||||
import type { RollbackTemplateDto, UpgradeTemplateDto } from "../admin.dto.js";
|
||||
import { PrismaService } from "../prisma.service.js";
|
||||
import { recordTemplateOperationFailure } from "../modules/admin/template-operation-failure.js";
|
||||
import { latestTemplateVersion } from "../template-version-order.js";
|
||||
import {
|
||||
compareFiles,
|
||||
compareKeyedRecords,
|
||||
compareRecords,
|
||||
hasBindingValue,
|
||||
manifestRecords,
|
||||
readPackageFiles,
|
||||
record,
|
||||
stringList,
|
||||
} from "./manifest-diff.helpers.js";
|
||||
|
||||
@Injectable()
|
||||
export class TemplateWorkspaceService {
|
||||
export class TemplateInstallationService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getPageSchemeCatalog() {
|
||||
const versions = await this.prisma.templatePackageVersion.findMany({
|
||||
where: { status: "published" },
|
||||
orderBy: [{ importedAt: "desc" }, { createdAt: "desc" }],
|
||||
});
|
||||
const candidates = versions.flatMap((version) => {
|
||||
const manifest = record(version.manifestSnapshot);
|
||||
const visualTemplateKey = manifest.visualTemplateKey;
|
||||
if (
|
||||
manifest.packageKey !== version.packageKey ||
|
||||
manifest.version !== version.version ||
|
||||
typeof visualTemplateKey !== "string" ||
|
||||
visualTemplateKey !== version.packageKey
|
||||
)
|
||||
return [];
|
||||
const visualTemplate = getVisualTemplate(visualTemplateKey);
|
||||
const visualManifest = getVisualTemplateManifest(visualTemplateKey);
|
||||
if (!visualTemplate || !visualManifest) return [];
|
||||
const supportedBusinessTypes = Array.isArray(manifest.supportedIndustryTemplates)
|
||||
? manifest.supportedIndustryTemplates.filter(
|
||||
(value): value is BrandTemplateKey =>
|
||||
typeof value === "string" &&
|
||||
brandTemplateKeys.includes(value) &&
|
||||
Boolean(getBrandTemplate(value)),
|
||||
)
|
||||
: [];
|
||||
if (
|
||||
supportedBusinessTypes.length === 0 ||
|
||||
supportedBusinessTypes.some(
|
||||
(businessType) => !isVisualTemplateCompatible(visualTemplate, businessType),
|
||||
) ||
|
||||
validateTemplatePackageManifest(manifest).length > 0
|
||||
)
|
||||
return [];
|
||||
return [
|
||||
{
|
||||
templatePackageVersionId: version.id,
|
||||
packageKey: version.packageKey,
|
||||
name: version.displayName,
|
||||
description: visualManifest.description,
|
||||
version: version.version,
|
||||
supportedBusinessTypes,
|
||||
},
|
||||
];
|
||||
});
|
||||
const latestByPackage = new Map<string, string>();
|
||||
for (const candidate of candidates) {
|
||||
const latestVersion = latestByPackage.get(candidate.packageKey);
|
||||
if (!latestVersion || compareTemplateVersions(candidate.version, latestVersion) > 0) {
|
||||
latestByPackage.set(candidate.packageKey, candidate.version);
|
||||
}
|
||||
}
|
||||
const pageSchemes = candidates.map(({ packageKey, ...candidate }) => ({
|
||||
...candidate,
|
||||
isLatestForPackage: latestByPackage.get(packageKey) === candidate.version,
|
||||
}));
|
||||
|
||||
return {
|
||||
businesses: brandTemplateKeys.map((key) => {
|
||||
const template = getBrandTemplate(key);
|
||||
if (!template) throw new BadRequestException("业务类型配置不完整");
|
||||
return { key, name: template.name, description: template.description };
|
||||
}),
|
||||
pageSchemes,
|
||||
};
|
||||
}
|
||||
|
||||
async getPageSchemeOptions(brandId: string) {
|
||||
const brand = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { templateKey: true },
|
||||
});
|
||||
const template = brand ? getBrandTemplate(brand.templateKey) : undefined;
|
||||
if (!brand || !template) throw new BadRequestException("品牌业务类型无效");
|
||||
const catalog = await this.getPageSchemeCatalog();
|
||||
return {
|
||||
business: {
|
||||
key: template.key,
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
},
|
||||
pageSchemes: catalog.pageSchemes.filter((scheme) =>
|
||||
scheme.supportedBusinessTypes.includes(template.key),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
async getTrustContentTypes(brandId: string): Promise<string[]> {
|
||||
const installation = await this.prisma.brandTemplateInstallation.findUnique({
|
||||
where: { brandId },
|
||||
include: { templatePackageVersion: true },
|
||||
});
|
||||
if (!installation?.templatePackageVersion)
|
||||
throw new BadRequestException("品牌没有锁定精确视觉模板包版本");
|
||||
const manifest = record(
|
||||
installation.templatePackageVersion.manifestSnapshot,
|
||||
) as unknown as TemplatePackageManifest;
|
||||
if (validateTemplatePackageManifest(manifest).length)
|
||||
throw new BadRequestException("当前安装的模板包不符合统一模板契约");
|
||||
return manifest.trustContentTypes?.map((item) => item.type) ?? [];
|
||||
}
|
||||
async createTrustContent(brandId: string, body: CreateTrustContentDto) {
|
||||
if (!(await this.getTrustContentTypes(brandId)).includes(body.type))
|
||||
throw new BadRequestException("当前模板不支持此信任内容类型");
|
||||
const { config, ...fields } = body;
|
||||
return this.prisma.trustContent.create({
|
||||
data: {
|
||||
...fields,
|
||||
brandId,
|
||||
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
||||
},
|
||||
});
|
||||
}
|
||||
async updateTrustContent(brandId: string, id: string, body: UpdateTrustContentDto) {
|
||||
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
|
||||
if (!item) throw new BadRequestException("信任内容不存在");
|
||||
if (body.type !== undefined && !(await this.getTrustContentTypes(brandId)).includes(body.type))
|
||||
throw new BadRequestException("当前模板不支持此信任内容类型");
|
||||
const { config, ...fields } = body;
|
||||
return this.prisma.trustContent.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...fields,
|
||||
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
listTrustContent(brandId: string) {
|
||||
return this.prisma.trustContent.findMany({
|
||||
where: { brandId },
|
||||
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
|
||||
});
|
||||
}
|
||||
|
||||
async deleteTrustContent(brandId: string, id: string) {
|
||||
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
|
||||
if (!item) throw new BadRequestException("信任内容不存在");
|
||||
await this.prisma.trustContent.delete({ where: { id } });
|
||||
return { deleted: true };
|
||||
}
|
||||
async getEffectiveTemplateKey(brandId: string): Promise<BrandTemplateKey> {
|
||||
const [brand, installation] = await Promise.all([
|
||||
this.prisma.brandProfile.findUnique({
|
||||
@@ -759,113 +626,3 @@ export class TemplateWorkspaceService {
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function readPackageFiles(
|
||||
version: Pick<TemplatePackageVersion, "validationReport">,
|
||||
): Record<string, unknown>[] {
|
||||
return manifestRecords(record(version.validationReport).files);
|
||||
}
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function manifestRecords(value: unknown): Record<string, unknown>[] {
|
||||
return Array.isArray(value)
|
||||
? value.filter((item): item is Record<string, unknown> =>
|
||||
Boolean(item && typeof item === "object" && !Array.isArray(item)),
|
||||
)
|
||||
: [];
|
||||
}
|
||||
|
||||
function stringList(value: unknown): string[] {
|
||||
return Array.isArray(value)
|
||||
? value.filter((item): item is string => typeof item === "string")
|
||||
: [];
|
||||
}
|
||||
|
||||
function hasBindingValue(config: Record<string, unknown>, binding: unknown): boolean {
|
||||
if (typeof binding !== "string" || !binding.startsWith("brand.config.")) return false;
|
||||
const value = binding
|
||||
.slice("brand.config.".length)
|
||||
.split(".")
|
||||
.reduce<unknown>((current, key) => record(current)[key], config);
|
||||
return value !== undefined && value !== null && value !== "";
|
||||
}
|
||||
|
||||
function compareRecords(current: Record<string, unknown>, target: Record<string, unknown>) {
|
||||
const currentKeys = Object.keys(current);
|
||||
const targetKeys = Object.keys(target);
|
||||
return {
|
||||
added: targetKeys
|
||||
.filter((key) => !(key in current))
|
||||
.map((key) => ({ key, target: target[key] })),
|
||||
removed: currentKeys
|
||||
.filter((key) => !(key in target))
|
||||
.map((key) => ({ key, current: current[key] })),
|
||||
changed: targetKeys
|
||||
.filter(
|
||||
(key) => key in current && JSON.stringify(current[key]) !== JSON.stringify(target[key]),
|
||||
)
|
||||
.map((key) => ({ key, current: current[key], target: target[key] })),
|
||||
};
|
||||
}
|
||||
|
||||
function compareKeyedRecords(
|
||||
current: Record<string, unknown>[],
|
||||
target: Record<string, unknown>[],
|
||||
) {
|
||||
const currentByKey = new Map(
|
||||
current
|
||||
.filter((item) => typeof item.key === "string")
|
||||
.map((item) => [item.key as string, item]),
|
||||
);
|
||||
const targetByKey = new Map(
|
||||
target.filter((item) => typeof item.key === "string").map((item) => [item.key as string, item]),
|
||||
);
|
||||
return {
|
||||
added: [...targetByKey].filter(([key]) => !currentByKey.has(key)).map(([, item]) => item),
|
||||
removed: [...currentByKey].filter(([key]) => !targetByKey.has(key)).map(([, item]) => item),
|
||||
changed: [...targetByKey].flatMap(([key, item]) => {
|
||||
const previous = currentByKey.get(key);
|
||||
return previous && JSON.stringify(previous) !== JSON.stringify(item)
|
||||
? [{ key, current: previous, target: item }]
|
||||
: [];
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function compareFiles(current: Record<string, unknown>[], target: Record<string, unknown>[]) {
|
||||
const currentByPath = new Map(
|
||||
current
|
||||
.filter((item) => typeof item.path === "string")
|
||||
.map((item) => [item.path as string, item]),
|
||||
);
|
||||
const targetByPath = new Map(
|
||||
target
|
||||
.filter((item) => typeof item.path === "string")
|
||||
.map((item) => [item.path as string, item]),
|
||||
);
|
||||
const available = currentByPath.size > 0 && targetByPath.size > 0;
|
||||
return {
|
||||
available,
|
||||
...(available
|
||||
? {
|
||||
added: [...targetByPath]
|
||||
.filter(([path]) => !currentByPath.has(path))
|
||||
.map(([, item]) => item),
|
||||
removed: [...currentByPath]
|
||||
.filter(([path]) => !targetByPath.has(path))
|
||||
.map(([, item]) => item),
|
||||
changed: [...targetByPath].flatMap(([path, item]) => {
|
||||
const previous = currentByPath.get(path);
|
||||
return previous && previous.sha256 !== item.sha256
|
||||
? [{ path, current: previous, target: item }]
|
||||
: [];
|
||||
}),
|
||||
}
|
||||
: { reason: "版本验证报告未包含完整文件清单" }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { validateTemplatePackageManifest } from "@personal-brand/config";
|
||||
import type { TemplatePackageManifest } from "@personal-brand/config";
|
||||
import type { CreateTrustContentDto, UpdateTrustContentDto } from "../admin.dto.js";
|
||||
import { PrismaService } from "../prisma.service.js";
|
||||
import { record } from "./manifest-diff.helpers.js";
|
||||
|
||||
@Injectable()
|
||||
export class TrustContentService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
async getTrustContentTypes(brandId: string): Promise<string[]> {
|
||||
const installation = await this.prisma.brandTemplateInstallation.findUnique({
|
||||
where: { brandId },
|
||||
include: { templatePackageVersion: true },
|
||||
});
|
||||
if (!installation?.templatePackageVersion)
|
||||
throw new BadRequestException("品牌没有锁定精确视觉模板包版本");
|
||||
const manifest = record(
|
||||
installation.templatePackageVersion.manifestSnapshot,
|
||||
) as unknown as TemplatePackageManifest;
|
||||
if (validateTemplatePackageManifest(manifest).length)
|
||||
throw new BadRequestException("当前安装的模板包不符合统一模板契约");
|
||||
return manifest.trustContentTypes?.map((item) => item.type) ?? [];
|
||||
}
|
||||
|
||||
async createTrustContent(brandId: string, body: CreateTrustContentDto) {
|
||||
if (!(await this.getTrustContentTypes(brandId)).includes(body.type))
|
||||
throw new BadRequestException("当前模板不支持此信任内容类型");
|
||||
const { config, ...fields } = body;
|
||||
return this.prisma.trustContent.create({
|
||||
data: {
|
||||
...fields,
|
||||
brandId,
|
||||
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async updateTrustContent(brandId: string, id: string, body: UpdateTrustContentDto) {
|
||||
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
|
||||
if (!item) throw new BadRequestException("信任内容不存在");
|
||||
if (body.type !== undefined && !(await this.getTrustContentTypes(brandId)).includes(body.type))
|
||||
throw new BadRequestException("当前模板不支持此信任内容类型");
|
||||
const { config, ...fields } = body;
|
||||
return this.prisma.trustContent.update({
|
||||
where: { id },
|
||||
data: {
|
||||
...fields,
|
||||
...(config === undefined ? {} : { config: config as Prisma.InputJsonValue }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
listTrustContent(brandId: string) {
|
||||
return this.prisma.trustContent.findMany({
|
||||
where: { brandId },
|
||||
orderBy: [{ type: "asc" }, { sortOrder: "asc" }],
|
||||
});
|
||||
}
|
||||
|
||||
async deleteTrustContent(brandId: string, id: string) {
|
||||
const item = await this.prisma.trustContent.findFirst({ where: { id, brandId } });
|
||||
if (!item) throw new BadRequestException("信任内容不存在");
|
||||
await this.prisma.trustContent.delete({ where: { id } });
|
||||
return { deleted: true };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
import { AdminAccessService } from "../src/admin-access.service.js";
|
||||
import { signIdentity } from "../src/auth.js";
|
||||
|
||||
process.env.SESSION_SECRET = "admin-access-service-test-secret-1234567890";
|
||||
|
||||
type RequestFixture = {
|
||||
headers: { authorization: string };
|
||||
};
|
||||
|
||||
function requestFixture(subject = "admin-1", brandId = "brand-1"): RequestFixture {
|
||||
return {
|
||||
headers: {
|
||||
authorization: `Bearer ${signIdentity({ subject, brandId, role: "admin" })}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function accessFixture() {
|
||||
const calls = { adminUser: 0, membership: 0 };
|
||||
const prisma = {
|
||||
adminUser: {
|
||||
findUnique: async () => {
|
||||
calls.adminUser += 1;
|
||||
return {
|
||||
isEnabled: true,
|
||||
mustChangePassword: false,
|
||||
tokenVersion: 0,
|
||||
platformTemplateRole: "none",
|
||||
};
|
||||
},
|
||||
},
|
||||
brandMembership: {
|
||||
findUnique: async () => {
|
||||
calls.membership += 1;
|
||||
return { role: "owner", isEnabled: true };
|
||||
},
|
||||
},
|
||||
};
|
||||
return { calls, prisma };
|
||||
}
|
||||
|
||||
test("同一请求内 Guard 与 Controller 复用访问校验结果", async () => {
|
||||
const { calls, prisma } = accessFixture();
|
||||
const service = new AdminAccessService(prisma as never);
|
||||
const request = requestFixture();
|
||||
|
||||
const [guardResult, controllerResult] = await Promise.all([
|
||||
service.requireBrand(request as never),
|
||||
service.requireBrand(request as never),
|
||||
]);
|
||||
assert.deepEqual(guardResult, controllerResult);
|
||||
await service.requireRole(request as never, ["owner"]);
|
||||
await assert.rejects(
|
||||
service.requireTemplateAdmin(request as never),
|
||||
(error: unknown) => error instanceof ForbiddenException,
|
||||
);
|
||||
|
||||
assert.equal(calls.adminUser, 1);
|
||||
assert.equal(calls.membership, 1);
|
||||
});
|
||||
|
||||
test("不同请求之间不共享访问校验缓存", async () => {
|
||||
const { calls, prisma } = accessFixture();
|
||||
const service = new AdminAccessService(prisma as never);
|
||||
|
||||
await service.requireBrand(requestFixture("admin-1") as never);
|
||||
await service.requireBrand(requestFixture("admin-2") as never);
|
||||
|
||||
assert.equal(calls.adminUser, 2);
|
||||
assert.equal(calls.membership, 2);
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { HttpException } from "@nestjs/common";
|
||||
import { AdminClientErrorService } from "../src/modules/admin/admin-client-error.service.js";
|
||||
import { MemoryClientErrorThrottleStore } from "../src/modules/admin/client-error-throttle.store.js";
|
||||
|
||||
function report(errorId: string, subject = "admin:user-1") {
|
||||
return {
|
||||
@@ -15,40 +16,42 @@ function report(errorId: string, subject = "admin:user-1") {
|
||||
};
|
||||
}
|
||||
|
||||
test("首次上报记录,相同 errorId 在窗口内按管理员去重", () => {
|
||||
const service = new AdminClientErrorService();
|
||||
assert.deepEqual(service.record(report("admin-error-1")), {
|
||||
function service() {
|
||||
return new AdminClientErrorService(new MemoryClientErrorThrottleStore());
|
||||
}
|
||||
|
||||
test("首次上报记录,相同 errorId 在窗口内按管理员去重", async () => {
|
||||
const errors = service();
|
||||
assert.deepEqual(await errors.record(report("admin-error-1")), {
|
||||
received: true,
|
||||
duplicate: false,
|
||||
});
|
||||
assert.deepEqual(service.record(report("admin-error-1")), {
|
||||
assert.deepEqual(await errors.record(report("admin-error-1")), {
|
||||
received: true,
|
||||
duplicate: true,
|
||||
});
|
||||
// 不同管理员使用相同 errorId 时互不影响
|
||||
assert.deepEqual(service.record(report("admin-error-1", "admin:user-2")), {
|
||||
assert.deepEqual(await errors.record(report("admin-error-1", "admin:user-2")), {
|
||||
received: true,
|
||||
duplicate: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("同一管理员 60 秒内最多接受 10 条不同错误", () => {
|
||||
const service = new AdminClientErrorService();
|
||||
test("同一管理员 60 秒内最多接受 10 条不同错误", async () => {
|
||||
const errors = service();
|
||||
for (let index = 0; index < 10; index += 1) {
|
||||
assert.deepEqual(service.record(report(`admin-rate-${index}`)), {
|
||||
assert.deepEqual(await errors.record(report(`admin-rate-${index}`)), {
|
||||
received: true,
|
||||
duplicate: false,
|
||||
});
|
||||
}
|
||||
try {
|
||||
service.record(report("admin-rate-overflow"));
|
||||
assert.fail("应当触发限流");
|
||||
} catch (error) {
|
||||
await assert.rejects(errors.record(report("admin-rate-overflow")), (error) => {
|
||||
assert.ok(error instanceof HttpException);
|
||||
assert.equal(error.getStatus(), 429);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
// 另一个管理员不受影响
|
||||
assert.deepEqual(service.record(report("admin-rate-other", "admin:user-2")), {
|
||||
assert.deepEqual(await errors.record(report("admin-rate-other", "admin:user-2")), {
|
||||
received: true,
|
||||
duplicate: false,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { createClientErrorThrottleStore } from "../src/modules/admin/client-error-throttle.factory.js";
|
||||
import { PostgresClientErrorThrottleStore } from "../src/modules/admin/client-error-throttle.postgres.store.js";
|
||||
import { MemoryClientErrorThrottleStore } from "../src/modules/admin/client-error-throttle.store.js";
|
||||
|
||||
const prisma = {} as never;
|
||||
|
||||
test("默认使用进程内存储", () => {
|
||||
const store = createClientErrorThrottleStore(prisma, "memory");
|
||||
assert.ok(store instanceof MemoryClientErrorThrottleStore);
|
||||
});
|
||||
|
||||
test("多实例可切换为 Postgres 共享存储", () => {
|
||||
const store = createClientErrorThrottleStore(prisma, "postgres");
|
||||
assert.ok(store instanceof PostgresClientErrorThrottleStore);
|
||||
});
|
||||
|
||||
test("未知存储模式在启动时快速失败", () => {
|
||||
assert.throws(
|
||||
() => createClientErrorThrottleStore(prisma, "redis"),
|
||||
/Unsupported CLIENT_ERROR_THROTTLE_STORE/,
|
||||
);
|
||||
});
|
||||
@@ -12,6 +12,11 @@ import { createApp } from "../dist/main.js";
|
||||
import { readIdentity, signIdentity } from "../dist/auth.js";
|
||||
import { WechatAuthService } from "../dist/wechat-auth.js";
|
||||
import { AdminMiniAppReleaseService } from "../dist/modules/admin/admin-miniapp-release.service.js";
|
||||
import { PostgresClientErrorThrottleStore } from "../dist/modules/admin/client-error-throttle.postgres.store.js";
|
||||
import {
|
||||
CLIENT_ERROR_DEDUPE_TTL_MS,
|
||||
CLIENT_ERROR_RATE_WINDOW_MS,
|
||||
} from "../dist/modules/admin/client-error-throttle.store.js";
|
||||
|
||||
let app;
|
||||
const prisma = new PrismaClient();
|
||||
@@ -1928,6 +1933,88 @@ test("admin client error reports are authenticated, validated, and deduplicated"
|
||||
assert.equal(invalid.statusCode, 400);
|
||||
});
|
||||
|
||||
test("postgres client error store deduplicates and rate limits across instances", async () => {
|
||||
const storeA = new PostgresClientErrorThrottleStore(prisma);
|
||||
const storeB = new PostgresClientErrorThrottleStore(prisma);
|
||||
const subjectPrefix = `pg-client-error-${randomUUID()}`;
|
||||
const dedupeSubject = `${subjectPrefix}-dedupe`;
|
||||
const concurrentSubject = `${subjectPrefix}-concurrent`;
|
||||
const rateSubject = `${subjectPrefix}-rate`;
|
||||
const lateSubject = `${subjectPrefix}-late`;
|
||||
const now = Date.now();
|
||||
try {
|
||||
assert.deepEqual(await storeA.record({ subject: dedupeSubject, errorId: "same" }, now), {
|
||||
duplicate: false,
|
||||
});
|
||||
assert.deepEqual(await storeB.record({ subject: dedupeSubject, errorId: "same" }, now), {
|
||||
duplicate: true,
|
||||
});
|
||||
assert.deepEqual(
|
||||
await storeB.record(
|
||||
{ subject: dedupeSubject, errorId: "same" },
|
||||
now + CLIENT_ERROR_DEDUPE_TTL_MS + 1_000,
|
||||
),
|
||||
{ duplicate: false },
|
||||
);
|
||||
|
||||
const concurrent = await Promise.all(
|
||||
Array.from({ length: 6 }, (_, index) =>
|
||||
(index % 2 === 0 ? storeA : storeB).record(
|
||||
{ subject: concurrentSubject, errorId: "concurrent-same" },
|
||||
now,
|
||||
),
|
||||
),
|
||||
);
|
||||
assert.equal(concurrent.filter((result) => !result.duplicate).length, 1);
|
||||
|
||||
for (let index = 0; index < 10; index += 1) {
|
||||
const store = index % 2 === 0 ? storeA : storeB;
|
||||
assert.deepEqual(
|
||||
await store.record({ subject: rateSubject, errorId: `rate-${index}` }, now),
|
||||
{ duplicate: false },
|
||||
);
|
||||
}
|
||||
await assert.rejects(
|
||||
storeB.record({ subject: rateSubject, errorId: "rate-overflow" }, now),
|
||||
(error) => error.getStatus?.() === 429,
|
||||
);
|
||||
assert.deepEqual(
|
||||
await storeA.record(
|
||||
{ subject: rateSubject, errorId: "rate-next-window" },
|
||||
now + CLIENT_ERROR_RATE_WINDOW_MS,
|
||||
),
|
||||
{ duplicate: false },
|
||||
);
|
||||
|
||||
// 旧窗口的迟到请求不得把窗口指针回拨,否则会额外放行一整窗口。
|
||||
await storeA.record(
|
||||
{ subject: lateSubject, errorId: "late-first" },
|
||||
now + CLIENT_ERROR_RATE_WINDOW_MS,
|
||||
);
|
||||
await storeB.record({ subject: lateSubject, errorId: "late-old" }, now);
|
||||
for (let index = 0; index < 9; index += 1) {
|
||||
assert.deepEqual(
|
||||
await storeA.record(
|
||||
{ subject: lateSubject, errorId: `late-next-${index}` },
|
||||
now + CLIENT_ERROR_RATE_WINDOW_MS,
|
||||
),
|
||||
{ duplicate: false },
|
||||
);
|
||||
}
|
||||
await assert.rejects(
|
||||
storeB.record(
|
||||
{ subject: lateSubject, errorId: "late-overflow" },
|
||||
now + CLIENT_ERROR_RATE_WINDOW_MS,
|
||||
),
|
||||
(error) => error.getStatus?.() === 429,
|
||||
);
|
||||
} finally {
|
||||
const subjects = [dedupeSubject, concurrentSubject, rateSubject, lateSubject];
|
||||
await prisma.clientErrorDedupe.deleteMany({ where: { subject: { in: subjects } } });
|
||||
await prisma.clientErrorThrottleWindow.deleteMany({ where: { subject: { in: subjects } } });
|
||||
}
|
||||
});
|
||||
|
||||
async function assertProtectedRouteBoundary(url, options = {}) {
|
||||
const { method = "GET", payload, forbiddenRole = "customer", headers = {} } = options;
|
||||
const requestOptions = payload === undefined ? { method, headers } : { method, headers, payload };
|
||||
@@ -5123,6 +5210,71 @@ test("disabled brand membership blocks existing admin token", async () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("booking endpoints share the brand access policy", async () => {
|
||||
const username = `booking-policy-${randomUUID()}`;
|
||||
const password = "booking-policy-password-123";
|
||||
const user = await prisma.adminUser.create({
|
||||
data: {
|
||||
username,
|
||||
passwordHash: await bcrypt.hash(password, 12),
|
||||
displayName: "预订策略测试管理员",
|
||||
mustChangePassword: true,
|
||||
},
|
||||
});
|
||||
const membership = await prisma.brandMembership.create({
|
||||
data: { brandId, adminUserId: user.id, role: "admin", isEnabled: true },
|
||||
});
|
||||
try {
|
||||
const login = await request("/admin/session/login", {
|
||||
method: "POST",
|
||||
payload: { username, password },
|
||||
});
|
||||
assert.equal(login.statusCode, 201, login.body);
|
||||
const headers = { authorization: `Bearer ${sessionToken(login)}` };
|
||||
const routes = [
|
||||
{ method: "GET", url: "/admin/bookings" },
|
||||
{ method: "GET", url: "/admin/bookings/unread-count" },
|
||||
{ method: "GET", url: "/admin/bookings/tags" },
|
||||
{ method: "POST", url: "/admin/bookings/tags", payload: { name: "策略测试标签" } },
|
||||
];
|
||||
|
||||
// 初始密码未修改时,预订路由必须与其他后台路由一样被拒绝。
|
||||
for (const route of routes) {
|
||||
const response = await request(route.url, {
|
||||
method: route.method,
|
||||
headers,
|
||||
...(route.payload ? { payload: route.payload } : {}),
|
||||
});
|
||||
assert.equal(response.statusCode, 403, `${route.method} ${route.url}: ${response.body}`);
|
||||
}
|
||||
|
||||
// 品牌成员被停用后,同一 token 也不能再访问预订数据。
|
||||
await prisma.adminUser.update({ where: { id: user.id }, data: { mustChangePassword: false } });
|
||||
const changed = await request("/admin/session/login", {
|
||||
method: "POST",
|
||||
payload: { username, password },
|
||||
});
|
||||
assert.equal(changed.statusCode, 201, changed.body);
|
||||
const activeHeaders = { authorization: `Bearer ${sessionToken(changed)}` };
|
||||
assert.equal((await request("/admin/bookings", { headers: activeHeaders })).statusCode, 200);
|
||||
|
||||
await prisma.brandMembership.update({
|
||||
where: { id: membership.id },
|
||||
data: { isEnabled: false },
|
||||
});
|
||||
for (const route of routes) {
|
||||
const response = await request(route.url, {
|
||||
method: route.method,
|
||||
headers: activeHeaders,
|
||||
...(route.payload ? { payload: route.payload } : {}),
|
||||
});
|
||||
assert.equal(response.statusCode, 403, `${route.method} ${route.url}: ${response.body}`);
|
||||
}
|
||||
} finally {
|
||||
await prisma.adminUser.delete({ where: { id: user.id } });
|
||||
}
|
||||
});
|
||||
|
||||
test("admin can read and update brand and service configuration", async () => {
|
||||
const login = await request("/admin/session/login", {
|
||||
method: "POST",
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { assertProductionSecret, isPlaceholderSecret } from "../src/runtime-config.js";
|
||||
|
||||
test("production rejects missing or short session secrets", () => {
|
||||
assert.throws(() => assertProductionSecret(undefined, "production"), /至少 32 位/);
|
||||
assert.throws(() => assertProductionSecret("short-secret", "production"), /至少 32 位/);
|
||||
});
|
||||
|
||||
test("production rejects example placeholder secrets", () => {
|
||||
assert.throws(
|
||||
() => assertProductionSecret("replace-with-at-least-32-random-characters", "production"),
|
||||
/示例占位符/,
|
||||
);
|
||||
assert.throws(
|
||||
() => assertProductionSecret("change-me-now-1234567890-abcdefghij", "production"),
|
||||
/示例占位符/,
|
||||
);
|
||||
});
|
||||
|
||||
test("production accepts a strong random secret", () => {
|
||||
assert.doesNotThrow(() =>
|
||||
assertProductionSecret("s3cure-Random-Value-0123456789-abcdefghij", "production"),
|
||||
);
|
||||
});
|
||||
|
||||
test("development keeps working with the example placeholder", () => {
|
||||
assert.doesNotThrow(() =>
|
||||
assertProductionSecret("replace-with-a-long-random-value", "development"),
|
||||
);
|
||||
});
|
||||
|
||||
test("placeholder detection covers documented example values", () => {
|
||||
assert.equal(isPlaceholderSecret("replace-with-a-long-random-value"), true);
|
||||
assert.equal(isPlaceholderSecret(" YOur-secret-value "), true);
|
||||
assert.equal(isPlaceholderSecret("s3cure-Random-Value-0123456789-abcdefghij"), false);
|
||||
});
|
||||
@@ -45,7 +45,6 @@ async function main() {
|
||||
.filter((entry) => entry.isDirectory() && entry.name !== targetMigration)
|
||||
.map((entry) => entry.name)
|
||||
.sort();
|
||||
assert.equal(migrationDirs.at(-1), "20261019100000_remove_brand_profile_defaults");
|
||||
await admin.$executeRawUnsafe(`CREATE SCHEMA "${schema}"`);
|
||||
createdSchema = true;
|
||||
|
||||
|
||||
@@ -88,6 +88,27 @@ async function verifyCanvasTargets(page: Page, manifest: any, pageKey: string) {
|
||||
}
|
||||
|
||||
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
|
||||
const consoleWarnings = new WeakMap<Page, string[]>();
|
||||
|
||||
test.beforeEach(({ page }) => {
|
||||
const warnings: string[] = [];
|
||||
consoleWarnings.set(page, warnings);
|
||||
page.on("console", (message) => {
|
||||
const text = message.text();
|
||||
const isWarning =
|
||||
message.type() === "warning" ||
|
||||
(message.type() === "error" &&
|
||||
(text.startsWith("Warning:") ||
|
||||
text.includes("non-boolean attribute") ||
|
||||
text.includes("empty string")));
|
||||
if (isWarning) warnings.push(text);
|
||||
});
|
||||
});
|
||||
|
||||
test.afterEach(({ page }) => {
|
||||
expect(consoleWarnings.get(page) ?? []).toEqual([]);
|
||||
});
|
||||
|
||||
const brand = {
|
||||
id: "brand-fixture",
|
||||
slug: "preview-fixture",
|
||||
|
||||
@@ -1,7 +1,28 @@
|
||||
import fs from "node:fs";
|
||||
import { test, expect } from "@playwright/test";
|
||||
import { test, expect, type Page } from "@playwright/test";
|
||||
|
||||
const adminOrigin = process.env.ADMIN_URL || "http://localhost:3005";
|
||||
const consoleWarnings = new WeakMap<Page, string[]>();
|
||||
|
||||
test.beforeEach(({ page }) => {
|
||||
const warnings: string[] = [];
|
||||
consoleWarnings.set(page, warnings);
|
||||
page.on("console", (message) => {
|
||||
const text = message.text();
|
||||
const isWarning =
|
||||
message.type() === "warning" ||
|
||||
(message.type() === "error" &&
|
||||
(text.startsWith("Warning:") ||
|
||||
text.includes("non-boolean attribute") ||
|
||||
text.includes("empty string")));
|
||||
if (isWarning) warnings.push(text);
|
||||
});
|
||||
});
|
||||
|
||||
test.afterEach(({ page }) => {
|
||||
expect(consoleWarnings.get(page) ?? []).toEqual([]);
|
||||
});
|
||||
|
||||
const templateContent = JSON.parse(
|
||||
fs.readFileSync("../../packages/template-acheng-campus-food/template.json", "utf8"),
|
||||
);
|
||||
|
||||
@@ -6,6 +6,8 @@ module.exports = {
|
||||
apps: [
|
||||
{
|
||||
name: "personal-brand-api",
|
||||
instances: 1,
|
||||
exec_mode: "fork",
|
||||
cwd: path.join(root, "current/apps/api"),
|
||||
script: "dist/main.js",
|
||||
interpreter: process.execPath,
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
process.env.DEPLOY_ROOT = "/srv/personal-brand";
|
||||
const require = createRequire(import.meta.url);
|
||||
const config = require("./ecosystem.config.cjs");
|
||||
|
||||
test("异常上报使用进程内存储时 PM2 必须保持单实例", () => {
|
||||
assert.equal(config.apps.length, 1);
|
||||
assert.equal(config.apps[0].instances, 1);
|
||||
assert.equal(config.apps[0].exec_mode, "fork");
|
||||
});
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import path from "node:path";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { checkPackage } from "../scripts/deploy/check-package.mjs";
|
||||
import { assertReleaseEnvironment } from "./release-environment.mjs";
|
||||
|
||||
const root = process.env.DEPLOY_ROOT;
|
||||
if (!root || !path.isAbsolute(root)) throw new Error("DEPLOY_ROOT must be absolute");
|
||||
@@ -28,20 +29,7 @@ if (!postgresContainer || !/^[a-zA-Z0-9_.-]+$/.test(postgresContainer)) {
|
||||
throw new Error("POSTGRES_CONTAINER is required for the database backup");
|
||||
}
|
||||
if (Number(process.versions.node.split(".")[0]) !== 24) throw new Error("Node.js 24 is required");
|
||||
if (
|
||||
process.env.NODE_ENV !== "production" ||
|
||||
!process.env.DATABASE_URL ||
|
||||
!process.env.SESSION_SECRET ||
|
||||
process.env.SESSION_SECRET.length < 32 ||
|
||||
!process.env.DEFAULT_BRAND_ID ||
|
||||
!process.env.LOCAL_MEDIA_ROOT
|
||||
) {
|
||||
throw new Error("Production environment is missing required values");
|
||||
}
|
||||
if (!path.isAbsolute(process.env.LOCAL_MEDIA_ROOT))
|
||||
throw new Error("LOCAL_MEDIA_ROOT must be absolute");
|
||||
if (process.env.API_PREFIX) throw new Error("API_PREFIX must be empty when Traefik strips /api");
|
||||
const databaseUrl = new URL(process.env.DATABASE_URL);
|
||||
const databaseUrl = assertReleaseEnvironment(process.env);
|
||||
const privateDatabaseHost = /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[0-1])\.)/.test(
|
||||
databaseUrl.hostname,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import path from "node:path";
|
||||
|
||||
const PLACEHOLDER_PATTERN = /(replace-with|change-me|changeme|^your[-_ ]|example|placeholder)/i;
|
||||
|
||||
/** 判断值是否仍是示例占位符,而不是真实随机密钥。 */
|
||||
export function isPlaceholderSecret(value) {
|
||||
return PLACEHOLDER_PATTERN.test(value.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* 切流前校验共享生产环境文件。
|
||||
* 除必填项外,必须拒绝示例密钥,避免上线后才在 API 启动时失败。
|
||||
*/
|
||||
export function assertReleaseEnvironment(environment) {
|
||||
if (
|
||||
environment.NODE_ENV !== "production" ||
|
||||
!environment.DATABASE_URL ||
|
||||
!environment.SESSION_SECRET ||
|
||||
!environment.DEFAULT_BRAND_ID ||
|
||||
!environment.LOCAL_MEDIA_ROOT
|
||||
) {
|
||||
throw new Error("Production environment is missing required values");
|
||||
}
|
||||
if (environment.SESSION_SECRET.trim().length < 32) {
|
||||
throw new Error("SESSION_SECRET must contain at least 32 characters");
|
||||
}
|
||||
if (isPlaceholderSecret(environment.SESSION_SECRET)) {
|
||||
throw new Error("SESSION_SECRET must not use an example placeholder");
|
||||
}
|
||||
if (!path.isAbsolute(environment.LOCAL_MEDIA_ROOT)) {
|
||||
throw new Error("LOCAL_MEDIA_ROOT must be absolute");
|
||||
}
|
||||
if (environment.API_PREFIX) {
|
||||
throw new Error("API_PREFIX must be empty when Traefik strips /api");
|
||||
}
|
||||
const throttleStore = environment.CLIENT_ERROR_THROTTLE_STORE ?? "memory";
|
||||
if (!["memory", "postgres"].includes(throttleStore)) {
|
||||
throw new Error("CLIENT_ERROR_THROTTLE_STORE must be memory or postgres");
|
||||
}
|
||||
return new URL(environment.DATABASE_URL);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { assertReleaseEnvironment } from "./release-environment.mjs";
|
||||
|
||||
const validEnvironment = {
|
||||
NODE_ENV: "production",
|
||||
DATABASE_URL: "postgresql://user:password@127.0.0.1:5432/personal_brand",
|
||||
SESSION_SECRET: "Zx9vQ2mK7pL4rT8wY3nB6cF1hJ5sD0gA",
|
||||
DEFAULT_BRAND_ID: "brand-1",
|
||||
LOCAL_MEDIA_ROOT: "/srv/personal-brand/media",
|
||||
};
|
||||
|
||||
test("生产环境校验接受真实随机密钥", () => {
|
||||
const databaseUrl = assertReleaseEnvironment(validEnvironment);
|
||||
assert.equal(databaseUrl.hostname, "127.0.0.1");
|
||||
});
|
||||
|
||||
test("生产环境校验拒绝示例占位密钥", () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
assertReleaseEnvironment({
|
||||
...validEnvironment,
|
||||
SESSION_SECRET: "replace-with-at-least-32-random-characters",
|
||||
}),
|
||||
/must not use an example placeholder/,
|
||||
);
|
||||
});
|
||||
|
||||
test("生产环境校验拒绝过短密钥", () => {
|
||||
assert.throws(
|
||||
() => assertReleaseEnvironment({ ...validEnvironment, SESSION_SECRET: "short-secret" }),
|
||||
/at least 32 characters/,
|
||||
);
|
||||
});
|
||||
|
||||
test("生产环境校验拒绝缺失的必填项", () => {
|
||||
assert.throws(
|
||||
() => assertReleaseEnvironment({ ...validEnvironment, DEFAULT_BRAND_ID: "" }),
|
||||
/missing required values/,
|
||||
);
|
||||
});
|
||||
|
||||
test("生产环境校验拒绝 Traefik 之外的 API 前缀", () => {
|
||||
assert.throws(
|
||||
() => assertReleaseEnvironment({ ...validEnvironment, API_PREFIX: "/api" }),
|
||||
/API_PREFIX must be empty/,
|
||||
);
|
||||
});
|
||||
|
||||
test("生产环境校验拒绝未知的异常限流存储", () => {
|
||||
assert.throws(
|
||||
() => assertReleaseEnvironment({ ...validEnvironment, CLIENT_ERROR_THROTTLE_STORE: "redis" }),
|
||||
/CLIENT_ERROR_THROTTLE_STORE must be memory or postgres/,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
# 0035 Admin 客户端异常上报的去重与限流
|
||||
|
||||
- 状态:已采纳
|
||||
- 日期:2026-10-23
|
||||
|
||||
## Context
|
||||
|
||||
Admin 渲染异常上报 `POST /admin/client-errors` 需要防止两类问题:
|
||||
|
||||
- 同一次渲染错误在多个组件或重试中重复上报,制造日志噪音。
|
||||
- 单账号在错误循环中高频上报,拖垮日志与请求处理。
|
||||
|
||||
生产 PM2 当前保持单实例(`deploy/ecosystem.config.cjs`),因此默认不需要额外基础设施。但当 API 扩展为多实例时,进程内窗口会让实际限流值按实例数放大,跨实例去重也会失效。
|
||||
|
||||
## Decision
|
||||
|
||||
1. 提供两种 `ClientErrorThrottleStore` 实现,由 `CLIENT_ERROR_THROTTLE_STORE` 选择:
|
||||
- `memory`(默认):适合当前单实例 PM2,使用进程内 `Map`。
|
||||
- `postgres`:适合多实例,使用数据库共享去重与限流状态。
|
||||
2. 两种实现使用一致语义:
|
||||
- 去重:`subject + errorId` 在 10 分钟内只接受一次。
|
||||
- 限流:同一 `subject` 每分钟最多接受 10 条不同错误,超出返回 429。
|
||||
3. Postgres 实现使用两张表:
|
||||
- `ClientErrorDedupe` 通过 `(subject, errorId)` 唯一约束去重,并用条件 UPSERT 刷新过期记录。
|
||||
- `ClientErrorThrottleWindow` 按 `subject` 单行保存当前窗口,使用原子 UPSERT 累加计数。
|
||||
- 去重与限流在同一事务内完成,限流拒绝会回滚去重标记,避免客户端重试同一 `errorId` 时被误判为已记录。
|
||||
4. 过期去重记录与旧限流窗口每分钟最多清理一次,清理失败只记录警告,不影响诊断上报。
|
||||
5. 只有通过 `requireBrand` 认证的管理员才能上报,避免匿名刷量。未知的 `CLIENT_ERROR_THROTTLE_STORE` 值必须在启动时失败。
|
||||
|
||||
## Alternatives
|
||||
|
||||
- 只保留进程内实现:多实例下计数与去重不准确,拒绝作为唯一方案。
|
||||
- 直接引入 Redis:增加部署与可用性依赖;当已经有 Postgres 时,数据库方案成本更低。
|
||||
- 不做限流:错误循环会持续写日志,并放大客户端重试,拒绝。
|
||||
- 把错误详情写入数据库:异常上报是诊断辅助数据,故障时不应继续给数据库增加业务写入压力;数据库只保存短期限流状态。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 默认 `memory` 模式保持现有单实例部署的零额外依赖和低延迟。
|
||||
- 多实例部署必须显式设置 `CLIENT_ERROR_THROTTLE_STORE=postgres`;只把 PM2 调成 cluster 模式而不切换存储,会重新引入按实例放大的问题。
|
||||
- Postgres 模式每个接受的上报会增加少量事务写入,但只有已被放行的错误才会进入日志记录路径。
|
||||
- 进程重启会清空 `memory` 模式的状态;`postgres` 模式在重启后仍能保持窗口。
|
||||
- `memory` 模式使用滑动窗口;`postgres` 模式按自然分钟切分,边界附近可能出现短时双倍突发。这是诊断上报可接受的取舍。
|
||||
|
||||
## Migration plan
|
||||
|
||||
1. 当前单实例 PM2 继续使用默认 `memory` 模式。
|
||||
2. 扩展 API 实例数前,先执行 `20261023130000_add_client_error_throttle` 迁移,并设置 `CLIENT_ERROR_THROTTLE_STORE=postgres`。
|
||||
3. 验证多实例下同一 `errorId` 只记录一次,且单账号跨实例超过 10 条/分钟返回 429。
|
||||
4. 如需 Redis 或消息队列,保留 `ClientErrorThrottleStore` 接口与响应形状,仅替换工厂实现并补充并发与过期测试。
|
||||
@@ -88,6 +88,8 @@ SEED_ADMIN_PASSWORD=<first-boot-admin-password>
|
||||
|
||||
`DATABASE_URL` 使用最小权限数据库账号。`SESSION_SECRET` 不能复用示例值或开发值。`DEFAULT_BRAND_ID` 供未携带 `brandSlug` 的公共请求使用,缺失时 API 返回 503,不会回退到硬编码品牌。
|
||||
|
||||
`CLIENT_ERROR_THROTTLE_STORE` 默认为 `memory`,与当前 PM2 单实例模式匹配。扩展到多实例前必须先执行数据库迁移并改为 `postgres`,否则每个实例会各自限流与去重,实际阈值会被实例数量放大。
|
||||
|
||||
`CORS_ORIGINS` 默认为空并关闭跨域访问;只有 Admin 或预览应用从其他 origin 调用 API 时,才配置逗号分隔的 HTTPS origin allow-list。
|
||||
|
||||
本次部署会为管理员账号引入 `tokenVersion`。既有 admin token 会因缺少当前版本号而失效,管理员需要重新登录;之后修改密码会立即撤销同一账号的旧 token。媒体上传使用 S3 兼容对象存储和预签名直传,生产环境必须配置独立的 `OBJECT_STORAGE_PUBLIC_URL`、最小权限访问密钥和专用 bucket。微信相关变量只在启用对应能力时配置,同样不能提交真实凭据。
|
||||
|
||||
Reference in new issue
Block a user