add email logs

This commit is contained in:
Rizki
2026-04-15 11:45:01 +07:00
parent ed97e695d1
commit dd815d8a8c

View File

@ -33,16 +33,27 @@ Procurement Division<br>
Finance Business Partner Unit</p>`;
}
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);