ads-marketing/mail-service/src/service/queueFiller.js
romantarkin 8a425b16e7 fix
2025-07-29 10:59:23 +05:00

59 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import dns from 'dns/promises';
import { topicManager } from './topicManager.js';
async function getMxDomain(email) {
const domain = email.split('@')[1];
try {
const mxRecords = await dns.resolveMx(domain);
if (mxRecords && mxRecords.length > 0) {
// Берём самый приоритетный MX
return mxRecords.sort((a, b) => a.priority - b.priority)[0].exchange;
}
} catch (e) {}
return domain;
}
export async function fillQueueForCampaign(campaign, subscribers, smtpServers) {
// Группируем подписчиков по домену
const domainMap = {};
for (const sub of subscribers) {
const domain = sub.email.split('@')[1];
if (!domainMap[domain]) domainMap[domain] = [];
domainMap[domain].push(sub);
}
// Обрабатываем каждый домен и SMTP сервер
for (const [domain, subs] of Object.entries(domainMap)) {
for (const smtp of smtpServers) {
const topicName = `mail-send-${domain}-${smtp.id}`;
// Создаем топик если его нет
const topicCreated = await topicManager.createTopic(topicName);
if (!topicCreated) {
console.error(`[queueFiller] Failed to create topic: ${topicName}`);
continue;
}
// Отправляем сообщения в топик
const messages = subs.map(sub => ({
campaignId: campaign.id,
subject: campaign.subject,
text: campaign.text,
html: campaign.html,
mx: domain, // для обратной совместимости
subscriberId: sub.id,
email: sub.email,
smtpServerId: smtp.id,
}));
for (const message of messages) {
const sent = await topicManager.sendMessage(topicName, message);
if (!sent) {
console.error(`[queueFiller] Failed to send message to topic: ${topicName}`);
}
}
console.log(`[queueFiller] Sent ${messages.length} messages to topic: ${topicName}`);
}
}
}