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 ConsumptionsDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const consumptions = await db.consumptions.create( { id: data.id || undefined, consumed_at: data.consumed_at || null , quantity_used: data.quantity_used || null , notes: data.notes || null , importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await consumptions.setTest_run( data.test_run || null, { transaction, }); await consumptions.setItem_batch( data.item_batch || null, { transaction, }); await consumptions.setLogged_by( data.logged_by || null, { transaction, }); return consumptions; } 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 consumptionsData = data.map((item, index) => ({ id: item.id || undefined, consumed_at: item.consumed_at || null , quantity_used: item.quantity_used || null , notes: item.notes || null , importHash: item.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, createdAt: new Date(Date.now() + index * 1000), })); // Bulk create items const consumptions = await db.consumptions.bulkCreate(consumptionsData, { transaction }); // For each item created, replace relation files return consumptions; } static async update(id, data, options) { const currentUser = (options && options.currentUser) || {id: null}; const transaction = (options && options.transaction) || undefined; const consumptions = await db.consumptions.findByPk(id, {}, {transaction}); const updatePayload = {}; if (data.consumed_at !== undefined) updatePayload.consumed_at = data.consumed_at; if (data.quantity_used !== undefined) updatePayload.quantity_used = data.quantity_used; if (data.notes !== undefined) updatePayload.notes = data.notes; updatePayload.updatedById = currentUser.id; await consumptions.update(updatePayload, {transaction}); if (data.test_run !== undefined) { await consumptions.setTest_run( data.test_run, { transaction } ); } if (data.item_batch !== undefined) { await consumptions.setItem_batch( data.item_batch, { transaction } ); } if (data.logged_by !== undefined) { await consumptions.setLogged_by( data.logged_by, { transaction } ); } return consumptions; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const consumptions = await db.consumptions.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of consumptions) { await record.update( {deletedBy: currentUser.id}, {transaction} ); } for (const record of consumptions) { await record.destroy({transaction}); } }); return consumptions; } static async remove(id, options) { const currentUser = (options && options.currentUser) || {id: null}; const transaction = (options && options.transaction) || undefined; const consumptions = await db.consumptions.findByPk(id, options); await consumptions.update({ deletedBy: currentUser.id }, { transaction, }); await consumptions.destroy({ transaction }); return consumptions; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const consumptions = await db.consumptions.findOne( { where }, { transaction }, ); if (!consumptions) { return consumptions; } const output = consumptions.get({plain: true}); output.test_run = await consumptions.getTest_run({ transaction }); output.item_batch = await consumptions.getItem_batch({ transaction }); output.logged_by = await consumptions.getLogged_by({ 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.test_runs, as: 'test_run', where: filter.test_run ? { [Op.or]: [ { id: { [Op.in]: filter.test_run.split('|').map(term => Utils.uuid(term)) } }, { summary_result: { [Op.or]: filter.test_run.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } }, ] } : {}, }, { model: db.item_batches, as: 'item_batch', where: filter.item_batch ? { [Op.or]: [ { id: { [Op.in]: filter.item_batch.split('|').map(term => Utils.uuid(term)) } }, { lot_number: { [Op.or]: filter.item_batch.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } }, ] } : {}, }, { model: db.users, as: 'logged_by', where: filter.logged_by ? { [Op.or]: [ { id: { [Op.in]: filter.logged_by.split('|').map(term => Utils.uuid(term)) } }, { firstName: { [Op.or]: filter.logged_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } }, ] } : {}, }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.notes) { where = { ...where, [Op.and]: Utils.ilike( 'consumptions', 'notes', filter.notes, ), }; } if (filter.consumed_atRange) { const [start, end] = filter.consumed_atRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, consumed_at: { ...where.consumed_at, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, consumed_at: { ...where.consumed_at, [Op.lte]: end, }, }; } } if (filter.quantity_usedRange) { const [start, end] = filter.quantity_usedRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, quantity_used: { ...where.quantity_used, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, quantity_used: { ...where.quantity_used, [Op.lte]: end, }, }; } } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true' }; } 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.consumptions.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( 'consumptions', 'notes', query, ), ], }; } const records = await db.consumptions.findAll({ attributes: [ 'id', 'notes' ], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['notes', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.notes, })); } };