Update public-api.js via upload script - 2026-10-12 15:23:08

This commit is contained in:
mike 2026-10-12 15:23:06 +08:00
parent ca828988c1
commit 59416e010f
1 changed files with 93 additions and 8 deletions

View File

@ -3,7 +3,9 @@
//
// 接入方法(server.js 里加三行,放在后台登录校验中间件之前):
// const mountPublicApi = require('./public-api');
// mountPublicApi(app, { dataFile: path.join(__dirname, 'data.json'), uploadsDir: path.join(__dirname, 'uploads'), requireAuth });
// 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。
//
@ -40,8 +42,8 @@ const FIELDS = {
sellingPoints: 'sellingPoints',
// —— 以下是需要在产品表单里新增的字段 ——
youtube: 'youtubeUrl', // YouTube 链接,输出时只保留视频 ID
description: 'webDescription', // { es, en, ru }
sale: 'webSale', // { mode: 'group'|'stock', stock, tiers: [[数量, 单价], ...] }
description: 'webDescription', // { en, es?, ru? }:只需填 en,其他语言自动翻译;手动填了的语言优先用手动的
sale: 'webSale', // { mode: 'group'|'stock', stock, minPrice, maxPrice }
};
const PUBLISH_FLAG = 'publishToWeb'; // 新增:"发布到网站"开关
const IMAGES_FIELD = 'webImages'; // 新增:主图文件名数组,最多 6 张;为空时用现有的 productImageFileName
@ -54,6 +56,87 @@ function conf(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) {
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 English 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);
}
// 给一批产品补齐各语言的介绍和卖点。翻译失败不影响构建:那一项网站上显示英文。
async function translateProducts(ai, products) {
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; } };
@ -83,7 +166,9 @@ function toPublic(p) {
if (v === undefined || v === '' || (Array.isArray(v) && !v.length)) continue;
out[pub] = v;
}
if (!out.ratedPower) delete out.ratedPowerUnit; // 没填额定功率时,单位单独出现没有意义
if (!out.ratedPower) delete out.ratedPowerUnit;
// 卖点:英文、每行一条(含中文的行不对外)
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');
out.images = imagesOf(p).map((f) => `${base}/api/public/media/${slug}/${encodeURIComponent(f)}`);
@ -99,13 +184,13 @@ function checkKey(req, res, next) {
next();
}
module.exports = function mountPublicApi(app, { dataFile, uploadsDir, requireAuth }) {
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, (req, res) => {
try { res.json(published().map(toPublic)); }
app.get('/api/public/products', checkKey, async (req, res) => {
try { res.json(await translateProducts(ai, published().map(toPublic))); }
catch (e) { res.status(500).json({ error: e.message }); }
});
@ -113,7 +198,7 @@ module.exports = function mountPublicApi(app, { dataFile, uploadsDir, requireAut
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' });
res.json(toPublic(p));
translateProducts(ai, [toPublic(p)]).then(([x]) => res.json(x), (e) => res.status(500).json({ error: e.message }));
});
// 产品图片:只允许读取"已发布产品自己的图片",防止借这个接口读到别的文件