40329-vm/backend/src/db/api/interview_responses.js
2026-06-25 16:37:26 +00:00

634 lines
16 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 Interview_responsesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const interview_responses = await db.interview_responses.create(
{
id: data.id || undefined,
turn_number: data.turn_number
||
null
,
response_format: data.response_format
||
null
,
response_text: data.response_text
||
null
,
is_clarification: data.is_clarification
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await interview_responses.setInterview( data.interview || null, {
transaction,
});
await interview_responses.setQuestion( data.question || null, {
transaction,
});
await interview_responses.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.interview_responses.getTableName(),
belongsToColumn: 'audio_attachments',
belongsToId: interview_responses.id,
},
data.audio_attachments,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.interview_responses.getTableName(),
belongsToColumn: 'other_attachments',
belongsToId: interview_responses.id,
},
data.other_attachments,
options,
);
return interview_responses;
}
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 interview_responsesData = data.map((item, index) => ({
id: item.id || undefined,
turn_number: item.turn_number
||
null
,
response_format: item.response_format
||
null
,
response_text: item.response_text
||
null
,
is_clarification: item.is_clarification
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const interview_responses = await db.interview_responses.bulkCreate(interview_responsesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < interview_responses.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.interview_responses.getTableName(),
belongsToColumn: 'audio_attachments',
belongsToId: interview_responses[i].id,
},
data[i].audio_attachments,
options,
);
}
for (let i = 0; i < interview_responses.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.interview_responses.getTableName(),
belongsToColumn: 'other_attachments',
belongsToId: interview_responses[i].id,
},
data[i].other_attachments,
options,
);
}
return interview_responses;
}
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 interview_responses = await db.interview_responses.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.turn_number !== undefined) updatePayload.turn_number = data.turn_number;
if (data.response_format !== undefined) updatePayload.response_format = data.response_format;
if (data.response_text !== undefined) updatePayload.response_text = data.response_text;
if (data.is_clarification !== undefined) updatePayload.is_clarification = data.is_clarification;
updatePayload.updatedById = currentUser.id;
await interview_responses.update(updatePayload, {transaction});
if (data.interview !== undefined) {
await interview_responses.setInterview(
data.interview,
{ transaction }
);
}
if (data.question !== undefined) {
await interview_responses.setQuestion(
data.question,
{ transaction }
);
}
if (data.organizations !== undefined) {
await interview_responses.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.interview_responses.getTableName(),
belongsToColumn: 'audio_attachments',
belongsToId: interview_responses.id,
},
data.audio_attachments,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.interview_responses.getTableName(),
belongsToColumn: 'other_attachments',
belongsToId: interview_responses.id,
},
data.other_attachments,
options,
);
return interview_responses;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const interview_responses = await db.interview_responses.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of interview_responses) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of interview_responses) {
await record.destroy({transaction});
}
});
return interview_responses;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const interview_responses = await db.interview_responses.findByPk(id, options);
await interview_responses.update({
deletedBy: currentUser.id
}, {
transaction,
});
await interview_responses.destroy({
transaction
});
return interview_responses;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const interview_responses = await db.interview_responses.findOne(
{ where },
{ transaction },
);
if (!interview_responses) {
return interview_responses;
}
const output = interview_responses.get({plain: true});
output.interview = await interview_responses.getInterview({
transaction
});
output.question = await interview_responses.getQuestion({
transaction
});
output.audio_attachments = await interview_responses.getAudio_attachments({
transaction
});
output.other_attachments = await interview_responses.getOther_attachments({
transaction
});
output.organizations = await interview_responses.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.interviews,
as: 'interview',
where: filter.interview ? {
[Op.or]: [
{ id: { [Op.in]: filter.interview.split('|').map(term => Utils.uuid(term)) } },
{
context_notes: {
[Op.or]: filter.interview.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.questions,
as: 'question',
where: filter.question ? {
[Op.or]: [
{ id: { [Op.in]: filter.question.split('|').map(term => Utils.uuid(term)) } },
{
prompt: {
[Op.or]: filter.question.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'audio_attachments',
},
{
model: db.file,
as: 'other_attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.response_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'interview_responses',
'response_text',
filter.response_text,
),
};
}
if (filter.turn_numberRange) {
const [start, end] = filter.turn_numberRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
turn_number: {
...where.turn_number,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
turn_number: {
...where.turn_number,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.response_format) {
where = {
...where,
response_format: filter.response_format,
};
}
if (filter.is_clarification) {
where = {
...where,
is_clarification: filter.is_clarification,
};
}
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.interview_responses.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(
'interview_responses',
'response_text',
query,
),
],
};
}
const records = await db.interview_responses.findAll({
attributes: [ 'id', 'response_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['response_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.response_text,
}));
}
};