diff --git a/emailnotif.js b/emailnotif.js index 7e84449..c7cd308 100644 --- a/emailnotif.js +++ b/emailnotif.js @@ -33,16 +33,27 @@ Procurement Division
Finance Business Partner Unit

`; } +function logEmail(trxId, toEmail, subject, html, fromEmail, status, responseMessage) { + const qry = ` + INSERT INTO email_logs (trx_id, to_email, subject, body, from_email, is_attachment, status, response_message, created_at) + VALUES (?, ?, ?, ?, ?, 0, ?, ?, NOW()) + `; + db.query(qry, [trxId, toEmail, subject, html, fromEmail, status, responseMessage], function(err) { + if (err) console.error('[email-notif] logEmail failed:', err.message); + }); +} + function postEmail(approverName, title, priorName, idxjustification, remark, status) { const subject = status === 'RETURNED' ? `[Returned] Justification for ${title}` : `[Approval Required] Justification for ${title}`; + const html = buildHtml(approverName, title, priorName, idxjustification, remark, status); const payload = JSON.stringify({ to: [RECIPIENT], cc: [], bcc: [], subject, - html: buildHtml(approverName, title, priorName, idxjustification, remark, status) + html }); const req = http.request({ @@ -55,11 +66,26 @@ function postEmail(approverName, title, priorName, idxjustification, remark, sta 'Content-Length': Buffer.byteLength(payload) } }, (res) => { - console.log('[email-notif] sent, status:', res.statusCode); + let body = ''; + res.on('data', (chunk) => { body += chunk; }); + res.on('end', () => { + let trxId = ''; + let responseMessage = body; + try { + const parsed = JSON.parse(body); + trxId = parsed?.data?.trx_id || ''; + responseMessage = JSON.stringify(parsed); + } catch (_) {} + + const logStatus = res.statusCode >= 200 && res.statusCode < 300 ? 'success' : 'failed'; + console.log('[email-notif] sent, status:', res.statusCode, '| trxId:', trxId); + logEmail(trxId, RECIPIENT, subject, html, '', logStatus, responseMessage); + }); }); req.on('error', (err) => { console.error('[email-notif] failed:', err.message); + logEmail('', RECIPIENT, subject, html, '', 'failed', err.message); }); req.write(payload);