29942/backend/src/db/api/calls.js
2025-03-16 21:11:55 +00:00

517 lines
12 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 CallsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const calls = await db.calls.create(
{
id: data.id || undefined,
call_time: data.call_time || null,
duration_seconds: data.duration_seconds || null,
twilio_call_sid: data.twilio_call_sid || null,
recording_url: data.recording_url || null,
transcript: data.transcript || null,
summary: data.summary || null,
notes: data.notes || null,
call_type: data.call_type || null,
outcome: data.outcome || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await calls.setContact(data.contact || null, {
transaction,
});
await calls.setUser(data.user || null, {
transaction,
});
await calls.setOrganizations(data.organizations || null, {
transaction,
});
return calls;
}
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 callsData = data.map((item, index) => ({
id: item.id || undefined,
call_time: item.call_time || null,
duration_seconds: item.duration_seconds || null,
twilio_call_sid: item.twilio_call_sid || null,
recording_url: item.recording_url || null,
transcript: item.transcript || null,
summary: item.summary || null,
notes: item.notes || null,
call_type: item.call_type || null,
outcome: item.outcome || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const calls = await db.calls.bulkCreate(callsData, { transaction });
// For each item created, replace relation files
return calls;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const calls = await db.calls.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.call_time !== undefined) updatePayload.call_time = data.call_time;
if (data.duration_seconds !== undefined)
updatePayload.duration_seconds = data.duration_seconds;
if (data.twilio_call_sid !== undefined)
updatePayload.twilio_call_sid = data.twilio_call_sid;
if (data.recording_url !== undefined)
updatePayload.recording_url = data.recording_url;
if (data.transcript !== undefined)
updatePayload.transcript = data.transcript;
if (data.summary !== undefined) updatePayload.summary = data.summary;
if (data.notes !== undefined) updatePayload.notes = data.notes;
if (data.call_type !== undefined) updatePayload.call_type = data.call_type;
if (data.outcome !== undefined) updatePayload.outcome = data.outcome;
updatePayload.updatedById = currentUser.id;
await calls.update(updatePayload, { transaction });
if (data.contact !== undefined) {
await calls.setContact(
data.contact,
{ transaction },
);
}
if (data.user !== undefined) {
await calls.setUser(
data.user,
{ transaction },
);
}
if (data.organizations !== undefined) {
await calls.setOrganizations(
data.organizations,
{ transaction },
);
}
return calls;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const calls = await db.calls.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of calls) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of calls) {
await record.destroy({ transaction });
}
});
return calls;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const calls = await db.calls.findByPk(id, options);
await calls.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await calls.destroy({
transaction,
});
return calls;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const calls = await db.calls.findOne({ where }, { transaction });
if (!calls) {
return calls;
}
const output = calls.get({ plain: true });
output.contact = await calls.getContact({
transaction,
});
output.user = await calls.getUser({
transaction,
});
output.organizations = await calls.getOrganizations({
transaction,
});
return output;
}
static async findAll(filter, globalAccess, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
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)),
},
},
{
first_name: {
[Op.or]: filter.contact
.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.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.twilio_call_sid) {
where = {
...where,
[Op.and]: Utils.ilike(
'calls',
'twilio_call_sid',
filter.twilio_call_sid,
),
};
}
if (filter.recording_url) {
where = {
...where,
[Op.and]: Utils.ilike('calls', 'recording_url', filter.recording_url),
};
}
if (filter.transcript) {
where = {
...where,
[Op.and]: Utils.ilike('calls', 'transcript', filter.transcript),
};
}
if (filter.summary) {
where = {
...where,
[Op.and]: Utils.ilike('calls', 'summary', filter.summary),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike('calls', 'notes', filter.notes),
};
}
if (filter.outcome) {
where = {
...where,
[Op.and]: Utils.ilike('calls', 'outcome', filter.outcome),
};
}
if (filter.call_timeRange) {
const [start, end] = filter.call_timeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
call_time: {
...where.call_time,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
call_time: {
...where.call_time,
[Op.lte]: end,
},
};
}
}
if (filter.duration_secondsRange) {
const [start, end] = filter.duration_secondsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
duration_seconds: {
...where.duration_seconds,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
duration_seconds: {
...where.duration_seconds,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.call_type) {
where = {
...where,
call_type: filter.call_type,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
organizationsId: { [Op.or]: listItems },
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
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.calls.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,
globalAccess,
organizationId,
) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('calls', 'twilio_call_sid', query),
],
};
}
const records = await db.calls.findAll({
attributes: ['id', 'twilio_call_sid'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['twilio_call_sid', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.twilio_call_sid,
}));
}
};