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 KpisDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const kpis = await db.kpis.create( { id: data.id || undefined, name: data.name || null , code: data.code || null , description: data.description || null , category: data.category || null , unit: data.unit || null , target_value: data.target_value || null , current_value: data.current_value || null , frequency: data.frequency || null , start_date: data.start_date || null , end_date: data.end_date || null , status: data.status || null , importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await kpis.setCompany( data.company || null, { transaction, }); await kpis.setDepartment( data.department || null, { transaction, }); await kpis.setOwner_employee( data.owner_employee || null, { transaction, }); return kpis; } 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 kpisData = data.map((item, index) => ({ id: item.id || undefined, name: item.name || null , code: item.code || null , description: item.description || null , category: item.category || null , unit: item.unit || null , target_value: item.target_value || null , current_value: item.current_value || null , frequency: item.frequency || null , start_date: item.start_date || null , end_date: item.end_date || null , status: item.status || null , importHash: item.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, createdAt: new Date(Date.now() + index * 1000), })); // Bulk create items const kpis = await db.kpis.bulkCreate(kpisData, { transaction }); // For each item created, replace relation files return kpis; } 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 kpis = await db.kpis.findByPk(id, {}, {transaction}); const updatePayload = {}; if (data.name !== undefined) updatePayload.name = data.name; if (data.code !== undefined) updatePayload.code = data.code; if (data.description !== undefined) updatePayload.description = data.description; if (data.category !== undefined) updatePayload.category = data.category; if (data.unit !== undefined) updatePayload.unit = data.unit; if (data.target_value !== undefined) updatePayload.target_value = data.target_value; if (data.current_value !== undefined) updatePayload.current_value = data.current_value; if (data.frequency !== undefined) updatePayload.frequency = data.frequency; if (data.start_date !== undefined) updatePayload.start_date = data.start_date; if (data.end_date !== undefined) updatePayload.end_date = data.end_date; if (data.status !== undefined) updatePayload.status = data.status; updatePayload.updatedById = currentUser.id; await kpis.update(updatePayload, {transaction}); if (data.company !== undefined) { await kpis.setCompany( data.company, { transaction } ); } if (data.department !== undefined) { await kpis.setDepartment( data.department, { transaction } ); } if (data.owner_employee !== undefined) { await kpis.setOwner_employee( data.owner_employee, { transaction } ); } return kpis; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const kpis = await db.kpis.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of kpis) { await record.update( {deletedBy: currentUser.id}, {transaction} ); } for (const record of kpis) { await record.destroy({transaction}); } }); return kpis; } static async remove(id, options) { const currentUser = (options && options.currentUser) || {id: null}; const transaction = (options && options.transaction) || undefined; const kpis = await db.kpis.findByPk(id, options); await kpis.update({ deletedBy: currentUser.id }, { transaction, }); await kpis.destroy({ transaction }); return kpis; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const kpis = await db.kpis.findOne( { where }, { transaction }, ); if (!kpis) { return kpis; } const output = kpis.get({plain: true}); output.bsc_metrics_kpi = await kpis.getBsc_metrics_kpi({ transaction }); output.company = await kpis.getCompany({ transaction }); output.department = await kpis.getDepartment({ transaction }); output.owner_employee = await kpis.getOwner_employee({ 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 userCompanies = (user && user.companies?.id) || null; if (userCompanies) { if (options?.currentUser?.companiesId) { where.companiesId = options.currentUser.companiesId; } } offset = currentPage * limit; const orderBy = null; const transaction = (options && options.transaction) || undefined; let include = [ { model: db.companies, as: 'company', }, { model: db.departments, as: 'department', where: filter.department ? { [Op.or]: [ { id: { [Op.in]: filter.department.split('|').map(term => Utils.uuid(term)) } }, { name: { [Op.or]: filter.department.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } }, ] } : {}, }, { model: db.employees, as: 'owner_employee', where: filter.owner_employee ? { [Op.or]: [ { id: { [Op.in]: filter.owner_employee.split('|').map(term => Utils.uuid(term)) } }, { full_name: { [Op.or]: filter.owner_employee.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( 'kpis', 'name', filter.name, ), }; } if (filter.code) { where = { ...where, [Op.and]: Utils.ilike( 'kpis', 'code', filter.code, ), }; } if (filter.description) { where = { ...where, [Op.and]: Utils.ilike( 'kpis', 'description', filter.description, ), }; } if (filter.target_valueRange) { const [start, end] = filter.target_valueRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, target_value: { ...where.target_value, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, target_value: { ...where.target_value, [Op.lte]: end, }, }; } } if (filter.current_valueRange) { const [start, end] = filter.current_valueRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, current_value: { ...where.current_value, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, current_value: { ...where.current_value, [Op.lte]: end, }, }; } } if (filter.start_dateRange) { const [start, end] = filter.start_dateRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, start_date: { ...where.start_date, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, start_date: { ...where.start_date, [Op.lte]: end, }, }; } } if (filter.end_dateRange) { const [start, end] = filter.end_dateRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, end_date: { ...where.end_date, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, end_date: { ...where.end_date, [Op.lte]: end, }, }; } } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true' }; } if (filter.category) { where = { ...where, category: filter.category, }; } if (filter.unit) { where = { ...where, unit: filter.unit, }; } if (filter.frequency) { where = { ...where, frequency: filter.frequency, }; } if (filter.status) { where = { ...where, status: filter.status, }; } if (filter.company) { const listItems = filter.company.split('|').map(item => { return Utils.uuid(item) }); where = { ...where, companyId: {[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.companiesId; } 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.kpis.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( 'kpis', 'name', query, ), ], }; } const records = await db.kpis.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, })); } };