Update public-api.js via upload script - 2026-11-13 23:04:05
This commit is contained in:
parent
9e828e1c54
commit
d3febdb383
130
public-api.js
130
public-api.js
|
|
@ -1659,6 +1659,136 @@ ${dialog}`;
|
||||||
} catch (e) { console.warn('[chat] 企业微信推送失败:', e.message); }
|
} catch (e) { console.warn('[chat] 企业微信推送失败:', e.message); }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---------------- 预约拜访(网站 /visit/ 页面提交) ---------------- */
|
||||||
|
// 客户填写日期、时间(北京时间整点)、人数、职位、公司、营业执照(图片或 PDF)、网站、电话/WhatsApp、邮箱、感兴趣的产品、拜访地点。
|
||||||
|
// 记录存在 chat-data.json 的 visits 里,营业执照存在 visit-files/ 目录;后台"网站管理 → 预约拜访"查看。
|
||||||
|
const VISIT_DIR = path.join(path.dirname(dataFile), 'visit-files');
|
||||||
|
const VISIT_HOURS = [9, 10, 11, 12, 14, 15, 16, 17, 18];
|
||||||
|
const VISIT_PLACES = {
|
||||||
|
beijing: '北京办公室(北京金亿达博瑞科技发展有限公司,北京市房山区福泽路4号院1号楼3层313)',
|
||||||
|
shenzhen: '深圳总部(山克新能源科技(深圳)有限公司,深圳市光明区特区建发乐府广场1B座24F)',
|
||||||
|
dongguan: '东莞工厂(广东省东莞市东坑镇科技路185号山克工业园)',
|
||||||
|
};
|
||||||
|
const VISIT_STATUS = ['new', 'confirmed', 'done', 'cancelled'];
|
||||||
|
let visitUpload = null;
|
||||||
|
try {
|
||||||
|
const multer = require('multer');
|
||||||
|
visitUpload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 10 * 1024 * 1024, files: 1, fields: 40, fieldSize: 20000 } }).single('license');
|
||||||
|
} catch (e) { console.warn('[visit] multer 不可用,预约拜访无法上传营业执照:', e.message); }
|
||||||
|
// 按文件内容判断类型(不信文件名和浏览器给的类型)
|
||||||
|
function sniffLicense(buf) {
|
||||||
|
if (!buf || buf.length < 12) return null;
|
||||||
|
const h = buf.subarray(0, 12);
|
||||||
|
if (h.subarray(0, 4).toString('latin1') === '%PDF') return { ext: '.pdf', mime: 'application/pdf' };
|
||||||
|
if (h[0] === 0xff && h[1] === 0xd8 && h[2] === 0xff) return { ext: '.jpg', mime: 'image/jpeg' };
|
||||||
|
if (h.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { ext: '.png', mime: 'image/png' };
|
||||||
|
if (h.subarray(0, 4).toString('latin1') === 'RIFF' && h.subarray(8, 12).toString('latin1') === 'WEBP') return { ext: '.webp', mime: 'image/webp' };
|
||||||
|
if (h.subarray(0, 3).toString('latin1') === 'GIF') return { ext: '.gif', mime: 'image/gif' };
|
||||||
|
if (h.subarray(4, 8).toString('latin1') === 'ftyp' && /^(heic|heix|mif1|msf1|hevc)$/.test(h.subarray(8, 12).toString('latin1'))) return { ext: '.heic', mime: 'image/heic' };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// 浏览器发来的中文文件名会被按 latin1 解码成乱码,转回 UTF-8;已经是正常 Unicode 的不动
|
||||||
|
const fixName = (n) => { n = String(n || ''); if (/[^\u0000-\u00ff]/.test(n)) return n; const u = Buffer.from(n, 'latin1').toString('utf8'); return u.includes('\ufffd') ? n : u; };
|
||||||
|
const clip = (v, n = 200) => String(v == null ? '' : v).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, '').trim().slice(0, n);
|
||||||
|
function visitDateOk(d) {
|
||||||
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(d)) return false;
|
||||||
|
const t = Date.parse(d + 'T00:00:00+08:00');
|
||||||
|
if (isNaN(t)) return false;
|
||||||
|
const todayBj = Date.parse(today() + 'T00:00:00+08:00');
|
||||||
|
return t > todayBj && t <= todayBj + 366 * 86400e3; // 明天起、一年以内(北京时间)
|
||||||
|
}
|
||||||
|
async function notifyVisit(v) {
|
||||||
|
const st = S();
|
||||||
|
if (!st.wecomWebhook) return;
|
||||||
|
const panel = (st.panelUrl || conf('PUBLIC_BASE_URL') || '').replace(/\/$/, '');
|
||||||
|
const content = [
|
||||||
|
'**📅 新的预约拜访**',
|
||||||
|
`> ${v.date} ${String(v.hour).padStart(2, '0')}:00(北京时间) · ${v.people} 人`,
|
||||||
|
`> 地点:${v.places.map((k) => VISIT_PLACES[k].split('(')[0]).join('、')}`,
|
||||||
|
`> ${[v.company, v.name && `${v.name}${v.title ? `(${v.title})` : ''}`].filter(Boolean).join(' / ')}${v.country ? ` · ${v.country}` : ''}`,
|
||||||
|
`> ${[v.phone, v.email].filter(Boolean).join(' · ')}`,
|
||||||
|
v.products.length || v.productsOther ? `> 感兴趣:${[...v.products, v.productsOther].filter(Boolean).join('、').slice(0, 200)}` : '',
|
||||||
|
panel ? `[打开预约](${panel}/?visit=${v.id})` : '',
|
||||||
|
].filter(Boolean).join('\n');
|
||||||
|
try {
|
||||||
|
const r = await fetch(st.wecomWebhook, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ msgtype: 'markdown', markdown: { content } }) });
|
||||||
|
if (!r.ok) console.warn('[visit] 企业微信推送失败:', r.status);
|
||||||
|
} catch (e) { console.warn('[visit] 企业微信推送失败:', e.message); }
|
||||||
|
}
|
||||||
|
app.post('/api/chat/visit', (req, res) => {
|
||||||
|
if (!visitUpload) return res.status(503).json({ error: 'unavailable' });
|
||||||
|
const ip = ipOf(req);
|
||||||
|
if (limited('visit:' + ip, 6, 3600e3)) return res.status(429).json({ error: 'too_many' });
|
||||||
|
visitUpload(req, res, (err) => {
|
||||||
|
if (err) return res.status(400).json({ error: err.code === 'LIMIT_FILE_SIZE' ? 'file_too_big' : 'bad_upload' });
|
||||||
|
const b = req.body || {};
|
||||||
|
if (clip(b.hp)) return res.json({ ok: true }); // 隐藏字段被填了:机器人,假装成功
|
||||||
|
const arr = (v) => { try { const a = JSON.parse(v || '[]'); return Array.isArray(a) ? a : []; } catch (e) { return []; } };
|
||||||
|
const v = {
|
||||||
|
id: uid('vis'), at: Date.now(), status: 'new',
|
||||||
|
date: clip(b.date, 10), hour: parseInt(b.hour, 10), people: parseInt(b.people, 10),
|
||||||
|
name: clip(b.name, 80), title: clip(b.title, 80), company: clip(b.company, 160), website: clip(b.website, 200),
|
||||||
|
phone: clip(b.phone, 60), email: clip(b.email, 120),
|
||||||
|
products: arr(b.products).map((x) => clip(x, 80)).filter(Boolean).slice(0, 40), productsOther: clip(b.productsOther, 500),
|
||||||
|
places: [...new Set(arr(b.places).map(String))].filter((k) => VISIT_PLACES[k]),
|
||||||
|
notes: clip(b.notes, 2000), lang: clip(b.lang, 5), page: clip(b.page, 300),
|
||||||
|
country: clip(req.headers['cf-ipcountry'], 2), ipHash: ipHash(ip),
|
||||||
|
};
|
||||||
|
const bad = [];
|
||||||
|
if (!visitDateOk(v.date)) bad.push('date');
|
||||||
|
if (!VISIT_HOURS.includes(v.hour)) bad.push('hour');
|
||||||
|
if (!(v.people >= 1 && v.people <= 50)) bad.push('people');
|
||||||
|
if (!v.name) bad.push('name');
|
||||||
|
if (!v.title) bad.push('title');
|
||||||
|
if (!v.company) bad.push('company');
|
||||||
|
if (!v.phone) bad.push('phone');
|
||||||
|
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.email)) bad.push('email');
|
||||||
|
if (!v.places.length) bad.push('places');
|
||||||
|
const f = req.file, kind = f && sniffLicense(f.buffer);
|
||||||
|
if (!f) bad.push('license'); else if (!kind) bad.push('license_type');
|
||||||
|
if (bad.length) return res.status(400).json({ error: 'invalid', fields: bad });
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(VISIT_DIR, { recursive: true });
|
||||||
|
const stored = v.id + kind.ext;
|
||||||
|
fs.writeFileSync(path.join(VISIT_DIR, stored), f.buffer);
|
||||||
|
v.license = { stored, mime: kind.mime, size: f.size, name: clip(fixName(f.originalname), 160) };
|
||||||
|
} catch (e) { console.warn('[visit] 保存营业执照失败:', e.message); return res.status(500).json({ error: 'save_failed' }); }
|
||||||
|
store.visits = [v, ...(store.visits || [])].slice(0, 2000);
|
||||||
|
bump(null);
|
||||||
|
notifyVisit(v);
|
||||||
|
res.json({ ok: true, id: v.id });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
// 后台:列表、营业执照文件、改状态 / 备注、删除
|
||||||
|
app.get('/api/chat/admin/visits', requireAuth, (req, res) => res.json({ list: store.visits || [], places: VISIT_PLACES }));
|
||||||
|
app.get('/api/chat/admin/visits/:id/license', requireAuth, (req, res) => {
|
||||||
|
const v = (store.visits || []).find((x) => x.id === req.params.id);
|
||||||
|
if (!v || !v.license) return res.status(404).end();
|
||||||
|
const fp = path.join(VISIT_DIR, path.basename(v.license.stored));
|
||||||
|
if (!fs.existsSync(fp)) return res.status(404).end();
|
||||||
|
res.setHeader('Content-Type', v.license.mime);
|
||||||
|
res.setHeader('Content-Disposition', `inline; filename="license${path.extname(v.license.stored)}"`);
|
||||||
|
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||||
|
fs.createReadStream(fp).pipe(res);
|
||||||
|
});
|
||||||
|
app.post('/api/chat/admin/visits/:id', requireAuth, (req, res) => {
|
||||||
|
const v = (store.visits || []).find((x) => x.id === req.params.id);
|
||||||
|
if (!v) return res.status(404).json({ error: 'not found' });
|
||||||
|
const b = req.body || {};
|
||||||
|
if (VISIT_STATUS.includes(b.status)) v.status = b.status;
|
||||||
|
if (typeof b.memo === 'string') v.memo = b.memo.slice(0, 4000);
|
||||||
|
v.updated = Date.now(); bump(null);
|
||||||
|
res.json({ ok: true, visit: v });
|
||||||
|
});
|
||||||
|
app.post('/api/chat/admin/visits/:id/delete', requireAuth, (req, res) => {
|
||||||
|
const v = (store.visits || []).find((x) => x.id === req.params.id);
|
||||||
|
if (!v) return res.status(404).json({ error: 'not found' });
|
||||||
|
store.visits = store.visits.filter((x) => x !== v);
|
||||||
|
if (v.license) { try { fs.unlinkSync(path.join(VISIT_DIR, path.basename(v.license.stored))); } catch (e) { /* 已经没了 */ } }
|
||||||
|
bump(null);
|
||||||
|
res.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
/* ---------------- 后台接口 ---------------- */
|
/* ---------------- 后台接口 ---------------- */
|
||||||
const A = '/api/chat/admin';
|
const A = '/api/chat/admin';
|
||||||
const summary = (c) => {
|
const summary = (c) => {
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue