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 AlertsDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const alerts = await db.alerts.create( { id: data.id || undefined, alert_time: data.alert_time || null, description: data.description || null, importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await alerts.setTyre(data.tyre || null, { transaction, }); await alerts.setSmarttyresystem(data.smarttyresystem || null, { transaction, }); await FileDBApi.replaceRelationFiles( { belongsTo: db.alerts.getTableName(), belongsToColumn: 'damage_images', belongsToId: alerts.id, }, data.damage_images, options, ); return alerts; } 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 alertsData = data.map((item, index) => ({ id: item.id || undefined, alert_time: item.alert_time || null, description: item.description || null, importHash: item.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, createdAt: new Date(Date.now() + index * 1000), })); // Bulk create items const alerts = await db.alerts.bulkCreate(alertsData, { transaction }); // For each item created, replace relation files for (let i = 0; i < alerts.length; i++) { await FileDBApi.replaceRelationFiles( { belongsTo: db.alerts.getTableName(), belongsToColumn: 'damage_images', belongsToId: alerts[i].id, }, data[i].damage_images, options, ); } return alerts; } 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 alerts = await db.alerts.findByPk(id, {}, { transaction }); const updatePayload = {}; if (data.alert_time !== undefined) updatePayload.alert_time = data.alert_time; if (data.description !== undefined) updatePayload.description = data.description; updatePayload.updatedById = currentUser.id; await alerts.update(updatePayload, { transaction }); if (data.tyre !== undefined) { await alerts.setTyre( data.tyre, { transaction }, ); } if (data.smarttyresystem !== undefined) { await alerts.setSmarttyresystem( data.smarttyresystem, { transaction }, ); } await FileDBApi.replaceRelationFiles( { belongsTo: db.alerts.getTableName(), belongsToColumn: 'damage_images', belongsToId: alerts.id, }, data.damage_images, options, ); return alerts; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const alerts = await db.alerts.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of alerts) { await record.update({ deletedBy: currentUser.id }, { transaction }); } for (const record of alerts) { await record.destroy({ transaction }); } }); return alerts; } static async remove(id, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const alerts = await db.alerts.findByPk(id, options); await alerts.update( { deletedBy: currentUser.id, }, { transaction, }, ); await alerts.destroy({ transaction, }); return alerts; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const alerts = await db.alerts.findOne({ where }, { transaction }); if (!alerts) { return alerts; } const output = alerts.get({ plain: true }); output.damage_images = await alerts.getDamage_images({ transaction, }); output.tyre = await alerts.getTyre({ transaction, }); output.smarttyresystem = await alerts.getSmarttyresystem({ 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 userSmarttyresystem = (user && user.smarttyresystem?.id) || null; if (userSmarttyresystem) { if (options?.currentUser?.smarttyresystemId) { where.smarttyresystemId = options.currentUser.smarttyresystemId; } } offset = currentPage * limit; const orderBy = null; const transaction = (options && options.transaction) || undefined; let include = [ { model: db.tyres, as: 'tyre', where: filter.tyre ? { [Op.or]: [ { id: { [Op.in]: filter.tyre .split('|') .map((term) => Utils.uuid(term)), }, }, { serial_number: { [Op.or]: filter.tyre .split('|') .map((term) => ({ [Op.iLike]: `%${term}%` })), }, }, ], } : {}, }, { model: db.smarttyresystem, as: 'smarttyresystem', }, { model: db.file, as: 'damage_images', }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.description) { where = { ...where, [Op.and]: Utils.ilike('alerts', 'description', filter.description), }; } if (filter.calendarStart && filter.calendarEnd) { where = { ...where, [Op.or]: [ { alert_time: { [Op.between]: [filter.calendarStart, filter.calendarEnd], }, }, { alert_time: { [Op.between]: [filter.calendarStart, filter.calendarEnd], }, }, ], }; } if (filter.alert_timeRange) { const [start, end] = filter.alert_timeRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, alert_time: { ...where.alert_time, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, alert_time: { ...where.alert_time, [Op.lte]: end, }, }; } } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true', }; } if (filter.smarttyresystem) { const listItems = filter.smarttyresystem.split('|').map((item) => { return Utils.uuid(item); }); where = { ...where, smarttyresystemId: { [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.smarttyresystemId; } 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.alerts.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('alerts', 'description', query), ], }; } const records = await db.alerts.findAll({ attributes: ['id', 'description'], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['description', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.description, })); } };