39289-vm/backend/src/db/api/scenarios.js
2026-03-24 09:55:44 +00:00

570 lines
14 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 ScenariosDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const scenarios = await db.scenarios.create(
{
id: data.id || undefined,
name: data.name
||
null
,
scenario_type: data.scenario_type
||
null
,
status: data.status
||
null
,
description: data.description
||
null
,
valid_from_at: data.valid_from_at
||
null
,
valid_to_at: data.valid_to_at
||
null
,
probability_weight: data.probability_weight
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await scenarios.setOwner( data.owner || null, {
transaction,
});
return scenarios;
}
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 scenariosData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
scenario_type: item.scenario_type
||
null
,
status: item.status
||
null
,
description: item.description
||
null
,
valid_from_at: item.valid_from_at
||
null
,
valid_to_at: item.valid_to_at
||
null
,
probability_weight: item.probability_weight
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const scenarios = await db.scenarios.bulkCreate(scenariosData, { transaction });
// For each item created, replace relation files
return scenarios;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const scenarios = await db.scenarios.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.scenario_type !== undefined) updatePayload.scenario_type = data.scenario_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.valid_from_at !== undefined) updatePayload.valid_from_at = data.valid_from_at;
if (data.valid_to_at !== undefined) updatePayload.valid_to_at = data.valid_to_at;
if (data.probability_weight !== undefined) updatePayload.probability_weight = data.probability_weight;
updatePayload.updatedById = currentUser.id;
await scenarios.update(updatePayload, {transaction});
if (data.owner !== undefined) {
await scenarios.setOwner(
data.owner,
{ transaction }
);
}
return scenarios;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const scenarios = await db.scenarios.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of scenarios) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of scenarios) {
await record.destroy({transaction});
}
});
return scenarios;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const scenarios = await db.scenarios.findByPk(id, options);
await scenarios.update({
deletedBy: currentUser.id
}, {
transaction,
});
await scenarios.destroy({
transaction
});
return scenarios;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const scenarios = await db.scenarios.findOne(
{ where },
{ transaction },
);
if (!scenarios) {
return scenarios;
}
const output = scenarios.get({plain: true});
output.scenario_shocks_scenario = await scenarios.getScenario_shocks_scenario({
transaction
});
output.scenario_results_scenario = await scenarios.getScenario_results_scenario({
transaction
});
output.owner = await scenarios.getOwner({
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.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}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'scenarios',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'scenarios',
'description',
filter.description,
),
};
}
if (filter.valid_from_atRange) {
const [start, end] = filter.valid_from_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
valid_from_at: {
...where.valid_from_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
valid_from_at: {
...where.valid_from_at,
[Op.lte]: end,
},
};
}
}
if (filter.valid_to_atRange) {
const [start, end] = filter.valid_to_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
valid_to_at: {
...where.valid_to_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
valid_to_at: {
...where.valid_to_at,
[Op.lte]: end,
},
};
}
}
if (filter.probability_weightRange) {
const [start, end] = filter.probability_weightRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
probability_weight: {
...where.probability_weight,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
probability_weight: {
...where.probability_weight,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.scenario_type) {
where = {
...where,
scenario_type: filter.scenario_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
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.scenarios.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(
'scenarios',
'name',
query,
),
],
};
}
const records = await db.scenarios.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};