diff --git a/api-server.js b/api-server.js index 6fe03a3..defa85d 100644 --- a/api-server.js +++ b/api-server.js @@ -126,38 +126,47 @@ function sendResendMail(to, subject, html) { }); } +function flushPending() { + if (!MAIL_TO || !RESEND_KEY) { return; } + const messages = readMessages(); + const pending = messages.filter(m => !m.notified); + if (!pending.length) { return; } + const lines = pending.map((m, i) => + `${i + 1}${m.name}${m.email || '-'}${m.countryCode || ''} ${m.phone || '-'}${m.inquiryType}${m.message}${new Date(m.createdAt).toLocaleString('zh-CN')}` + ).join(''); + const html = `

海古纪网站 - 新联系消息汇总

共有 ${pending.length} 条新消息:

+ + +${lines}
#姓名邮箱电话咨询类型消息内容提交时间
`; + const now = new Date().toISOString(); + sendResendMail(MAIL_TO, `【海古纪-联系我们】${pending.length} 条新消息汇总`, html) + .then(r => { + if (r && r.id) { + const updated = messages.map(m => m.notified ? m : { ...m, notified: true, notifiedAt: now }); + writeMessages(updated); + console.log(`汇总邮件已发送 (${pending.length} 条) 至 ${MAIL_TO}`); + } else { + console.error('汇总邮件发送失败:', JSON.stringify(r)); + } + }) + .catch(err => console.error('汇总邮件发送失败:', err.message)); +} + let summaryTimer = null; function scheduleSummary() { if (summaryTimer) return; summaryTimer = setTimeout(() => { summaryTimer = null; - if (!MAIL_TO || !RESEND_KEY) { return; } - const messages = readMessages(); - const pending = messages.filter(m => !m.notified); - if (!pending.length) { return; } - const lines = pending.map((m, i) => - `${i + 1}${m.name}${m.email || '-'}${m.countryCode || ''} ${m.phone || '-'}${m.inquiryType}${m.message}${new Date(m.createdAt).toLocaleString('zh-CN')}` - ).join(''); - const html = `

海古纪网站 - 新联系消息汇总

共有 ${pending.length} 条新消息:

- - -${lines}
#姓名邮箱电话咨询类型消息内容提交时间
`; - const now = new Date().toISOString(); - sendResendMail(MAIL_TO, `【海古纪-联系我们】${pending.length} 条新消息汇总`, html) - .then(r => { - if (r && r.id) { - const updated = messages.map(m => m.notified ? m : { ...m, notified: true, notifiedAt: now }); - writeMessages(updated); - console.log(`汇总邮件已发送 (${pending.length} 条) 至 ${MAIL_TO}`); - } else { - console.error('汇总邮件发送失败:', JSON.stringify(r)); - } - }) - .catch(err => console.error('汇总邮件发送失败:', err.message)); + flushPending(); }, SUMMARY_INTERVAL); } +function sendSummaryImmediately() { + flushPending(); + scheduleSummary(); +} + const server = http.createServer((req, res) => { if (req.method === 'OPTIONS') { res.writeHead(204, { 'Access-Control-Allow-Origin': CORS_ORIGIN, 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Max-Age': '86400' }); @@ -177,8 +186,8 @@ server.listen(PORT, () => { console.log(`✅ 有表单提交后 ${SUMMARY_INTERVAL / 60000} 分钟发送汇总邮件至 ${MAIL_TO}`); const pending = readMessages().filter(m => !m.notified); if (pending.length > 0) { - console.log(`检测到 ${pending.length} 条未发送的待处理消息,启动汇总定时器`); - scheduleSummary(); + console.log(`检测到 ${pending.length} 条未发送的待处理消息,立即发送汇总`); + sendSummaryImmediately(); } } });