33980/backend/src/db/api/projects.js
2025-09-10 00:23:36 +00:00

569 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 ProjectsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.create(
{
id: data.id || undefined,
recommended_use: data.recommended_use || null,
floors: data.floors || null,
total_units: data.total_units || null,
estimated_roi: data.estimated_roi || null,
payback_period_years: data.payback_period_years || null,
npv_usd: data.npv_usd || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await projects.setUser(data.user || null, {
transaction,
});
await projects.setProperty(data.property || null, {
transaction,
});
await projects.setTenant(data.tenant || null, {
transaction,
});
await projects.setOrganizations(data.organizations || null, {
transaction,
});
return projects;
}
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 projectsData = data.map((item, index) => ({
id: item.id || undefined,
recommended_use: item.recommended_use || null,
floors: item.floors || null,
total_units: item.total_units || null,
estimated_roi: item.estimated_roi || null,
payback_period_years: item.payback_period_years || null,
npv_usd: item.npv_usd || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const projects = await db.projects.bulkCreate(projectsData, {
transaction,
});
// For each item created, replace relation files
return projects;
}
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 projects = await db.projects.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.recommended_use !== undefined)
updatePayload.recommended_use = data.recommended_use;
if (data.floors !== undefined) updatePayload.floors = data.floors;
if (data.total_units !== undefined)
updatePayload.total_units = data.total_units;
if (data.estimated_roi !== undefined)
updatePayload.estimated_roi = data.estimated_roi;
if (data.payback_period_years !== undefined)
updatePayload.payback_period_years = data.payback_period_years;
if (data.npv_usd !== undefined) updatePayload.npv_usd = data.npv_usd;
updatePayload.updatedById = currentUser.id;
await projects.update(updatePayload, { transaction });
if (data.user !== undefined) {
await projects.setUser(
data.user,
{ transaction },
);
}
if (data.property !== undefined) {
await projects.setProperty(
data.property,
{ transaction },
);
}
if (data.tenant !== undefined) {
await projects.setTenant(
data.tenant,
{ transaction },
);
}
if (data.organizations !== undefined) {
await projects.setOrganizations(
data.organizations,
{ transaction },
);
}
return projects;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of projects) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of projects) {
await record.destroy({ transaction });
}
});
return projects;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findByPk(id, options);
await projects.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await projects.destroy({
transaction,
});
return projects;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findOne({ where }, { transaction });
if (!projects) {
return projects;
}
const output = projects.get({ plain: true });
output.user = await projects.getUser({
transaction,
});
output.property = await projects.getProperty({
transaction,
});
output.tenant = await projects.getTenant({
transaction,
});
output.organizations = await projects.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.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.properties,
as: 'property',
where: filter.property
? {
[Op.or]: [
{
id: {
[Op.in]: filter.property
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
title: {
[Op.or]: filter.property
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.organizations,
as: 'tenant',
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.recommended_use) {
where = {
...where,
[Op.and]: Utils.ilike(
'projects',
'recommended_use',
filter.recommended_use,
),
};
}
if (filter.floorsRange) {
const [start, end] = filter.floorsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
floors: {
...where.floors,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
floors: {
...where.floors,
[Op.lte]: end,
},
};
}
}
if (filter.total_unitsRange) {
const [start, end] = filter.total_unitsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_units: {
...where.total_units,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_units: {
...where.total_units,
[Op.lte]: end,
},
};
}
}
if (filter.estimated_roiRange) {
const [start, end] = filter.estimated_roiRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
estimated_roi: {
...where.estimated_roi,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
estimated_roi: {
...where.estimated_roi,
[Op.lte]: end,
},
};
}
}
if (filter.payback_period_yearsRange) {
const [start, end] = filter.payback_period_yearsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
payback_period_years: {
...where.payback_period_years,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
payback_period_years: {
...where.payback_period_years,
[Op.lte]: end,
},
};
}
}
if (filter.npv_usdRange) {
const [start, end] = filter.npv_usdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
npv_usd: {
...where.npv_usd,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
npv_usd: {
...where.npv_usd,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.tenant) {
const listItems = filter.tenant.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
tenantId: { [Op.or]: listItems },
};
}
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.projects.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('projects', 'recommended_use', query),
],
};
}
const records = await db.projects.findAll({
attributes: ['id', 'recommended_use'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['recommended_use', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.recommended_use,
}));
}
};