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 EquipmentDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const equipment = await db.equipment.create( { id: data.id || undefined, asset_tag: data.asset_tag || null, type: data.type || null, last_service_date: data.last_service_date || null, next_service_due: data.next_service_due || null, importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await equipment.setAssigned_project(data.assigned_project || null, { transaction, }); await equipment.setDivisions(data.divisions || null, { transaction, }); return equipment; } 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 equipmentData = data.map((item, index) => ({ id: item.id || undefined, asset_tag: item.asset_tag || null, type: item.type || null, last_service_date: item.last_service_date || null, next_service_due: item.next_service_due || null, importHash: item.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, createdAt: new Date(Date.now() + index * 1000), })); // Bulk create items const equipment = await db.equipment.bulkCreate(equipmentData, { transaction, }); // For each item created, replace relation files return equipment; } 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 equipment = await db.equipment.findByPk(id, {}, { transaction }); const updatePayload = {}; if (data.asset_tag !== undefined) updatePayload.asset_tag = data.asset_tag; if (data.type !== undefined) updatePayload.type = data.type; if (data.last_service_date !== undefined) updatePayload.last_service_date = data.last_service_date; if (data.next_service_due !== undefined) updatePayload.next_service_due = data.next_service_due; updatePayload.updatedById = currentUser.id; await equipment.update(updatePayload, { transaction }); if (data.assigned_project !== undefined) { await equipment.setAssigned_project( data.assigned_project, { transaction }, ); } if (data.divisions !== undefined) { await equipment.setDivisions( data.divisions, { transaction }, ); } return equipment; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const equipment = await db.equipment.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of equipment) { await record.update({ deletedBy: currentUser.id }, { transaction }); } for (const record of equipment) { await record.destroy({ transaction }); } }); return equipment; } static async remove(id, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const equipment = await db.equipment.findByPk(id, options); await equipment.update( { deletedBy: currentUser.id, }, { transaction, }, ); await equipment.destroy({ transaction, }); return equipment; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const equipment = await db.equipment.findOne({ where }, { transaction }); if (!equipment) { return equipment; } const output = equipment.get({ plain: true }); output.assigned_project = await equipment.getAssigned_project({ transaction, }); output.divisions = await equipment.getDivisions({ 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 userDivisions = (user && user.divisions?.id) || null; if (userDivisions) { if (options?.currentUser?.divisionsId) { where.divisionsId = options.currentUser.divisionsId; } } offset = currentPage * limit; const orderBy = null; const transaction = (options && options.transaction) || undefined; let include = [ { model: db.projects, as: 'assigned_project', where: filter.assigned_project ? { [Op.or]: [ { id: { [Op.in]: filter.assigned_project .split('|') .map((term) => Utils.uuid(term)), }, }, { name: { [Op.or]: filter.assigned_project .split('|') .map((term) => ({ [Op.iLike]: `%${term}%` })), }, }, ], } : {}, }, { model: db.divisions, as: 'divisions', }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.asset_tag) { where = { ...where, [Op.and]: Utils.ilike('equipment', 'asset_tag', filter.asset_tag), }; } if (filter.last_service_dateRange) { const [start, end] = filter.last_service_dateRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, last_service_date: { ...where.last_service_date, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, last_service_date: { ...where.last_service_date, [Op.lte]: end, }, }; } } if (filter.next_service_dueRange) { const [start, end] = filter.next_service_dueRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, next_service_due: { ...where.next_service_due, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, next_service_due: { ...where.next_service_due, [Op.lte]: end, }, }; } } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true', }; } if (filter.type) { where = { ...where, type: filter.type, }; } if (filter.divisions) { const listItems = filter.divisions.split('|').map((item) => { return Utils.uuid(item); }); where = { ...where, divisionsId: { [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.divisionsId; } 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.equipment.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('equipment', 'asset_tag', query), ], }; } const records = await db.equipment.findAll({ attributes: ['id', 'asset_tag'], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['asset_tag', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.asset_tag, })); } };