39218-vm/backend/src/db/api/communications.js
2026-03-16 16:27:18 +00:00

632 lines
15 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 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,
audience: data.audience
||
null
,
channel: data.channel
||
null
,
occurred_at: data.occurred_at
||
null
,
subject: data.subject
||
null
,
body: data.body
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await communications.setEvent( data.event || null, {
transaction,
});
await communications.setOwner( data.owner || null, {
transaction,
});
await communications.setVendor_booking( data.vendor_booking || null, {
transaction,
});
await communications.setGuest( data.guest || 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,
audience: item.audience
||
null
,
channel: item.channel
||
null
,
occurred_at: item.occurred_at
||
null
,
subject: item.subject
||
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.audience !== undefined) updatePayload.audience = data.audience;
if (data.channel !== undefined) updatePayload.channel = data.channel;
if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
if (data.subject !== undefined) updatePayload.subject = data.subject;
if (data.body !== undefined) updatePayload.body = data.body;
updatePayload.updatedById = currentUser.id;
await communications.update(updatePayload, {transaction});
if (data.event !== undefined) {
await communications.setEvent(
data.event,
{ transaction }
);
}
if (data.owner !== undefined) {
await communications.setOwner(
data.owner,
{ transaction }
);
}
if (data.vendor_booking !== undefined) {
await communications.setVendor_booking(
data.vendor_booking,
{ transaction }
);
}
if (data.guest !== undefined) {
await communications.setGuest(
data.guest,
{ 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.event = await communications.getEvent({
transaction
});
output.owner = await communications.getOwner({
transaction
});
output.vendor_booking = await communications.getVendor_booking({
transaction
});
output.guest = await communications.getGuest({
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.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.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.event_vendor_bookings,
as: 'vendor_booking',
where: filter.vendor_booking ? {
[Op.or]: [
{ id: { [Op.in]: filter.vendor_booking.split('|').map(term => Utils.uuid(term)) } },
{
scope_of_work: {
[Op.or]: filter.vendor_booking.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.guests,
as: 'guest',
where: filter.guest ? {
[Op.or]: [
{ id: { [Op.in]: filter.guest.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.guest.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.subject) {
where = {
...where,
[Op.and]: Utils.ilike(
'communications',
'subject',
filter.subject,
),
};
}
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.audience) {
where = {
...where,
audience: filter.audience,
};
}
if (filter.channel) {
where = {
...where,
channel: filter.channel,
};
}
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',
'subject',
query,
),
],
};
}
const records = await db.communications.findAll({
attributes: [ 'id', 'subject' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['subject', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.subject,
}));
}
};