30537/backend/src/db/api/subscribers.js
2025-04-07 15:12:14 +00:00

380 lines
8.8 KiB
JavaScript

const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class SubscribersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subscribers = await db.subscribers.create(
{
id: data.id || undefined,
email: data.email || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await subscribers.setCategory(data.category || null, {
transaction,
});
await subscribers.setGeo(data.geo || null, {
transaction,
});
await subscribers.setEngagement(data.engagement || null, {
transaction,
});
return subscribers;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const subscribersData = data.map((item, index) => ({
id: item.id || undefined,
email: item.email || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const subscribers = await db.subscribers.bulkCreate(subscribersData, {
transaction,
});
// For each item created, replace relation files
return subscribers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subscribers = await db.subscribers.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.email !== undefined) updatePayload.email = data.email;
updatePayload.updatedById = currentUser.id;
await subscribers.update(updatePayload, { transaction });
if (data.category !== undefined) {
await subscribers.setCategory(
data.category,
{ transaction },
);
}
if (data.geo !== undefined) {
await subscribers.setGeo(
data.geo,
{ transaction },
);
}
if (data.engagement !== undefined) {
await subscribers.setEngagement(
data.engagement,
{ transaction },
);
}
return subscribers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subscribers = await db.subscribers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of subscribers) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of subscribers) {
await record.destroy({ transaction });
}
});
return subscribers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subscribers = await db.subscribers.findByPk(id, options);
await subscribers.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await subscribers.destroy({
transaction,
});
return subscribers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const subscribers = await db.subscribers.findOne(
{ where },
{ transaction },
);
if (!subscribers) {
return subscribers;
}
const output = subscribers.get({ plain: true });
output.category = await subscribers.getCategory({
transaction,
});
output.geo = await subscribers.getGeo({
transaction,
});
output.engagement = await subscribers.getEngagement({
transaction,
});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.categories,
as: 'category',
where: filter.category
? {
[Op.or]: [
{
id: {
[Op.in]: filter.category
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
name: {
[Op.or]: filter.category
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.geos,
as: 'geo',
where: filter.geo
? {
[Op.or]: [
{
id: {
[Op.in]: filter.geo
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
country_name: {
[Op.or]: filter.geo
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.engagements,
as: 'engagement',
where: filter.engagement
? {
[Op.or]: [
{
id: {
[Op.in]: filter.engagement
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
level: {
[Op.or]: filter.engagement
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike('subscribers', 'email', filter.email),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order:
filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log,
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.subscribers.findAndCountAll(
queryOptions,
);
return {
rows: options?.countOnly ? [] : rows,
count: count,
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('subscribers', 'email', query),
],
};
}
const records = await db.subscribers.findAll({
attributes: ['id', 'email'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['email', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.email,
}));
}
};