@infrab4a/connect-angular 0.17.0-beta.2 → 0.17.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -414,17 +414,18 @@
414
414
  }(Error));
415
415
 
416
416
  var CouponService = /** @class */ (function () {
417
- function CouponService(couponRepository, defaultShop, orderRepository) {
417
+ function CouponService(couponRepository, defaultShop, orderRepository, subscriptionRepository) {
418
418
  var _this = this;
419
419
  this.couponRepository = couponRepository;
420
420
  this.defaultShop = defaultShop;
421
421
  this.orderRepository = orderRepository;
422
+ this.subscriptionRepository = subscriptionRepository;
422
423
  this.emailIsFromCollaborator = function (userEmail) { return !!(userEmail === null || userEmail === void 0 ? void 0 : userEmail.match(/@b4a.com.br/g)); };
423
424
  this.separateValidCoupons = function (coupons, userEmail) { return coupons
424
425
  .map(function (coupon) {
425
426
  try {
426
427
  if (!(coupon instanceof i2.Coupon))
427
- throw new InvalidCouponError('Coupon is not valid');
428
+ throw new InvalidCouponError('Cupom inválido.');
428
429
  if (_this.isValidCoupon(coupon, userEmail))
429
430
  return coupon;
430
431
  }
@@ -439,61 +440,67 @@
439
440
  invalids: [],
440
441
  }); };
441
442
  }
442
- CouponService.prototype.checkCoupon = function (nickname, userEmail, checkoutType, plan, checkout) {
443
+ CouponService.prototype.checkCoupon = function (nickname, userEmail, checkoutType, plan, checkout, isSubscription) {
443
444
  var _this = this;
444
445
  return rxjs.from(this.couponRepository.find([
445
446
  {
446
447
  nickname: { operator: i2.Where.EQUALS, value: nickname },
447
448
  },
448
- ])).pipe(operators.concatMap(function (coupons) { return _this.checkCouponRules(coupons, checkoutType, plan, checkout); }), operators.concatMap(function (coupon) { return _this.checkCouponUseLimit(coupon, userEmail); }), operators.map(function (coupon) { return _this.isValidCoupon(coupon, userEmail); }), operators.map(function (coupon) { return coupon; }));
449
+ ])).pipe(operators.concatMap(function (coupons) { return _this.checkCouponRules(coupons, checkoutType, plan, checkout, isSubscription); }), operators.concatMap(function (coupon) { return _this.checkCouponUseLimit(coupon, userEmail); }), operators.map(function (coupon) { return _this.isValidCoupon(coupon, userEmail); }), operators.map(function (coupon) { return coupon; }));
449
450
  };
450
451
  CouponService.prototype.isValidCoupon = function (coupon, userEmail) {
451
452
  // Verifica se o email do usuário é coorporativo
452
453
  if (!this.emailIsFromCollaborator(userEmail) && coupon.exclusivityType === i2.Exclusivities.COLLABORATORS)
453
- throw new InvalidCouponError('User is not a collaborator');
454
+ throw new InvalidCouponError('Você não é colaborador.');
454
455
  // Verifica se o email do usuário é associado ao cupom de uso por usuario
455
456
  if (coupon.exclusivityType === i2.Exclusivities.SPECIFIC_USER && coupon.userExclusiveEmail !== userEmail)
456
- throw new InvalidCouponError('Coupon is not valid for user');
457
+ throw new InvalidCouponError('Cupom não é válido para este usuário.');
457
458
  // Verifica a data de inicio de validade do cupom
458
459
  if ((coupon === null || coupon === void 0 ? void 0 : coupon.beginAt) > new Date())
459
- throw new InvalidCouponError('Coupon not avaliable yet');
460
+ throw new InvalidCouponError('Cupom inválido.');
460
461
  // Verifica a data de validade do cupom
461
462
  if ((coupon === null || coupon === void 0 ? void 0 : coupon.expiresIn) < new Date())
462
- throw new InvalidCouponError('Coupon is expired');
463
+ throw new InvalidCouponError('Cupom expirado.');
463
464
  return coupon;
464
465
  };
465
- CouponService.prototype.checkCouponRules = function (coupons, checkoutType, plan, checkout) {
466
+ CouponService.prototype.checkCouponRules = function (coupons, checkoutType, plan, checkout, isSubscription) {
466
467
  // Caso não ache nenhum cupom, retorna erro
467
468
  if (coupons.count < 1)
468
- return rxjs.throwError(function () { return new i2.NotFoundError('Coupon not found'); });
469
+ return rxjs.throwError('Cupom inválido.');
469
470
  // Get Primeiro Cupom (o find do repository retorna um array)
470
471
  var coupon = coupons.data.shift();
471
472
  // Verifica se o cupom é aplicavel na loja
472
473
  var isInShop = coupon.shopAvailability === i2.Shops.ALL || coupon.shopAvailability === this.defaultShop;
473
474
  // Cupon não aplicavel a loja retorna erro
474
475
  if (!isInShop)
475
- return rxjs.throwError(function () { return new InvalidCouponError('Coupon not correct shop'); });
476
+ return rxjs.throwError('Cupom inválido.');
476
477
  // Verifica se o coupon é aplicado no checkout que está sendo realizado
477
478
  var isCheckoutType = coupon.checkoutType === i2.CheckoutTypes.ALL || coupon.checkoutType === checkoutType;
478
479
  // Cupon não aplicavel ao checkout retorna erro
479
480
  if (!isCheckoutType)
480
- return rxjs.throwError(function () { return new InvalidCouponError('Coupon not correct checkout'); });
481
+ return rxjs.throwError('Cupom inválido.');
481
482
  // Verifica se o cupom é ou pode ser aplicado para subscription
482
483
  if (checkoutType === i2.CheckoutTypes.ALL || checkoutType === i2.CheckoutTypes.SUBSCRIPTION) {
483
484
  // Se o cupom tiver um plano associado, verifica se é o mesmo plano do checkout da assinatura
485
+ console.log('1', coupon.plan, plan.toUpperCase());
484
486
  if (coupon.plan && coupon.plan.toUpperCase() !== plan.toUpperCase())
485
- return rxjs.throwError(function () { return new InvalidCouponError('Coupon not valid for this plan'); });
487
+ return rxjs.throwError('Cupom inválido.');
486
488
  }
489
+ if (isSubscription)
490
+ return rxjs.of(coupon);
487
491
  // Verifica se possui o valor minimo de compra para utilização do cupom
488
492
  var hasMinSubTotal = this.hasMinSubTotal(coupon, checkout);
489
493
  // Se não tem valor mínimo atingido, retorna erro
490
494
  if (!hasMinSubTotal)
491
- return rxjs.throwError(function () { return new InvalidCouponError('Valor mínimo não atingido'); });
495
+ return rxjs.throwError('Valor mínimo não atingido');
492
496
  // Verifica se a compra possui produtos elegíveis para desconto
493
497
  var hasProductCategories = this.hasProductCategories(coupon, checkout);
494
498
  // Se não tem produtos elegíveis, retorna erro
495
499
  if (!hasProductCategories)
496
- return rxjs.throwError(function () { return new InvalidCouponError('Checkout não possui produtos elegíveis para desconto'); });
500
+ return rxjs.throwError('Seu carrinho não possui produtos elegíveis para desconto.');
501
+ // const validUser = this.userSubscriberStatus(coupon, checkout)
502
+ // console.log(validUser)
503
+ // if (!validUser) return throwError('Usuário não elegível.')
497
504
  return rxjs.of(coupon);
498
505
  };
499
506
  CouponService.prototype.checkCouponUseLimit = function (coupon, userEmail) {
@@ -507,10 +514,10 @@
507
514
  ordersUserCoupon = orders.data.filter(function (o) { return o.user.email == userEmail; });
508
515
  // Verifica o limite de uso de cupom por usuario
509
516
  if (coupon.useLimitPerUser && ordersUserCoupon.length)
510
- throw new InvalidCouponError('Coupon user use limit reached');
517
+ throw new InvalidCouponError('Limite de uso por usuário atingido.');
511
518
  // Verifica o limite de uso geral por usuario
512
519
  if (coupon.useLimit && orders.data.length >= coupon.useLimit)
513
- throw new InvalidCouponError('Coupon use limit reached');
520
+ throw new InvalidCouponError('Limite de uso atingido.');
514
521
  return [2 /*return*/, coupon];
515
522
  }
516
523
  });
@@ -544,8 +551,14 @@
544
551
  var discount = 0;
545
552
  var shop = checkout.shop;
546
553
  var lineItensDiscount = [];
547
- if (coupon.productsCategories) {
548
- lineItensDiscount = (_a = checkout.lineItems) === null || _a === void 0 ? void 0 : _a.filter(function (i) { return i.categories.some(function (c) { return coupon.productsCategories.includes(c); }); });
554
+ if (coupon.productsCategories && coupon.productsCategories.length) {
555
+ lineItensDiscount = (_a = checkout.lineItems) === null || _a === void 0 ? void 0 : _a.filter(function (i) {
556
+ var _a;
557
+ if ((_a = i.categories) === null || _a === void 0 ? void 0 : _a.length) {
558
+ return i.categories.some(function (c) { return coupon.productsCategories.includes(c); });
559
+ }
560
+ return true;
561
+ });
549
562
  }
550
563
  else {
551
564
  lineItensDiscount = checkout.lineItems;
@@ -576,17 +589,56 @@
576
589
  };
577
590
  CouponService.prototype.hasProductCategories = function (coupon, checkout) {
578
591
  var _a;
579
- if (coupon.productsCategories) {
580
- var hasCategories = (_a = checkout.lineItems) === null || _a === void 0 ? void 0 : _a.filter(function (i) { return i.categories.some(function (c) { return coupon.productsCategories.includes(c); }); });
581
- return hasCategories ? true : false;
592
+ if (coupon.productsCategories && coupon.productsCategories.length) {
593
+ var hasCategories = (_a = checkout.lineItems) === null || _a === void 0 ? void 0 : _a.filter(function (i) {
594
+ var _a;
595
+ if ((_a = i.categories) === null || _a === void 0 ? void 0 : _a.length) {
596
+ return i.categories.some(function (c) { return coupon.productsCategories.includes(c); });
597
+ }
598
+ return true;
599
+ });
600
+ return hasCategories.length ? true : false;
582
601
  }
583
602
  else {
584
603
  return true;
585
604
  }
586
605
  };
606
+ CouponService.prototype.userSubscriberStatus = function (coupon, checkout) {
607
+ return __awaiter(this, void 0, void 0, function () {
608
+ var sub, active;
609
+ return __generator(this, function (_d) {
610
+ switch (_d.label) {
611
+ case 0: return [4 /*yield*/, this.subscriptionRepository
612
+ .find([
613
+ {
614
+ user: {
615
+ email: { operator: i2.Where.EQUALS, value: checkout.user.email },
616
+ },
617
+ },
618
+ ])
619
+ .then(function (sub) { return sub.data; })];
620
+ case 1:
621
+ sub = _d.sent();
622
+ active = sub === null || sub === void 0 ? void 0 : sub.filter(function (s) { return s.status === i2.Status.ACTIVE; });
623
+ console.log("active", active, active.length, sub);
624
+ switch (coupon.exclusivityType) {
625
+ case i2.Exclusivities.ACTIVE_SUBSCRIBER:
626
+ return [2 /*return*/, active.length > 0];
627
+ case i2.Exclusivities.INACTIVE_SUBSCRIBER:
628
+ return [2 /*return*/, active.length === 0];
629
+ case i2.Exclusivities.NON_SUBSCRIBER:
630
+ return [2 /*return*/, sub.length === 0];
631
+ default:
632
+ return [2 /*return*/, false];
633
+ }
634
+ return [2 /*return*/];
635
+ }
636
+ });
637
+ });
638
+ };
587
639
  return CouponService;
588
640
  }());
589
- CouponService.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.12", ngImport: i0__namespace, type: CouponService, deps: [{ token: 'CouponRepository' }, { token: DEFAULT_SHOP }, { token: 'OrderRepository' }], target: i0__namespace.ɵɵFactoryTarget.Injectable });
641
+ CouponService.ɵfac = i0__namespace.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.12", ngImport: i0__namespace, type: CouponService, deps: [{ token: 'CouponRepository' }, { token: DEFAULT_SHOP }, { token: 'OrderRepository' }, { token: 'SubscriptionRepository' }], target: i0__namespace.ɵɵFactoryTarget.Injectable });
590
642
  CouponService.ɵprov = i0__namespace.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.2.12", ngImport: i0__namespace, type: CouponService, providedIn: 'root' });
591
643
  i0__namespace.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.12", ngImport: i0__namespace, type: CouponService, decorators: [{
592
644
  type: i0.Injectable,
@@ -603,6 +655,9 @@
603
655
  }] }, { type: undefined, decorators: [{
604
656
  type: i0.Inject,
605
657
  args: ['OrderRepository']
658
+ }] }, { type: undefined, decorators: [{
659
+ type: i0.Inject,
660
+ args: ['SubscriptionRepository']
606
661
  }] }];
607
662
  } });
608
663
 
@@ -640,7 +695,12 @@
640
695
  };
641
696
  CheckoutService.prototype.checkCoupon = function (nickname, checkoutType) {
642
697
  var _this = this;
643
- return this.getCheckout().pipe(operators.concatMap(function (checkout) { var _a; return _this.couponService.checkCoupon(nickname, (_a = checkout.user) === null || _a === void 0 ? void 0 : _a.email, i2.CheckoutTypes.ECOMMERCE).pipe(); }));
698
+ return this.getCheckout().pipe(operators.concatMap(function (checkout) {
699
+ var _a;
700
+ return _this.couponService
701
+ .checkCoupon(nickname, (_a = checkout.user) === null || _a === void 0 ? void 0 : _a.email, i2.CheckoutTypes.ECOMMERCE, checkout.user.subscriptionPlan, checkout, false)
702
+ .pipe();
703
+ }));
644
704
  };
645
705
  CheckoutService.prototype.createCheckout = function (checkoutData) {
646
706
  return __awaiter(this, void 0, void 0, function () {
@@ -866,22 +926,7 @@
866
926
  };
867
927
  CheckoutSubscriptionService.prototype.checkCoupon = function (nickname, userEmail) {
868
928
  var _this = this;
869
- return this.getCheckoutSubscription().pipe(operators.concatMap(function (checkout) { return _this.couponService.checkCoupon(nickname, userEmail, i2.CheckoutTypes.SUBSCRIPTION, checkout.subscriptionPlan.name).pipe(); }
870
- // .pipe(
871
- // concatMap((coupon: Coupon) => {
872
- // const couponsWithSamePlan = coupons.filter((coupon) => checkout.subscriptionPlan.name === coupon.plan)
873
- // const couponsWithNoPlan = coupons.filter((coupon) => !coupon.plan)
874
- // if (couponsWithSamePlan.length > 0) return of(couponsWithSamePlan)
875
- // if (couponsWithNoPlan.length > 0) return of(couponsWithNoPlan)
876
- // throw new Error(`Coupon subscription plan is invalid.`)
877
- // })
878
- // ,
879
- // concatMap((coupons) =>
880
- // !!checkout.user?.email ? this.checkCouponsWithCheckout(coupons, checkout) : of(coupons),
881
- // )
882
- // map((validatedCoupons) => validatedCoupons.shift()),
883
- // ),
884
- ));
929
+ return this.getCheckoutSubscription().pipe(operators.concatMap(function (checkout) { return _this.couponService.checkCoupon(nickname, userEmail, i2.CheckoutTypes.SUBSCRIPTION, checkout.subscriptionPlan.name, null, true).pipe(); }));
885
930
  };
886
931
  CheckoutSubscriptionService.prototype.calcDiscountSubscription = function (coupon) {
887
932
  var _this = this;