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, channel: data.channel || null , direction: data.direction || null , occurred_at: data.occurred_at || null , summary: data.summary || null , body: data.body || null , importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await communications.setContact( data.contact || null, { transaction, }); await communications.setLead( data.lead || null, { transaction, }); await communications.setDeal( data.deal || null, { transaction, }); await communications.setUser( data.user || null, { transaction, }); await FileDBApi.replaceRelationFiles( { belongsTo: db.communications.getTableName(), belongsToColumn: 'attachments', belongsToId: communications.id, }, data.attachments, options, ); 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, channel: item.channel || null , direction: item.direction || null , occurred_at: item.occurred_at || null , summary: item.summary || null , body: item.body || 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 for (let i = 0; i < communications.length; i++) { await FileDBApi.replaceRelationFiles( { belongsTo: db.communications.getTableName(), belongsToColumn: 'attachments', belongsToId: communications[i].id, }, data[i].attachments, options, ); } 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.channel !== undefined) updatePayload.channel = data.channel; if (data.direction !== undefined) updatePayload.direction = data.direction; if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at; if (data.summary !== undefined) updatePayload.summary = data.summary; if (data.body !== undefined) updatePayload.body = data.body; updatePayload.updatedById = currentUser.id; await communications.update(updatePayload, {transaction}); if (data.contact !== undefined) { await communications.setContact( data.contact, { transaction } ); } if (data.lead !== undefined) { await communications.setLead( data.lead, { transaction } ); } if (data.deal !== undefined) { await communications.setDeal( data.deal, { transaction } ); } if (data.user !== undefined) { await communications.setUser( data.user, { transaction } ); } await FileDBApi.replaceRelationFiles( { belongsTo: db.communications.getTableName(), belongsToColumn: 'attachments', belongsToId: communications.id, }, data.attachments, options, ); 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.contact = await communications.getContact({ transaction }); output.lead = await communications.getLead({ transaction }); output.deal = await communications.getDeal({ transaction }); output.user = await communications.getUser({ transaction }); output.attachments = await communications.getAttachments({ 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.contacts, as: 'contact', where: filter.contact ? { [Op.or]: [ { id: { [Op.in]: filter.contact.split('|').map(term => Utils.uuid(term)) } }, { full_name: { [Op.or]: filter.contact.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } }, ] } : {}, }, { model: db.leads, as: 'lead', where: filter.lead ? { [Op.or]: [ { id: { [Op.in]: filter.lead.split('|').map(term => Utils.uuid(term)) } }, { lead_title: { [Op.or]: filter.lead.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } }, ] } : {}, }, { model: db.deals, as: 'deal', where: filter.deal ? { [Op.or]: [ { id: { [Op.in]: filter.deal.split('|').map(term => Utils.uuid(term)) } }, { deal_name: { [Op.or]: filter.deal.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } }, ] } : {}, }, { model: db.users, as: 'user', where: filter.user ? { [Op.or]: [ { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } }, { firstName: { [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } }, ] } : {}, }, { model: db.file, as: 'attachments', }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.summary) { where = { ...where, [Op.and]: Utils.ilike( 'communications', 'summary', filter.summary, ), }; } if (filter.body) { where = { ...where, [Op.and]: Utils.ilike( 'communications', 'body', filter.body, ), }; } if (filter.occurred_atRange) { const [start, end] = filter.occurred_atRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, occurred_at: { ...where.occurred_at, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, occurred_at: { ...where.occurred_at, [Op.lte]: end, }, }; } } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true' }; } if (filter.channel) { where = { ...where, channel: filter.channel, }; } if (filter.direction) { where = { ...where, direction: filter.direction, }; } 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', 'summary', query, ), ], }; } const records = await db.communications.findAll({ attributes: [ 'id', 'summary' ], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['summary', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.summary, })); } };