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

312 lines
9.8 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.
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'],
},
];
// Metric fields store plain numbers; the official site renders "+", "%", "万/亿" itself.
// kind: integer = positive integer, amount = positive number + 万/亿 unit, percent = 0~100.
export const FIELDS = {
paidCustomers: {
label: '付费企业客户',
placeholder: '请输入付费企业客户数量,例如 300',
metric: { kind: 'integer', suffix: '+' },
},
dailyTokens: {
label: '平台日均 Token 调用',
placeholder: '请输入调用量,例如 500',
metric: { kind: 'amount', suffix: '+' },
},
costReduction: {
label: '客户月度 AI 调用成本',
note: '降幅',
placeholder: '请输入成本降幅,例如 20',
metric: { kind: 'percent', suffix: '%', prefix: '↓' },
},
teamMembers: {
label: '团队成员',
note: '首页与“关于我们”共用',
placeholder: '请输入团队成员数量,例如 50',
metric: { kind: 'integer', suffix: '+' },
},
researchRatio: {
label: '研发人员占比',
placeholder: '请输入研发人员占比,例如 60',
metric: { kind: 'percent', suffix: '%' },
},
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 const AMOUNT_UNITS = ['万', '亿'];
export const DEFAULT_AMOUNT_UNIT = '亿';
// Typed or pasted numbers: full-width digits / dots become half-width, everything else is dropped.
export function sanitizeMetricInput(value) {
return String(value ?? '')
.replace(/[0-9]/g, (char) =>
String.fromCharCode(char.charCodeAt(0) - 0xfee0),
)
.replace(/[.。]/g, '.')
.replace(/[^\d.]/g, '');
}
// "500亿" -> { number: '500', unit: '亿' }; values without a unit keep the default unit.
export function splitAmount(value) {
const text = String(value ?? '').trim();
const unit = AMOUNT_UNITS.find((item) => text.endsWith(item));
return {
number: unit ? text.slice(0, -unit.length) : text,
unit: unit || DEFAULT_AMOUNT_UNIT,
};
}
export const joinAmount = (number, unit) => (number ? `${number}${unit}` : '');
// Text shown under a metric input, matching how the official site renders the value.
export function metricPreview(key, value) {
const metric = FIELDS[key]?.metric;
if (!metric || validateField(key, value)) return '';
const text = String(value).trim();
return `${metric.prefix || ''}${text}${metric.suffix}`;
}
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 '请输入大于 0 的整数';
if (
key === 'dailyTokens' &&
(!/^(?:0|[1-9]\d*)(?:\.\d{1,2})?[万亿]$/.test(value) ||
parseFloat(value) <= 0)
)
return '请输入大于 0 的数字,最多两位小数';
if (
['costReduction', 'researchRatio'].includes(key) &&
(!/^(?:0|[1-9]\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 '';
}
// An empty article list is valid: the official list page shows its "内容筹备中" empty state.
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(
'上传接口未返回可供官网使用的绝对图片地址,请配置公共资源域名或联系后端。',
);
}