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 BusinessesDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const businesses = await db.businesses.create( { id: data.id || undefined, name: data.name || null, whatsapp_number: data.whatsapp_number || null, importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await businesses.setBisnis(data.bisnis || null, { transaction, }); await businesses.setBranches(data.branches || [], { transaction, }); await businesses.setProducts(data.products || [], { transaction, }); await businesses.setCustomers(data.customers || [], { transaction, }); await businesses.setTransactions(data.transactions || [], { transaction, }); await businesses.setStaff(data.staff || [], { transaction, }); await FileDBApi.replaceRelationFiles( { belongsTo: db.businesses.getTableName(), belongsToColumn: 'logo', belongsToId: businesses.id, }, data.logo, options, ); return businesses; } 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 businessesData = data.map((item, index) => ({ id: item.id || undefined, name: item.name || null, whatsapp_number: item.whatsapp_number || null, importHash: item.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, createdAt: new Date(Date.now() + index * 1000), })); // Bulk create items const businesses = await db.businesses.bulkCreate(businessesData, { transaction, }); // For each item created, replace relation files for (let i = 0; i < businesses.length; i++) { await FileDBApi.replaceRelationFiles( { belongsTo: db.businesses.getTableName(), belongsToColumn: 'logo', belongsToId: businesses[i].id, }, data[i].logo, options, ); } return businesses; } 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 businesses = await db.businesses.findByPk(id, {}, { transaction }); const updatePayload = {}; if (data.name !== undefined) updatePayload.name = data.name; if (data.whatsapp_number !== undefined) updatePayload.whatsapp_number = data.whatsapp_number; updatePayload.updatedById = currentUser.id; await businesses.update(updatePayload, { transaction }); if (data.bisnis !== undefined) { await businesses.setBisnis( data.bisnis, { transaction }, ); } if (data.branches !== undefined) { await businesses.setBranches(data.branches, { transaction }); } if (data.products !== undefined) { await businesses.setProducts(data.products, { transaction }); } if (data.customers !== undefined) { await businesses.setCustomers(data.customers, { transaction }); } if (data.transactions !== undefined) { await businesses.setTransactions(data.transactions, { transaction }); } if (data.staff !== undefined) { await businesses.setStaff(data.staff, { transaction }); } await FileDBApi.replaceRelationFiles( { belongsTo: db.businesses.getTableName(), belongsToColumn: 'logo', belongsToId: businesses.id, }, data.logo, options, ); return businesses; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const businesses = await db.businesses.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of businesses) { await record.update({ deletedBy: currentUser.id }, { transaction }); } for (const record of businesses) { await record.destroy({ transaction }); } }); return businesses; } static async remove(id, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const businesses = await db.businesses.findByPk(id, options); await businesses.update( { deletedBy: currentUser.id, }, { transaction, }, ); await businesses.destroy({ transaction, }); return businesses; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const businesses = await db.businesses.findOne({ where }, { transaction }); if (!businesses) { return businesses; } const output = businesses.get({ plain: true }); output.branches_business = await businesses.getBranches_business({ transaction, }); output.customers_business = await businesses.getCustomers_business({ transaction, }); output.products_business = await businesses.getProducts_business({ transaction, }); output.subscriptions_business = await businesses.getSubscriptions_business({ transaction, }); output.transactions_business = await businesses.getTransactions_business({ transaction, }); output.logo = await businesses.getLogo({ transaction, }); output.branches = await businesses.getBranches({ transaction, }); output.products = await businesses.getProducts({ transaction, }); output.customers = await businesses.getCustomers({ transaction, }); output.transactions = await businesses.getTransactions({ transaction, }); output.staff = await businesses.getStaff({ transaction, }); output.bisnis = await businesses.getBisnis({ 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 userBisnis = (user && user.bisnis?.id) || null; if (userBisnis) { if (options?.currentUser?.bisnisId) { where.bisnisId = options.currentUser.bisnisId; } } offset = currentPage * limit; const orderBy = null; const transaction = (options && options.transaction) || undefined; let include = [ { model: db.bisnis, as: 'bisnis', }, { model: db.branches, as: 'branches', required: false, }, { model: db.products, as: 'products', required: false, }, { model: db.customers, as: 'customers', required: false, }, { model: db.transactions, as: 'transactions', required: false, }, { model: db.users, as: 'staff', required: false, }, { model: db.file, as: 'logo', }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.name) { where = { ...where, [Op.and]: Utils.ilike('businesses', 'name', filter.name), }; } if (filter.whatsapp_number) { where = { ...where, [Op.and]: Utils.ilike( 'businesses', 'whatsapp_number', filter.whatsapp_number, ), }; } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true', }; } if (filter.bisnis) { const listItems = filter.bisnis.split('|').map((item) => { return Utils.uuid(item); }); where = { ...where, bisnisId: { [Op.or]: listItems }, }; } if (filter.branches) { const searchTerms = filter.branches.split('|'); include = [ { model: db.branches, as: 'branches_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.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.customers) { const searchTerms = filter.customers.split('|'); include = [ { model: db.customers, as: 'customers_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.transactions) { const searchTerms = filter.transactions.split('|'); include = [ { model: db.transactions, as: 'transactions_filter', required: searchTerms.length > 0, where: searchTerms.length > 0 ? { [Op.or]: [ { id: { [Op.in]: searchTerms.map((term) => Utils.uuid(term)), }, }, { transaction_date: { [Op.or]: searchTerms.map((term) => ({ [Op.iLike]: `%${term}%`, })), }, }, ], } : undefined, }, ...include, ]; } if (filter.staff) { const searchTerms = filter.staff.split('|'); include = [ { model: db.users, as: 'staff_filter', required: searchTerms.length > 0, where: searchTerms.length > 0 ? { [Op.or]: [ { id: { [Op.in]: searchTerms.map((term) => Utils.uuid(term)), }, }, { firstName: { [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.bisnisId; } 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.businesses.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('businesses', 'name', query), ], }; } const records = await db.businesses.findAll({ attributes: ['id', 'name'], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['name', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.name, })); } };