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 CommunicationsDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const communications = await db.communications.create( { id: data.id || undefined, message: data.message || null, importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await communications.setEvent(data.event || null, { transaction, }); await communications.setRecipients(data.recipients || [], { transaction, }); return communications; } 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 communicationsData = data.map((item, index) => ({ id: item.id || undefined, message: item.message || null, importHash: item.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, createdAt: new Date(Date.now() + index * 1000), })); // Bulk create items const communications = await db.communications.bulkCreate( communicationsData, { transaction }, ); // For each item created, replace relation files return communications; } static async update(id, data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const communications = await db.communications.findByPk( id, {}, { transaction }, ); const updatePayload = {}; if (data.message !== undefined) updatePayload.message = data.message; updatePayload.updatedById = currentUser.id; await communications.update(updatePayload, { transaction }); if (data.event !== undefined) { await communications.setEvent( data.event, { transaction }, ); } if (data.recipients !== undefined) { await communications.setRecipients(data.recipients, { transaction }); } return communications; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const communications = await db.communications.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of communications) { await record.update({ deletedBy: currentUser.id }, { transaction }); } for (const record of communications) { await record.destroy({ transaction }); } }); return communications; } static async remove(id, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const communications = await db.communications.findByPk(id, options); await communications.update( { deletedBy: currentUser.id, }, { transaction, }, ); await communications.destroy({ transaction, }); return communications; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const communications = await db.communications.findOne( { where }, { transaction }, ); if (!communications) { return communications; } const output = communications.get({ plain: true }); output.event = await communications.getEvent({ transaction, }); output.recipients = await communications.getRecipients({ 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.events, as: 'event', where: filter.event ? { [Op.or]: [ { id: { [Op.in]: filter.event .split('|') .map((term) => Utils.uuid(term)), }, }, { name: { [Op.or]: filter.event .split('|') .map((term) => ({ [Op.iLike]: `%${term}%` })), }, }, ], } : {}, }, { model: db.volunteers, as: 'recipients', required: false, }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.message) { where = { ...where, [Op.and]: Utils.ilike('communications', 'message', filter.message), }; } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true', }; } if (filter.recipients) { const searchTerms = filter.recipients.split('|'); include = [ { model: db.volunteers, as: 'recipients_filter', required: searchTerms.length > 0, where: searchTerms.length > 0 ? { [Op.or]: [ { id: { [Op.in]: searchTerms.map((term) => Utils.uuid(term)), }, }, { first_name: { [Op.or]: searchTerms.map((term) => ({ [Op.iLike]: `%${term}%`, })), }, }, ], } : undefined, }, ...include, ]; } 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.communications.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('communications', 'message', query), ], }; } const records = await db.communications.findAll({ attributes: ['id', 'message'], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['message', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.message, })); } };