import { Request, Response } from 'express'; import httpStatus from 'http-status'; import { EcommerceService } from '../services/ecommerce.service'; import { BaseController } from './base.controller'; import { ms } from '../server'; require('dotenv/config'); export class AffiliatesController extends BaseController { async upsertAffiliateCoupon(req: Request, res: Response) { try { const discount = Number(req.body.discount) || 10; if (discount > 20 || discount < 0) { throw new Error('Invalid discount'); } const affiliate = await EcommerceService.getInstance().insertAffiliate(req.body); const coupon = await EcommerceService.getInstance() .insertAffiliateCoupon(affiliate, discount); res.status(httpStatus.OK).json(coupon); } catch (e) { ms.logger.error(e); res.status(httpStatus.BAD_REQUEST).json({ error: e.message, }); } } async listCouponUsage(req: Request, res: Response) { try { const { coupon } = req.params; let orders = await EcommerceService.getInstance().listCouponUsage(coupon); const otherMGMCouponOrders = await AffiliatesController.listOtherMGMCouponsOrders(coupon); orders = orders.concat(otherMGMCouponOrders); res.status(httpStatus.OK).json(orders); } catch (e) { res.status(httpStatus.BAD_REQUEST).json({ error: e.message, }); } } private static async listOtherMGMCouponsOrders(coupon: string) : Promise { let orders = []; try { const coupons = await EcommerceService.getInstance().findCoupon(coupon); const affiliateId = coupons.filter((c) => c.affId)[0]?.affId; if (affiliateId) { const affiliateCoupons = await EcommerceService.getInstance() .listAffiliateCoupons(affiliateId); await Promise.all(affiliateCoupons.map(async (c) => { if (c.cupCodigo !== coupon && c.cupCodigo.endsWith('MGM')) { const moreOrders = await EcommerceService.getInstance().listCouponUsage(c.cupCodigo); orders = orders.concat(moreOrders); } })); } return orders; } catch (e) { // eslint-disable-next-line no-console console.error('Error listing other MGM coupons orders', e); return []; } } }