From a738a371aec2d0217f7ec0c01b3ae3823566de37 Mon Sep 17 00:00:00 2001 From: Bilal Catic Date: Mon, 30 Sep 2019 10:28:29 +0200 Subject: [PATCH] add notificationService to handle when, what and to whom to send email --- app/services/notificationService.js | 74 ++++++++++++++++++++--------- 1 file changed, 51 insertions(+), 23 deletions(-) diff --git a/app/services/notificationService.js b/app/services/notificationService.js index e5625ca..f7500af 100644 --- a/app/services/notificationService.js +++ b/app/services/notificationService.js @@ -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 +};