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 AttachmentsDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const attachments = await db.attachments.create( { id: data.id || undefined, kind: data.kind || null , filename: data.filename || null , mime_type: data.mime_type || null , size_bytes: data.size_bytes || null , storage_key: data.storage_key || null , notes: data.notes || null , importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await attachments.setMessage( data.message || null, { transaction, }); await FileDBApi.replaceRelationFiles( { belongsTo: db.attachments.getTableName(), belongsToColumn: 'file', belongsToId: attachments.id, }, data.file, options, ); await FileDBApi.replaceRelationFiles( { belongsTo: db.attachments.getTableName(), belongsToColumn: 'image', belongsToId: attachments.id, }, data.image, options, ); return attachments; } 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 attachmentsData = data.map((item, index) => ({ id: item.id || undefined, kind: item.kind || null , filename: item.filename || null , mime_type: item.mime_type || null , size_bytes: item.size_bytes || null , storage_key: item.storage_key || 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 attachments = await db.attachments.bulkCreate(attachmentsData, { transaction }); // For each item created, replace relation files for (let i = 0; i < attachments.length; i++) { await FileDBApi.replaceRelationFiles( { belongsTo: db.attachments.getTableName(), belongsToColumn: 'file', belongsToId: attachments[i].id, }, data[i].file, options, ); } for (let i = 0; i < attachments.length; i++) { await FileDBApi.replaceRelationFiles( { belongsTo: db.attachments.getTableName(), belongsToColumn: 'image', belongsToId: attachments[i].id, }, data[i].image, options, ); } return attachments; } static async update(id, data, options) { const currentUser = (options && options.currentUser) || {id: null}; const transaction = (options && options.transaction) || undefined; const attachments = await db.attachments.findByPk(id, {}, {transaction}); const updatePayload = {}; if (data.kind !== undefined) updatePayload.kind = data.kind; if (data.filename !== undefined) updatePayload.filename = data.filename; if (data.mime_type !== undefined) updatePayload.mime_type = data.mime_type; if (data.size_bytes !== undefined) updatePayload.size_bytes = data.size_bytes; if (data.storage_key !== undefined) updatePayload.storage_key = data.storage_key; if (data.notes !== undefined) updatePayload.notes = data.notes; updatePayload.updatedById = currentUser.id; await attachments.update(updatePayload, {transaction}); if (data.message !== undefined) { await attachments.setMessage( data.message, { transaction } ); } await FileDBApi.replaceRelationFiles( { belongsTo: db.attachments.getTableName(), belongsToColumn: 'file', belongsToId: attachments.id, }, data.file, options, ); await FileDBApi.replaceRelationFiles( { belongsTo: db.attachments.getTableName(), belongsToColumn: 'image', belongsToId: attachments.id, }, data.image, options, ); return attachments; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const attachments = await db.attachments.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of attachments) { await record.update( {deletedBy: currentUser.id}, {transaction} ); } for (const record of attachments) { await record.destroy({transaction}); } }); return attachments; } static async remove(id, options) { const currentUser = (options && options.currentUser) || {id: null}; const transaction = (options && options.transaction) || undefined; const attachments = await db.attachments.findByPk(id, options); await attachments.update({ deletedBy: currentUser.id }, { transaction, }); await attachments.destroy({ transaction }); return attachments; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const attachments = await db.attachments.findOne( { where }, { transaction }, ); if (!attachments) { return attachments; } const output = attachments.get({plain: true}); output.message = await attachments.getMessage({ transaction }); output.file = await attachments.getFile({ transaction }); output.image = await attachments.getImage({ 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.messages, as: 'message', where: filter.message ? { [Op.or]: [ { id: { [Op.in]: filter.message.split('|').map(term => Utils.uuid(term)) } }, { content: { [Op.or]: filter.message.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } }, ] } : {}, }, { model: db.file, as: 'file', }, { model: db.file, as: 'image', }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.filename) { where = { ...where, [Op.and]: Utils.ilike( 'attachments', 'filename', filter.filename, ), }; } if (filter.mime_type) { where = { ...where, [Op.and]: Utils.ilike( 'attachments', 'mime_type', filter.mime_type, ), }; } if (filter.storage_key) { where = { ...where, [Op.and]: Utils.ilike( 'attachments', 'storage_key', filter.storage_key, ), }; } if (filter.notes) { where = { ...where, [Op.and]: Utils.ilike( 'attachments', 'notes', filter.notes, ), }; } if (filter.size_bytesRange) { const [start, end] = filter.size_bytesRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, size_bytes: { ...where.size_bytes, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, size_bytes: { ...where.size_bytes, [Op.lte]: end, }, }; } } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true' }; } if (filter.kind) { where = { ...where, kind: filter.kind, }; } 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.attachments.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( 'attachments', 'filename', query, ), ], }; } const records = await db.attachments.findAll({ attributes: [ 'id', 'filename' ], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['filename', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.filename, })); } };