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 CouponsDBApi { static async create(data, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const coupons = await db.coupons.create( { id: data.id || undefined, code: data.code || null , discount_type: data.discount_type || null , discount_value: data.discount_value || null , min_order_total_iqd: data.min_order_total_iqd || null , usage_limit_total: data.usage_limit_total || null , usage_limit_per_user: data.usage_limit_per_user || null , is_active: data.is_active || false , starts_at: data.starts_at || null , ends_at: data.ends_at || null , importHash: data.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, }, { transaction }, ); await coupons.setRedemptions(data.redemptions || [], { transaction, }); return coupons; } 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 couponsData = data.map((item, index) => ({ id: item.id || undefined, code: item.code || null , discount_type: item.discount_type || null , discount_value: item.discount_value || null , min_order_total_iqd: item.min_order_total_iqd || null , usage_limit_total: item.usage_limit_total || null , usage_limit_per_user: item.usage_limit_per_user || null , is_active: item.is_active || false , starts_at: item.starts_at || null , ends_at: item.ends_at || null , importHash: item.importHash || null, createdById: currentUser.id, updatedById: currentUser.id, createdAt: new Date(Date.now() + index * 1000), })); // Bulk create items const coupons = await db.coupons.bulkCreate(couponsData, { transaction }); // For each item created, replace relation files return coupons; } static async update(id, data, options) { const currentUser = (options && options.currentUser) || {id: null}; const transaction = (options && options.transaction) || undefined; const coupons = await db.coupons.findByPk(id, {}, {transaction}); const updatePayload = {}; if (data.code !== undefined) updatePayload.code = data.code; if (data.discount_type !== undefined) updatePayload.discount_type = data.discount_type; if (data.discount_value !== undefined) updatePayload.discount_value = data.discount_value; if (data.min_order_total_iqd !== undefined) updatePayload.min_order_total_iqd = data.min_order_total_iqd; if (data.usage_limit_total !== undefined) updatePayload.usage_limit_total = data.usage_limit_total; if (data.usage_limit_per_user !== undefined) updatePayload.usage_limit_per_user = data.usage_limit_per_user; if (data.is_active !== undefined) updatePayload.is_active = data.is_active; if (data.starts_at !== undefined) updatePayload.starts_at = data.starts_at; if (data.ends_at !== undefined) updatePayload.ends_at = data.ends_at; updatePayload.updatedById = currentUser.id; await coupons.update(updatePayload, {transaction}); if (data.redemptions !== undefined) { await coupons.setRedemptions(data.redemptions, { transaction }); } return coupons; } static async deleteByIds(ids, options) { const currentUser = (options && options.currentUser) || { id: null }; const transaction = (options && options.transaction) || undefined; const coupons = await db.coupons.findAll({ where: { id: { [Op.in]: ids, }, }, transaction, }); await db.sequelize.transaction(async (transaction) => { for (const record of coupons) { await record.update( {deletedBy: currentUser.id}, {transaction} ); } for (const record of coupons) { await record.destroy({transaction}); } }); return coupons; } static async remove(id, options) { const currentUser = (options && options.currentUser) || {id: null}; const transaction = (options && options.transaction) || undefined; const coupons = await db.coupons.findByPk(id, options); await coupons.update({ deletedBy: currentUser.id }, { transaction, }); await coupons.destroy({ transaction }); return coupons; } static async findBy(where, options) { const transaction = (options && options.transaction) || undefined; const coupons = await db.coupons.findOne( { where }, { transaction }, ); if (!coupons) { return coupons; } const output = coupons.get({plain: true}); output.carts_applied_coupon = await coupons.getCarts_applied_coupon({ transaction }); output.orders_applied_coupon = await coupons.getOrders_applied_coupon({ transaction }); output.coupon_redemptions_coupon = await coupons.getCoupon_redemptions_coupon({ transaction }); output.redemptions = await coupons.getRedemptions({ 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.coupon_redemptions, as: 'redemptions', required: false, }, ]; if (filter) { if (filter.id) { where = { ...where, ['id']: Utils.uuid(filter.id), }; } if (filter.code) { where = { ...where, [Op.and]: Utils.ilike( 'coupons', 'code', filter.code, ), }; } if (filter.discount_valueRange) { const [start, end] = filter.discount_valueRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, discount_value: { ...where.discount_value, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, discount_value: { ...where.discount_value, [Op.lte]: end, }, }; } } if (filter.min_order_total_iqdRange) { const [start, end] = filter.min_order_total_iqdRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, min_order_total_iqd: { ...where.min_order_total_iqd, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, min_order_total_iqd: { ...where.min_order_total_iqd, [Op.lte]: end, }, }; } } if (filter.usage_limit_totalRange) { const [start, end] = filter.usage_limit_totalRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, usage_limit_total: { ...where.usage_limit_total, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, usage_limit_total: { ...where.usage_limit_total, [Op.lte]: end, }, }; } } if (filter.usage_limit_per_userRange) { const [start, end] = filter.usage_limit_per_userRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, usage_limit_per_user: { ...where.usage_limit_per_user, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, usage_limit_per_user: { ...where.usage_limit_per_user, [Op.lte]: end, }, }; } } if (filter.starts_atRange) { const [start, end] = filter.starts_atRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, starts_at: { ...where.starts_at, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, starts_at: { ...where.starts_at, [Op.lte]: end, }, }; } } if (filter.ends_atRange) { const [start, end] = filter.ends_atRange; if (start !== undefined && start !== null && start !== '') { where = { ...where, ends_at: { ...where.ends_at, [Op.gte]: start, }, }; } if (end !== undefined && end !== null && end !== '') { where = { ...where, ends_at: { ...where.ends_at, [Op.lte]: end, }, }; } } if (filter.active !== undefined) { where = { ...where, active: filter.active === true || filter.active === 'true' }; } if (filter.discount_type) { where = { ...where, discount_type: filter.discount_type, }; } if (filter.is_active) { where = { ...where, is_active: filter.is_active, }; } if (filter.redemptions) { const searchTerms = filter.redemptions.split('|'); include = [ { model: db.coupon_redemptions, as: 'redemptions_filter', required: searchTerms.length > 0, where: searchTerms.length > 0 ? { [Op.or]: [ { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } }, { redeemed_at: { [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, }, }; } } } 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.coupons.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( 'coupons', 'code', query, ), ], }; } const records = await db.coupons.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, })); } };