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

This commit is contained in:
zhanjunhao
2026-10-31 19:02:58 +08:00
parent 7b80c3bbb3
commit 1bf13bc226
54 changed files with 4898 additions and 203 deletions
+88
View File
@@ -0,0 +1,88 @@
/*
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 { Card, Input, Tag, Typography } from '@douyinfe/semi-ui';
import { CalendarDays, Globe } from 'lucide-react';
import { useTranslation } from 'react-i18next';
export default function AdminMenuPreview({ type }) {
const { t } = useTranslation();
const isWebsite = type === 'website';
const Icon = isWebsite ? Globe : CalendarDays;
const title = isWebsite ? t('官网设置') : t('预约演示');
return (
<div className='mt-[60px] px-2 pb-6 md:px-4'>
<div className='mb-6 flex flex-wrap items-center gap-3'>
<Icon size={28} className='text-blue-500' />
<Typography.Title heading={3} style={{ margin: 0 }}>
{title}
</Typography.Title>
<Tag color='blue'>{t('功能预览')}</Tag>
</div>
<Typography.Paragraph type='tertiary'>
{t('当前为示例内容,仅用于预览页面,暂未接入数据保存。')}
</Typography.Paragraph>
{isWebsite ? (
<Card title={t('官网基础信息')}>
<div className='grid max-w-3xl gap-5 md:grid-cols-2'>
{[
[t('网站名称'), t('Monkey AI 官网')],
[t('官网地址'), 'https://www.example.com'],
[t('首页标题'), t('让 AI 为业务创造更多价值')],
[t('联系邮箱'), 'contact@example.com'],
].map(([label, value]) => (
<label key={label} className='flex flex-col gap-2'>
<span>{label}</span>
<Input value={value} readOnly />
</label>
))}
</div>
</Card>
) : (
<Card title={t('预约演示列表')}>
<div className='overflow-x-auto'>
<table className='w-full min-w-[560px] text-left text-sm'>
<thead>
<tr className='border-b border-[var(--semi-color-border)]'>
{['联系人', '企业名称', '演示需求', '状态'].map((label) => (
<th key={label} className='px-3 py-3 font-medium'>
{t(label)}
</th>
))}
</tr>
</thead>
<tbody>
<tr>
<td className='px-3 py-4'>{t('示例联系人')}</td>
<td className='px-3 py-4'>{t('示例科技有限公司')}</td>
<td className='px-3 py-4'>{t('企业 AI 应用演示')}</td>
<td className='px-3 py-4'>
<Tag color='orange'>{t('待联系')}</Tag>
</td>
</tr>
</tbody>
</table>
</div>
</Card>
)}
</div>
);
}
+26
View File
@@ -0,0 +1,26 @@
# 预约演示列表
页面复用 CardPro、CardTable、CompactModeToggle 和 createCardProPagination。
桌面端搜索栏靠左,移动端沿用系统的操作区展开和卡片展示方式。
## 已接入接口
GET /api/website/demo-requests,通过项目共享 API 实例发送 Cookie 和 New-Api-User。
不再使用本地演示列表。业务 success 必须严格为 true,否则显示后端 message 或错误提示。
筛选字段:name、contact、companyName,去除首尾空白并以 URLSearchParams 编码。
模糊搜索由后端执行,三个条件为 AND。请求分页为 p 和 page_size;
响应读取 data.items、data.total、data.page 和 data.page_size。
查询、重置和切换每页条数回到第一页;翻页保留已提交的筛选条件。
页面忽略过期请求结果,错误时清空表格并显示错误原因。
公司名称与需求分别使用 companyName 和 requirement,不使用原型字段 company/requirements。
需求列表最多显示三行,保留内部换行,不提供查看完整需求按钮或弹窗。
## 模拟提交与验收
本地脚本 scripts/seed-demo-requests.mjs 默认仅预览,添加 --submit 才真实新增三条联调测试预约。
页面初始化不会新增数据。脚本和测试文件已加入 Git 忽略规则。
运行 npm run test:e2e 验证桌面与移动端交互;npm run test:e2e:report 查看本地报告。
完整验收要求见 docs/website-api-acceptance.md,模拟接口验收与真实服务验收分别记录。
+294
View File
@@ -0,0 +1,294 @@
/*
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, useMemo, useRef, useState } from 'react';
import {
Banner,
Button,
Empty,
Form,
Select,
Spin,
Typography,
} from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import CardPro from '../../components/common/ui/CardPro';
import CardTable from '../../components/common/ui/CardTable';
import CompactModeToggle from '../../components/common/ui/CompactModeToggle';
import {
IllustrationNoResult,
IllustrationNoResultDark,
} from '../../components/common/illustrations';
import { createCardProPagination } from '../../helpers/utils';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import { useTableCompactMode } from '../../hooks/common/useTableCompactMode';
import { fetchDemoReservations } from './reservationsApi';
const EMPTY_FILTERS = { name: '', contact: '', companyName: '' };
export default function DemoReservations() {
const { t } = useTranslation();
const isMobile = useIsMobile();
const [compactMode, setCompactMode] =
useTableCompactMode('demo-reservations');
const formRef = useRef(null);
const [query, setQuery] = useState({
...EMPTY_FILTERS,
page: 1,
pageSize: 10,
});
const [result, setResult] = useState({ items: [], total: 0 });
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
useEffect(() => {
let active = true;
setLoading(true);
setError('');
fetchDemoReservations(query)
.then((data) => {
if (active) setResult(data);
})
.catch((error) => {
if (active) {
setError(error.message || '预约信息加载失败,请重新查询');
setResult({ items: [], total: 0 });
}
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, [query]);
const columns = useMemo(
() =>
[
['name', '姓名', 100],
['contact', '联系方式', 210],
['companyName', '公司名称', 180],
['position', '职位', 140],
['industry', '行业', 160],
['interest', '关注方向', 190],
['requirement', '需求', 360],
].map(([dataIndex, title, width]) => ({
title: t(title),
dataIndex,
key: dataIndex,
...(compactMode ? {} : { width }),
render: (value) =>
dataIndex === 'requirement' && value ? (
<div>
<span
style={{
display: '-webkit-box',
WebkitLineClamp: 3,
WebkitBoxOrient: 'vertical',
overflow: 'hidden',
overflowWrap: 'anywhere',
whiteSpace: 'pre-wrap',
}}
>
{value}
</span>
</div>
) : (
<span style={{ overflowWrap: 'anywhere', whiteSpace: 'pre-wrap' }}>
{value || '—'}
</span>
),
})),
[t, compactMode],
);
const reset = () => {
formRef.current?.reset();
setQuery((previous) => ({
...EMPTY_FILTERS,
page: 1,
pageSize: previous.pageSize,
}));
};
const changePageSize = (pageSize) =>
setQuery((previous) => ({ ...previous, page: 1, pageSize }));
const pagination = createCardProPagination({
currentPage: result.page ?? query.page,
pageSize: result.page_size ?? query.pageSize,
total: result.total,
onPageChange: (page) => setQuery((previous) => ({ ...previous, page })),
onPageSizeChange: changePageSize,
preventPageChangeOnPageSizeChange: true,
isMobile,
t,
});
return (
<div className='mt-[60px] px-2' aria-busy={loading}>
<Spin
spinning={loading}
size='large'
style={{ minHeight: 200, width: '100%' }}
data-testid='demo-reservations-loading'
>
<CardPro
type='type1'
t={t}
descriptionArea={
<div className='flex w-full flex-col items-start justify-between gap-2 md:flex-row md:items-center'>
<div>
<Typography.Title heading={4} style={{ marginBottom: 8 }}>
{t('预约演示')}
</Typography.Title>
<Typography.Text type='tertiary' size='small'>
{t('查看官网访客提交的预约信息,支持模糊查询与分页。')}
</Typography.Text>
</div>
<CompactModeToggle
compactMode={compactMode}
setCompactMode={setCompactMode}
t={t}
/>
</div>
}
actionsArea={
<div className='flex w-full justify-start'>
<Form
initValues={EMPTY_FILTERS}
getFormApi={(api) => (formRef.current = api)}
onSubmit={(values) =>
setQuery((previous) => ({
name: (values.name || '').trim(),
contact: (values.contact || '').trim(),
companyName: (values.companyName || '').trim(),
page: 1,
pageSize: previous.pageSize,
}))
}
allowEmpty
autoComplete='off'
layout='horizontal'
className='w-full md:w-auto'
>
<div className='flex w-full flex-col items-center gap-2 md:w-auto md:flex-row'>
{[
['name', '请输入姓名'],
['contact', '请输入联系方式'],
['companyName', '请输入公司名称'],
].map(([field, placeholder]) => (
<div key={field} className='w-full md:w-44'>
<Form.Input
field={field}
aria-label={t(placeholder)}
placeholder={t(placeholder)}
showClear
pure
size='small'
maxLength={254}
/>
</div>
))}
<div className='flex w-full gap-2 md:w-auto'>
<Button
type='tertiary'
htmlType='submit'
loading={loading}
size='small'
className='flex-1 md:flex-initial'
>
{t('查询')}
</Button>
<Button
type='tertiary'
onClick={reset}
size='small'
className='flex-1 md:flex-initial'
>
{t('重置')}
</Button>
</div>
</div>
</Form>
</div>
}
paginationArea={
isMobile && result.total > 0 ? (
<div className='flex w-full flex-col items-center gap-3'>
<div className='flex items-center gap-3'>
<Typography.Text type='tertiary'>
{t('共')} {result.total} {t('条')}
</Typography.Text>
<Select
aria-label={t('每页条数')}
size='small'
value={result.page_size ?? query.pageSize}
onChange={changePageSize}
optionList={[10, 20, 50, 100].map((value) => ({
value,
label: `${value} ${t('条/页')}`,
}))}
/>
</div>
{pagination}
</div>
) : (
pagination
)
}
>
{error && (
<Banner
type='danger'
closeIcon={null}
description={t(error)}
className='mb-4'
/>
)}
<CardTable
rowKey='id'
columns={columns}
dataSource={result.items}
scroll={compactMode ? undefined : { x: 'max-content' }}
hidePagination
className='overflow-hidden'
size='middle'
empty={
<Empty
image={
<IllustrationNoResult style={{ width: 150, height: 150 }} />
}
darkModeImage={
<IllustrationNoResultDark
style={{ width: 150, height: 150 }}
/>
}
description={t(
error ? '预约信息加载失败' : '暂无符合条件的预约信息',
)}
style={{ padding: 30 }}
/>
}
/>
</CardPro>
</Spin>
</div>
);
}
@@ -0,0 +1,54 @@
/*
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';
export async function fetchDemoReservations({
name = '',
contact = '',
companyName = '',
page = 1,
pageSize = 10,
} = {}) {
const params = new URLSearchParams({
name: name.trim(),
contact: contact.trim(),
companyName: companyName.trim(),
p: String(page),
page_size: String(pageSize),
});
const data = await requestWebsite(
'get',
`/api/website/demo-requests?${params}`,
undefined,
'预约信息加载失败,请重新查询',
);
if (
!data ||
!Array.isArray(data.items) ||
!Number.isInteger(data.total) ||
data.total < 0 ||
!Number.isInteger(data.page) ||
data.page < 1 ||
!Number.isInteger(data.page_size) ||
data.page_size < 1
)
throw new Error('预约列表响应格式不正确,请联系管理员检查');
return data;
}
@@ -16,26 +16,20 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useEffect, useState, useRef } from 'react';
import React, { useContext, useEffect, useState, useRef } from 'react';
import { Banner, Button, Card, Checkbox, Form, Spin } from '@douyinfe/semi-ui';
import { API, isRoot, showError, showSuccess } from '../../../helpers';
import { useTranslation } from 'react-i18next';
import { DELEGATABLE_SETTING_TABS } from '../../../constants/settingTabs';
const OPTION_KEY = 'AdminDelegatedSettingTabs';
function parseTabs(raw) {
if (!raw) return [];
try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : [];
} catch (e) {
return [];
}
}
import {
ADMIN_DELEGATION_OPTIONS,
ADMIN_DELEGATION_OPTION_KEY as OPTION_KEY,
} from '../../../constants/settingTabs';
import { parseAdminDelegation } from '../../../helpers/adminDelegation';
import { StatusContext } from '../../../context/Status';
export default function SettingsAdminDelegation(props) {
const { t } = useTranslation();
const [statusState, statusDispatch] = useContext(StatusContext);
const [loading, setLoading] = useState(false);
const [selected, setSelected] = useState([]);
const [savedRaw, setSavedRaw] = useState('');
@@ -44,7 +38,7 @@ export default function SettingsAdminDelegation(props) {
useEffect(() => {
const raw = props.options?.[OPTION_KEY] ?? '';
setSavedRaw(raw);
const tabs = parseTabs(raw);
const tabs = parseAdminDelegation(raw);
setSelected(tabs);
refForm.current?.setValues({ [OPTION_KEY]: tabs });
}, [props.options]);
@@ -56,7 +50,7 @@ export default function SettingsAdminDelegation(props) {
function onSubmit() {
const value = JSON.stringify(selected);
if (value === JSON.stringify(parseTabs(savedRaw))) {
if (value === JSON.stringify(parseAdminDelegation(savedRaw))) {
showSuccess(t('保存成功'));
return;
}
@@ -65,6 +59,11 @@ export default function SettingsAdminDelegation(props) {
.then((res) => {
const { success, message } = res.data;
if (success) {
setSavedRaw(value);
statusDispatch({
type: 'set',
payload: { ...statusState?.status, [OPTION_KEY]: value },
});
showSuccess(t('保存成功'));
props.refresh?.();
} else {
@@ -91,7 +90,7 @@ export default function SettingsAdminDelegation(props) {
<Banner
type='warning'
description={t(
'勾选后,普通管理员(非超级管理员)将能够看到并编辑这些系统设置 Tab。请谨慎下放含密钥的页面(如系统设置、支付设置、数据安全)。未勾选的 Tab 仍仅超级管理员可见。',
'勾选后,普通管理员(非超级管理员)将能够访问对应的系统设置 Tab 或管理页面,菜单同步按权限显示。请谨慎下放含密钥的页面(如系统设置、支付设置、数据安全)。未勾选的项目仍仅超级管理员可访问。',
)}
bordered
fullMode={false}
@@ -102,9 +101,15 @@ export default function SettingsAdminDelegation(props) {
field={OPTION_KEY}
noLabel
direction='horizontal'
onChange={(value) => setSelected(value)}
onChange={(value) => {
const unknown = parseAdminDelegation(savedRaw).filter(
(key) =>
!ADMIN_DELEGATION_OPTIONS.some((item) => item.key === key),
);
setSelected([...new Set([...unknown, ...value])]);
}}
>
{DELEGATABLE_SETTING_TABS.map((tab) => (
{ADMIN_DELEGATION_OPTIONS.map((tab) => (
<Checkbox key={tab.key} value={tab.key}>
{t(tab.labelKey)}
</Checkbox>
@@ -404,7 +404,7 @@ export default function SettingsHeaderNavModules(props) {
minHeight: '80px',
}}
bodyStyle={{ padding: '16px' }}
hoverable
shadows='hover'
>
<div
style={{
@@ -558,7 +558,7 @@ export default function SettingsHeaderNavModules(props) {
minHeight: '80px',
}}
bodyStyle={{ padding: '16px' }}
hoverable
shadows='hover'
>
<div
style={{
@@ -636,7 +636,7 @@ export default function SettingsHeaderNavModules(props) {
minHeight: '80px',
}}
bodyStyle={{ padding: '16px' }}
hoverable
shadows='hover'
>
<div
style={{
@@ -168,7 +168,7 @@ export default function SettingsOrgUserNavModules(props) {
minHeight: '64px',
}}
bodyStyle={{ padding: '16px' }}
hoverable
shadows='hover'
>
<div
style={{
@@ -695,7 +695,7 @@ export default function SettingsSidebarModulesAdmin(props) {
<Col key={module.key} xs={24} sm={12} md={8} lg={6} xl={6}>
<Card
bodyStyle={{ padding: '16px' }}
hoverable
shadows='hover'
style={{
opacity: sectionConfig.enabled ? 1 : 0.5,
transition: 'opacity 0.2s',
@@ -26,6 +26,7 @@ import {
showError,
showSuccess,
showWarning,
toBoolean,
} from '../../../helpers';
// InputNumber 清空时 onChange 会收到 ''/null,parseInt 得到 NaN,
@@ -76,12 +77,11 @@ export default function SettingsSkillInject(props) {
useEffect(() => {
const currentInputs = {};
for (const key in DEFAULTS) {
currentInputs[key] = Object.prototype.hasOwnProperty.call(
props.options,
key,
)
const value = Object.prototype.hasOwnProperty.call(props.options, key)
? props.options[key]
: DEFAULTS[key];
currentInputs[key] =
typeof DEFAULTS[key] === 'boolean' ? toBoolean(value) : value;
}
setInputs(currentInputs);
setInputsRow(structuredClone(currentInputs));
+52 -36
View File
@@ -17,13 +17,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, {
useContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import {
Button,
Card,
@@ -136,7 +130,8 @@ const TOKEN_GROUPS = [
{
key: 'bg',
labelKey: '页面背景晕染(大面积底色 / 光晕)',
descKey: '影响 user-center、experience 等页面的整页背景渲染与动态光晕,不影响按钮气泡',
descKey:
'影响 user-center、experience 等页面的整页背景渲染与动态光晕,不影响按钮气泡',
},
{
key: 'accent',
@@ -286,7 +281,8 @@ export default function SettingsTheme(props) {
() => ({ ...getEffectivePreset(selectedPreset).dark, ...customDark }),
[selectedPreset, customDark, presetOverridesState],
);
const effectivePalette = colorMode === 'light' ? effectiveLight : effectiveDark;
const effectivePalette =
colorMode === 'light' ? effectiveLight : effectiveDark;
// 任何编辑都即时前端预览(不写 cache)。
// 注意:必须等首次 props 解析完成再开启预览,否则挂载瞬间会用 default state
@@ -553,10 +549,9 @@ export default function SettingsTheme(props) {
setPresetOverrides(payload);
setPresetOverridesState(nextOverrides);
setPresetDraft({});
applyTheme(
JSON.stringify({ preset: editingPresetKey }),
{ persist: false },
);
applyTheme(JSON.stringify({ preset: editingPresetKey }), {
persist: false,
});
statusDispatch({
type: 'set',
payload: { ...(statusState?.status || {}), theme_presets: payload },
@@ -624,9 +619,11 @@ export default function SettingsTheme(props) {
const cleanLight = sanitizeImportedTokens(cfg.lightTokens);
const cleanDark = sanitizeImportedTokens(cfg.darkTokens);
const droppedLight =
Object.keys(cfg.lightTokens || {}).length - Object.keys(cleanLight).length;
Object.keys(cfg.lightTokens || {}).length -
Object.keys(cleanLight).length;
const droppedDark =
Object.keys(cfg.darkTokens || {}).length - Object.keys(cleanDark).length;
Object.keys(cfg.darkTokens || {}).length -
Object.keys(cleanDark).length;
setSelectedPreset(presetKey);
setCustomLight(cleanLight);
setCustomDark(cleanDark);
@@ -769,9 +766,7 @@ export default function SettingsTheme(props) {
colorMode={colorMode}
setColorMode={setColorMode}
palette={effectivePalette}
customOverrides={
colorMode === 'light' ? customLight : customDark
}
customOverrides={colorMode === 'light' ? customLight : customDark}
onChange={handleTokenChange}
onResetToken={handleTokenReset}
onCopyToOther={handleCopyToOther}
@@ -863,7 +858,7 @@ function PresetGrid({
return (
<Col key={key} xs={24} sm={12} md={8}>
<Card
hoverable
shadows='hover'
onClick={() => onSelect(key)}
style={{
cursor: 'pointer',
@@ -926,7 +921,10 @@ function PresetGrid({
)}
</Title>
{isSaved && (
<Text size='small' style={{ color: 'var(--semi-color-primary)' }}>
<Text
size='small'
style={{ color: 'var(--semi-color-primary)' }}
>
{t('已应用')}
</Text>
)}
@@ -1015,19 +1013,13 @@ function PresetTemplateEditor({
/>
</div>
<div style={{ display: 'flex', gap: 8, marginTop: 16, alignItems: 'center' }}>
<Button
type='primary'
theme='solid'
loading={saving}
onClick={onSave}
>
<div
style={{ display: 'flex', gap: 8, marginTop: 16, alignItems: 'center' }}
>
<Button type='primary' theme='solid' loading={saving} onClick={onSave}>
{t('保存预设模板')}
</Button>
<Button
disabled={!isEdited || saving}
onClick={onRestore}
>
<Button disabled={!isEdited || saving} onClick={onRestore}>
{t('恢复此预设出厂')}
</Button>
</div>
@@ -1053,7 +1045,14 @@ function CustomEditor({
return (
<>
{/* 基础预设选择(决定未覆盖 token 的兜底值) */}
<div style={{ marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8 }}>
<div
style={{
marginBottom: 12,
display: 'flex',
alignItems: 'center',
gap: 8,
}}
>
<Text type='secondary' size='small'>
{t('基础预设:')}
</Text>
@@ -1115,7 +1114,9 @@ function CustomEditor({
<Button
size='small'
onClick={onDeriveToDark}
title={t('按 deriveDarkTokens 规则自动调亮,与编辑预设模板的派生逻辑一致')}
title={t(
'按 deriveDarkTokens 规则自动调亮,与编辑预设模板的派生逻辑一致',
)}
>
{t('派生到深色(自动调亮)')}
</Button>
@@ -1148,7 +1149,13 @@ function GroupedTokenList({ palette, isCustomOf, onChange, onReset, t }) {
}}
>
<div style={{ marginBottom: 6, padding: '0 4px' }}>
<div style={{ fontSize: 12, fontWeight: 600, color: 'var(--semi-color-text-1)' }}>
<div
style={{
fontSize: 12,
fontWeight: 600,
color: 'var(--semi-color-text-1)',
}}
>
{t(g.labelKey)}
</div>
<Text type='tertiary' size='small' style={{ fontSize: 11 }}>
@@ -1186,7 +1193,12 @@ function TokenRow({ label, desc, value, isCustom, onChange, onReset }) {
const alphaPct = valid ? Math.round(c.alpha() * 100) : 100;
// colord.toHex():alpha=1 → 6 位,alpha<1 → 8 位,天然兼容存储格式
const emit = (hex, pct) => onChange(colord(hex).alpha(pct / 100).toHex());
const emit = (hex, pct) =>
onChange(
colord(hex)
.alpha(pct / 100)
.toHex(),
);
return (
<div
@@ -1259,7 +1271,11 @@ function TokenRow({ label, desc, value, isCustom, onChange, onReset }) {
step={1}
value={alphaPct}
onChange={(e) => emit(rgbHex, Number(e.target.value))}
style={{ flex: 1, accentColor: 'var(--brand-primary)', cursor: 'pointer' }}
style={{
flex: 1,
accentColor: 'var(--brand-primary)',
cursor: 'pointer',
}}
aria-label={`${label} alpha`}
/>
<span
+4 -7
View File
@@ -22,6 +22,7 @@ import { Layout, TabPane, Tabs } from '@douyinfe/semi-ui';
import { useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { StatusContext } from '../../context/Status';
import { getDelegatedSettingTabs } from '../../helpers/adminDelegation';
import {
ALWAYS_ADMIN_VISIBLE_TABS,
ROOT_ONLY_SETTING_TABS,
@@ -264,13 +265,9 @@ const Setting = () => {
}
// 解析 root 配置的「下放给普通管理员」tab 列表
let delegatedTabs = [];
try {
const raw = statusState?.status?.AdminDelegatedSettingTabs;
if (raw) delegatedTabs = JSON.parse(raw);
} catch (e) {
delegatedTabs = [];
}
const delegatedTabs = getDelegatedSettingTabs(
statusState?.status?.AdminDelegatedSettingTabs,
);
// 可见性过滤:root 看全部;普通管理员看「会员管理 + 被下放的 tab」;其余看不到。
if (!isRoot()) {
+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;
}