30609/backend/src/db/api/specs.js
2025-04-10 11:28:39 +00:00

453 lines
11 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 SpecsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const specs = await db.specs.create(
{
id: data.id || undefined,
name: data.name || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await specs.setProject(data.project || null, {
transaction,
});
await specs.setWorkspaces(data.workspaces || null, {
transaction,
});
await specs.setDiagrams(data.diagrams || [], {
transaction,
});
await specs.setLogic_flows(data.logic_flows || [], {
transaction,
});
return specs;
}
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 specsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const specs = await db.specs.bulkCreate(specsData, { transaction });
// For each item created, replace relation files
return specs;
}
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 specs = await db.specs.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await specs.update(updatePayload, { transaction });
if (data.project !== undefined) {
await specs.setProject(
data.project,
{ transaction },
);
}
if (data.workspaces !== undefined) {
await specs.setWorkspaces(
data.workspaces,
{ transaction },
);
}
if (data.diagrams !== undefined) {
await specs.setDiagrams(data.diagrams, { transaction });
}
if (data.logic_flows !== undefined) {
await specs.setLogic_flows(data.logic_flows, { transaction });
}
return specs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const specs = await db.specs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of specs) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of specs) {
await record.destroy({ transaction });
}
});
return specs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const specs = await db.specs.findByPk(id, options);
await specs.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await specs.destroy({
transaction,
});
return specs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const specs = await db.specs.findOne({ where }, { transaction });
if (!specs) {
return specs;
}
const output = specs.get({ plain: true });
output.diagrams_spec = await specs.getDiagrams_spec({
transaction,
});
output.logic_flows_spec = await specs.getLogic_flows_spec({
transaction,
});
output.project = await specs.getProject({
transaction,
});
output.diagrams = await specs.getDiagrams({
transaction,
});
output.logic_flows = await specs.getLogic_flows({
transaction,
});
output.workspaces = await specs.getWorkspaces({
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 userWorkspaces = (user && user.workspaces?.id) || null;
if (userWorkspaces) {
if (options?.currentUser?.workspacesId) {
where.workspacesId = options.currentUser.workspacesId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.projects,
as: 'project',
where: filter.project
? {
[Op.or]: [
{
id: {
[Op.in]: filter.project
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
title: {
[Op.or]: filter.project
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.workspaces,
as: 'workspaces',
},
{
model: db.diagrams,
as: 'diagrams',
required: false,
},
{
model: db.logic_flows,
as: 'logic_flows',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike('specs', 'name', filter.name),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.workspaces) {
const listItems = filter.workspaces.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
workspacesId: { [Op.or]: listItems },
};
}
if (filter.diagrams) {
const searchTerms = filter.diagrams.split('|');
include = [
{
model: db.diagrams,
as: 'diagrams_filter',
required: searchTerms.length > 0,
where:
searchTerms.length > 0
? {
[Op.or]: [
{
id: {
[Op.in]: searchTerms.map((term) => Utils.uuid(term)),
},
},
{
title: {
[Op.or]: searchTerms.map((term) => ({
[Op.iLike]: `%${term}%`,
})),
},
},
],
}
: undefined,
},
...include,
];
}
if (filter.logic_flows) {
const searchTerms = filter.logic_flows.split('|');
include = [
{
model: db.logic_flows,
as: 'logic_flows_filter',
required: searchTerms.length > 0,
where:
searchTerms.length > 0
? {
[Op.or]: [
{
id: {
[Op.in]: searchTerms.map((term) => Utils.uuid(term)),
},
},
{
title: {
[Op.or]: searchTerms.map((term) => ({
[Op.iLike]: `%${term}%`,
})),
},
},
],
}
: undefined,
},
...include,
];
}
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.workspacesId;
}
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.specs.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('specs', 'name', query),
],
};
}
const records = await db.specs.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,
}));
}
};