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 TransactionsDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const transactions = await db.transactions.create( { id: data.id || undefined, transaction_date: data.transaction_date || null, total_amount: data.total_amount || null, payment_method: data.payment_method || null, importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await transactions.setUser(data.user || null, { transaction, }); await transactions.setCabang(data.cabang || null, { transaction, }); await transactions.setCabangs(data.cabangs || null, { transaction, }); await transactions.setProducts(data.products || [], { transaction, }); return transactions; } 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 transactionsData = data.map((item, index) => ({ id: item.id || undefined, transaction_date: item.transaction_date || null, total_amount: item.total_amount || null, payment_method: item.payment_method || null, importHash: item.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, createdAt: new Date(Date.now() + index * 1000), })); // Bulk create items const transactions = await db.transactions.bulkCreate(transactionsData, { transaction, }); // For each item created, replace relation files return transactions; } 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 transactions = await db.transactions.findByPk( id, {}, { transaction }, ); const updatePayload = {}; if (data.transaction_date !== undefined) updatePayload.transaction_date = data.transaction_date; if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount; if (data.payment_method !== undefined) updatePayload.payment_method = data.payment_method; updatePayload.updatedById = currentUser.id; await transactions.update(updatePayload, { transaction }); if (data.user !== undefined) { await transactions.setUser( data.user, { transaction }, ); } if (data.cabang !== undefined) { await transactions.setCabang( data.cabang, { transaction }, ); } if (data.cabangs !== undefined) { await transactions.setCabangs( data.cabangs, { transaction }, ); } if (data.products !== undefined) { await transactions.setProducts(data.products, { transaction }); } return transactions; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const transactions = await db.transactions.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of transactions) { await record.update({ deletedBy: currentUser.id }, { transaction }); } for (const record of transactions) { await record.destroy({ transaction }); } }); return transactions; } static async remove(id, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const transactions = await db.transactions.findByPk(id, options); await transactions.update( { deletedBy: currentUser.id, }, { transaction, }, ); await transactions.destroy({ transaction, }); return transactions; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const transactions = await db.transactions.findOne( { where }, { transaction }, ); if (!transactions) { return transactions; } const output = transactions.get({ plain: true }); output.invoices_transaction = await transactions.getInvoices_transaction({ transaction, }); output.user = await transactions.getUser({ transaction, }); output.cabang = await transactions.getCabang({ transaction, }); output.products = await transactions.getProducts({ transaction, }); output.cabangs = await transactions.getCabangs({ 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 userCabangs = (user && user.cabangs?.id) || null; if (userCabangs) { if (options?.currentUser?.cabangsId) { where.cabangsId = options.currentUser.cabangsId; } } offset = currentPage * limit; const orderBy = null; const transaction = (options && options.transaction) || undefined; let include = [ { model: db.users, as: 'user', where: filter.user ? { [Op.or]: [ { id: { [Op.in]: filter.user .split('|') .map((term) => Utils.uuid(term)), }, }, { firstName: { [Op.or]: filter.user .split('|') .map((term) => ({ [Op.iLike]: `%${term}%` })), }, }, ], } : {}, }, { model: db.cabangs, as: 'cabang', }, { model: db.cabangs, as: 'cabangs', }, { model: db.products, as: 'products', required: false, }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.calendarStart && filter.calendarEnd) { where = { ...where, [Op.or]: [ { transaction_date: { [Op.between]: [filter.calendarStart, filter.calendarEnd], }, }, { transaction_date: { [Op.between]: [filter.calendarStart, filter.calendarEnd], }, }, ], }; } if (filter.transaction_dateRange) { const [start, end] = filter.transaction_dateRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, transaction_date: { ...where.transaction_date, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, transaction_date: { ...where.transaction_date, [Op.lte]: end, }, }; } } if (filter.total_amountRange) { const [start, end] = filter.total_amountRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, total_amount: { ...where.total_amount, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, total_amount: { ...where.total_amount, [Op.lte]: end, }, }; } } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true', }; } if (filter.payment_method) { where = { ...where, payment_method: filter.payment_method, }; } if (filter.cabang) { const listItems = filter.cabang.split('|').map((item) => { return Utils.uuid(item); }); where = { ...where, cabangId: { [Op.or]: listItems }, }; } if (filter.cabangs) { const listItems = filter.cabangs.split('|').map((item) => { return Utils.uuid(item); }); where = { ...where, cabangsId: { [Op.or]: listItems }, }; } if (filter.products) { const searchTerms = filter.products.split('|'); include = [ { model: db.products, as: 'products_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, }, }; } } } if (globalAccess) { delete where.cabangsId; } 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.transactions.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('transactions', 'transaction_date', query), ], }; } const records = await db.transactions.findAll({ attributes: ['id', 'transaction_date'], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['transaction_date', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.transaction_date, })); } };