add notificationService to handle when, what and to whom to send email

This commit is contained in:
Bilal Catic
2019-09-30 10:28:29 +02:00
parent 9c0104a57c
commit a738a371ae

View File

@@ -1,28 +1,56 @@
const db = require("../models/index");
const { allMarketAlerts } = require("../helpers/db/dbHelper");
"use strict";
const {
createMarketAlertEmailTemplate,
sendBulkEmail
} = require("../helpers/awsEmail");
findSearchRequestsForRealEstate
} = require("../helpers/db/searchRequest");
const {
generateNotificationEmail,
generateNewSearchRequestEmail
} = require("../helpers/emailContentGenerator");
const { sendEmail } = require("../services/emailService");
async function processNotifications() {
try {
const marketAlerts = await allMarketAlerts(false, false);
await createMarketAlertEmailTemplate();
if (marketAlerts.length > 0) {
await sendBulkEmail(marketAlerts);
}
const notifyForNewRealEstates = async newRealEstates => {
const matches = {};
const asyncSearchActions = [];
for (const realEstate of newRealEstates) {
const searchRequestsPromise = findSearchRequestsForRealEstate(realEstate);
await db.MarketAlert.update(
{ notified: true } /* set attributes' value */,
{ where: { notified: false } } /* where criteria */
);
} catch (e) {
console.log(
"NOTIFICATION SERVICE: could not send notifications reason: ",
e
);
asyncSearchActions.push(searchRequestsPromise);
searchRequestsPromise.then(searchRequests => {
for (const searchRequest of searchRequests) {
const { id } = searchRequest;
if (!matches[id]) {
matches[id] = {
searchRequest,
realEstates: []
};
}
matches[id].realEstates.push(realEstate);
}
});
}
}
module.exports = processNotifications;
await Promise.all(asyncSearchActions);
const searchRequestsToNotify = Object.keys(matches);
for (const id of searchRequestsToNotify) {
const { searchRequest } = matches[id];
const { email } = searchRequest;
const allMatchingRealEstates = matches[id].realEstates || [];
const emailContent = generateNotificationEmail(allMatchingRealEstates, id);
const res = await sendEmail(email, "Nove nekretnine", emailContent);
console.log("Email sent, result :", res);
}
};
const notifyForNewSearchRequest = async searchRequest => {
const emailContent = generateNewSearchRequestEmail(searchRequest);
const { email } = searchRequest;
await sendEmail(email, "Market Alert", emailContent);
};
module.exports = {
notifyForNewRealEstates,
notifyForNewSearchRequest
};