Skip to content

Push mails

Christophe BENARD edited this page Jul 20, 2021 · 4 revisions
require('module-alias/register');
const { sequelize } = require('#db/models');
const userModel = require('#server/models/userModel')(sequelize);
const agenda = require('#server/loaders/agendaLoader')();

function getTime(registered_since, days) {
    return days - Math.ceil((((registered_since / 24) / 60) / 60));
}

function scheduleJ14(row) {
    agenda.schedule(
        `in ${getTime(row.seconds_since_registration, 14)} days`,
        'idealco_invitation',
        {
            user: row.user,
        },
    );
}

function scheduleJ30(row) {
    agenda.schedule(
        `in ${getTime(row.seconds_since_registration, 30)} days`,
        'user_features',
        {
            user: row.user,
        },
    );
}

function scheduleJ60(row) {
    agenda.schedule(
        `in ${getTime(row.seconds_since_registration, 60)} days`,
        'user_share',
        {
            user: row.user,
        },
    );
}

function scheduleJ90(row) {
    agenda.schedule(
        `in ${getTime(row.seconds_since_registration, 90)} days`,
        'user_review',
        {
            user: row.user,
        },
    );
}

(async () => {
    const users = await sequelize.query(
        `SELECT
            user_id,
            EXTRACT(epoch FROM NOW()) - EXTRACT(epoch FROM ua.used_at) AS "seconds_since_registration",
            FLOOR(EXTRACT(epoch FROM (NOW() - ua.used_at)) / (60 * 60 * 24))::INTEGER AS "registered_since_days"
        FROM users u
        LEFT JOIN user_accesses ua ON ua.fk_user = u.user_id
        WHERE ua.used_at IS NOT NULL AND (NOW() - ua.used_at) < '90 days'
        ORDER BY used_at DESC`,
        {
            type: sequelize.QueryTypes.SELECT,
        },
    );

    const hashedUsers = users.reduce((acc, row) => ({
        ...acc,
        [row.user_id]: row,
    }), {});

    (await userModel.findByIds(null, Object.keys(hashedUsers)))
        .forEach((row) => {
            hashedUsers[row.id].user = row;
        });

    try {
        await Promise.all(
            users.reduce((promises, row) => {
                if (row.registered_since_days < 14) {
                    promises.push(scheduleJ14(row));
                }
                if (row.registered_since_days < 30) {
                    promises.push(scheduleJ30(row));
                }
                if (row.registered_since_days < 60) {
                    promises.push(scheduleJ60(row));
                }
                if (row.registered_since_days < 90) {
                    promises.push(scheduleJ90(row));
                }

                return promises;
            }, []),
        );
    } catch (error) {
        console.log(error);
        throw error;
    }

    console.log('Success!');
})();