663 lines
39 KiB
JavaScript
663 lines
39 KiB
JavaScript
// public-api.js — 给网站(Astro 构建)用的只读产品接口
|
||
// 位置:/opt/customer-crm/server/public-api.js
|
||
//
|
||
// 接入方法(server.js 里加三行,放在后台登录校验中间件之前):
|
||
// const mountPublicApi = require('./public-api');
|
||
// mountPublicApi(app, { dataFile: DATA_FILE, uploadsDir: UPLOADS_DIR, requireAuth,
|
||
// ai: { loadAiConfig, callDeepSeekWithRetry, extractJson } });
|
||
// ai:server.js 里现成的 DeepSeek 函数,用来把英文介绍/卖点自动翻译成其他语言(不传就不翻译,网站显示英文)。
|
||
// requireAuth = 现有的后台登录校验中间件,只用于"发布到网站"按钮那个接口。
|
||
// 如果 server.js 用的是 import 写法,把 require / module.exports 换成 import / export default。
|
||
//
|
||
// 配置项(环境变量或 site-config.json):
|
||
// SITE_BUILD_KEY 网站构建时携带的密钥(一串长随机字符)
|
||
// CF_DEPLOY_HOOK Cloudflare Pages 的 Deploy Hook 地址
|
||
// PUBLIC_BASE_URL https://b2b.google-helper.com
|
||
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
const crypto = require('crypto');
|
||
|
||
const PRODUCTS_KEY = 'crm:products';
|
||
|
||
// 白名单:对外字段名 → 产品记录里的字段名。
|
||
// 不在这里的字段一律不输出:costPrice、notes(含采购价)、id、productImageOriginalName 等。
|
||
const FIELDS = {
|
||
model: 'name',
|
||
brand: 'brand',
|
||
category: 'category',
|
||
type: 'type', // 中文值,如"迷你UPS",网站端按词典翻译
|
||
extraTypes: 'extraTypes', // 同时属于的其他细分品类(数组),网站上产品同时出现在这些栏目
|
||
machineVariant: 'machineVariant',// 中文值,如"标机"
|
||
outputPower: 'powerOrCapacity',
|
||
ratedPower: 'ratedPower',
|
||
ratedPowerUnit: 'ratedPowerUnit',
|
||
powerFactor: 'powerFactor',
|
||
inputVoltage: 'voltage',
|
||
outputPortCount: 'outputPortCount',
|
||
outputPorts: 'outputPorts', // [{ type, voltage, current }]
|
||
batterySpec: 'batterySpec',
|
||
dimensions: 'dimensions',
|
||
netWeight: 'netWeight',
|
||
extraSpecs: 'extraSpecs',
|
||
sellingPoints: 'sellingPoints',
|
||
// —— 以下是需要在产品表单里新增的字段 ——
|
||
youtube: 'youtubeUrl', // YouTube 链接,输出时只保留视频 ID
|
||
description: 'webDescription', // { en, es?, ru? }:只需填 en,其他语言自动翻译;手动填了的语言优先用手动的
|
||
sale: 'webSale',
|
||
// 箱规:产品关联的 Packing List(webPackId → crm:webPackSpecs);早期直接填在产品里的 webPack 作后备,见 toPublic // { mode: 'group'|'stock', stock, minPrice, maxPrice }
|
||
// —— 离线式 / 在线互动式 UPS 的参数(迷你UPS 一般不填,空的不输出)——
|
||
acInputVoltage: 'inputVoltage', // 离线式UPS 的输入电压(迷你UPS 用上面的 inputVoltage ← voltage)
|
||
inputVoltageRange: 'inputVoltageRange',
|
||
inputFrequency: 'inputFrequency',
|
||
outputVoltage: 'outputVoltage',
|
||
outputVoltageRange: 'outputVoltageRange',
|
||
transferTime: 'transferTime',
|
||
waveform: 'waveform',
|
||
frequencyRangeBatteryMode: 'frequencyRangeBatteryMode',
|
||
batteryVoltage: 'batteryVoltage',
|
||
chargeCurrent: 'chargeCurrent',
|
||
chargeTime: 'chargeTime',
|
||
lcdDisplay: 'lcdDisplay',
|
||
ledDisplay: 'ledDisplay',
|
||
fullProtection: 'fullProtection',
|
||
alarmInfo: 'alarmInfo',
|
||
interfacePort: 'interfacePort',
|
||
humidity: 'humidity',
|
||
noiseLevel: 'noiseLevel',
|
||
// —— 机架式 / 在线式 UPS 的参数 ——
|
||
phase: 'phase',
|
||
inputPowerFactor: 'inputPowerFactor',
|
||
transferTimeAcToBattery: 'transferTimeAcToBattery',
|
||
currentCrestRatio: 'currentCrestRatio',
|
||
harmonicDistortion: 'harmonicDistortion',
|
||
efficiencyAcMode: 'efficiencyAcMode',
|
||
efficiencyBatteryMode: 'efficiencyBatteryMode',
|
||
chargingVoltage: 'chargingVoltage',
|
||
optionalSnmp: 'optionalSnmp',
|
||
outputPowerFactor: 'outputPowerFactor',
|
||
parallelUnits: 'parallelUnits',
|
||
overload: 'overload',
|
||
// —— 模块化 UPS 的功率模块 ——
|
||
upsModuleCapacity: 'upsModuleCapacity',
|
||
upsModuleCount: 'upsModuleCount',
|
||
upsModuleDimensions: 'upsModuleDimensions',
|
||
upsModuleWeight: 'upsModuleWeight',
|
||
sockets: 'webSockets', // 网站展示的默认插座配置 [{ type: 'SCHUKO'|'NEMA'|'UK'|'UNIVERSAL'|'IEC'|'AU', count }]
|
||
};
|
||
const PUBLISH_FLAG = 'publishToWeb'; // 新增:"发布到网站"开关
|
||
const IMAGES_FIELD = 'webImages'; // 新增:主图文件名数组,最多 6 张;为空时用现有的 productImageFileName
|
||
const DETAIL_FIELD = 'webDetailImages'; // 新增:详情图文件名数组,最多 20 张,显示在规格表下方
|
||
const TEMPLATES_KEY = 'crm:webDetailTemplates'; // 详情模板:[{ id, name, kind: 'images'|'html', images: [文件名], html }],图片在 uploads/<模板id>/
|
||
const TEMPLATE_IDS_FIELD = 'webDetailTemplateIds'; // 产品引用的模板id,按顺序显示在详情图下方
|
||
// —— 网站管理(非产品内容)——
|
||
const SITE_ASSETS_KEY = 'crm:webAssets'; // { 图片位id: [文件名 或 { file, caption:{en,es?,ru?} }] },文件在 uploads/site_assets/
|
||
const SITE_ASSETS_DIR = 'site_assets';
|
||
const SITE_NEWS_KEY = 'crm:webNews'; // [{ id, date:'2025-12', title:{en,es?,ru?}, text:{en,es?,ru?}, youtubeUrl }]
|
||
|
||
// 配置:优先读环境变量,没有就读同目录下的 site-config.json(不用改进程启动方式)
|
||
// { "SITE_BUILD_KEY": "...", "CF_DEPLOY_HOOK": "...", "PUBLIC_BASE_URL": "https://b2b.google-helper.com" }
|
||
function conf(name) {
|
||
if (process.env[name]) return process.env[name];
|
||
try { return JSON.parse(fs.readFileSync(path.join(__dirname, 'site-config.json'), 'utf8'))[name] || ''; }
|
||
catch { return ''; }
|
||
}
|
||
|
||
// —— 自动翻译 ——
|
||
// 英文是源语言;这里列出要自动翻译出来的语言。以后加语言:这里加一项,网站 src/config.mjs 的 LANGS 也加上。
|
||
const WEB_TRANSLATE_LANGS = {
|
||
es: 'Latin American Spanish (neutral, for Venezuela/Colombia buyers; say "UPS", never "SAI")',
|
||
ru: 'Russian',
|
||
};
|
||
// 译文缓存:英文没改就不重复调用 DeepSeek(省钱、构建也快)。单独一个文件,不碰 data.json。
|
||
const TRANSLATION_CACHE_FILE = path.join(__dirname, 'web-translations.json');
|
||
const cacheKey = (lang, text) => crypto.createHash('sha256').update(lang + '\n' + text).digest('hex').slice(0, 32);
|
||
function loadCache() { try { return JSON.parse(fs.readFileSync(TRANSLATION_CACHE_FILE, 'utf8')); } catch { return {}; } }
|
||
function saveCache(c) {
|
||
const tmp = TRANSLATION_CACHE_FILE + '.tmp';
|
||
fs.writeFileSync(tmp, JSON.stringify(c));
|
||
fs.renameSync(tmp, TRANSLATION_CACHE_FILE);
|
||
}
|
||
|
||
async function translateBatch(ai, texts, langDesc, srcLang = 'English') {
|
||
const cfg = ai.loadAiConfig();
|
||
if (!cfg.apiKey) throw new Error('DeepSeek API key not configured');
|
||
const system = `You translate B2B product copy for a power-equipment manufacturer (UPS, mini UPS, batteries) from ${srcLang} into ${langDesc}.
|
||
Rules: keep model numbers, brand names, units and numbers exactly as written (e.g. POE-36E-LFP-48V, 24V/48V, 5000mAh, PoE, LiFePO4, USB, DC). Use natural commercial wording, not word-for-word.
|
||
Input is a JSON array of strings. Return ONLY a JSON array of the translated strings, same length and same order, no markdown, no extra text.`;
|
||
const content = await ai.callDeepSeekWithRetry(cfg.apiKey, [
|
||
{ role: 'system', content: system },
|
||
{ role: 'user', content: JSON.stringify(texts) },
|
||
], { maxTokens: 4000, temperature: 0.2 });
|
||
const { data } = ai.extractJson(content);
|
||
if (!Array.isArray(data) || data.length !== texts.length) throw new Error('translation result has wrong shape');
|
||
return data.map(String);
|
||
}
|
||
|
||
// 通用:把一批英文字符串翻译成各语言,返回 { lang: { 英文: 译文 } }(走同一个译文缓存)
|
||
async function translateStrings(ai, strings) {
|
||
const out = {};
|
||
for (const lang of Object.keys(WEB_TRANSLATE_LANGS)) out[lang] = {};
|
||
const uniq = [...new Set(strings.filter((x) => x && x.trim()))];
|
||
if (!uniq.length) return out;
|
||
const cache = loadCache();
|
||
let dirty = false;
|
||
if (ai) {
|
||
for (const [lang, langDesc] of Object.entries(WEB_TRANSLATE_LANGS)) {
|
||
const need = uniq.filter((t) => !cache[cacheKey(lang, t)]);
|
||
for (let i = 0; i < need.length; i += 20) {
|
||
const chunk = need.slice(i, i + 20);
|
||
try {
|
||
const res = await translateBatch(ai, chunk, langDesc);
|
||
chunk.forEach((src, j) => { cache[cacheKey(lang, src)] = res[j]; });
|
||
dirty = true;
|
||
} catch (e) { console.warn(`[public-api] 网站文字翻译成 ${lang} 失败:${e.message}`); }
|
||
}
|
||
}
|
||
}
|
||
if (dirty) { try { saveCache(cache); } catch (e) {} }
|
||
for (const lang of Object.keys(WEB_TRANSLATE_LANGS)) for (const t of uniq) if (cache[cacheKey(lang, t)]) out[lang][t] = cache[cacheKey(lang, t)];
|
||
return out;
|
||
}
|
||
|
||
// 参数值里带中文的(比如"8小时恢复到90%容量"、LCD 显示说明),自动翻译成英语 / 西语 / 俄语。
|
||
// 结果放在 specI18n: { 字段: { en, es, ru } },网站按语言取用;翻译失败的字段网站上不显示(不会露出中文)。
|
||
const SPEC_TRANSLATE_FIELDS = ['inputVoltage', 'acInputVoltage', 'inputVoltageRange', 'inputFrequency', 'outputVoltage', 'outputVoltageRange', 'transferTime', 'waveform',
|
||
'frequencyRangeBatteryMode', 'batteryVoltage', 'chargeCurrent', 'chargeTime', 'lcdDisplay', 'ledDisplay', 'fullProtection', 'alarmInfo', 'interfacePort',
|
||
'humidity', 'noiseLevel', 'outputPower', 'powerFactor', 'batterySpec', 'dimensions', 'netWeight',
|
||
'phase', 'inputPowerFactor', 'transferTimeAcToBattery', 'harmonicDistortion', 'efficiencyAcMode', 'efficiencyBatteryMode', 'chargingVoltage',
|
||
'optionalSnmp', 'outputPowerFactor', 'parallelUnits', 'overload'];
|
||
const ZH_TARGETS = { en: 'English', ...WEB_TRANSLATE_LANGS };
|
||
const hasZh = (s) => /[\u4e00-\u9fff]/.test(String(s || ''));
|
||
async function translateSpecs(ai, products) {
|
||
const need = new Set();
|
||
for (const p of products) for (const f of SPEC_TRANSLATE_FIELDS) if (typeof p[f] === 'string' && hasZh(p[f])) need.add(p[f]);
|
||
if (!need.size) return;
|
||
const cache = loadCache();
|
||
let dirty = false;
|
||
if (ai) {
|
||
for (const [lang, desc] of Object.entries(ZH_TARGETS)) {
|
||
const list = [...need].filter((t) => !cache[cacheKey('zh>' + lang, t)]);
|
||
for (let i = 0; i < list.length; i += 20) {
|
||
const chunk = list.slice(i, i + 20);
|
||
try {
|
||
const out = await translateBatch(ai, chunk, desc, 'Chinese');
|
||
chunk.forEach((src, j) => { cache[cacheKey('zh>' + lang, src)] = out[j]; });
|
||
dirty = true;
|
||
} catch (e) { console.warn(`[public-api] 参数翻译成 ${lang} 失败:${e.message}`); }
|
||
}
|
||
}
|
||
}
|
||
if (dirty) { try { saveCache(cache); } catch (e) {} }
|
||
for (const p of products) {
|
||
for (const f of SPEC_TRANSLATE_FIELDS) {
|
||
if (typeof p[f] !== 'string' || !hasZh(p[f])) continue;
|
||
const t = {};
|
||
for (const lang of Object.keys(ZH_TARGETS)) { const v = cache[cacheKey('zh>' + lang, p[f])]; if (v) t[lang] = v; }
|
||
if (Object.keys(t).length) (p.specI18n = p.specI18n || {})[f] = t;
|
||
}
|
||
}
|
||
}
|
||
|
||
// ===== HTML 详情模板 =====
|
||
// 模板 kind = 'html' 时,html 字段是一段 HTML(通常是系列参数表)。这里只做基础清理 + 翻译文字;
|
||
// 网站构建时会重新解析成表格 / 标题 / 列表,丢掉原文件的所有样式和不安全标签,统一用网站样式显示。
|
||
const HTML_ENTITIES = { nbsp: ' ', amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", plusmn: '±', deg: '°', times: '×', middot: '·', ndash: '–', mdash: '—', le: '≤', ge: '≥', micro: 'µ', ohm: 'Ω', hellip: '…', bull: '•', reg: '®', copy: '©', trade: '™' };
|
||
function decodeEntities(t) {
|
||
return String(t).replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e) => {
|
||
if (e[0] === '#') { const n = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10); return Number.isFinite(n) && n > 0 && n < 0x110000 ? String.fromCodePoint(n) : m; }
|
||
const k = e.toLowerCase();
|
||
return k in HTML_ENTITIES && k !== 'amp' && k !== 'lt' && k !== 'gt' ? HTML_ENTITIES[k] : m;
|
||
});
|
||
}
|
||
function cleanTplHtml(html) {
|
||
let h = String(html || '');
|
||
const body = h.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
|
||
if (body) h = body[1];
|
||
h = h.replace(/<!--[\s\S]*?-->/g, '')
|
||
.replace(/<(script|style|head|title|iframe|object|embed|noscript|template)[\s\S]*?<\/\1>/gi, '')
|
||
.replace(/<(script|style|link|meta|iframe|object|embed|base)[^>]*>/gi, '')
|
||
.replace(/\s*\[cite:[^\]]*\]/gi, ''); // AI 生成文件里常见的引用标记
|
||
return decodeEntities(h).trim();
|
||
}
|
||
// 标签之间的文字片段;纯型号 / 数值(有数字、没有小写字母,如 GS400BI MAX、12V7AH*2)不翻译
|
||
const shouldTranslateSeg = (t) => /[A-Za-z]{2,}/.test(t) && !(/\d/.test(t) && !/[a-z]/.test(t));
|
||
function htmlSegments(h) {
|
||
const out = [];
|
||
String(h).replace(/>([^<]+)</g, (m, t) => { const x = t.trim(); if (x && shouldTranslateSeg(x)) out.push(x); return m; });
|
||
return out;
|
||
}
|
||
const tplHtmlOf = (t) => (t && String(t.html || '').trim() ? cleanTplHtml(t.html) : '');
|
||
// HTML 内容可以有多段:htmls = [{ id, name, html }];旧数据只有一段 html,当作 id 为 h_main 的一段
|
||
const tplHtmlsOf = (t) => (!t ? [] : Array.isArray(t.htmls) ? t.htmls : String(t.html || '').trim() ? [{ id: 'h_main', html: t.html }] : [])
|
||
.filter((h) => h && String(h.html || '').trim());
|
||
// 详情图片里的 HTML 片段(原样显示,网站上放在隔离的 iframe 里):detailHtml = [{ id, html, pos }],pos = 排在第几张图后面(0 = 最上面)
|
||
const tplDetailBlocks = (t) => arr(t && t.detailHtml).filter((b) => b && String(b.html || '').trim());
|
||
// 同一模板下给某个型号去掉部分内容:modelExclude = { 产品id: { images: [文件名], blocks: [片段id], html: true } };没设置 = 全部都用
|
||
const exclOf = (t, p) => (t && t.modelExclude && p && t.modelExclude[p.id]) || {};
|
||
// 新的按型号选择:modelPick = { 产品id: { main?: [文件名,按点选顺序], images?: [文件名], blocks?: [片段id], html?: true/false } }
|
||
// 某一项有 = 只用点选的;没有 = 默认(全部,按模板顺序),再看旧的 modelExclude / mainCover
|
||
const pickOf = (t, p) => (t && t.modelPick && p && t.modelPick[p.id]) || {};
|
||
const tplImagesFor = (t, p) => {
|
||
const pk = pickOf(t, p).images;
|
||
if (Array.isArray(pk)) return tplImagesOf(t).filter((f) => pk.includes(f));
|
||
const ex = arr(exclOf(t, p).images); return tplImagesOf(t).filter((f) => !ex.includes(f));
|
||
};
|
||
const tplBlocksFor = (t, p) => {
|
||
const pk = pickOf(t, p).blocks;
|
||
if (Array.isArray(pk)) return tplDetailBlocks(t).filter((b) => pk.includes(b.id));
|
||
const ex = arr(exclOf(t, p).blocks); return tplDetailBlocks(t).filter((b) => !ex.includes(b.id));
|
||
};
|
||
// 某个型号用哪几段 HTML 内容:modelPick.htmls = [id](只用选中的);旧数据 html:true/false = 全部 / 不用;没设置 = 全部
|
||
const tplHtmlListFor = (t, p) => {
|
||
const all = tplHtmlsOf(t), pk = pickOf(t, p);
|
||
let list = all;
|
||
if (Array.isArray(pk.htmls)) list = all.filter((h) => pk.htmls.includes(h.id));
|
||
else if (pk.html === false || (pk.html !== true && exclOf(t, p).html)) list = [];
|
||
return list.map((h) => ({ id: h.id, html: cleanTplHtml(h.html) })).filter((h) => h.html);
|
||
};
|
||
// 详情图片 + HTML 片段的顺序:片段位置按模板里的原始图片序号算,去掉的图片 / 片段跳过
|
||
function tplDetailSeq(t, p) {
|
||
const all = tplImagesOf(t), keep = tplImagesFor(t, p), blocks = tplBlocksFor(t, p);
|
||
const out = [];
|
||
for (let i = 0; i <= all.length; i++) {
|
||
for (const b of blocks) if (Math.min(Math.max(0, Math.round(+b.pos || 0)), all.length) === i) out.push({ html: String(b.html).replace(/\s*\[cite:[^\]]*\]/gi, '') });
|
||
if (i < all.length && keep.includes(all[i])) out.push({ img: all[i] });
|
||
}
|
||
return out;
|
||
}
|
||
// 原样 HTML 的翻译:只翻译正文文字,<style> / <script> / <head> 里的内容原样保留
|
||
function rawHtmlParts(h) {
|
||
return String(h).split(/(<(?:style|script|head|svg)[\s\S]*?<\/(?:style|script|head|svg)>)/i);
|
||
}
|
||
function rawHtmlSegments(h) {
|
||
const out = [];
|
||
rawHtmlParts(h).forEach((part, i) => { if (i % 2 === 0) out.push(...htmlSegments(part)); });
|
||
return out;
|
||
}
|
||
function translateRawHtml(h, dict) {
|
||
return rawHtmlParts(h).map((part, i) => (i % 2 ? part : part.replace(/>([^<]+)</g, (m, raw) => {
|
||
const x = raw.trim(); const v = x && dict[x];
|
||
return v ? '>' + raw.replace(x, v.replace(/</g, '‹').replace(/>/g, '›')) + '<' : m;
|
||
}))).join('');
|
||
}
|
||
async function translateTemplateHtml(ai, products) {
|
||
const segs = [];
|
||
for (const p of products) for (const t of p.templateHtml || []) segs.push(...htmlSegments(t.html.en));
|
||
for (const p of products) for (const x of p.templateDetail || []) if (x.html) segs.push(...rawHtmlSegments(x.html.en));
|
||
if (!segs.length) return;
|
||
const tr = ai ? await translateStrings(ai, segs) : {};
|
||
for (const p of products) {
|
||
for (const x of p.templateDetail || []) {
|
||
if (!x.html) continue;
|
||
for (const lang of Object.keys(WEB_TRANSLATE_LANGS)) x.html[lang] = translateRawHtml(x.html.en, tr[lang] || {});
|
||
}
|
||
for (const t of p.templateHtml || []) {
|
||
for (const lang of Object.keys(WEB_TRANSLATE_LANGS)) {
|
||
const dict = tr[lang] || {};
|
||
t.html[lang] = t.html.en.replace(/>([^<]+)</g, (m, raw) => {
|
||
const x = raw.trim();
|
||
const v = x && dict[x];
|
||
return v ? '>' + raw.replace(x, v.replace(/</g, '‹').replace(/>/g, '›')) + '<' : m;
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// ===== 网站产品介绍:没手动填英文介绍的产品,由 AI 根据参数自动写一段 =====
|
||
// 参数变了会重新生成(缓存按参数内容算);手动填了英文介绍就一直用手动的。
|
||
const TYPE_EN = { '迷你UPS': 'Mini DC UPS', '离线式UPS': 'Offline UPS', '离线式锂电UPS': 'Lithium-ion offline UPS', '在线互动式UPS': 'Line-interactive UPS', '机架式UPS': 'Rack-mount online double-conversion UPS', '机架式锂电UPS': 'Lithium-ion rack-mount online double-conversion UPS', '模块化UPS': 'Modular online UPS with hot-swappable power modules', '机架式模块化UPS': 'Rack-mount modular online UPS with hot-swappable power modules' };
|
||
const DESC_SKIP = new Set(['model', 'brand', 'category', 'type', 'machineVariant', 'description', 'sale', 'youtube', 'sellingPoints', 'sockets', 'extraSpecs', 'pack']);
|
||
const SOCKET_EN = { SCHUKO: 'Schuko', NEMA: 'NEMA 5-15', UK: 'BS 1363 (UK)', UNIVERSAL: 'universal', IEC: 'IEC C13', AU: 'Type I (AU/CN)' };
|
||
function descFacts(p) {
|
||
const f = { model: p.model };
|
||
if (TYPE_EN[p.type]) f.type = TYPE_EN[p.type];
|
||
if ((p.type === '机架式UPS' || p.type === '机架式锂电UPS') && p.machineVariant) f.variant = /长/.test(p.machineVariant) ? 'Long-run model: no internal batteries, connects to an external battery bank' : 'Standard model with internal batteries';
|
||
for (const [k, v] of Object.entries(p)) {
|
||
if (DESC_SKIP.has(k) || k.startsWith('_') || ['slug', 'images', 'detailImages', 'templateImages', 'templateDetail', 'templateHtml', 'specI18n'].includes(k)) continue;
|
||
const en = p.specI18n && p.specI18n[k] && p.specI18n[k].en;
|
||
if (en) { f[k] = en; continue; }
|
||
if (typeof v === 'string' && v.trim() && !hasZh(v)) f[k] = v.trim();
|
||
else if (Array.isArray(v) && k === 'outputPorts') f[k] = v.map((o) => [o.type, o.voltage, o.current].filter(Boolean).join(' ')).filter((x) => !hasZh(x));
|
||
}
|
||
if (Array.isArray(p.sockets) && p.sockets.length) f.sockets = p.sockets.map((x) => `${x.count} x ${SOCKET_EN[x.type] || x.type}`).join(' + ');
|
||
if (p._points && p._points.length) f.sellingPoints = p._points;
|
||
return f;
|
||
}
|
||
async function generateDescriptions(ai, products) {
|
||
const todo = products.filter((p) => !(p.description && String(p.description.en || '').trim()));
|
||
if (!todo.length) return;
|
||
const cache = loadCache();
|
||
// 参数太少(只有型号、类型)不生成,免得 AI 编内容
|
||
const items = todo.map((p) => { const f = descFacts(p); const facts = JSON.stringify(f); return { p, facts, key: cacheKey('aidesc', facts), n: Object.keys(f).length }; }).filter((x) => x.n >= 4);
|
||
const need = items.filter((x) => !cache[x.key]);
|
||
let dirty = false;
|
||
if (ai && need.length) {
|
||
const cfg = ai.loadAiConfig();
|
||
if (cfg.apiKey) {
|
||
const system = `You write short product introductions for the B2B website of a Chinese UPS manufacturer that sells to importers and distributors.
|
||
For each product spec object, write 2-3 sentences (45-80 words), plain English text, no markdown, no line breaks.
|
||
Use ONLY facts present in the specs: never invent certifications, warranty, prices, runtime figures or features that are not given.
|
||
Mention the model and product type, its capacity or output, and the 2-3 most useful specs for a buyer (battery, transfer time, waveform, sockets or output ports, display).
|
||
Finish with typical applications that fit this kind of product. Confident, factual tone; no superlatives such as "best" or "ultimate".
|
||
Input is a JSON array of spec objects. Return ONLY a JSON array of strings, same length and order, no extra text.`;
|
||
for (let i = 0; i < need.length; i += 6) {
|
||
const chunk = need.slice(i, i + 6);
|
||
try {
|
||
const content = await ai.callDeepSeekWithRetry(cfg.apiKey, [
|
||
{ role: 'system', content: system },
|
||
{ role: 'user', content: '[' + chunk.map((x) => x.facts).join(',') + ']' },
|
||
], { maxTokens: 2500, temperature: 0.4 });
|
||
const { data } = ai.extractJson(content);
|
||
if (!Array.isArray(data) || data.length !== chunk.length) throw new Error('wrong shape');
|
||
chunk.forEach((x, j) => { const t = String(data[j] || '').trim(); if (t) { cache[x.key] = t; dirty = true; } });
|
||
} catch (e) { console.warn('[public-api] AI 产品介绍生成失败:', e.message); }
|
||
}
|
||
}
|
||
}
|
||
if (dirty) { try { saveCache(cache); } catch (e) {} }
|
||
for (const x of items) if (cache[x.key]) x.p.description = { ...(x.p.description || {}), en: cache[x.key] };
|
||
}
|
||
|
||
// 给一批产品补齐各语言的介绍和卖点。翻译失败不影响构建:那一项网站上显示英文。
|
||
async function translateProducts(ai, products) {
|
||
try { await translateSpecs(ai, products); } catch (e) { console.warn('[public-api] 参数翻译失败:', e.message); }
|
||
try { await translateTemplateHtml(ai, products); } catch (e) { console.warn('[public-api] HTML 模板翻译失败:', e.message); }
|
||
try { await generateDescriptions(ai, products); } catch (e) { console.warn('[public-api] AI 产品介绍失败:', e.message); }
|
||
if (!ai) {
|
||
for (const p of products) { if (p._points.length) p.sellingPointsI18n = { en: p._points }; delete p._points; }
|
||
return products;
|
||
}
|
||
const cache = loadCache();
|
||
let dirty = false;
|
||
for (const [lang, langDesc] of Object.entries(WEB_TRANSLATE_LANGS)) {
|
||
const need = new Set();
|
||
for (const p of products) {
|
||
const en = p.description && p.description.en;
|
||
if (en && !(p.description[lang] || '').trim() && !cache[cacheKey(lang, en)]) need.add(en);
|
||
for (const line of p._points) if (!cache[cacheKey(lang, line)]) need.add(line);
|
||
}
|
||
const list = [...need];
|
||
for (let i = 0; i < list.length; i += 20) {
|
||
const chunk = list.slice(i, i + 20);
|
||
try {
|
||
const out = await translateBatch(ai, chunk, langDesc);
|
||
chunk.forEach((src, j) => { cache[cacheKey(lang, src)] = out[j]; });
|
||
dirty = true;
|
||
} catch (e) {
|
||
console.warn(`[public-api] 翻译成 ${lang} 失败:${e.message}`);
|
||
}
|
||
}
|
||
}
|
||
if (dirty) { try { saveCache(cache); } catch (e) { console.warn('[public-api] 译文缓存写入失败:', e.message); } }
|
||
|
||
for (const p of products) {
|
||
const en = p.description && p.description.en;
|
||
if (en) {
|
||
const d = { en };
|
||
for (const lang of Object.keys(WEB_TRANSLATE_LANGS)) {
|
||
const manual = (p.description[lang] || '').trim();
|
||
d[lang] = manual || cache[cacheKey(lang, en)] || '';
|
||
}
|
||
p.description = d;
|
||
}
|
||
if (p._points.length) {
|
||
p.sellingPointsI18n = { en: p._points };
|
||
for (const lang of Object.keys(WEB_TRANSLATE_LANGS)) {
|
||
p.sellingPointsI18n[lang] = p._points.map((l) => cache[cacheKey(lang, l)] || l);
|
||
}
|
||
}
|
||
delete p._points;
|
||
}
|
||
return products;
|
||
}
|
||
|
||
const slugify =(s) => String(s || '').trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
||
const parse = (v) => { try { return typeof v === 'string' ? JSON.parse(v) : v; } catch { return v; } };
|
||
|
||
function readKey(dataFile, key) {
|
||
const data = JSON.parse(fs.readFileSync(dataFile, 'utf8'));
|
||
const raw = data[key];
|
||
const list = parse(raw && raw.value !== undefined ? raw.value : raw);
|
||
return Array.isArray(list) ? list : [];
|
||
}
|
||
const readProducts = (dataFile) => readKey(dataFile, PRODUCTS_KEY);
|
||
const readTemplates = (dataFile) => readKey(dataFile, TEMPLATES_KEY);
|
||
function readObj(dataFile, key) {
|
||
const data = JSON.parse(fs.readFileSync(dataFile, 'utf8'));
|
||
const raw = data[key];
|
||
const v = parse(raw && raw.value !== undefined ? raw.value : raw);
|
||
return v && typeof v === 'object' && !Array.isArray(v) ? v : {};
|
||
}
|
||
const safeSlot = (k) => /^[A-Za-z0-9_-]{1,40}$/.test(k);
|
||
// 图片位条目:普通图片位是文件名;图集(生产线、研发、仓库)是 { file, caption },可以有多张
|
||
function siteAssetItems(dataFile) {
|
||
const a = readObj(dataFile, SITE_ASSETS_KEY);
|
||
const out = {};
|
||
for (const [k, list] of Object.entries(a)) {
|
||
if (!safeSlot(k) || !Array.isArray(list)) continue;
|
||
const items = list
|
||
.map((x) => (typeof x === 'string' ? { file: x, caption: {} } : x && typeof x.file === 'string' ? { file: x.file, caption: x.caption || {} } : null))
|
||
.filter((x) => x && x.file && x.file === path.basename(x.file))
|
||
.slice(0, 20);
|
||
if (items.length) out[k] = items;
|
||
}
|
||
return out;
|
||
}
|
||
function siteAssetFiles(dataFile) {
|
||
const out = {};
|
||
for (const [k, items] of Object.entries(siteAssetItems(dataFile))) out[k] = items.map((x) => x.file);
|
||
return out;
|
||
}
|
||
// 模板三种:images = 详情图片组(详情图下方);html = 系列参数表;main = 主图模板(同系列共用的主图,接在产品自己的主图后面)
|
||
// 一个模板里主图、详情图片、HTML 分开存,各自生效:mainImages = 主图,images = 详情图片,html = 参数表。
|
||
// 早先的主图模板(kind = main 且没有 mainImages)图片存在 images 里,按主图处理。
|
||
const arr = (v) => (Array.isArray(v) ? v : []).filter(Boolean);
|
||
const legacyMain = (t) => t && t.kind === 'main' && !Array.isArray(t.mainImages);
|
||
const tplImagesOf = (t) => (t && !legacyMain(t) ? arr(t.images).slice(0, 20) : []);
|
||
const tplMainOf = (t) => (!t ? [] : legacyMain(t) ? arr(t.images) : arr(t.mainImages)).slice(0, 6);
|
||
const tplFilesOf = (t) => [...tplImagesOf(t), ...tplMainOf(t)];
|
||
// 主图模板里给某个型号单独指定了主图(mainCover[产品id]):那张排第一,其余按模板顺序
|
||
const tplMainFor = (t, p) => {
|
||
const list = !t ? [] : legacyMain(t) ? arr(t.images) : arr(t.mainImages);
|
||
const pk = pickOf(t, p).main;
|
||
if (Array.isArray(pk)) return pk.filter((f) => list.includes(f)).slice(0, 6); // 手动选的:按点选顺序
|
||
const c = t && t.mainCover && p && t.mainCover[p.id];
|
||
return (c && list.includes(c) ? [c, ...list.filter((f) => f !== c)] : list).slice(0, 6);
|
||
};
|
||
// 产品引用的模板(按产品里选的顺序;已删除的模板自动忽略)
|
||
const templatesOf = (p, templates) => (Array.isArray(p[TEMPLATE_IDS_FIELD]) ? p[TEMPLATE_IDS_FIELD] : [])
|
||
.map((id) => templates.find((t) => t.id === id)).filter(Boolean);
|
||
|
||
const youtubeId = (url) => {
|
||
const m = String(url || '').match(/(?:youtu\.be\/|v=|embed\/|shorts\/)([\w-]{11})/);
|
||
return m ? m[1] : null;
|
||
};
|
||
|
||
const imagesOf = (p) => {
|
||
const list = Array.isArray(p[IMAGES_FIELD]) && p[IMAGES_FIELD].length
|
||
? p[IMAGES_FIELD] : [p.productImageFileName];
|
||
return list.filter(Boolean).slice(0, 6);
|
||
};
|
||
const detailsOf = (p) => (Array.isArray(p[DETAIL_FIELD]) ? p[DETAIL_FIELD] : []).filter(Boolean).slice(0, 20);
|
||
|
||
const PACK_KEY = 'crm:webPackSpecs'; // 箱规:[{ id, name, per, nw, gw, l, w, h }]
|
||
function toPublic(p, templates = [], packSpecs = []) {
|
||
const slug = slugify(p.name);
|
||
const out = { slug };
|
||
for (const [pub, src] of Object.entries(FIELDS)) {
|
||
const v = p[src];
|
||
if (v === undefined || v === '' || (Array.isArray(v) && !v.length)) continue;
|
||
out[pub] = v;
|
||
}
|
||
if (!out.ratedPower) delete out.ratedPowerUnit;
|
||
{
|
||
const sp = (p.webPackId && packSpecs.find((x) => x.id === p.webPackId)) || p.webPack;
|
||
if (sp && sp.per && sp.gw) out.pack = { per: sp.per, nw: sp.nw || '', gw: sp.gw, l: sp.l, w: sp.w, h: sp.h };
|
||
}
|
||
// 卖点:英文、每行一条(含中文的行不对外)
|
||
out._points = String(p.sellingPoints || '').split('\n').map((l) => l.trim()).filter((l) => l && !/[\u4e00-\u9fff]/.test(l)); // 没填额定功率时,单位单独出现没有意义
|
||
if (out.youtube) out.youtube = youtubeId(out.youtube);
|
||
const base = conf('PUBLIC_BASE_URL');
|
||
// 主图:产品自己的网站主图在前,主图模板的图片接在后面,最多 6 张;
|
||
// 产品没有自己的网站主图、也没用主图模板时,才退回用产品档案里的"产品主图"
|
||
const mainTpl = templatesOf(p, templates).flatMap((t) => tplMainFor(t, p)
|
||
.map((f) => `${base}/api/public/tplmedia/${encodeURIComponent(t.id)}/${encodeURIComponent(f)}`));
|
||
const own = (Array.isArray(p[IMAGES_FIELD]) && p[IMAGES_FIELD].length) || !mainTpl.length ? imagesOf(p) : [];
|
||
// 在模板管理里给这个型号单独指定了主图:它排在最前面(作列表封面),然后是产品自己的主图,再是模板其余的图
|
||
// 按型号手动选了主图(modelPick.main):选的第一张就是封面;旧数据 mainCover 同理
|
||
const coverOf = (t) => { const pk = pickOf(t, p).main; if (Array.isArray(pk)) return tplMainFor(t, p)[0] || ''; const c = t.mainCover && t.mainCover[p.id]; return c && tplMainFor(t, p)[0] === c ? c : ''; };
|
||
const coverTpl = templatesOf(p, templates).find((t) => coverOf(t));
|
||
const coverUrl = coverTpl ? `${base}/api/public/tplmedia/${encodeURIComponent(coverTpl.id)}/${encodeURIComponent(coverOf(coverTpl))}` : '';
|
||
const ownUrls = own.map((f) => `${base}/api/public/media/${slug}/${encodeURIComponent(f)}`);
|
||
out.images = (coverUrl ? [coverUrl, ...ownUrls, ...mainTpl.filter((u) => u !== coverUrl)] : [...ownUrls, ...mainTpl]).slice(0, 6);
|
||
out.detailImages = detailsOf(p).map((f) => `${base}/api/public/media/${slug}/${encodeURIComponent(f)}`);
|
||
// 模板图片:同一个模板被多个产品引用时 URL 相同,网站构建时只下载一次
|
||
const tplUrls = templatesOf(p, templates).flatMap((t) => tplImagesFor(t, p)
|
||
.map((f) => `${base}/api/public/tplmedia/${encodeURIComponent(t.id)}/${encodeURIComponent(f)}`));
|
||
if (tplUrls.length) out.templateImages = tplUrls;
|
||
// 有 HTML 片段时,额外给出"图片 + HTML"的完整顺序(网站按这个顺序显示;没有 HTML 片段的模板不输出,网站沿用 templateImages)
|
||
if (templatesOf(p, templates).some((t) => tplBlocksFor(t, p).length)) {
|
||
out.templateDetail = templatesOf(p, templates).flatMap((t) => tplDetailSeq(t, p).map((x) => (x.img
|
||
? { img: `${base}/api/public/tplmedia/${encodeURIComponent(t.id)}/${encodeURIComponent(x.img)}` }
|
||
: { html: { en: x.html } })));
|
||
}
|
||
// HTML 模板(系列参数表等):显示在详情图下方
|
||
const tplHtml = templatesOf(p, templates).flatMap((t) => tplHtmlListFor(t, p).map((h) => ({ id: h.id === 'h_main' ? t.id : `${t.id}~${h.id}`, html: { en: h.html } })));
|
||
if (tplHtml.length) out.templateHtml = tplHtml;
|
||
return out;
|
||
}
|
||
|
||
function checkKey(req, res, next) {
|
||
const want = conf('SITE_BUILD_KEY');
|
||
const got = req.get('x-site-key') || '';
|
||
const ok = want && got.length === want.length &&
|
||
crypto.timingSafeEqual(Buffer.from(got), Buffer.from(want));
|
||
if (!ok) return res.status(403).json({ error: 'forbidden' });
|
||
next();
|
||
}
|
||
|
||
module.exports = function mountPublicApi(app, { dataFile, uploadsDir, requireAuth, ai }) {
|
||
const published = () => readProducts(dataFile).filter((p) => p[PUBLISH_FLAG]);
|
||
const findBySlug = (slug) => published().find((p) => slugify(p.name) === slug);
|
||
|
||
// 网站构建时调用:全部已发布产品
|
||
app.get('/api/public/products', checkKey, async (req, res) => {
|
||
try {
|
||
const templates = readTemplates(dataFile);
|
||
const packSpecs = readKey(dataFile, PACK_KEY);
|
||
res.json(await translateProducts(ai, published().map((p) => toPublic(p, templates, packSpecs))));
|
||
}
|
||
catch (e) { res.status(500).json({ error: e.message }); }
|
||
});
|
||
|
||
// 单个产品
|
||
app.get('/api/public/products/:slug', checkKey, (req, res) => {
|
||
const p = findBySlug(req.params.slug);
|
||
if (!p) return res.status(404).json({ error: 'not found' });
|
||
translateProducts(ai, [toPublic(p, readTemplates(dataFile), readKey(dataFile, PACK_KEY))]).then(([x]) => res.json(x), (e) => res.status(500).json({ error: e.message }));
|
||
});
|
||
|
||
// 产品图片:只允许读取"已发布产品自己的图片",防止借这个接口读到别的文件
|
||
app.get('/api/public/media/:slug/:file', checkKey, (req, res) => {
|
||
const p = findBySlug(req.params.slug);
|
||
const file = path.basename(req.params.file);
|
||
if (!p || !(imagesOf(p).includes(file) || detailsOf(p).includes(file))) return res.status(404).end();
|
||
// 图片按产品 id 分目录存放:uploads/<产品id>/<文件名>
|
||
res.sendFile(path.resolve(uploadsDir, path.basename(String(p.id)), file), (err) => { if (err) res.status(404).end(); });
|
||
});
|
||
|
||
// 模板图片:只允许读取"被已发布产品引用的模板"里的图片
|
||
app.get('/api/public/tplmedia/:tplId/:file', checkKey, (req, res) => {
|
||
const tplId = String(req.params.tplId);
|
||
const file = path.basename(req.params.file);
|
||
const t = readTemplates(dataFile).find((x) => x.id === tplId);
|
||
const used = t && published().some((p) => Array.isArray(p[TEMPLATE_IDS_FIELD]) && p[TEMPLATE_IDS_FIELD].includes(tplId));
|
||
if (!used || !tplFilesOf(t).includes(file) || !/^[A-Za-z0-9_-]+$/.test(tplId)) return res.status(404).end();
|
||
res.sendFile(path.resolve(uploadsDir, tplId, file), (err) => { if (err) res.status(404).end(); });
|
||
});
|
||
|
||
// 网站管理:图片位 + 近期动态(标题、说明自动翻译;手动填了的语言优先)
|
||
app.get('/api/public/site', checkKey, async (req, res) => {
|
||
try {
|
||
const base = conf('PUBLIC_BASE_URL');
|
||
const items = siteAssetItems(dataFile);
|
||
const rawNews = readKey(dataFile, SITE_NEWS_KEY).filter((n) => n && n.title && String(n.title.en || '').trim());
|
||
const captionsEn = Object.values(items).flat().map((x) => String((x.caption && x.caption.en) || '').trim());
|
||
const tr = await translateStrings(ai, [...rawNews.flatMap((n) => [n.title.en, (n.text && n.text.en) || '']), ...captionsEn]);
|
||
const i18n = (o) => {
|
||
const en = String((o && o.en) || '').trim();
|
||
const r = { en };
|
||
for (const lang of Object.keys(WEB_TRANSLATE_LANGS)) r[lang] = String((o && o[lang]) || '').trim() || (en && tr[lang][en]) || en;
|
||
return r;
|
||
};
|
||
// 图片位:{ url, caption:{en,es,ru} },没写标题的 caption 为空
|
||
const assets = {};
|
||
for (const [k, list] of Object.entries(items)) {
|
||
assets[k] = list.map((x) => ({ url: `${base}/api/public/site-media/${encodeURIComponent(x.file)}`, caption: i18n(x.caption) }));
|
||
}
|
||
const news = rawNews
|
||
.map((n) => ({ date: String(n.date || '').slice(0, 10), title: i18n(n.title), text: i18n(n.text), youtube: youtubeId(n.youtubeUrl) || undefined }))
|
||
.sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0));
|
||
res.json({ assets, news });
|
||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||
});
|
||
|
||
// 网站管理的图片:只允许读取"已分配到某个图片位"的文件
|
||
app.get('/api/public/site-media/:file', checkKey, (req, res) => {
|
||
const file = path.basename(req.params.file);
|
||
const used = Object.values(siteAssetFiles(dataFile)).some((list) => list.includes(file));
|
||
if (!used) return res.status(404).end();
|
||
res.sendFile(path.resolve(uploadsDir, SITE_ASSETS_DIR, file), (err) => { if (err) res.status(404).end(); });
|
||
});
|
||
|
||
// 后台产品编辑页"查看 AI 生成的介绍":不管有没有发布都能看;用的是同一份缓存,网站上就是这段
|
||
app.get('/api/site/ai-description/:id', requireAuth, async (req, res) => {
|
||
try {
|
||
const p = readProducts(dataFile).find((x) => String(x.id) === String(req.params.id));
|
||
if (!p) return res.status(404).json({ error: '产品不存在(新建的产品先保存一次)' });
|
||
const pub = toPublic(p, readTemplates(dataFile), readKey(dataFile, PACK_KEY));
|
||
pub.description = {}; // 预览时忽略手动介绍,看 AI 会写什么
|
||
await translateSpecs(ai, [pub]);
|
||
await generateDescriptions(ai, [pub]);
|
||
const text = pub.description && pub.description.en;
|
||
if (!text) return res.status(502).json({ error: 'AI 生成失败,请检查 DeepSeek 设置或稍后再试' });
|
||
res.json({ text });
|
||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||
});
|
||
|
||
// 后台"更新到网站"按钮:触发 Cloudflare Pages 重新构建(需要后台登录)
|
||
// Cloudflare 在上一次构建还没跑完时会返回 304(不新建构建)。这时不让用户等:
|
||
// 服务器记下"还有一次待更新",每 20 秒自动重试,直到 Cloudflare 接受新的构建为止。
|
||
// 期间不管点多少次(不同产品),都合并成这一次待更新——它开始构建时会拉取最新的全部数据。
|
||
const deployQ = { pending: false, timer: null, tries: 0, since: 0 };
|
||
const hook = async () => (await fetch(conf('CF_DEPLOY_HOOK'), { method: 'POST' })).status;
|
||
function scheduleRetry() {
|
||
if (deployQ.timer) return;
|
||
deployQ.timer = setTimeout(async () => {
|
||
deployQ.timer = null;
|
||
deployQ.tries++;
|
||
let st = 0;
|
||
try { st = await hook(); } catch (e) { st = 0; }
|
||
if (st >= 200 && st < 300) { deployQ.pending = false; deployQ.tries = 0; console.log('[public-api] 排队的网站更新已提交给 Cloudflare'); return; }
|
||
if (deployQ.tries >= 45) { deployQ.pending = false; deployQ.tries = 0; console.warn('[public-api] 网站更新重试 15 分钟仍未被接受,已放弃(最后状态 ' + st + ')'); return; }
|
||
scheduleRetry();
|
||
}, 20000);
|
||
}
|
||
app.post('/api/site/deploy', requireAuth, async (req, res) => {
|
||
if (!conf('CF_DEPLOY_HOOK')) return res.status(500).json({ error: '未配置 CF_DEPLOY_HOOK' });
|
||
if (deployQ.pending) return res.json({ ok: true, queued: true, note: '已加入更新队列:当前这次构建结束后自动再更新一次,包含你刚才的修改,不用再点' });
|
||
try {
|
||
const st = await hook();
|
||
if (st === 304) {
|
||
deployQ.pending = true; deployQ.tries = 0; deployQ.since = Date.now();
|
||
scheduleRetry();
|
||
return res.json({ ok: true, queued: true, note: '已加入更新队列:当前这次构建结束后自动再更新一次,包含你刚才的修改,不用再点' });
|
||
}
|
||
if (st < 200 || st >= 300) throw new Error(`Cloudflare 返回 HTTP ${st}`);
|
||
res.json({ ok: true });
|
||
} catch (e) { res.status(502).json({ error: e.message }); }
|
||
});
|
||
};
|