diff --git a/public-api.js b/public-api.js index 6bd4bb7..8cc7b45 100644 --- a/public-api.js +++ b/public-api.js @@ -1789,6 +1789,121 @@ ${dialog}`; res.json({ ok: true }); }); + /* ---------------- 售后服务申请(网站 /service/ 页面提交) ---------------- */ + // 客户填写产品(类目、型号、数量、SN 码、购买时间、购买渠道)、故障(类型、是否还能运行、故障代码、描述、最多 3 张照片/PDF)、 + // 所在地区、联系方式。记录存在 chat-data.json 的 services 里,附件存在 service-files/;后台"网站管理 → 售后服务"处理。 + // 每张单有一个给客户看的单号,如 SV-20261114-7Q3K。 + const SVC_DIR = path.join(path.dirname(dataFile), 'service-files'); + const SVC_STATUS = ['new', 'processing', 'waiting', 'resolved', 'closed']; + const SVC_ISSUES = ['no_power', 'alarm', 'battery', 'no_backup', 'noise', 'install', 'parts', 'warranty', 'other']; + const SVC_ISSUE_ZH = { no_power: '无法开机 / 无输出', alarm: '报警 / 故障代码', battery: '电池问题', no_backup: '断电不切换 / 后备时间短', noise: '异响 / 发热 / 异味', install: '安装 / 调试 / 设置', parts: '需要备件', warranty: '保修咨询', other: '其他' }; + const SVC_RUNNING_ZH = { yes: '还在运行', partial: '部分功能可用', no: '已停机' }; + let svcUpload = null; + try { + const multer = require('multer'); + svcUpload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 10 * 1024 * 1024, files: 3, fields: 50, fieldSize: 20000 } }).array('files', 3); + } catch (e) { console.warn('[service] multer 不可用:', e.message); } + const svcRef = () => { + const A = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; + let r = ''; for (const b of crypto.randomBytes(4)) r += A[b % A.length]; + return `SV-${today().replace(/-/g, '')}-${r}`; + }; + async function notifyService(v) { + const st = S(); + if (!st.wecomWebhook) return; + const panel = (st.panelUrl || conf('PUBLIC_BASE_URL') || '').replace(/\/$/, ''); + const content = [ + `**🛠 新的售后服务申请 ${v.ref}**`, + `> ${v.model || '型号未填'}${v.category ? `(${v.category})` : ''} × ${v.qty}${v.sns.length ? ` · SN ${v.sns.slice(0, 3).join(', ')}${v.sns.length > 3 ? ` 等 ${v.sns.length} 个` : ''}` : ''}`, + `> 问题:${v.issues.map((k) => SVC_ISSUE_ZH[k]).join('、') || '—'}${v.running ? ` · ${SVC_RUNNING_ZH[v.running]}` : ''}${v.errorCode ? ` · 代码 ${v.errorCode}` : ''}`, + `> 地区:${[v.city, v.country].filter(Boolean).join(', ') || '—'}${v.purchase ? ` · 购买 ${v.purchase}` : ''}`, + `> ${[v.company, v.name].filter(Boolean).join(' / ')} · ${[v.phone, v.email].filter(Boolean).join(' · ')}`, + v.files.length ? `> 附件 ${v.files.length} 个` : '', + panel ? `[打开工单](${panel}/?service=${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('[service] 企业微信推送失败:', r.status); + } catch (e) { console.warn('[service] 企业微信推送失败:', e.message); } + } + app.post('/api/chat/service', (req, res) => { + if (!svcUpload) return res.status(503).json({ error: 'unavailable' }); + const ip = ipOf(req); + if (limited('service:' + ip, 8, 3600e3)) return res.status(429).json({ error: 'too_many' }); + svcUpload(req, res, (err) => { + if (err) return res.status(400).json({ error: err.code === 'LIMIT_FILE_SIZE' ? 'file_too_big' : err.code === 'LIMIT_FILE_COUNT' || err.code === 'LIMIT_UNEXPECTED_FILE' ? 'too_many_files' : 'bad_upload' }); + const b = req.body || {}; + if (clip(b.hp)) return res.json({ ok: true, ref: svcRef() }); + const arr = (v) => { try { const a = JSON.parse(v || '[]'); return Array.isArray(a) ? a : []; } catch (e) { return []; } }; + const v = { + id: uid('svc'), ref: svcRef(), at: Date.now(), status: 'new', + category: clip(b.category, 80), model: clip(b.model, 120), qty: parseInt(b.qty, 10), + sns: [...new Set(String(b.sns || '').split(/[\n,;,;]+/).map((x) => clip(x, 60)).filter(Boolean))].slice(0, 200), + purchase: /^\d{4}-\d{2}$/.test(String(b.purchase || '')) ? String(b.purchase) : '', + channel: ['direct', 'distributor', 'other'].includes(b.channel) ? b.channel : '', seller: clip(b.seller, 160), order: clip(b.order, 80), + issues: [...new Set(arr(b.issues).map(String))].filter((k) => SVC_ISSUES.includes(k)), + running: ['yes', 'partial', 'no'].includes(b.running) ? b.running : '', + errorCode: clip(b.errorCode, 120), desc: clip(b.desc, 4000), + country: clip(b.country, 80), city: clip(b.city, 120), site: clip(b.site, 300), + name: clip(b.name, 80), company: clip(b.company, 160), phone: clip(b.phone, 60), email: clip(b.email, 120), + lang: clip(b.lang, 5), page: clip(b.page, 300), ipCountry: clip(req.headers['cf-ipcountry'], 2), ipHash: ipHash(ip), files: [], + }; + const bad = []; + if (!v.model) bad.push('model'); + if (!(v.qty >= 1 && v.qty <= 100000)) bad.push('qty'); + if (!v.issues.length) bad.push('issues'); + if (v.desc.length < 5) bad.push('desc'); + if (!v.country) bad.push('country'); + if (!v.name) bad.push('name'); + if (!v.phone) bad.push('phone'); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.email)) bad.push('email'); + const files = (req.files || []).map((f) => ({ f, kind: sniffLicense(f.buffer) })); + if (files.some((x) => !x.kind)) bad.push('file_type'); + if (bad.length) return res.status(400).json({ error: 'invalid', fields: bad }); + try { + if (files.length) fs.mkdirSync(SVC_DIR, { recursive: true }); + files.forEach(({ f, kind }, i) => { + const stored = `${v.id}-${i + 1}${kind.ext}`; + fs.writeFileSync(path.join(SVC_DIR, stored), f.buffer); + v.files.push({ stored, mime: kind.mime, size: f.size, name: clip(fixName(f.originalname), 160) }); + }); + } catch (e) { console.warn('[service] 保存附件失败:', e.message); return res.status(500).json({ error: 'save_failed' }); } + store.services = [v, ...(store.services || [])].slice(0, 3000); + bump(null); + notifyService(v); + res.json({ ok: true, ref: v.ref }); + }); + }); + app.get('/api/chat/admin/services', requireAuth, (req, res) => res.json({ list: store.services || [] })); + app.get('/api/chat/admin/services/:id/file/:n', requireAuth, (req, res) => { + const v = (store.services || []).find((x) => x.id === req.params.id); + const f = v && v.files[parseInt(req.params.n, 10)]; + if (!f) return res.status(404).end(); + const fp = path.join(SVC_DIR, path.basename(f.stored)); + if (!fs.existsSync(fp)) return res.status(404).end(); + res.setHeader('Content-Type', f.mime); + res.setHeader('Content-Disposition', `inline; filename="file${path.extname(f.stored)}"`); + res.setHeader('X-Content-Type-Options', 'nosniff'); + fs.createReadStream(fp).pipe(res); + }); + app.post('/api/chat/admin/services/:id', requireAuth, (req, res) => { + const v = (store.services || []).find((x) => x.id === req.params.id); + if (!v) return res.status(404).json({ error: 'not found' }); + const b = req.body || {}; + if (SVC_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, item: v }); + }); + app.post('/api/chat/admin/services/:id/delete', requireAuth, (req, res) => { + const v = (store.services || []).find((x) => x.id === req.params.id); + if (!v) return res.status(404).json({ error: 'not found' }); + store.services = store.services.filter((x) => x !== v); + for (const f of v.files || []) { try { fs.unlinkSync(path.join(SVC_DIR, path.basename(f.stored))); } catch (e) { /* 已经没了 */ } } + bump(null); + res.json({ ok: true }); + }); + /* ---------------- 后台接口 ---------------- */ const A = '/api/chat/admin'; const summary = (c) => {