33606/backend/src/db/api/answers.js
2025-08-25 03:29:10 +00:00

318 lines
7.7 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 AnswersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const answers = await db.answers.create(
{
id: data.id || undefined,
test_section: data.test_section || null,
question_text: data.question_text || null,
answer_value: data.answer_value || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await answers.setAssessment(data.assessment || null, {
transaction,
});
return answers;
}
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 answersData = data.map((item, index) => ({
id: item.id || undefined,
test_section: item.test_section || null,
question_text: item.question_text || null,
answer_value: item.answer_value || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const answers = await db.answers.bulkCreate(answersData, { transaction });
// For each item created, replace relation files
return answers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const answers = await db.answers.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.test_section !== undefined)
updatePayload.test_section = data.test_section;
if (data.question_text !== undefined)
updatePayload.question_text = data.question_text;
if (data.answer_value !== undefined)
updatePayload.answer_value = data.answer_value;
updatePayload.updatedById = currentUser.id;
await answers.update(updatePayload, { transaction });
if (data.assessment !== undefined) {
await answers.setAssessment(
data.assessment,
{ transaction },
);
}
return answers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const answers = await db.answers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of answers) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of answers) {
await record.destroy({ transaction });
}
});
return answers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const answers = await db.answers.findByPk(id, options);
await answers.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await answers.destroy({
transaction,
});
return answers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const answers = await db.answers.findOne({ where }, { transaction });
if (!answers) {
return answers;
}
const output = answers.get({ plain: true });
output.assessment = await answers.getAssessment({
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.assessments,
as: 'assessment',
where: filter.assessment
? {
[Op.or]: [
{
id: {
[Op.in]: filter.assessment
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
report_html: {
[Op.or]: filter.assessment
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.test_section) {
where = {
...where,
[Op.and]: Utils.ilike('answers', 'test_section', filter.test_section),
};
}
if (filter.question_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'answers',
'question_text',
filter.question_text,
),
};
}
if (filter.answer_value) {
where = {
...where,
[Op.and]: Utils.ilike('answers', 'answer_value', filter.answer_value),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
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.answers.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('answers', 'question_text', query),
],
};
}
const records = await db.answers.findAll({
attributes: ['id', 'question_text'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['question_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.question_text,
}));
}
};