Files
monkey-ai-web/src/pages/WebsiteSettings/model.js
T

297 lines
9.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
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,
key === 'insights' && !values.insights?.articles?.length
? '请完善动态与洞察的配置'
: 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(
'上传接口未返回可供官网使用的绝对图片地址,请配置公共资源域名或联系后端。',
);
}