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 VouchersDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const vouchers = await db.vouchers.create( { id: data.id || undefined, code: data.code || null, type: data.type || null, value: data.value || null, single_use: data.single_use || false, global: data.global || false, expiration_date: data.expiration_date || null, minimum_spend: data.minimum_spend || null, importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await vouchers.setLocations(data.locations || null, { transaction, }); return vouchers; } 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 vouchersData = data.map((item, index) => ({ id: item.id || undefined, code: item.code || null, type: item.type || null, value: item.value || null, single_use: item.single_use || false, global: item.global || false, expiration_date: item.expiration_date || null, minimum_spend: item.minimum_spend || null, importHash: item.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, createdAt: new Date(Date.now() + index * 1000), })); // Bulk create items const vouchers = await db.vouchers.bulkCreate(vouchersData, { transaction, }); // For each item created, replace relation files return vouchers; } 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 vouchers = await db.vouchers.findByPk(id, {}, { transaction }); const updatePayload = {}; if (data.code !== undefined) updatePayload.code = data.code; if (data.type !== undefined) updatePayload.type = data.type; if (data.value !== undefined) updatePayload.value = data.value; if (data.single_use !== undefined) updatePayload.single_use = data.single_use; if (data.global !== undefined) updatePayload.global = data.global; if (data.expiration_date !== undefined) updatePayload.expiration_date = data.expiration_date; if (data.minimum_spend !== undefined) updatePayload.minimum_spend = data.minimum_spend; updatePayload.updatedById = currentUser.id; await vouchers.update(updatePayload, { transaction }); if (data.locations !== undefined) { await vouchers.setLocations( data.locations, { transaction }, ); } return vouchers; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const vouchers = await db.vouchers.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of vouchers) { await record.update({ deletedBy: currentUser.id }, { transaction }); } for (const record of vouchers) { await record.destroy({ transaction }); } }); return vouchers; } static async remove(id, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const vouchers = await db.vouchers.findByPk(id, options); await vouchers.update( { deletedBy: currentUser.id, }, { transaction, }, ); await vouchers.destroy({ transaction, }); return vouchers; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const vouchers = await db.vouchers.findOne({ where }, { transaction }); if (!vouchers) { return vouchers; } const output = vouchers.get({ plain: true }); output.locations = await vouchers.getLocations({ 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 userLocations = (user && user.locations?.id) || null; if (userLocations) { if (options?.currentUser?.locationsId) { where.locationsId = options.currentUser.locationsId; } } offset = currentPage * limit; const orderBy = null; const transaction = (options && options.transaction) || undefined; let include = [ { model: db.locations, as: 'locations', }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.code) { where = { ...where, [Op.and]: Utils.ilike('vouchers', 'code', filter.code), }; } if (filter.valueRange) { const [start, end] = filter.valueRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, value: { ...where.value, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, value: { ...where.value, [Op.lte]: end, }, }; } } if (filter.expiration_dateRange) { const [start, end] = filter.expiration_dateRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, expiration_date: { ...where.expiration_date, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, expiration_date: { ...where.expiration_date, [Op.lte]: end, }, }; } } if (filter.minimum_spendRange) { const [start, end] = filter.minimum_spendRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, minimum_spend: { ...where.minimum_spend, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, minimum_spend: { ...where.minimum_spend, [Op.lte]: end, }, }; } } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true', }; } if (filter.type) { where = { ...where, type: filter.type, }; } if (filter.single_use) { where = { ...where, single_use: filter.single_use, }; } if (filter.global) { where = { ...where, global: filter.global, }; } if (filter.locations) { const listItems = filter.locations.split('|').map((item) => { return Utils.uuid(item); }); where = { ...where, locationsId: { [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.locationsId; } 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.vouchers.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('vouchers', 'code', query), ], }; } const records = await db.vouchers.findAll({ attributes: ['id', 'code'], where, limit: limit ? Number(limit) : undefined, offset: offset ? Number(offset) : undefined, orderBy: [['code', 'ASC']], }); return records.map((record) => ({ id: record.id, label: record.code, })); } };