client/public-api.js

859 lines
54 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.

// 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 }]
// —— 光伏逆变器(混网 / 并网 / 离网)——
batteryType: 'batteryType',
maxChargingVoltage: 'maxChargingVoltage',
maxChargeDischargeCurrent: 'maxChargeDischargeCurrent',
maxDcInputPower: 'maxDcInputPower',
maxDcInputVoltage: 'maxDcInputVoltage',
mpptVoltageRange: 'mpptVoltageRange',
startingVoltage: 'startingVoltage',
maxInputCurrent: 'maxInputCurrent',
mpptNumber: 'mpptNumber',
onGridMaxApparentPower: 'onGridMaxApparentPower',
ratedOutputFrequency: 'ratedOutputFrequency',
onGridMaxOutputCurrent: 'onGridMaxOutputCurrent',
offGridRatedApparentPower: 'offGridRatedApparentPower',
offGridMaxApparentPower: 'offGridMaxApparentPower',
offGridMaxOutputCurrent: 'offGridMaxOutputCurrent',
efficiencyMppt: 'efficiencyMppt',
efficiencyMax: 'efficiencyMax',
efficiencyEurope: 'efficiencyEurope',
protectionFunctions: 'protectionFunctions',
operatingTemp: 'operatingTemp',
storageTemp: 'storageTemp',
protectionClass: 'protectionClass',
cooling: 'cooling',
topology: 'topology',
altitude: 'altitude',
safetyStandard: 'safetyStandard',
gridStandard: 'gridStandard',
otherStandard: 'otherStandard',
// —— 储能电池(机架式 / 壁挂式锂电、铅酸、家庭储能系统)——
moduleType: 'moduleType',
cellType: 'cellType',
cellConfiguration: 'cellConfiguration',
moduleVoltage: 'moduleVoltage',
moduleCapacity: 'moduleCapacity',
moduleMaxEnergy: 'moduleMaxEnergy',
moduleOutputPower: 'moduleOutputPower',
moduleDimensions: 'moduleDimensions',
moduleWeight: 'moduleWeight',
cycleLife: 'cycleLife',
selfDischargeRate: 'selfDischargeRate',
chargeRate: 'chargeRate',
dischargeRate: 'dischargeRate',
chargingEfficiency: 'chargingEfficiency',
dischargingEfficiency: 'dischargingEfficiency',
recommendedChargingVoltage: 'recommendedChargingVoltage',
recommendedDischargeCurrent: 'recommendedDischargeCurrent',
maxChargingCurrent: 'maxChargingCurrent',
maxDischargeCurrent: 'maxDischargeCurrent',
dischargeCutoffVoltage: 'dischargeCutoffVoltage',
cabinetMaxEnergy: 'cabinetMaxEnergy',
cabinetRatedVoltage: 'cabinetRatedVoltage',
cabinetDimensions: 'cabinetDimensions',
cabinetWeight: 'cabinetWeight',
commInterface: 'commInterface',
color: 'color',
};
const PUBLISH_FLAG = 'publishToWeb'; // 新增:"发布到网站"开关
const IMAGES_FIELD = 'webImages'; // 新增:主图文件名数组,最多 6 张;为空时用现有的 productImageFileName
const DETAIL_FIELD = 'webDetailImages'; // 新增:详情图文件名数组,最多 20 张,显示在规格表下方
// 网站上用的是"已同步"的模板(crm:webTemplatesLive):后台改模板不会直接影响网站,
// 在模板管理里点"更新到网站"、勾选要同步的模板后,才把它们复制到这里。还没有这份数据时(第一次)用后台的模板。
const LIVE_TEMPLATES_KEY = 'crm:webTemplatesLive';
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',
// 光伏逆变器
'batteryType', 'maxChargingVoltage', 'maxChargeDischargeCurrent', 'maxDcInputPower', 'maxDcInputVoltage', 'mpptVoltageRange', 'startingVoltage',
'maxInputCurrent', 'mpptNumber', 'onGridMaxApparentPower', 'ratedOutputFrequency', 'onGridMaxOutputCurrent', 'offGridRatedApparentPower',
'offGridMaxApparentPower', 'offGridMaxOutputCurrent', 'efficiencyMppt', 'efficiencyMax', 'efficiencyEurope', 'protectionFunctions', 'operatingTemp',
'storageTemp', 'protectionClass', 'cooling', 'topology', 'altitude', 'safetyStandard', 'gridStandard', 'otherStandard',
// 储能电池
'moduleType', 'cellType', 'cellConfiguration', 'moduleVoltage', 'moduleCapacity', 'moduleMaxEnergy', 'moduleOutputPower', 'moduleDimensions', 'moduleWeight',
'cycleLife', 'selfDischargeRate', 'chargeRate', 'dischargeRate', 'chargingEfficiency', 'dischargingEfficiency', 'recommendedChargingVoltage',
'recommendedDischargeCurrent', 'maxChargingCurrent', 'maxDischargeCurrent', 'dischargeCutoffVoltage', 'cabinetMaxEnergy', 'cabinetRatedVoltage',
'cabinetDimensions', 'cabinetWeight', 'commInterface', 'color'];
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 片段里的图片:CRM 里插入的图片存成模板目录下的文件(uploads/<模板id>/<文件名>),HTML 里写 /uploads/<模板id>/<文件名>。
// 对外输出时换成 /api/public/tplmedia/<模板id>/<文件名>,网站构建时下载到网站自己的 /media/,HTML 里再换成网站地址。
// (复制模板时 HTML 可能引用原模板目录里的图片,所以不限定是当前模板的 id)
const HTML_IMG_RE = /\/uploads\/([A-Za-z0-9_-]+)\/([A-Za-z0-9_.-]+)/g;
const htmlImgRefs = (h) => [...String(h || '').matchAll(HTML_IMG_RE)].map((m) => `${m[1]}/${m[2]}`);
const tplHtmlRefs = (t) => [...tplDetailBlocks(t).flatMap((b) => htmlImgRefs(b.html)), ...tplHtmlsOf(t).flatMap((h) => htmlImgRefs(h.html))];
const publicHtmlImgs = (h) => String(h).replace(HTML_IMG_RE, (m, id, f) => `${conf('PUBLIC_BASE_URL')}/api/public/tplmedia/${id}/${f}`);
// 详情图片 + 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: publicHtmlImgs(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', '工频UPS': 'Industrial-frequency (transformer-based) online UPS with output isolation transformer', '在线式高频UPS': 'Online double-conversion high-frequency tower UPS', '太阳能混网逆变器': 'Hybrid solar inverter (solar + battery + grid, with backup output)', '并网/离网逆变器': 'Solar inverter (grid-tied / off-grid)', '机架式磷酸铁锂电池': 'Rack-mount LiFePO4 lithium battery module (19-inch, for solar energy storage and telecom)', '机架式锂电池': 'Rack-mount LiFePO4 lithium battery module (19-inch, for solar energy storage and telecom)', '一体式锂电UPS': 'All-in-one online double-conversion UPS with built-in LiFePO4 lithium battery (choose the number of battery packs for the backup time)', '锂电一体式UPS': 'All-in-one online double-conversion UPS with built-in LiFePO4 lithium battery (choose the number of battery packs for the backup time)', '壁挂式锂电池': 'Wall-mount LiFePO4 home battery (powerwall type, for solar and backup)', '壁挂式磷酸铁锂电池': 'Wall-mount LiFePO4 home battery (powerwall type, for solar and backup)', '落地式锂电池': 'Floor-standing LiFePO4 home battery on wheels (high capacity, for solar and backup)', '壁挂式储能一体机': 'Wall-mounted all-in-one home energy storage system (LiFePO4 battery and hybrid inverter in one unit, PV and mains input, UPS function)', '落地式储能一体机': 'Floor-standing all-in-one home energy storage system (LiFePO4 battery and hybrid inverter in one unit, PV and mains input, UPS function)', '高压堆叠式储能一体机': 'High-voltage stacked all-in-one home energy storage system (10 kW hybrid inverter on top of stackable high-voltage LiFePO4 battery layers, 10–20 kWh)', '低压堆叠式储能一体机': 'Low-voltage stacked all-in-one home energy storage system (5 kW hybrid inverter on top of stackable 51.2 V LiFePO4 battery layers, 15–25 kWh)', '锂电替换铅酸电池': 'LiFePO4 drop-in replacement for lead-acid batteries (12.8 V / 25.6 V / 51.2 V, same sizes as VRLA, for UPS, solar, RV and security)', '磷酸铁锂储能柜': 'High-voltage LiFePO4 battery cabinet (19-inch cabinet with master BMS, for online / industrial UPS and high-voltage hybrid inverters, replaces lead-acid battery strings)', '高压锂电池柜': 'High-voltage LiFePO4 battery cabinet (for UPS and high-voltage inverters)', '高压磷酸铁锂电池柜': 'High-voltage LiFePO4 battery cabinet (for UPS and high-voltage inverters)', '落地式磷酸铁锂电池': 'Floor-standing LiFePO4 home battery on wheels (high capacity, for solar and backup)' };
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.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, '');
// 网址里的产品标识(slug)按型号生成。两个已发布产品型号相同时(比如壁挂式和落地式储能一体机都叫"2.5kWh + 3kW"),
// 后面加上细分品类的英文后缀(-wall / -floor),没有对应后缀的按产品 id 顺序加 -2、-3……,保证每个产品的网址和图片目录不重复。
const SLUG_TYPE_SUFFIX = { '壁挂式储能一体机': 'wall', '落地式储能一体机': 'floor', '高压堆叠式储能一体机': 'hv', '低压堆叠式储能一体机': 'lv' };
function uniqueSlugs(list) {
const groups = new Map();
for (const p of list) { const b = slugify(p.name); if (!groups.has(b)) groups.set(b, []); groups.get(b).push(p); }
const out = new Map();
for (const [b, ps] of groups) {
if (ps.length === 1) { out.set(String(ps[0].id), b); continue; }
const used = new Set();
const sorted = [...ps].sort((x, y) => String(x.id).localeCompare(String(y.id)));
sorted.forEach((p, i) => {
const sx = SLUG_TYPE_SUFFIX[String(p.type || '').trim()];
let slug = sx && !used.has(`${b}-${sx}`) ? `${b}-${sx}` : i === 0 && !sx ? b : `${b}-${i + 1}`;
while (used.has(slug)) slug += 'x';
used.add(slug); out.set(String(p.id), slug);
});
}
return out;
}
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 hasKey = (dataFile, key) => { try { return key in JSON.parse(fs.readFileSync(dataFile, 'utf8')); } catch { return false; } };
const readTemplates = (dataFile) => (hasKey(dataFile, LIVE_TEMPLATES_KEY) ? readKey(dataFile, LIVE_TEMPLATES_KEY) : readKey(dataFile, TEMPLATES_KEY));
// 比较"后台模板"和"网站模板"是否一样:kind 只是后台当前打开的是哪一栏(主图 / 详情 / HTML),不影响网站,不算改动
const tplNorm = (t) => JSON.stringify({ ...t, kind: t && !Array.isArray(t.mainImages) ? t.kind : undefined });
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 = [], slugMap = null) {
const slug = (slugMap && slugMap.get(String(p.id))) || 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, writeData }) {
// —— 模板同步状态 / 选择性同步 ——
const loadAll = () => JSON.parse(fs.readFileSync(dataFile, 'utf8'));
const listOf = (data, key) => { const raw = data[key]; const v = parse(raw && raw.value !== undefined ? raw.value : raw); return Array.isArray(v) ? v : []; };
function ensureLive(data) {
// 第一次:网站上现在用的就是后台的全部模板,把它们记成"已同步"
if (!(LIVE_TEMPLATES_KEY in data)) { data[LIVE_TEMPLATES_KEY] = JSON.stringify(listOf(data, TEMPLATES_KEY)); if (writeData) writeData(data); }
return data;
}
// 每个模板的状态:synced 已同步 / changed 改过没同步 / new 新建没同步;deleted = 后台已删除、网站上还在
app.get('/api/site/templates-status', requireAuth, (req, res) => {
try {
const data = ensureLive(loadAll());
const work = listOf(data, TEMPLATES_KEY), live = new Map(listOf(data, LIVE_TEMPLATES_KEY).map((t) => [t.id, t]));
const status = {};
for (const t of work) status[t.id] = !live.has(t.id) ? 'new' : tplNorm(live.get(t.id)) === tplNorm(t) ? 'synced' : 'changed';
const workIds = new Set(work.map((t) => t.id));
const deleted = [...live.values()].filter((t) => !workIds.has(t.id)).map((t) => ({ id: t.id, name: t.name || '' }));
res.json({ status, deleted, siteChanged: siteChanged(ensureFp(data)), autoAt: autoSync.at || 0, autoRunning: autoSync.running });
} catch (e) { res.status(500).json({ error: e.message }); }
});
// 把选中的模板同步到网站(复制到"网站模板");没选的保持网站上原来的版本。之后再调用 /api/site/deploy 重新构建网站
app.post('/api/site/templates-publish', requireAuth, (req, res) => {
try {
if (!writeData) return res.status(500).json({ error: 'server.js 需要把 writeData 传给 public-api' });
const ids = new Set((Array.isArray(req.body && req.body.ids) ? req.body.ids : []).map(String));
const data = ensureLive(loadAll());
const work = listOf(data, TEMPLATES_KEY), oldLive = listOf(data, LIVE_TEMPLATES_KEY);
const live = new Map(oldLive.map((t) => [t.id, t]));
const next = [];
for (const t of work) { if (ids.has(t.id)) next.push(t); else if (live.has(t.id)) next.push(live.get(t.id)); }
const workIds = new Set(work.map((t) => t.id));
for (const t of oldLive) if (!workIds.has(t.id) && !ids.has(t.id)) next.push(t); // 后台删了但这次没选:网站上先保留
data[LIVE_TEMPLATES_KEY] = JSON.stringify(next);
writeData(data);
res.json({ ok: true, count: ids.size });
} catch (e) { res.status(500).json({ error: e.message }); }
});
const published = () => readProducts(dataFile).filter((p) => p[PUBLISH_FLAG]);
const findBySlug = (slug) => { const list = published(), m = uniqueSlugs(list); return list.find((p) => m.get(String(p.id)) === slug); };
// 网站构建时调用:全部已发布产品
app.get('/api/public/products', checkKey, async (req, res) => {
try {
const templates = readTemplates(dataFile);
const packSpecs = readKey(dataFile, PACK_KEY);
const list = published(), slugMap = uniqueSlugs(list);
res.json(await translateProducts(ai, list.map((p) => toPublic(p, templates, packSpecs, slugMap))));
}
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), uniqueSlugs(published()))]).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);
if (!/^[A-Za-z0-9_-]+$/.test(tplId)) return res.status(404).end();
const templates = readTemplates(dataFile);
const usedIds = new Set(published().flatMap((p) => (Array.isArray(p[TEMPLATE_IDS_FIELD]) ? p[TEMPLATE_IDS_FIELD] : [])));
const t = templates.find((x) => x.id === tplId);
// 模板自己的主图 / 详情图片;或者被已发布产品用到的模板,在 HTML 片段里引用了这个文件
const ownFile = t && usedIds.has(tplId) && tplFilesOf(t).includes(file);
const inHtml = !ownFile && templates.some((x) => usedIds.has(x.id) && tplHtmlRefs(x).includes(`${tplId}/${file}`));
if (!ownFile && !inHtml) 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);
}
// 触发网站重新构建:上一次构建还没结束(304)就排队,结束后自动再构建一次
async function requestDeploy() {
if (!conf('CF_DEPLOY_HOOK')) throw new Error('未配置 CF_DEPLOY_HOOK');
if (deployQ.pending) return { queued: true };
const st = await hook();
if (st === 304) { deployQ.pending = true; deployQ.tries = 0; deployQ.since = Date.now(); scheduleRetry(); return { queued: true }; }
if (st < 200 || st >= 300) throw new Error(`Cloudflare 返回 HTTP ${st}`);
return { queued: false };
}
app.post('/api/site/deploy', requireAuth, async (req, res) => {
try {
const r = await requestDeploy();
res.json(r.queued ? { ok: true, queued: true, note: '已加入更新队列:当前这次构建结束后自动再更新一次,包含你刚才的修改,不用再点' } : { ok: true });
} catch (e) { res.status(e.message.includes('CF_DEPLOY_HOOK') ? 500 : 502).json({ error: e.message }); }
});
// —— 模板自动同步到网站 ——
// 后台保存模板后不马上同步:等模板停止修改 AUTO_SYNC_DELAY 之后,把所有改过的模板一次同步到网站并重新构建一次。
// 连续改很多个模板也只构建一次;改到一半的内容不会马上出现在网站上。服务重启后如果还有没同步的,自动补上。
const AUTO_SYNC_DELAY = 3 * 60 * 1000;
const autoSync = { timer: null, at: 0, running: false };
// 网站内容指纹:只看会出现在网站上的东西(已发布产品的对外字段和图片、箱规、网站图片、近期动态)。
// 改了进价、备注这类只在后台用的字段,指纹不变,不会白白重新构建网站。
const FP_KEY = '__siteFingerprint';
const PUB_SRC = [...new Set([...Object.values(FIELDS), 'name', 'id', PUBLISH_FLAG, IMAGES_FIELD, DETAIL_FIELD, TEMPLATE_IDS_FIELD, 'productImageFileName', 'webPackId', 'webPack'])];
function siteFingerprint(data) {
const prods = listOf(data, PRODUCTS_KEY).filter((p) => p && p[PUBLISH_FLAG]).map((p) => PUB_SRC.map((k) => p[k]));
const raw = (k) => { const v = data[k]; return v && v.value !== undefined ? v.value : v; };
return crypto.createHash('sha256').update(JSON.stringify([prods, raw(PACK_KEY), raw(SITE_ASSETS_KEY), raw(SITE_NEWS_KEY)])).digest('hex');
}
function ensureFp(data) { if (!data[FP_KEY] && writeData) { data[FP_KEY] = siteFingerprint(data); writeData(data); } return data; }
const siteChanged = (data) => !!data[FP_KEY] && data[FP_KEY] !== siteFingerprint(data);
function unsyncedCount() {
const data = ensureLive(loadAll());
const work = listOf(data, TEMPLATES_KEY), live = listOf(data, LIVE_TEMPLATES_KEY);
const liveMap = new Map(live.map((t) => [t.id, tplNorm(t)]));
const workIds = new Set(work.map((t) => t.id));
return work.filter((t) => liveMap.get(t.id) !== tplNorm(t)).length + live.filter((t) => !workIds.has(t.id)).length;
}
async function runAutoSync() {
autoSync.timer = null; autoSync.at = 0;
if (autoSync.running) { scheduleTemplateSync(); return; }
autoSync.running = true;
try {
if (!writeData) return;
const tplN = unsyncedCount();
const data = ensureFp(ensureLive(loadAll()));
const prodChanged = siteChanged(data);
if (!tplN && !prodChanged) return;
if (tplN) data[LIVE_TEMPLATES_KEY] = JSON.stringify(listOf(data, TEMPLATES_KEY)); // 网站模板 = 后台现在的全部模板(删掉的也去掉)
data[FP_KEY] = siteFingerprint(data);
writeData(data);
const r = await requestDeploy();
console.log(`[public-api] 自动更新网站:${tplN ? tplN + ' 个模板' : ''}${tplN && prodChanged ? ' + ' : ''}${prodChanged ? '产品 / 网站内容' : ''}${r.queued ? '(网站正在构建,排队等下一次)' : ''}`);
} catch (e) {
console.warn('[public-api] 模板自动同步失败,1 分钟后重试:', e.message);
autoSync.at = Date.now() + 60000;
autoSync.timer = setTimeout(runAutoSync, 60000);
} finally { autoSync.running = false; }
}
function scheduleTemplateSync() {
if (autoSync.timer) clearTimeout(autoSync.timer);
autoSync.at = Date.now() + AUTO_SYNC_DELAY;
autoSync.timer = setTimeout(runAutoSync, AUTO_SYNC_DELAY);
}
setTimeout(() => { try { const d = ensureFp(ensureLive(loadAll())); if (unsyncedCount() || siteChanged(d)) scheduleTemplateSync(); } catch (e) {} }, 10000);
return { scheduleTemplateSync };
};