client/public-api.js

251 lines
13 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",网站端按词典翻译
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', // { mode: 'group'|'stock', stock, minPrice, maxPrice }
};
const PUBLISH_FLAG = 'publishToWeb'; // 新增:"发布到网站"开关
const IMAGES_FIELD = 'webImages'; // 新增:主图文件名数组,最多 6 张;为空时用现有的 productImageFileName
const DETAIL_FIELD = 'webDetailImages'; // 新增:详情图文件名数组,最多 20 张,显示在规格表下方
const TEMPLATES_KEY = 'crm:webDetailTemplates'; // 详情模板:[{ id, name, images: [文件名] }],图片在 uploads/<模板id>/
const TEMPLATE_IDS_FIELD = 'webDetailTemplateIds'; // 产品引用的模板id,按顺序显示在详情图下方
// 配置:优先读环境变量,没有就读同目录下的 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) {
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; } };
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);
const tplImagesOf = (t) => (Array.isArray(t && t.images) ? t.images : []).filter(Boolean).slice(0, 10);
// 产品引用的模板(按产品里选的顺序;已删除的模板自动忽略)
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);
function toPublic(p, templates = []) {
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;
// 卖点:英文、每行一条(含中文的行不对外)
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)}`);
out.detailImages = detailsOf(p).map((f) => `${base}/api/public/media/${slug}/${encodeURIComponent(f)}`);
// 模板图片:同一个模板被多个产品引用时 URL 相同,网站构建时只下载一次
const tplUrls = templatesOf(p, templates).flatMap((t) => tplImagesOf(t)
.map((f) => `${base}/api/public/tplmedia/${encodeURIComponent(t.id)}/${encodeURIComponent(f)}`));
if (tplUrls.length) out.templateImages = tplUrls;
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);
res.json(await translateProducts(ai, published().map((p) => toPublic(p, templates))));
}
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))]).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 || !tplImagesOf(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(); });
});
// 后台"发布到网站"按钮:触发 Cloudflare Pages 重新构建(需要后台登录)
app.post('/api/site/deploy', requireAuth, async (req, res) => {
if (!conf('CF_DEPLOY_HOOK')) return res.status(500).json({ error: '未配置 CF_DEPLOY_HOOK' });
try {
const r = await fetch(conf('CF_DEPLOY_HOOK'), { method: 'POST' });
if (!r.ok) throw new Error(`Cloudflare 返回 HTTP ${r.status}`);
res.json({ ok: true });
} catch (e) { res.status(502).json({ error: e.message }); }
});
};