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 IncidentsDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const incidents = await db.incidents.create( { id: data.id || undefined, incident_name: data.incident_name || null, incident_date: data.incident_date || null, details: data.details || null, importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await incidents.setRelated_persons(data.related_persons || [], { transaction, }); return incidents; } 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 incidentsData = data.map((item, index) => ({ id: item.id || undefined, incident_name: item.incident_name || null, incident_date: item.incident_date || null, details: item.details || null, importHash: item.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, createdAt: new Date(Date.now() + index * 1000), })); // Bulk create items const incidents = await db.incidents.bulkCreate(incidentsData, { transaction, }); // For each item created, replace relation files return incidents; } static async update(id, data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const incidents = await db.incidents.findByPk(id, {}, { transaction }); const updatePayload = {}; if (data.incident_name !== undefined) updatePayload.incident_name = data.incident_name; if (data.incident_date !== undefined) updatePayload.incident_date = data.incident_date; if (data.details !== undefined) updatePayload.details = data.details; updatePayload.updatedById = currentUser.id; await incidents.update(updatePayload, { transaction }); if (data.related_persons !== undefined) { await incidents.setRelated_persons(data.related_persons, { transaction }); } return incidents; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const incidents = await db.incidents.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of incidents) { await record.update({ deletedBy: currentUser.id }, { transaction }); } for (const record of incidents) { await record.destroy({ transaction }); } }); return incidents; } static async remove(id, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const incidents = await db.incidents.findByPk(id, options); await incidents.update( { deletedBy: currentUser.id, }, { transaction, }, ); await incidents.destroy({ transaction, }); return incidents; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const incidents = await db.incidents.findOne({ where }, { transaction }); if (!incidents) { return incidents; } const output = incidents.get({ plain: true }); output.related_persons = await incidents.getRelated_persons({ transaction, }); return output; } static async findAll(filter, options) { const limit = filter.limit || 0; let offset = 0; let where = {}; const currentPage = +filter.page; offset = currentPage * limit; const orderBy = null; const transaction = (options && options.transaction) || undefined; let include = [ { model: db.students, as: 'related_persons', required: false, }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.incident_name) { where = { ...where, [Op.and]: Utils.ilike( 'incidents', 'incident_name', filter.incident_name, ), }; } if (filter.details) { where = { ...where, [Op.and]: Utils.ilike('incidents', 'details', filter.details), }; } if (filter.calendarStart && filter.calendarEnd) { where = { ...where, [Op.or]: [ { incident_date: { [Op.between]: [filter.calendarStart, filter.calendarEnd], }, }, { incident_date: { [Op.between]: [filter.calendarStart, filter.calendarEnd], }, }, ], }; } if (filter.incident_dateRange) { const [start, end] = filter.incident_dateRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, incident_date: { ...where.incident_date, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, incident_date: { ...where.incident_date, [Op.lte]: end, }, }; } } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true', }; } if (filter.related_persons) { const searchTerms = filter.related_persons.split('|'); include = [ { model: db.students, as: 'related_persons_filter', required: searchTerms.length > 0, where: searchTerms.length > 0 ? { [Op.or]: [ { id: { [Op.in]: searchTerms.map((term) => Utils.uuid(term)), }, }, { name: { [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, }, }; } } } 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.incidents.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) { let where = {}; if (query) { where = { [Op.or]: [ { ['id']: Utils.uuid(query) }, Utils.ilike('incidents', 'incident_name', query), ], }; } const records = await db.incidents.findAll({ attributes: ['id', 'incident_name'], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['incident_name', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.incident_name, })); } };