feat: 完善官网配置、预约管理与文章编辑

This commit is contained in:
zhanjunhao
2026-10-31 19:02:58 +08:00
parent b8659d0a9a
commit 2e6fe73939
54 changed files with 4898 additions and 203 deletions
+297
View File
@@ -0,0 +1,297 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useState } from 'react';
import {
Button,
Card,
Checkbox,
Form,
Input,
Modal,
Select,
SideSheet,
TextArea,
Typography,
} from '@douyinfe/semi-ui';
import { articleErrors } from './insightsModel';
import { articleContentInfo, sanitizeArticleHtml } from './insightsContent';
import ArticleRichEditor from './ArticleRichEditor';
export default function ArticleEditor({ initial, insights, onApply, onClose }) {
const [draft, setDraft] = useState(initial);
const [errors, setErrors] = useState({});
const [processingImage, setProcessingImage] = useState(false);
const hasDraftChanges = JSON.stringify(draft) !== JSON.stringify(initial);
useEffect(() => {
if (!hasDraftChanges && !processingImage) return;
const warn = (event) => {
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [hasDraftChanges, processingImage]);
const change = (name, value) => {
setDraft((previous) => ({ ...previous, [name]: value }));
setErrors((previous) => ({ ...previous, [name]: '' }));
};
const close = () => {
if (JSON.stringify(draft) === JSON.stringify(initial) && !processingImage)
onClose();
else
Modal.confirm({
title: '放弃本次编辑?',
content: '当前文章的修改尚未应用,关闭后将丢失本次编辑内容。',
okText: '放弃修改',
cancelText: '继续编辑',
onOk: onClose,
});
};
const apply = () => {
if (processingImage) return;
const article = { ...draft, body: sanitizeArticleHtml(draft.body) };
for (const key of ['title', 'summary', 'subtitle', 'tag'])
article[key] = article[key].trim();
const nextErrors = articleErrors(article, insights);
setErrors(nextErrors);
if (Object.keys(nextErrors).length) return;
onApply(article);
};
const field = (name, label, children, required = false) => (
<Form.Slot
className='website-insights-editor-field'
label={{ text: label, required }}
error={{ error: errors[name] || undefined }}
>
{children}
</Form.Slot>
);
const info = articleContentInfo(draft.body);
return (
<SideSheet
visible
title={initial.id ? '编辑文章' : '新增文章'}
width='min(1100px, 100vw)'
onCancel={close}
maskClosable={false}
footer={
<div className='website-insights-editor-footer'>
<div className='flex gap-2'>
<Button onClick={close}>取消</Button>
<Button theme='solid' disabled={processingImage} onClick={apply}>
{processingImage ? '图片处理中' : '保存'}
</Button>
</div>
</div>
}
>
<div className='website-insights-editor-layout'>
<div className='website-insights-editor-main'>
<Typography.Title
heading={5}
className='website-insights-section-title'
>
基础信息
</Typography.Title>
{field(
'title',
'文章标题',
<Input
aria-label='文章标题'
validateStatus={errors.title ? 'error' : 'default'}
aria-invalid={Boolean(errors.title)}
value={draft.title}
placeholder='请输入文章标题'
maxLength={80}
showClear
suffix={`${draft.title.length} / 80`}
onChange={(value) => change('title', value)}
/>,
true,
)}
<div className='grid grid-cols-1 gap-x-6 md:grid-cols-2'>
{field(
'category',
'所属分类',
<Select
aria-label='所属分类'
validateStatus={errors.category ? 'error' : 'default'}
aria-invalid={Boolean(errors.category)}
value={draft.category || undefined}
placeholder='请选择文章分类'
style={{ width: '100%' }}
optionList={[
{ label: '全部内容', value: 'all' },
...insights.categories.map((c) => ({
label: c.name,
value: c.id,
})),
]}
onChange={(value) => change('category', value)}
/>,
true,
)}
{field(
'date',
'发布日期',
<Input
aria-label='发布日期'
validateStatus={errors.date ? 'error' : 'default'}
aria-invalid={Boolean(errors.date)}
type='date'
value={draft.date}
onChange={(value) => change('date', value)}
/>,
true,
)}
</div>
{field(
'subtitle',
'详情副标题',
<Input
aria-label='详情副标题'
validateStatus={errors.subtitle ? 'error' : 'default'}
aria-invalid={Boolean(errors.subtitle)}
value={draft.subtitle}
maxLength={160}
placeholder='留空时使用卡片摘要作为副标题'
onChange={(value) => change('subtitle', value)}
/>,
)}
{field(
'summary',
'卡片摘要',
<TextArea
aria-label='卡片摘要'
validateStatus={errors.summary ? 'error' : 'default'}
aria-invalid={Boolean(errors.summary)}
value={draft.summary}
placeholder='请输入卡片摘要'
maxCount={200}
rows={3}
onChange={(value) => change('summary', value)}
/>,
true,
)}
{field(
'tag',
'角标标签',
<Input
aria-label='角标标签'
validateStatus={errors.tag ? 'error' : 'default'}
aria-invalid={Boolean(errors.tag)}
value={draft.tag}
maxLength={12}
placeholder='例如 NEW、推荐'
onChange={(value) => change('tag', value)}
/>,
)}
<Typography.Title
heading={5}
className='website-insights-section-title website-insights-detail-title'
>
详情内容
</Typography.Title>
{field(
'body',
'文章正文',
<ArticleRichEditor
value={draft.body}
invalid={Boolean(errors.body)}
onChange={(value) => change('body', value)}
onBusyChange={setProcessingImage}
/>,
true,
)}
</div>
<aside className='website-insights-aside'>
<Card title='文章目录'>
<Checkbox
checked={draft.toc}
onChange={(e) => change('toc', e.target.checked)}
>
根据正文标题自动生成
</Checkbox>
<div className='website-insights-toc'>
{!draft.toc ? (
<Typography.Text type='tertiary'>
已关闭目录展示
</Typography.Text>
) : info.headings.length ? (
info.headings.map((h, i) => (
<div
key={i}
style={{ paddingLeft: h.level === 'H3' ? 12 : 0 }}
>
{h.text}
</div>
))
) : (
<Typography.Text type='tertiary'>
添加 H2 / H3 标题后自动生成目录
</Typography.Text>
)}
</div>
</Card>
<Card title={`相关推荐(${draft.related.length} / 3)`}>
<div className='website-insights-related'>
{insights.articles
.filter((a) => a.id !== draft.id)
.map((a) => (
<Checkbox
key={a.id}
checked={draft.related.includes(a.id)}
disabled={
!draft.related.includes(a.id) && draft.related.length >= 3
}
onChange={(e) =>
change(
'related',
e.target.checked
? [...draft.related, a.id]
: draft.related.filter((id) => id !== a.id),
)
}
>
{a.title}
</Checkbox>
))}
</div>
{!insights.articles.some((a) => a.id !== draft.id) && (
<Typography.Text type='tertiary'>
暂无可推荐的其他文章
</Typography.Text>
)}
{errors.related && (
<Typography.Text type='danger'>{errors.related}</Typography.Text>
)}
</Card>
<Card title='展示说明'>
<Typography.Paragraph type='tertiary'>
列表页:标题、摘要、分类、日期、角标。
</Typography.Paragraph>
<Typography.Text type='tertiary'>
详情页:副标题(留空时使用摘要)、正文、目录和推荐。
</Typography.Text>
</Card>
</aside>
</div>
</SideSheet>
);
}
@@ -0,0 +1,33 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import RichTextEditor from '../../components/common/ui/RichTextEditor';
import { ARTICLE_BODY_LIMIT } from '../../components/common/ui/richTextLength';
export default function ArticleRichEditor(props) {
return (
<RichTextEditor
{...props}
maxLength={ARTICLE_BODY_LIMIT}
label='文章正文'
placeholder='请输入文章正文,支持文本、图片及复制粘贴'
/>
);
}
+417
View File
@@ -0,0 +1,417 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState } from 'react';
import {
Button,
Card,
Empty,
Input,
Modal,
Select,
Typography,
} from '@douyinfe/semi-ui';
import {
IconPlus,
IconSearch,
IconEdit,
IconClose,
} from '@douyinfe/semi-icons';
import CardTable from '../../components/common/ui/CardTable';
import { showError, showInfo } from '../../helpers';
import {
categoryError,
createContentId,
filterArticles,
newArticle,
removeArticle,
} from './insightsModel';
import ArticleEditor from './ArticleEditor';
export default function InsightsPanel({ value, onChange, disabled, error }) {
const [keyword, setKeyword] = useState('');
const [category, setCategory] = useState('all');
const [managing, setManaging] = useState(false);
const [categoryDraft, setCategoryDraft] = useState(null);
const [categoryMessage, setCategoryMessage] = useState('');
const [article, setArticle] = useState(null);
const activeCategory = value.categories.some((c) => c.id === category)
? category
: 'all';
const rows = filterArticles(value, keyword, activeCategory);
const count = (id) =>
id === 'all'
? value.articles.length
: value.articles.filter((a) => a.category === id).length;
const selectCategory = (id) => {
setCategory(id);
};
const editCategory = (item = { id: '', name: '' }) => {
setCategoryMessage('');
setCategoryDraft({ ...item });
};
const saveCategory = () => {
const message = categoryError(
categoryDraft.name,
value.categories,
categoryDraft.id,
);
if (message) {
setCategoryMessage(message);
return;
}
const item = {
id: categoryDraft.id || createContentId(),
name: categoryDraft.name.trim(),
};
onChange({
...value,
categories: categoryDraft.id
? value.categories.map((c) => (c.id === item.id ? item : c))
: [...value.categories, item],
});
setCategoryDraft(null);
};
const deleteCategory = (item) => {
if (count(item.id)) {
showError('该分类下仍有文章,请先调整文章所属分类,再删除分类。');
return;
}
Modal.confirm({
title: '删除分类',
content: `确定删除“${item.name}”分类吗?点击页面底部“保存”后统一提交。`,
okText: '确定删除',
cancelText: '取消',
onOk: () => {
onChange({
...value,
categories: value.categories.filter((c) => c.id !== item.id),
});
if (category === item.id) selectCategory('all');
},
});
};
const deleteArticle = (item) =>
Modal.confirm({
title: '删除文章',
content: `确定删除“${item.title}”吗?删除后将同步清理其他文章中的推荐引用。点击页面底部“保存”后统一提交。`,
okText: '确定删除',
cancelText: '取消',
onOk: () => onChange(removeArticle(value, item.id)),
});
const applyArticle = (draft) => {
const next = { ...draft, id: draft.id || createContentId() };
onChange({
...value,
articles: draft.id
? value.articles.map((a) => (a.id === draft.id ? next : a))
: [next, ...value.articles],
});
setArticle(null);
showInfo('文章已应用到当前配置,请点击页面底部“保存”统一提交。');
};
const columns = [
{
title: '文章标题',
dataIndex: 'title',
width: 420,
render: (_, item) => (
<div className='website-insights-article-meta'>
<button
type='button'
className='website-insights-title'
title={item.title}
disabled={disabled}
onClick={() => setArticle({ ...item, related: [...item.related] })}
>
{item.title}
</button>
<Typography.Paragraph
type='tertiary'
className='truncate'
title={item.summary}
style={{ marginBottom: 0 }}
>
{item.summary}
</Typography.Paragraph>
</div>
),
},
{
title: '所属分类',
dataIndex: 'category',
width: 140,
render: (id) =>
id === 'all'
? '全部内容'
: value.categories.find((c) => c.id === id)?.name || '未分类',
},
{ title: '发布日期', dataIndex: 'date', width: 140 },
{
title: '操作',
key: 'actions',
width: 160,
render: (_, item) => (
<div className='flex gap-2'>
<Button
type='tertiary'
theme='borderless'
disabled={disabled}
onClick={() => setArticle({ ...item, related: [...item.related] })}
>
编辑
</Button>
<Button
theme='borderless'
type='danger'
disabled={disabled}
onClick={() => deleteArticle(item)}
>
删除
</Button>
</div>
),
},
];
return (
<div className='website-insights'>
{error && (
<Typography.Paragraph type='danger' role='alert'>
{error}
</Typography.Paragraph>
)}
<Card
className='website-insights-categories'
title={
<Typography.Title heading={6} className='truncate' title='内容分类'>
内容分类
</Typography.Title>
}
headerExtraContent={
<Button
type='tertiary'
theme='borderless'
disabled={disabled}
onClick={() => setManaging(true)}
>
管理分类
</Button>
}
>
<div className='website-insights-category-list'>
{[{ id: 'all', name: '全部内容' }, ...value.categories].map((c) => (
<div
key={c.id}
className={`website-insights-category ${activeCategory === c.id ? 'is-selected' : ''}`}
>
<Button
type='tertiary'
theme='borderless'
aria-pressed={activeCategory === c.id}
onClick={() => selectCategory(c.id)}
>
<span>{c.name}</span>
<span className='website-insights-category-count'>
{count(c.id)}
</span>
</Button>
{c.id !== 'all' && (
<div className='website-insights-category-actions'>
<Button
type='tertiary'
icon={<IconEdit />}
size='small'
theme='borderless'
aria-label={`编辑${c.name}`}
disabled={disabled}
onClick={() => editCategory(c)}
/>
<Button
icon={<IconClose />}
size='small'
theme='borderless'
type='danger'
aria-label={`删除${c.name}`}
disabled={disabled}
onClick={() => deleteCategory(c)}
/>
</div>
)}
</div>
))}
<Button
type='tertiary'
icon={<IconPlus />}
theme='borderless'
disabled={disabled}
onClick={() => editCategory()}
>
新增分类
</Button>
</div>
</Card>
<div className='website-insights-toolbar'>
<Input
prefix={<IconSearch />}
aria-label='搜索文章标题或摘要'
placeholder='搜索文章标题或摘要'
value={keyword}
showClear
onEnterPress={(event) => event.preventDefault()}
onChange={(text) => {
setKeyword(text);
}}
/>
<Select
aria-label='筛选文章分类'
value={activeCategory}
optionList={[
{ label: '全部分类', value: 'all' },
...value.categories.map((c) => ({ label: c.name, value: c.id })),
]}
onChange={selectCategory}
/>
<Button
icon={<IconPlus />}
theme='solid'
disabled={disabled}
onClick={() => {
setArticle(newArticle(activeCategory));
}}
>
新增文章
</Button>
</div>
<CardTable
rowKey='id'
columns={columns}
dataSource={rows}
scroll={{ x: 860 }}
empty={<Empty description='暂无匹配的文章,请调整筛选条件或新增文章' />}
hidePagination
/>
<Modal
visible={managing}
title='管理分类'
onCancel={() => setManaging(false)}
footer={
<Button
icon={<IconPlus />}
theme='solid'
disabled={disabled}
onClick={() => editCategory()}
>
新增分类
</Button>
}
>
<Typography.Paragraph type='tertiary'>
“全部内容”为默认分类,也汇总展示全部文章;已有文章的自定义分类需先迁移文章再删除。
</Typography.Paragraph>
<div className='website-insights-manage-row'>
<span>全部内容</span>
<Typography.Text type='tertiary'>
默认分类(不可删除)
</Typography.Text>
</div>
{value.categories.map((c) => (
<div className='website-insights-manage-row' key={c.id}>
<span>
{c.name}({count(c.id)} 篇)
</span>
<Button
type='tertiary'
theme='borderless'
disabled={disabled}
onClick={() => editCategory(c)}
>
编辑
</Button>
<Button
theme='borderless'
type='danger'
disabled={disabled}
onClick={() => deleteCategory(c)}
>
删除
</Button>
</div>
))}
</Modal>
<Modal
visible={Boolean(categoryDraft)}
title={categoryDraft?.id ? '编辑分类' : '新增分类'}
onCancel={() => setCategoryDraft(null)}
onOk={saveCategory}
okText='确定'
cancelText='取消'
okButtonProps={{ disabled }}
>
<Typography.Paragraph
className='website-category-dialog-description'
type='tertiary'
>
分类名称将用于官网导航与文章分类标签。
</Typography.Paragraph>
<div className='website-category-dialog-field'>
<label
htmlFor='website-category-name'
className='website-category-dialog-label'
>
分类名称 <span aria-hidden='true'>*</span>
</label>
<Input
id='website-category-name'
aria-required='true'
aria-invalid={Boolean(categoryMessage)}
aria-describedby={
categoryMessage ? 'website-category-name-error' : undefined
}
aria-label='分类名称'
value={categoryDraft?.name || ''}
maxLength={12}
placeholder='请输入分类名称,最多 12 个字符'
validateStatus={categoryMessage ? 'error' : 'default'}
onChange={(name) => {
setCategoryDraft((previous) => ({ ...previous, name }));
setCategoryMessage('');
}}
onEnterPress={saveCategory}
/>
{categoryMessage && (
<Typography.Text
id='website-category-name-error'
type='danger'
role='alert'
>
{categoryMessage}
</Typography.Text>
)}
</div>
</Modal>
{article && (
<ArticleEditor
initial={article}
insights={value}
onApply={applyArticle}
onClose={() => setArticle(null)}
/>
)}
</div>
);
}
+138
View File
@@ -0,0 +1,138 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useRef, useState } from 'react';
import { Button, Image, Typography } from '@douyinfe/semi-ui';
import { Upload } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { showError } from '../../helpers';
import { validateImageFile } from './model';
import { uploadWebsiteQrCode } from './settingsApi';
export default function QrCodeUpload({
value,
onChange,
busy,
onBusyChange,
resetVersion,
invalid,
}) {
const { t } = useTranslation();
const inputRef = useRef(null);
const requestVersion = useRef(0);
const [uploading, setUploading] = useState(false);
useEffect(() => {
requestVersion.current += 1;
setUploading(false);
onBusyChange(false);
if (inputRef.current) inputRef.current.value = '';
return () => {
requestVersion.current += 1;
onBusyChange(false);
};
}, [resetVersion, onBusyChange]);
const upload = async (event) => {
const file = event.target.files?.[0];
event.target.value = '';
if (!file) return;
const error = validateImageFile(file);
if (error) {
showError(t(error));
return;
}
const version = ++requestVersion.current;
setUploading(true);
onBusyChange(true);
try {
// Verify the content is decodable, rather than trusting the filename or MIME alone.
try {
const bitmap = await createImageBitmap(file);
bitmap.close();
} catch {
throw new Error(
'无法读取二维码图片,请选择有效的 JPG、PNG 或 WebP 图片',
);
}
if (version !== requestVersion.current) return;
const url = await uploadWebsiteQrCode(file);
if (version === requestVersion.current) onChange(url);
} catch (err) {
if (version === requestVersion.current)
showError(t(err.message || '二维码上传失败,请选择有效图片后重试'));
} finally {
if (version === requestVersion.current) {
setUploading(false);
onBusyChange(false);
}
}
};
return (
<div
className='flex flex-wrap items-center gap-4 rounded-lg border border-dashed p-4'
style={{
borderColor: invalid
? 'var(--semi-color-danger)'
: 'var(--semi-color-border)',
background: 'var(--semi-color-fill-0)',
}}
>
{value ? (
<div className='relative inline-flex'>
<Image
src={value}
width={100}
height={100}
style={{ objectFit: 'contain' }}
alt={t('企业微信二维码')}
/>
</div>
) : (
<Upload size={28} className='m-4 text-[var(--semi-color-text-2)]' />
)}
<div className='flex flex-col gap-2'>
<input
ref={inputRef}
type='file'
accept='image/jpeg,image/png,image/webp'
onChange={upload}
hidden
/>
<Button
icon={<Upload size={14} />}
loading={uploading}
disabled={busy || uploading}
onClick={() => inputRef.current?.click()}
>
{t(value ? '重新上传' : '上传二维码')}
</Button>
<Typography.Text type='tertiary' size='small'>
{t('支持 JPG、PNG、WebP,单张不超过 2 MB')}
</Typography.Text>
{value && (
<Typography.Text type='tertiary' size='small'>
{t('点击图片可放大预览')}
</Typography.Text>
)}
</div>
</div>
);
}
+106
View File
@@ -0,0 +1,106 @@
# 官网设置接入说明
二维码使用后端上传与 HTTP(S) 绝对地址校验,缩略图支持放大预览和替换。
## 单一表单数据
首页、关于微词元、预约演示、动态与洞察共用一个配置对象,切换页签保留输入。
teamMembers 在两个页签共用,不生成不同的副本。原有 11 个字段均必填。
动态与洞察绑定 insights 对象,包含 categories 和 articles,不按页签拆分保存。
model.js 定义字段、页签、初始化、标准化和校验规则。
保存按首页、关于微词元、预约演示、动态与洞察顺序校验全部字段,错误保存在各表单项内。
空输入框提示“请输入中文字段名”,选择框提示“请选择中文字段名”,二维码提示“请上传企业微信二维码”。
每个非当前页签有错误时只显示一条“请完善某页签的配置”警告,不列出全部字段,不自动切换页签。
当前页签只显示表单项错误;切换页签后,其他页签的错误状态仍会显示。
清空会清除全部字段、二维码、错误状态,同时让尚未完成的上传结果失效。
## 读取与保存接口
进入页面 GET /api/website/page-config,解析 data 字符串并回填所有页签。
data 为 null 时回填空表单。读取失败可重试,成功前禁止编辑和保存,避免覆盖原配置。
保存 POST /api/website/page-config,请求为 { config: JSON.stringify(完整配置) }。
config 内部按 home/about/demo 分组;动态与洞察保存在 insights 扩展字段。
paidCustomers/dailyTokens/costReduction 分别映射 home.payingCustomers/dailyTokenCalls/monthlyAiCostReduction。
teamMembers/researchRatio 映射 about.teamMembers/researchStaffRatio;首页和关于页共用这两个值。
其余总部、服务网络和商务字段依联调文档映射。保存保留后端返回的未知字段。
严格检查 success === true 后才提示成功,失败保留当前编辑。提交期间防止重复请求。
完整配置按 UTF-8 字节限制为 60 KiB,超限时提示精简内容。
客户数和人数支持正整数及末尾 +;Token 支持正数、万/亿单位及末尾 +。
百分比支持 0~100,最多两位小数,% 可选。上述展示值以字符串提交。
## 二维码上传
复用客服模块 POST /api/customer-service/upload,multipart 字段 file。
期望响应 { success: true, data: { url: "https://公共资源域名/图片路径" } }。
前端限制 JPG/PNG/WebP、0~2 MB(不含 0),并在上传前尝试解码图片。
上传返回 HTTP(S) 绝对 URL 后才写入表单,可预览和替换。
切换页签或清空会使旧上传回调失效。
如果接口返回 /uploads/...,配置 VITE_WEBSITE_ASSET_BASE_URL 为公开资源域名;
禁止用开发代理地址、blob: 或 data: 地址作为提交资源路径。
绝对 URL 只保证地址形式正确,后端还需要保证图片无需后台登录即可被官网访问,
并在 HTTPS 官网部署时提供 HTTPS 图片地址。需在联调时通过未登录环境验证。
清空只移除配置引用,不删除服务器文件,文件回收由后端确定。
管理接口复用项目 API 实例的登录 Cookie 和 New-Api-User,401 沿用重新登录流程。
## 验证
```sh
node --test src/pages/WebsiteSettings/*.test.js src/components/common/ui/richTextImages.test.js
```
## 动态与洞察
InsightsPanel.jsx 承载分类管理、文章列表、标题/摘要即时搜索和分类筛选。
搜索为纯前端模糊匹配,不请求后端;不设分页,展示当前筛选后的全部文章。
ArticleEditor.jsx 承载文章新增/编辑抽屉,ArticleRichEditor.jsx 复用公共 RichTextEditor。
公共组件位于 src/components/common/ui/RichTextEditor.jsx,基于 Quill 2.0.3 core 封装,按需注册所用格式。
上游项目:https://github.com/slab/quill,BSD-3-Clause 许可;直接封装核心,不额外依赖 React 适配包。
支持 H2/H3、加粗、斜体、下划线、无序/有序列表、引用、撤销/重做、清除格式和图片。
工具栏采用独立的中性样式,避免项目 primary 按钮全局渐变影响编辑工具和选中状态。
默认保留公司动态、产品更新、行业洞察三个分类,文章为空,不向官网注入原型示例文章。
单篇文章结构:
```json
{
"id": "由前端生成的 UUID,后续可替换为后端 ID",
"title": "文章标题",
"category": "all",
"date": "2026-10-31",
"subtitle": "详情副标题,空值时由官网使用 summary",
"summary": "卡片摘要",
"tag": "NEW",
"body": "<h2>章节标题</h2><p>文章正文</p>",
"toc": true,
"related": []
}
```
必填:title(最多 80 字)、category、date、summary(最多 200 字)、body。
subtitle 最多 160 字,tag 最多 12 字,推荐最多 3 篇且不能选择自己。
正文 H2/H3 自动生成目录预览;toc 为是否展示目录,官网可从 body 提取标题。
“全部内容”是内置默认归属(category 为 all),也汇总展示所有分类的文章,不存入自定义 categories 数组。
新增文章默认归属当前分类,从全部内容新增时直接归属 all;自定义分类为空时也可新增文章。
分类名称最多 12 字,禁止空白、重名和系统保留名称;已有文章的自定义分类不能直接删除,可先迁移到全部内容。
删除文章同步清理其他文章的 related 引用。列表按发布日期倒序排列。
文章抽屉“保存”、分类编辑与文章删除只更新当前内存配置,不请求后端保存接口。
页面底部“保存”统一校验四个页签后,将整个配置序列化为 JSON 字符串调用 saveWebsiteSettings。
保存成功后刷新会从后端回填;文章抽屉内保存仅更新本地,仍需点击页面底部保存。
文章抽屉必填项错误只在字段内提示,不弹出汇总错误 Toast;不提供封面字段。
正文支持复制/粘贴 HTML 图文、剪贴板图片文件,以及工具栏选择本地图片。
HTTP(S) 图片保留绝对地址;JPG/PNG/WebP/GIF 内嵌图片每张限制 2 MB,
本地文件先解码校验,编辑期间使用 Base64 data URI;页面最终保存前上传到图片接口,将 body 中的图片替换为公开 URL。
相同内嵌图片在一次保存中仅上传一次;上传失败终止配置保存并保留本地内容。
二维码仍走原后端上传接口并强制 HTTP(S) 绝对地址,与文章内嵌图片分开处理。
HTML 在粘贴、编辑输出、应用文章时均进行白名单清理,不保留事件属性、脚本或 SVG 图片。
使用 getSemanticHTML 导出标准 HTML 列表,无需官网额外依赖 Quill 的 CSS 或 Delta 数据结构。
不可访问的外链图片会在编辑器内提示,需换为可公开访问的地址或插入本地文件。
不抓取第三方图片,无法自动绕过防盗链、登录权限及浏览器的混合内容限制。
后端正式接入时仍应进行服务端 HTML 清理(允许受限的图片 data URI)与权限校验,
官网 CSP 如有 img-src 白名单,需允许 data: 和所用图片域名。
@@ -0,0 +1,63 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React from 'react';
import { Form, Input } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { FIELDS } from './model';
export default function WebsiteField({
name,
value,
error,
onChange,
onBlur,
disabled,
children,
}) {
const { t } = useTranslation();
const field = FIELDS[name];
return (
<Form.Slot
label={{ text: t(field.label), required: true, name: `website-${name}` }}
error={{
error: error ? t(error) : undefined,
errorMessageId: `website-${name}-error`,
}}
>
{children || (
<Input
id={`website-${name}`}
aria-label={t(field.label)}
aria-required={true}
aria-invalid={Boolean(error)}
aria-describedby={error ? `website-${name}-error` : undefined}
value={value}
onChange={onChange}
onBlur={onBlur}
disabled={disabled}
placeholder={t(field.placeholder)}
validateStatus={error ? 'error' : 'default'}
maxLength={name === 'businessEmail' ? 254 : 200}
showClear
/>
)}
</Form.Slot>
);
}
@@ -0,0 +1,264 @@
.website-settings-page {
display: flex;
flex-direction: column;
box-sizing: border-box;
/* Match Settings: 24px layout padding + 8px page padding on each side. */
padding-inline: 32px;
min-height: calc(100vh - var(--content-top-offset, 0px));
min-height: calc(100dvh - var(--content-top-offset, 0px));
/* PageLayout already inserts the marquee spacer above this page. */
padding-top: calc(
var(--app-header-height, 64px) - var(--content-top-offset, 0px) + 20px
);
padding-bottom: 20px;
}
.website-settings-page .website-settings-card {
flex: 1;
min-height: 100%;
}
.website-settings-page .website-settings-notice .semi-banner-icon {
margin-right: 4px;
}
.website-insights {
min-width: 0;
}
.website-settings-page .website-settings-tab-description {
margin-bottom: 16px;
line-height: 22px;
}
.website-category-dialog-description {
margin: 0 0 18px;
line-height: 22px;
}
.website-category-dialog-field {
display: flex;
flex-direction: column;
gap: 8px;
padding-bottom: 8px;
}
.website-category-dialog-label {
color: var(--semi-color-text-0);
font-weight: 600;
line-height: 20px;
}
.website-category-dialog-label > span {
color: var(--semi-color-danger);
}
.website-insights-categories {
margin-bottom: 20px;
}
.website-insights-category-list,
.website-insights-category,
.website-insights-toolbar,
.website-insights-manage-row,
.website-insights-editor-footer,
.website-rich-tools {
display: flex;
align-items: center;
gap: 8px;
}
.website-insights-category-list,
.website-rich-tools,
.website-insights-editor-footer {
flex-wrap: wrap;
}
.website-insights-category {
border: 1px solid var(--semi-color-border);
border-radius: var(--semi-border-radius-small);
gap: 0;
background: var(--semi-color-fill-0);
min-height: 34px;
padding-inline: 2px;
}
.website-insights-category.is-selected {
border-color: var(--semi-color-primary-light-active);
background: var(--semi-color-primary-light-default);
}
.website-insights-category .semi-button {
background: transparent !important;
border: 0 !important;
border-radius: 3px !important;
box-shadow: none !important;
}
.website-insights-category > .semi-button .semi-button-content {
display: flex;
align-items: center;
gap: 10px;
color: var(--semi-color-text-1);
font-weight: 400;
}
.website-insights-category.is-selected > .semi-button .semi-button-content {
color: var(--semi-color-primary);
}
.website-insights-category-count {
font-size: 12px;
opacity: 0.65;
}
.website-insights-category-actions {
display: flex;
visibility: hidden;
}
.website-insights-category-actions .semi-button {
width: 24px;
height: 24px;
padding: 4px;
}
.website-insights-category .semi-button:hover {
background: var(--semi-color-fill-1) !important;
}
.website-insights-category:hover .website-insights-category-actions,
.website-insights-category:focus-within .website-insights-category-actions {
visibility: visible;
}
.website-insights-toolbar {
flex-wrap: wrap;
margin-bottom: 16px;
}
.website-insights-toolbar > .semi-input-wrapper {
width: 290px;
max-width: 100%;
}
.website-insights-toolbar > .semi-select {
width: 160px;
}
.website-insights-toolbar > .semi-button {
margin-left: auto;
}
.website-insights-article-meta {
display: grid;
gap: 4px;
min-width: 0;
}
.website-insights .website-insights-title {
display: block;
width: 100%;
padding: 0;
border: 0;
border-radius: 0;
background: transparent;
color: var(--semi-color-text-0);
font-weight: 500;
line-height: 1.6;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: left;
cursor: pointer;
}
.website-insights .website-insights-title:hover {
color: var(--semi-color-primary);
}
.website-insights .website-insights-title:focus-visible {
outline: 2px solid var(--semi-color-primary);
outline-offset: 2px;
}
.website-insights-manage-row {
padding-block: 10px;
border-bottom: 1px solid var(--semi-color-border);
}
.website-insights-manage-row > span:first-child {
flex: 1;
}
.website-insights-editor-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) 250px;
gap: 24px;
}
.website-insights-editor-main {
min-width: 0;
}
.website-insights-editor-main .website-insights-section-title {
margin: 0 0 14px;
line-height: 24px;
}
.website-insights-editor-main .website-insights-detail-title {
margin-top: 10px;
}
/* SideSheet renders outside Form, so its slots need their own field spacing. */
.website-insights-editor-main .website-insights-editor-field {
min-width: 0;
margin: 0 0 18px;
padding: 0;
}
.website-insights-editor-field > .semi-form-field-label {
margin-bottom: 8px;
}
.website-insights-aside,
.website-insights-related {
display: flex;
flex-direction: column;
gap: 16px;
}
.website-insights-related {
max-height: 260px;
overflow-y: auto;
}
.website-insights-toc {
margin-top: 12px;
line-height: 1.8;
overflow-wrap: anywhere;
}
.website-insights-editor-footer {
justify-content: flex-end;
}
@media (max-width: 767px) {
.website-settings-page {
/* Match the shared mobile layout's 5px plus the page's 8px. */
padding-inline: 13px;
}
.website-insights-editor-layout {
grid-template-columns: minmax(0, 1fr);
}
.website-insights-category-actions {
visibility: visible;
}
.website-insights-toolbar > .semi-input-wrapper {
width: 100%;
}
}
+285
View File
@@ -0,0 +1,285 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useRef, useState } from 'react';
import {
Banner,
Button,
Card,
Form,
Spin,
Tabs,
Typography,
} from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { showError, showSuccess, showWarning } from '../../helpers';
import {
TABS,
emptySettings,
settingsFromConfig,
serializeSettings,
validateField,
validateSettings,
} from './model';
import { getWebsiteSettings, saveWebsiteSettings } from './settingsApi';
import WebsiteField from './WebsiteField';
import QrCodeUpload from './QrCodeUpload';
import InsightsPanel from './InsightsPanel';
import './WebsiteSettings.css';
export default function WebsiteSettings() {
const { t } = useTranslation();
const [activeTab, setActiveTab] = useState('home');
const [values, setValues] = useState(emptySettings);
const [errors, setErrors] = useState({});
const [saving, setSaving] = useState(false);
const [uploading, setUploading] = useState(false);
const [resetVersion, setResetVersion] = useState(0);
const [dirty, setDirty] = useState(false);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState('');
const [loadVersion, setLoadVersion] = useState(0);
const originalConfig = useRef({});
const savePending = useRef(false);
useEffect(() => {
let active = true;
setLoading(true);
setLoadError('');
getWebsiteSettings()
.then((config) => {
if (!active) return;
originalConfig.current = config ?? {};
setValues(settingsFromConfig(config));
setDirty(false);
setErrors({});
})
.catch((error) => {
if (active)
setLoadError(error.message || '官网配置读取失败,请稍后重试');
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, [loadVersion]);
const disabled = saving || loading || Boolean(loadError);
useEffect(() => {
if (!dirty) return;
const warn = (event) => {
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [dirty]);
const tab = TABS.find((item) => item.key === activeTab);
const change = (name, value) => {
setDirty(true);
setValues((previous) => ({ ...previous, [name]: value }));
setErrors((previous) =>
previous[name]
? { ...previous, [name]: validateField(name, value) }
: previous,
);
};
const clear = () => {
setDirty(true);
setResetVersion((version) => version + 1);
setValues(emptySettings());
setErrors({});
setUploading(false);
};
const save = async () => {
if (savePending.current || disabled || uploading) return;
const nextErrors = validateSettings(values);
setErrors(nextErrors);
if (Object.keys(nextErrors).length) {
// Keep field errors for every tab; report each hidden invalid tab only once.
for (const item of TABS) {
if (
item.key !== activeTab &&
item.fields.some((name) => nextErrors[name])
) {
showWarning(t(`请完善${item.label}的配置`));
}
}
return;
}
savePending.current = true;
setSaving(true);
try {
const configurationJson = serializeSettings(
values,
originalConfig.current,
);
const result = await saveWebsiteSettings(configurationJson);
originalConfig.current = result.config ?? JSON.parse(configurationJson);
setValues(settingsFromConfig(originalConfig.current));
setDirty(false);
showSuccess(t('官网设置已保存'));
} catch (error) {
showError(t(error.message || '保存失败,请稍后重试'));
} finally {
setSaving(false);
savePending.current = false;
}
};
return (
<div className='website-settings-page' aria-busy={loading || saving}>
<Spin
spinning={loading || saving}
size='large'
style={{
minHeight: 200,
width: '100%',
flex: 1,
display: 'flex',
flexDirection: 'column',
}}
childStyle={{ flex: 1, display: 'flex', flexDirection: 'column' }}
data-testid='website-settings-loading'
>
<Card className='website-settings-card'>
<Typography.Title heading={4} style={{ marginBottom: 8 }}>
{t('官网设置')}
</Typography.Title>
<Typography.Paragraph type='tertiary'>
{t('配置官网展示内容与商务联系信息')}
</Typography.Paragraph>
{loadError ? (
<Banner
type='danger'
closeIcon={null}
description={t(loadError)}
fullMode={false}
>
<Button onClick={() => setLoadVersion((version) => version + 1)}>
{t('重新加载')}
</Button>
</Banner>
) : null}
<Tabs type='line' activeKey={activeTab} onChange={setActiveTab}>
{TABS.map((item) => (
<Tabs.TabPane
key={item.key}
itemKey={item.key}
tab={t(item.label)}
/>
))}
</Tabs>
<Form
onSubmit={save}
className={activeTab === 'insights' ? 'py-5' : 'max-w-4xl py-5'}
autoComplete='off'
>
<Typography.Paragraph
type='tertiary'
className='website-settings-tab-description'
>
{t(tab.description)}
</Typography.Paragraph>
{activeTab === 'insights' ? (
<InsightsPanel
key={resetVersion}
value={values.insights}
onChange={(value) => change('insights', value)}
disabled={disabled}
error={errors.insights}
/>
) : (
<div className='grid grid-cols-1 gap-x-7 md:grid-cols-2'>
{tab.fields.map((name) => (
<div
key={name}
className={name === 'address' ? 'md:col-span-2' : ''}
>
<WebsiteField
name={name}
value={values[name]}
error={errors[name]}
disabled={disabled}
onChange={(value) => change(name, value)}
onBlur={() =>
setErrors((previous) => ({
...previous,
[name]: validateField(name, values[name]),
}))
}
>
{name === 'wechatQrCode' && (
<QrCodeUpload
value={values.wechatQrCode}
onChange={(url) => change(name, url)}
busy={disabled}
onBusyChange={setUploading}
resetVersion={resetVersion}
invalid={Boolean(errors[name])}
/>
)}
</WebsiteField>
{activeTab === 'home' && name === 'teamMembers' && (
<Typography.Text type='tertiary' size='small'>
{t('研发人员占比')}:
{values.researchRatio || t('未配置')}
</Typography.Text>
)}
</div>
))}
</div>
)}
<Banner
type='info'
closeIcon={null}
className='website-settings-notice !rounded-lg'
style={{
marginTop: 10,
marginBottom: 2,
paddingTop: 2,
paddingBottom: 2,
}}
description={t('四个页签共用一份配置,保存时将统一校验并提交。')}
/>
<div
className='flex justify-center gap-2'
style={{ marginTop: 18 }}
>
<Button onClick={clear} disabled={disabled}>
{t('清空')}
</Button>
<Button
theme='solid'
htmlType='submit'
loading={saving}
disabled={disabled || uploading}
>
{t('保存')}
</Button>
</div>
</Form>
</Card>
</Spin>
</div>
);
}
@@ -0,0 +1,32 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { sanitizeArticleHtml } from '../../components/common/ui/richTextContent.js';
import { countRichText } from '../../components/common/ui/richTextLength.js';
export { sanitizeArticleHtml };
export function articleContentInfo(html) {
const template = document.createElement('template');
template.innerHTML = sanitizeArticleHtml(html);
return {
count: countRichText(template.content.textContent),
headings: [...template.content.querySelectorAll('h2,h3')]
.map((h) => ({ level: h.tagName, text: h.textContent.trim() }))
.filter((h) => h.text),
};
}
+201
View File
@@ -0,0 +1,201 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { articleImageSource } from '../../components/common/ui/richTextImages.js';
import {
ARTICLE_BODY_LIMIT,
countArticleHtml,
} from '../../components/common/ui/richTextLength.js';
export const emptyInsights = () => ({
categories: [
{ id: 'company', name: '公司动态' },
{ id: 'product', name: '产品更新' },
{ id: 'industry', name: '行业洞察' },
],
articles: [],
});
export function createContentId() {
// randomUUID requires HTTPS; getRandomValues also works on HTTP admin sites.
return (
globalThis.crypto.randomUUID?.() ??
Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)), (byte) =>
byte.toString(16).padStart(2, '0'),
).join('')
);
}
export function categoryError(name, categories, id) {
const value = String(name ?? '').trim();
if (!value) return '请输入分类名称';
if (value.length > 12) return '分类名称不能超过 12 个字符';
if (
['全部内容', '全部分类'].includes(value) ||
categories.some((c) => c.id !== id && c.name === value)
)
return '分类名称已存在,请使用其他名称';
return '';
}
export function newArticle(category = 'all') {
const now = new Date();
const date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
return {
id: '',
title: '',
category,
date,
subtitle: '',
summary: '',
tag: '',
body: '',
toc: true,
related: [],
};
}
export function articleErrors(article, insights) {
const errors = {};
for (const [key, label, limit, required] of [
['title', '文章标题', 80, true],
['summary', '卡片摘要', 200, true],
['subtitle', '详情副标题', 160, false],
['tag', '角标标签', 12, false],
]) {
const text = String(article[key] ?? '').trim();
if (required && !text) errors[key] = `请输入${label}`;
else if (text.length > limit)
errors[key] = `${label}不能超过 ${limit} 个字符`;
}
if (
article.category !== 'all' &&
!insights.categories.some((c) => c.id === article.category)
)
errors.category = '请选择所属分类';
const date = String(article.date ?? '');
if (
!/^\d{4}-\d{2}-\d{2}$/.test(date) ||
!Number.isFinite(Date.parse(date)) ||
new Date(date).toISOString().slice(0, 10) !== date
)
errors.date = date ? '请选择有效的发布日期' : '请选择发布日期';
const body = String(article.body ?? '');
if (
!body.replace(/<[^>]*>/g, '').replace(/&nbsp;|&#160;|\s/g, '') &&
!/<img\s/i.test(body)
)
errors.body = '请输入文章正文';
else if (countArticleHtml(body) > ARTICLE_BODY_LIMIT)
errors.body = `文章正文不能超过 ${ARTICLE_BODY_LIMIT} 字`;
if (
/<(?:script|style|iframe|object|svg|math)\b|\son\w+\s*=|(?:javascript|blob):/i.test(
body,
) ||
[...body.matchAll(/<img\b[^>]*\bsrc\s*=\s*["']([^"']*)["'][^>]*>/gi)].some(
(match) => !articleImageSource(match[1]),
)
)
errors.body = '正文包含不支持的内容,请清除格式后重试';
if (
!Array.isArray(article.related) ||
article.related.length > 3 ||
new Set(article.related).size !== article.related.length ||
article.related.some(
(id) => id === article.id || !insights.articles.some((a) => a.id === id),
)
)
errors.related = '最多选择 3 篇有效的其他文章';
return errors;
}
export function normalizeInsights(value) {
const data = value ?? emptyInsights();
return {
...data,
categories: (data.categories || []).map((c) => ({
...c,
id: String(c.id),
name: String(c.name ?? '').trim(),
})),
articles: (data.articles || []).map((a) => ({
...a,
...Object.fromEntries(
[
'id',
'title',
'category',
'date',
'subtitle',
'summary',
'tag',
'body',
].map((key) => [key, String(a[key] ?? '').trim()]),
),
toc: a.toc !== false,
related: [...(a.related || [])],
})),
};
}
export function validateInsights(value) {
if (!value) return '';
if (!Array.isArray(value.categories) || !Array.isArray(value.articles))
return '动态与洞察配置格式不正确';
const { categories, articles } = value;
if (
categories.some(
(c) =>
!c?.id || c.id === 'all' || categoryError(c.name, categories, c.id),
) ||
new Set(categories.map((c) => c.id)).size !== categories.length
)
return '请检查内容分类配置';
if (new Set(articles.map((a) => a?.id)).size !== articles.length)
return '文章标识不能重复';
for (const article of articles) {
if (!article?.id) return '文章标识不能为空';
const errors = articleErrors(article, value);
if (Object.keys(errors).length)
return `${article.title || '未命名文章'}:${Object.values(errors)[0]}`;
}
return '';
}
export function removeArticle(insights, id) {
return {
...insights,
articles: insights.articles
.filter((a) => a.id !== id)
.map((a) => ({
...a,
related: a.related.filter((other) => other !== id),
})),
};
}
export function filterArticles(insights, keyword, category) {
const query = keyword.trim().toLocaleLowerCase();
return insights.articles
.filter(
(a) =>
(category === 'all' || a.category === category) &&
`${a.title} ${a.summary}`.toLocaleLowerCase().includes(query),
)
.sort((a, b) => b.date.localeCompare(a.date));
}
+291
View File
@@ -0,0 +1,291 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { isLocalQrPreview } from './qrPreview.js';
import {
emptyInsights,
normalizeInsights,
validateInsights,
} from './insightsModel.js';
export const TABS = [
{
key: 'home',
label: '首页',
description: '配置官网首页展示的核心指标。',
fields: ['paidCustomers', 'dailyTokens', 'costReduction', 'teamMembers'],
},
{
key: 'about',
label: '关于微词元',
description: '配置官网关于微词元区域展示的团队与服务信息。',
fields: ['teamMembers', 'researchRatio', 'headquarters', 'serviceNetwork'],
},
{
key: 'demo',
label: '预约演示',
description: '配置官网预约演示区域的联系信息,便于客户直接联系商务团队。',
fields: ['businessPhone', 'businessEmail', 'wechatQrCode', 'address'],
},
{
key: 'insights',
label: '动态与洞察',
description: '管理官网文章与内容分类,让每一次更新清晰可见。',
fields: ['insights'],
},
];
export const FIELDS = {
paidCustomers: {
label: '付费企业客户',
placeholder: '请输入付费企业客户数量,例如 300+',
help: '正整数,可带 +。',
},
dailyTokens: {
label: '平台日均 Token 调用',
placeholder: '请输入平台日均 Token 调用量,例如 500亿+',
help: '支持正数及万、亿单位,可带 +。',
},
costReduction: {
label: '客户月度 AI 调用成本',
placeholder: '请输入成本降幅,例如 20%',
help: '填写 0~100 的百分比,官网可展示为 ↓20%。',
},
teamMembers: {
label: '团队成员',
placeholder: '请输入团队成员数量,例如 50+',
help: '首页与关于微词元共用此字段,正整数,可带 +。',
},
researchRatio: {
label: '研发人员占比',
placeholder: '请输入研发人员占比,例如 60%',
help: '填写 0~100 的百分比。',
},
headquarters: {
label: '总部',
placeholder: '请输入总部所在地,例如 珠海 / 广州',
},
serviceNetwork: {
label: '服务网络',
placeholder: '请输入服务网络覆盖范围,例如 辐射全国',
},
businessPhone: {
label: '商务电话',
placeholder: '请输入手机号、固定电话或 400 电话',
help: '例如 13800138000、020-88888888、400-123-4567。',
},
businessEmail: {
label: '商务邮箱',
placeholder: '请输入商务联系邮箱,例如 business@example.com',
},
wechatQrCode: { label: '企业微信' },
address: { label: '联系地址', placeholder: '请输入详细联系地址' },
insights: { label: '动态与洞察' },
};
export const emptySettings = () =>
Object.fromEntries(
Object.keys(FIELDS).map((key) => [
key,
key === 'insights' ? emptyInsights() : '',
]),
);
const PHONE =
/^(?:(?:\+?86[- ]?)?1[3-9]\d{9}|0\d{2,3}-?\d{7,8}(?:[-转]\d{1,6})?|400-?\d{3}-?\d{4})$/;
const EMAIL =
/^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+$/;
export function isAbsoluteImageUrl(value) {
try {
const url = new URL(value);
return (
['http:', 'https:'].includes(url.protocol) &&
!url.username &&
!url.password
);
} catch {
return false;
}
}
export function validateField(key, rawValue) {
if (key === 'insights') return validateInsights(rawValue);
const value = String(rawValue ?? '').trim();
if (!value)
return key === 'wechatQrCode'
? '请上传企业微信二维码'
: `请输入${FIELDS[key].label}`;
if (
['paidCustomers', 'teamMembers'].includes(key) &&
!/^[1-9]\d*\+?$/.test(value)
)
return '请输入正整数,可在末尾添加 +';
if (
key === 'dailyTokens' &&
(!/^\d+(?:\.\d+)?[万亿]?\+?$/.test(value) || parseFloat(value) <= 0)
)
return '请输入大于 0 的调用量,例如 500亿+';
if (
['costReduction', 'researchRatio'].includes(key) &&
(!/^\d+(?:\.\d{1,2})?%?$/.test(value) || parseFloat(value) > 100)
)
return '请输入 0~100 的百分比,最多两位小数';
if (key === 'businessPhone' && !PHONE.test(value))
return '请输入有效的手机号、固定电话或 400 电话';
if (
key === 'businessEmail' &&
(value.length > 254 ||
!EMAIL.test(value) ||
value.split('@')[0].includes('..') ||
/^\.|\.$/.test(value.split('@')[0]))
)
return '请输入有效的商务邮箱';
if (
key === 'wechatQrCode' &&
!isAbsoluteImageUrl(value) &&
!isLocalQrPreview(value)
)
return '请上传二维码并获取有效的 HTTP(S) 绝对地址';
if (value.length > 200 && key !== 'wechatQrCode' && key !== 'businessEmail')
return '内容不能超过 200 个字符';
return '';
}
export function validateSettings(values) {
return Object.fromEntries(
[...new Set(TABS.flatMap((tab) => tab.fields))]
.map((key) => [key, validateField(key, values[key])])
.filter(([, error]) => error),
);
}
export function normalizeSettings(values) {
return Object.fromEntries(
Object.keys(FIELDS).map((key) => [
key,
key === 'insights'
? normalizeInsights(values[key])
: String(values[key] ?? '').trim(),
]),
);
}
export function serializeSettings(values, original = {}) {
return JSON.stringify(settingsToConfig(values, original));
}
const CONFIG_FIELDS = {
home: {
paidCustomers: 'payingCustomers',
dailyTokens: 'dailyTokenCalls',
costReduction: 'monthlyAiCostReduction',
},
about: {
teamMembers: 'teamMembers',
researchRatio: 'researchStaffRatio',
headquarters: 'headquarters',
serviceNetwork: 'serviceNetwork',
},
demo: {
businessPhone: 'businessPhone',
businessEmail: 'businessEmail',
wechatQrCode: 'wechatQrCode',
address: 'address',
},
};
export function settingsFromConfig(config) {
const values = emptySettings();
if (config === null) return values;
if (!config || typeof config !== 'object' || Array.isArray(config))
throw new Error('官网配置格式不正确,请联系管理员检查');
for (const [group, fields] of Object.entries(CONFIG_FIELDS)) {
if (
config[group] !== undefined &&
(!config[group] ||
typeof config[group] !== 'object' ||
Array.isArray(config[group]))
)
throw new Error('官网配置分组格式不正确,请联系管理员检查');
for (const [field, apiField] of Object.entries(fields)) {
const value = config[group]?.[apiField];
if (value !== undefined && typeof value !== 'string')
throw new Error('官网配置字段格式不正确,请联系管理员检查');
values[field] = value ?? '';
}
}
if (config.insights !== undefined) {
if (
!config.insights ||
!Array.isArray(config.insights.categories) ||
!Array.isArray(config.insights.articles)
)
throw new Error('动态与洞察配置格式不正确,请联系管理员检查');
try {
values.insights = normalizeInsights(config.insights);
} catch {
throw new Error('动态与洞察配置格式不正确,请联系管理员检查');
}
}
return values;
}
export function settingsToConfig(values, original = {}) {
const normalized = normalizeSettings(values);
const config = { ...original };
for (const [group, fields] of Object.entries(CONFIG_FIELDS)) {
config[group] = {
...original?.[group],
...Object.fromEntries(
Object.entries(fields).map(([field, apiField]) => [
apiField,
normalized[field],
]),
),
};
}
config.insights = normalized.insights;
return config;
}
export function validateImageFile(file) {
if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type))
return '仅支持 JPG、PNG、WebP 图片';
if (!file.size || file.size > 2 * 1024 * 1024)
return '图片大小需大于 0 且不能超过 2 MB';
return '';
}
export function resolveImageUrl(value, publicBaseUrl = '') {
if (isAbsoluteImageUrl(value)) return new URL(value).href;
// A dev proxy origin is not a public asset host. Only use an explicitly configured base.
if (
publicBaseUrl &&
isAbsoluteImageUrl(publicBaseUrl) &&
typeof value === 'string' &&
value.startsWith('/') &&
!value.startsWith('//')
) {
return new URL(value, publicBaseUrl).href;
}
throw new Error(
'上传接口未返回可供官网使用的绝对图片地址,请配置公共资源域名或联系后端。',
);
}
+40
View File
@@ -0,0 +1,40 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// Local preview is disabled; uploads use the backend resource endpoint.
export const LOCAL_QR_PREVIEW_ENABLED = false;
export function isLocalQrPreview(value) {
return (
LOCAL_QR_PREVIEW_ENABLED &&
/^data:image\/(?:jpeg|png|webp);base64,(?:[A-Za-z0-9+/]{4})+(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(
value,
)
);
}
export function readLocalQrPreview(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(new Error('图片读取失败,请重新选择'));
reader.onabort = () => reject(new Error('图片读取已取消,请重新选择'));
reader.readAsDataURL(file);
});
}
+119
View File
@@ -0,0 +1,119 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { requestWebsite } from '../../helpers/websiteApi';
import { articleImageSource } from '../../components/common/ui/richTextImages';
import {
resolveImageUrl,
settingsFromConfig,
validateImageFile,
validateSettings,
} from './model';
export async function uploadWebsiteQrCode(file) {
return uploadWebsiteImage(file);
}
export async function uploadWebsiteImage(file) {
const error = validateImageFile(file);
if (error) throw new Error(error);
return uploadImage(file);
}
async function uploadImage(file) {
const body = new FormData();
body.append('file', file);
const data = await requestWebsite(
'post',
'/api/customer-service/upload',
body,
'图片上传失败,请重试',
);
if (!data?.url) throw new Error('上传接口未返回图片地址,请重试');
return resolveImageUrl(
data.url,
import.meta.env.VITE_WEBSITE_ASSET_BASE_URL || '',
);
}
export async function saveWebsiteSettings(configurationJson) {
if (typeof configurationJson !== 'string')
throw new Error('官网设置需序列化为 JSON 字符串后提交');
const payload = JSON.parse(configurationJson);
if (Object.keys(validateSettings(settingsFromConfig(payload))).length)
throw new Error('请完整填写并检查官网设置');
// Existing article editors keep local images in memory; persist URLs in the public config.
const uploaded = new Map();
for (const article of payload.insights?.articles || []) {
const images = [
...article.body.matchAll(
/<img\b[^>]*\bsrc\s*=\s*["'](data:image\/[^"']+)["'][^>]*>/gi,
),
];
for (const [, source] of images) {
if (!articleImageSource(source))
throw new Error('文章中包含无效图片,请重新插入');
if (!uploaded.has(source)) {
const [meta, encoded] = source.split(',');
const type = meta.slice(5).split(';')[0];
const bytes = Uint8Array.from(atob(encoded), (char) =>
char.charCodeAt(0),
);
const file = new File([bytes], `article.${type.split('/')[1]}`, {
type,
});
uploaded.set(source, await uploadImage(file));
}
article.body = article.body.replaceAll(
source,
uploaded.get(source).replaceAll('&', '&amp;'),
);
}
}
configurationJson = JSON.stringify(payload);
if (new TextEncoder().encode(configurationJson).byteLength > 60 * 1024)
throw new Error('官网配置不能超过 60 KiB,请精简内容或减少图片');
await requestWebsite(
'post',
'/api/website/page-config',
{ config: configurationJson },
'官网设置保存失败,请稍后重试',
);
return { saved: true, config: payload };
}
export async function getWebsiteSettings() {
const data = await requestWebsite(
'get',
'/api/website/page-config',
undefined,
'官网配置读取失败,请稍后重试',
);
if (data === null) return null;
if (typeof data !== 'string') throw new Error('官网配置响应格式不正确');
let config;
try {
config = JSON.parse(data);
} catch {
throw new Error('官网配置不是有效的 JSON,请联系管理员检查');
}
if (config === null) throw new Error('官网配置格式不正确');
settingsFromConfig(config);
return config;
}