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 PaymentsDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const payments = await db.payments.create( { id: data.id || undefined, provider: data.provider || null , method: data.method || null , provider_payment_reference: data.provider_payment_reference || null , provider_order_reference: data.provider_order_reference || null , status: data.status || null , amount: data.amount || null , expires_on: data.expires_on || null , approved_on: data.approved_on || null , pix_qr_code_text: data.pix_qr_code_text || null , importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await payments.setOrder( data.order || null, { transaction, }); await payments.setOrganizations( data.organizations || null, { transaction, }); await FileDBApi.replaceRelationFiles( { belongsTo: db.payments.getTableName(), belongsToColumn: 'pix_qr_code_images', belongsToId: payments.id, }, data.pix_qr_code_images, options, ); await FileDBApi.replaceRelationFiles( { belongsTo: db.payments.getTableName(), belongsToColumn: 'provider_payload_files', belongsToId: payments.id, }, data.provider_payload_files, options, ); return payments; } 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 paymentsData = data.map((item, index) => ({ id: item.id || undefined, provider: item.provider || null , method: item.method || null , provider_payment_reference: item.provider_payment_reference || null , provider_order_reference: item.provider_order_reference || null , status: item.status || null , amount: item.amount || null , expires_on: item.expires_on || null , approved_on: item.approved_on || null , pix_qr_code_text: item.pix_qr_code_text || null , importHash: item.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, createdAt: new Date(Date.now() + index * 1000), })); // Bulk create items const payments = await db.payments.bulkCreate(paymentsData, { transaction }); // For each item created, replace relation files for (let i = 0; i < payments.length; i++) { await FileDBApi.replaceRelationFiles( { belongsTo: db.payments.getTableName(), belongsToColumn: 'pix_qr_code_images', belongsToId: payments[i].id, }, data[i].pix_qr_code_images, options, ); } for (let i = 0; i < payments.length; i++) { await FileDBApi.replaceRelationFiles( { belongsTo: db.payments.getTableName(), belongsToColumn: 'provider_payload_files', belongsToId: payments[i].id, }, data[i].provider_payload_files, options, ); } return payments; } 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 payments = await db.payments.findByPk(id, {}, {transaction}); const updatePayload = {}; if (data.provider !== undefined) updatePayload.provider = data.provider; if (data.method !== undefined) updatePayload.method = data.method; if (data.provider_payment_reference !== undefined) updatePayload.provider_payment_reference = data.provider_payment_reference; if (data.provider_order_reference !== undefined) updatePayload.provider_order_reference = data.provider_order_reference; if (data.status !== undefined) updatePayload.status = data.status; if (data.amount !== undefined) updatePayload.amount = data.amount; if (data.expires_on !== undefined) updatePayload.expires_on = data.expires_on; if (data.approved_on !== undefined) updatePayload.approved_on = data.approved_on; if (data.pix_qr_code_text !== undefined) updatePayload.pix_qr_code_text = data.pix_qr_code_text; updatePayload.updatedById = currentUser.id; await payments.update(updatePayload, {transaction}); if (data.order !== undefined) { await payments.setOrder( data.order, { transaction } ); } if (data.organizations !== undefined) { await payments.setOrganizations( data.organizations, { transaction } ); } await FileDBApi.replaceRelationFiles( { belongsTo: db.payments.getTableName(), belongsToColumn: 'pix_qr_code_images', belongsToId: payments.id, }, data.pix_qr_code_images, options, ); await FileDBApi.replaceRelationFiles( { belongsTo: db.payments.getTableName(), belongsToColumn: 'provider_payload_files', belongsToId: payments.id, }, data.provider_payload_files, options, ); return payments; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const payments = await db.payments.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of payments) { await record.update( {deletedBy: currentUser.id}, {transaction} ); } for (const record of payments) { await record.destroy({transaction}); } }); return payments; } static async remove(id, options) { const currentUser = (options && options.currentUser) || {id: null}; const transaction = (options && options.transaction) || undefined; const payments = await db.payments.findByPk(id, options); await payments.update({ deletedBy: currentUser.id }, { transaction, }); await payments.destroy({ transaction }); return payments; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const payments = await db.payments.findOne( { where }, { transaction }, ); if (!payments) { return payments; } const output = payments.get({plain: true}); output.order = await payments.getOrder({ transaction }); output.pix_qr_code_images = await payments.getPix_qr_code_images({ transaction }); output.provider_payload_files = await payments.getProvider_payload_files({ transaction }); output.organizations = await payments.getOrganizations({ 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 userOrganizations = (user && user.organizations?.id) || null; if (userOrganizations) { if (options?.currentUser?.organizationsId) { where.organizationsId = options.currentUser.organizationsId; } } offset = currentPage * limit; const orderBy = null; const transaction = (options && options.transaction) || undefined; let include = [ { model: db.orders, as: 'order', where: filter.order ? { [Op.or]: [ { id: { [Op.in]: filter.order.split('|').map(term => Utils.uuid(term)) } }, { public_checkout_code: { [Op.or]: filter.order.split('|').map(term => ({ [Op.iLike]: `%${term}%` })) } }, ] } : {}, }, { model: db.organizations, as: 'organizations', }, { model: db.file, as: 'pix_qr_code_images', }, { model: db.file, as: 'provider_payload_files', }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.provider_payment_reference) { where = { ...where, [Op.and]: Utils.ilike( 'payments', 'provider_payment_reference', filter.provider_payment_reference, ), }; } if (filter.provider_order_reference) { where = { ...where, [Op.and]: Utils.ilike( 'payments', 'provider_order_reference', filter.provider_order_reference, ), }; } if (filter.pix_qr_code_text) { where = { ...where, [Op.and]: Utils.ilike( 'payments', 'pix_qr_code_text', filter.pix_qr_code_text, ), }; } if (filter.amountRange) { const [start, end] = filter.amountRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, amount: { ...where.amount, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, amount: { ...where.amount, [Op.lte]: end, }, }; } } if (filter.expires_onRange) { const [start, end] = filter.expires_onRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, expires_on: { ...where.expires_on, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, expires_on: { ...where.expires_on, [Op.lte]: end, }, }; } } if (filter.approved_onRange) { const [start, end] = filter.approved_onRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, approved_on: { ...where.approved_on, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, approved_on: { ...where.approved_on, [Op.lte]: end, }, }; } } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true' }; } if (filter.provider) { where = { ...where, provider: filter.provider, }; } if (filter.method) { where = { ...where, method: filter.method, }; } if (filter.status) { where = { ...where, status: filter.status, }; } if (filter.organizations) { const listItems = filter.organizations.split('|').map(item => { return Utils.uuid(item) }); where = { ...where, organizationsId: {[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.organizationsId; } 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.payments.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( 'payments', 'provider_payment_reference', query, ), ], }; } const records = await db.payments.findAll({ attributes: [ 'id', 'provider_payment_reference' ], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['provider_payment_reference', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.provider_payment_reference, })); } };