@infrab4a/connect 4.21.3 → 4.22.0-beta.0

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.
Files changed (83) hide show
  1. package/index.cjs.js +882 -243
  2. package/index.esm.js +860 -247
  3. package/package.json +1 -1
  4. package/src/domain/catalog/models/types/index.d.ts +0 -1
  5. package/src/domain/catalog/repositories/product.repository.d.ts +1 -2
  6. package/src/domain/general/models/index.d.ts +1 -0
  7. package/src/domain/general/models/sequences.d.ts +9 -0
  8. package/src/domain/general/repositories/index.d.ts +1 -0
  9. package/src/domain/general/repositories/sequences.repository.d.ts +4 -0
  10. package/src/domain/shopping/enums/antifraud-providers.enum.d.ts +6 -0
  11. package/src/domain/shopping/enums/business-unit.enum.d.ts +4 -0
  12. package/src/domain/shopping/enums/index.d.ts +6 -0
  13. package/src/domain/shopping/enums/order-blocked.enum.d.ts +5 -0
  14. package/src/domain/shopping/enums/pagarme-payment-status.enum.d.ts +10 -0
  15. package/src/domain/shopping/enums/payment-methods.enum.d.ts +6 -0
  16. package/src/domain/shopping/enums/payment-providers.enum.d.ts +5 -0
  17. package/src/domain/shopping/factories/adyen-payment-method.factory.d.ts +9 -0
  18. package/src/domain/shopping/factories/antifraud-provider.factory.d.ts +15 -0
  19. package/src/domain/shopping/factories/base-payment-method.factory.d.ts +7 -0
  20. package/src/domain/shopping/factories/glampoints-payment-method.factory.d.ts +8 -0
  21. package/src/domain/shopping/factories/index.d.ts +5 -0
  22. package/src/domain/shopping/factories/pagarme-payment-method.factory.d.ts +11 -0
  23. package/src/domain/shopping/factories/payment-provider.factory.d.ts +15 -0
  24. package/src/domain/shopping/index.d.ts +4 -0
  25. package/src/domain/shopping/interfaces/antifraud-method-factory.interface.d.ts +11 -0
  26. package/src/domain/shopping/interfaces/antifraud-provider.interface.d.ts +5 -0
  27. package/src/domain/shopping/interfaces/index.d.ts +7 -0
  28. package/src/domain/shopping/interfaces/payment-method-factory.interface.d.ts +14 -0
  29. package/src/domain/shopping/interfaces/payment-provider-bank-slip.interface.d.ts +7 -0
  30. package/src/domain/shopping/interfaces/payment-provider-card.interface.d.ts +13 -0
  31. package/src/domain/shopping/interfaces/payment-provider-glampoints.interface.d.ts +9 -0
  32. package/src/domain/shopping/interfaces/payment-provider-pix.interface.d.ts +5 -0
  33. package/src/domain/shopping/models/index.d.ts +1 -0
  34. package/src/domain/shopping/models/order-blocked.d.ts +4 -6
  35. package/src/domain/shopping/models/order.d.ts +2 -2
  36. package/src/domain/shopping/models/payment-transaction.d.ts +67 -0
  37. package/src/domain/shopping/models/payment.d.ts +10 -63
  38. package/src/domain/shopping/models/types/index.d.ts +4 -4
  39. package/src/domain/shopping/services/antifraud-bankslip.service.d.ts +9 -0
  40. package/src/domain/shopping/services/antifraud-card.service.d.ts +18 -0
  41. package/src/domain/shopping/services/antifraud-glampoints.service.d.ts +6 -0
  42. package/src/domain/shopping/services/antifraud-pix.service.d.ts +6 -0
  43. package/src/domain/shopping/services/glampoints-payment.service.d.ts +13 -0
  44. package/src/domain/shopping/services/index.d.ts +5 -0
  45. package/src/domain/shopping/types/adyen-card.type.d.ts +3 -0
  46. package/src/domain/shopping/types/adyen-credentials.type.d.ts +6 -0
  47. package/src/domain/shopping/types/antifraud-provider.type.d.ts +2 -0
  48. package/src/domain/shopping/types/base-card.type.d.ts +2 -0
  49. package/src/domain/shopping/types/card-info.type.d.ts +8 -0
  50. package/src/domain/shopping/types/glam-credentials.type.d.ts +6 -0
  51. package/src/domain/shopping/types/index.d.ts +9 -0
  52. package/src/domain/shopping/types/pagarme-card-manual-hash.type.d.ts +6 -0
  53. package/src/domain/shopping/types/pagarme-card.type.d.ts +16 -0
  54. package/src/domain/shopping/types/pagarme-credentials.type.d.ts +7 -0
  55. package/src/domain/shopping/types/payment-card-info.type.d.ts +3 -0
  56. package/src/domain/shopping/types/payment-method.type.d.ts +2 -0
  57. package/src/domain/shopping/types/payment-provider.type.d.ts +2 -0
  58. package/src/errors/business.error.d.ts +7 -0
  59. package/src/errors/fraud-validation.error.d.ts +7 -0
  60. package/src/errors/index.d.ts +8 -2
  61. package/src/errors/payment.error.d.ts +7 -0
  62. package/src/errors/stock-limit.error.d.ts +5 -0
  63. package/src/errors/stock-out.error.d.ts +5 -0
  64. package/src/errors/types/checkout-additional-data-erro.type.d.ts +6 -0
  65. package/src/errors/types/index.d.ts +2 -0
  66. package/src/errors/types/pagarme-erros.type.d.ts +9 -0
  67. package/src/infra/adyen/adapters/adyen-card-payment-axios.adapter.d.ts +17 -0
  68. package/src/infra/adyen/adapters/index.d.ts +1 -0
  69. package/src/infra/adyen/index.d.ts +1 -0
  70. package/src/infra/firebase/firestore/repositories/catalog/product-firestore.repository.d.ts +1 -2
  71. package/src/infra/firebase/firestore/repositories/general/index.d.ts +1 -0
  72. package/src/infra/firebase/firestore/repositories/general/sequences-firestore.repository.d.ts +7 -0
  73. package/src/infra/firebase/firestore/repositories/shopping/index.d.ts +1 -1
  74. package/src/infra/firebase/firestore/repositories/shopping/{order-blocked-firestore.repository.ts.d.ts → order-blocked-firestore.repository.d.ts} +2 -2
  75. package/src/infra/hasura-graphql/repositories/catalog/product-hasura-graphql.repository.d.ts +1 -2
  76. package/src/infra/index.d.ts +2 -0
  77. package/src/infra/pagarme/adapters/index.d.ts +3 -0
  78. package/src/infra/pagarme/adapters/pagarme-bank-slip-payment-axios.adapter.d.ts +12 -0
  79. package/src/infra/pagarme/adapters/pagarme-card-payment-axios.adapter.d.ts +17 -0
  80. package/src/infra/pagarme/adapters/pagarme-pix-payment-axios.adapter.d.ts +11 -0
  81. package/src/infra/pagarme/index.d.ts +1 -0
  82. package/src/utils/index.d.ts +2 -2
  83. package/src/domain/catalog/models/types/product-variant-report.type.d.ts +0 -46
package/index.esm.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import 'reflect-metadata';
2
2
  import { __decorate, __metadata, __values, __spreadArray, __read, __extends, __rest } from 'tslib';
3
- import { plainToInstance, instanceToPlain, Type, Expose } from 'class-transformer';
4
- import { parseISO } from 'date-fns';
5
- export { add, addBusinessDays, addDays, addMonths, addYears, endOfDay, format, formatISO9075, parseISO, startOfDay, sub } from 'date-fns';
3
+ import { plainToInstance, instanceToPlain, Type } from 'class-transformer';
4
+ import { parseISO, format, startOfDay, endOfDay, subDays, addDays } from 'date-fns';
5
+ export { add, addBusinessDays, addDays, addMonths, addYears, endOfDay, format, formatISO9075, parseISO, startOfDay, sub, subDays } from 'date-fns';
6
6
  import { isNil, isArray, first, last, flatten, compact, get, isString, each, unset, isObject, set, isNumber, chunk, isEmpty, isDate, isBoolean, isInteger, isNaN as isNaN$1, sortBy, omit } from 'lodash';
7
7
  export { chunk, each, get, isBoolean, isDate, isEmpty, isInteger, isNaN, isNil, isNumber, isObject, isString, now, omit, pick, set, sortBy, unset } from 'lodash';
8
8
  import { debug } from 'debug';
@@ -13,6 +13,90 @@ import { deleteField, arrayUnion, arrayRemove, Timestamp, doc, getDoc, updateDoc
13
13
  import { ref, uploadBytes } from 'firebase/storage';
14
14
  import { mutation, query as query$1 } from 'gql-query-builder';
15
15
 
16
+ var AntifraudProviders;
17
+ (function (AntifraudProviders) {
18
+ AntifraudProviders["BANKSLIP"] = "bankSlip";
19
+ AntifraudProviders["CARD"] = "card";
20
+ AntifraudProviders["PIX"] = "pix";
21
+ AntifraudProviders["POINTS"] = "glampoints";
22
+ })(AntifraudProviders || (AntifraudProviders = {}));
23
+
24
+ var BusinessUnitEnum;
25
+ (function (BusinessUnitEnum) {
26
+ BusinessUnitEnum[BusinessUnitEnum["SUBSCRIPTION"] = 1] = "SUBSCRIPTION";
27
+ BusinessUnitEnum[BusinessUnitEnum["SHOP"] = 2] = "SHOP";
28
+ })(BusinessUnitEnum || (BusinessUnitEnum = {}));
29
+
30
+ var OrderBlockedType;
31
+ (function (OrderBlockedType) {
32
+ OrderBlockedType["Checkout"] = "Checkout";
33
+ OrderBlockedType["Card"] = "Card";
34
+ OrderBlockedType["Boleto"] = "Boleto";
35
+ })(OrderBlockedType || (OrderBlockedType = {}));
36
+
37
+ var PagarmePaymentStatus;
38
+ (function (PagarmePaymentStatus) {
39
+ PagarmePaymentStatus["Em processamento"] = "processing";
40
+ PagarmePaymentStatus["Autorizada"] = "authorized";
41
+ PagarmePaymentStatus["Pago"] = "paid";
42
+ PagarmePaymentStatus["Estornada"] = "refunded";
43
+ PagarmePaymentStatus["Aguardando pagamento"] = "waiting_payment";
44
+ PagarmePaymentStatus["Aguardando estorno"] = "pending_refund";
45
+ PagarmePaymentStatus["Recusada/N\u00E3o autorizada"] = "refused";
46
+ PagarmePaymentStatus["Chargedback"] = "chargedback";
47
+ })(PagarmePaymentStatus || (PagarmePaymentStatus = {}));
48
+
49
+ var PaymentMethods;
50
+ (function (PaymentMethods) {
51
+ PaymentMethods["CARD"] = "card";
52
+ PaymentMethods["BANKSLIP"] = "bankSlip";
53
+ PaymentMethods["PIX"] = "pix";
54
+ PaymentMethods["POINTS"] = "glampoints";
55
+ })(PaymentMethods || (PaymentMethods = {}));
56
+
57
+ var PaymentProviders;
58
+ (function (PaymentProviders) {
59
+ PaymentProviders["PAGARME"] = "pagarMe";
60
+ PaymentProviders["ADYEN"] = "adyen";
61
+ PaymentProviders["GLAMPOINTS"] = "glampoints";
62
+ })(PaymentProviders || (PaymentProviders = {}));
63
+
64
+ class BasePaymentMethodFactory {
65
+ constructor(methods) {
66
+ this.methods = methods;
67
+ }
68
+ build(method) {
69
+ return this.methods[method];
70
+ }
71
+ }
72
+
73
+ class AdyenPaymentMethodFactory extends BasePaymentMethodFactory {
74
+ }
75
+
76
+ class AntifraudProviderFactory {
77
+ constructor(antifraudProviders) {
78
+ this.antifraudProviders = antifraudProviders;
79
+ }
80
+ build(provider) {
81
+ return this.antifraudProviders[provider];
82
+ }
83
+ }
84
+
85
+ class GlampointsPaymentMethodFactory extends BasePaymentMethodFactory {
86
+ }
87
+
88
+ class PagarmePaymentMethodFactory extends BasePaymentMethodFactory {
89
+ }
90
+
91
+ class PaymentProviderFactory {
92
+ constructor(paymentProviders) {
93
+ this.paymentProviders = paymentProviders;
94
+ }
95
+ build(provider) {
96
+ return this.paymentProviders[provider];
97
+ }
98
+ }
99
+
16
100
  class BaseModel {
17
101
  get identifier() {
18
102
  const fields = this.constructor.identifiersFields.filter((field) => field !== 'identifier');
@@ -573,175 +657,18 @@ var Status;
573
657
  Status["CANCELLED"] = "Cancelado";
574
658
  })(Status || (Status = {}));
575
659
 
660
+ class PaymentTransaction extends BaseModel {
661
+ }
662
+
576
663
  class Payment extends BaseModel {
577
664
  static get identifiersFields() {
578
665
  return ['id'];
579
666
  }
580
667
  }
581
668
  __decorate([
582
- Expose({ name: 'refuse_reason' }),
583
- __metadata("design:type", String)
584
- ], Payment.prototype, "refuseReason", void 0);
585
- __decorate([
586
- Expose({ name: 'status_reason' }),
587
- __metadata("design:type", String)
588
- ], Payment.prototype, "statusReason", void 0);
589
- __decorate([
590
- Expose({ name: 'acquirer_response_code' }),
591
- __metadata("design:type", String)
592
- ], Payment.prototype, "acquirerResponseCode", void 0);
593
- __decorate([
594
- Expose({ name: 'acquirer_name' }),
595
- __metadata("design:type", String)
596
- ], Payment.prototype, "acquirerName", void 0);
597
- __decorate([
598
- Expose({ name: 'acquirer_id' }),
599
- __metadata("design:type", String)
600
- ], Payment.prototype, "acquirerId", void 0);
601
- __decorate([
602
- Expose({ name: 'authorization_code' }),
603
- __metadata("design:type", String)
604
- ], Payment.prototype, "authorizationCode", void 0);
605
- __decorate([
606
- Expose({ name: 'soft_descriptor' }),
607
- __metadata("design:type", String)
608
- ], Payment.prototype, "softDescriptor", void 0);
609
- __decorate([
610
- Expose({ name: 'date_created' }),
611
- __metadata("design:type", String)
612
- ], Payment.prototype, "dateCreated", void 0);
613
- __decorate([
614
- Expose({ name: 'date_updated' }),
615
- __metadata("design:type", String)
616
- ], Payment.prototype, "dateUpdated", void 0);
617
- __decorate([
618
- Expose({ name: 'authorized_amount' }),
619
- __metadata("design:type", Number)
620
- ], Payment.prototype, "authorizedAmount", void 0);
621
- __decorate([
622
- Expose({ name: 'paid_amount' }),
623
- __metadata("design:type", Number)
624
- ], Payment.prototype, "paidAmount", void 0);
625
- __decorate([
626
- Expose({ name: 'paid_at' }),
627
- __metadata("design:type", String)
628
- ], Payment.prototype, "paidAt", void 0);
629
- __decorate([
630
- Expose({ name: 'refunded_amount' }),
631
- __metadata("design:type", Number)
632
- ], Payment.prototype, "refundedAmount", void 0);
633
- __decorate([
634
- Expose({ name: 'card_holder_name' }),
635
- __metadata("design:type", String)
636
- ], Payment.prototype, "cardHolderName", void 0);
637
- __decorate([
638
- Expose({ name: 'card_last_digits' }),
639
- __metadata("design:type", String)
640
- ], Payment.prototype, "cardLastDigits", void 0);
641
- __decorate([
642
- Expose({ name: 'card_first_digits' }),
643
- __metadata("design:type", String)
644
- ], Payment.prototype, "cardFirstDigits", void 0);
645
- __decorate([
646
- Expose({ name: 'card_brand' }),
647
- __metadata("design:type", String)
648
- ], Payment.prototype, "cardBrand", void 0);
649
- __decorate([
650
- Expose({ name: 'card_pin_mode' }),
651
- __metadata("design:type", String)
652
- ], Payment.prototype, "cardPinMode", void 0);
653
- __decorate([
654
- Expose({ name: 'card_magstripe_fallback' }),
655
- __metadata("design:type", Boolean)
656
- ], Payment.prototype, "cardMagstripeFallback", void 0);
657
- __decorate([
658
- Expose({ name: 'cvm_pin' }),
659
- __metadata("design:type", Boolean)
660
- ], Payment.prototype, "cvmPin", void 0);
661
- __decorate([
662
- Expose({ name: 'postback_url' }),
663
- __metadata("design:type", String)
664
- ], Payment.prototype, "postbackUrl", void 0);
665
- __decorate([
666
- Expose({ name: 'payment_method' }),
667
- __metadata("design:type", String)
668
- ], Payment.prototype, "paymentMethod", void 0);
669
- __decorate([
670
- Expose({ name: 'capture_method' }),
671
- __metadata("design:type", String)
672
- ], Payment.prototype, "captureMethod", void 0);
673
- __decorate([
674
- Expose({ name: 'antifraud_score' }),
675
- __metadata("design:type", String)
676
- ], Payment.prototype, "antifraudScore", void 0);
677
- __decorate([
678
- Expose({ name: 'boleto_url' }),
679
- __metadata("design:type", String)
680
- ], Payment.prototype, "boletoUrl", void 0);
681
- __decorate([
682
- Expose({ name: 'boleto_barcode' }),
683
- __metadata("design:type", String)
684
- ], Payment.prototype, "boletoBarcode", void 0);
685
- __decorate([
686
- Expose({ name: 'boleto_expiration_date' }),
687
- __metadata("design:type", String)
688
- ], Payment.prototype, "boletoExpirationDate", void 0);
689
- __decorate([
690
- Expose({ name: 'subscription_id' }),
691
- __metadata("design:type", String)
692
- ], Payment.prototype, "subscriptionId", void 0);
693
- __decorate([
694
- Expose({ name: 'split_rules' }),
695
- __metadata("design:type", String)
696
- ], Payment.prototype, "splitRules", void 0);
697
- __decorate([
698
- Expose({ name: 'antifraud_metadata' }),
699
- __metadata("design:type", Object)
700
- ], Payment.prototype, "antifraudMetadata", void 0);
701
- __decorate([
702
- Expose({ name: 'reference_key' }),
703
- __metadata("design:type", String)
704
- ], Payment.prototype, "referenceKey", void 0);
705
- __decorate([
706
- Expose({ name: 'local_transaction_id' }),
707
- __metadata("design:type", String)
708
- ], Payment.prototype, "localTransactionId", void 0);
709
- __decorate([
710
- Expose({ name: 'local_time' }),
711
- __metadata("design:type", String)
712
- ], Payment.prototype, "localTime", void 0);
713
- __decorate([
714
- Expose({ name: 'fraud_covered' }),
715
- __metadata("design:type", Boolean)
716
- ], Payment.prototype, "fraudCovered", void 0);
717
- __decorate([
718
- Expose({ name: 'fraud_reimbursed' }),
719
- __metadata("design:type", String)
720
- ], Payment.prototype, "fraudReimbursed", void 0);
721
- __decorate([
722
- Expose({ name: 'order_id' }),
723
- __metadata("design:type", String)
724
- ], Payment.prototype, "orderId", void 0);
725
- __decorate([
726
- Expose({ name: 'risk_level' }),
727
- __metadata("design:type", String)
728
- ], Payment.prototype, "riskLevel", void 0);
729
- __decorate([
730
- Expose({ name: 'receipt_url' }),
731
- __metadata("design:type", String)
732
- ], Payment.prototype, "receiptUrl", void 0);
733
- __decorate([
734
- Expose({ name: 'private_label' }),
735
- __metadata("design:type", String)
736
- ], Payment.prototype, "privateLabel", void 0);
737
- __decorate([
738
- Expose({ name: 'pix_qr_code' }),
739
- __metadata("design:type", String)
740
- ], Payment.prototype, "pixQrCode", void 0);
741
- __decorate([
742
- Expose({ name: 'pix_expiration_date' }),
743
- __metadata("design:type", String)
744
- ], Payment.prototype, "pixExpirationDate", void 0);
669
+ Type(() => PaymentTransaction),
670
+ __metadata("design:type", PaymentTransaction)
671
+ ], Payment.prototype, "transaction", void 0);
745
672
 
746
673
  class SubscriptionPayment extends BaseModel {
747
674
  static get identifiersFields() {
@@ -2243,8 +2170,8 @@ var OrderStatus;
2243
2170
  class Order extends Checkout {
2244
2171
  }
2245
2172
  __decorate([
2246
- Type(() => Payment),
2247
- __metadata("design:type", Payment)
2173
+ Type(() => PaymentTransaction),
2174
+ __metadata("design:type", PaymentTransaction)
2248
2175
  ], Order.prototype, "payment", void 0);
2249
2176
 
2250
2177
  class OrderBlocked extends BaseModel {
@@ -2275,6 +2202,370 @@ __decorate([
2275
2202
  __metadata("design:type", Coupon)
2276
2203
  ], CheckoutSubscription.prototype, "coupon", void 0);
2277
2204
 
2205
+ class BusinessError extends CustomError {
2206
+ constructor(message, additionalData, type = '') {
2207
+ super(message);
2208
+ this.additionalData = additionalData;
2209
+ this.type = type;
2210
+ }
2211
+ }
2212
+
2213
+ class DuplicatedResultsError extends CustomError {
2214
+ constructor(message) {
2215
+ super(message);
2216
+ }
2217
+ }
2218
+
2219
+ class FraudValidationError extends CustomError {
2220
+ constructor(message, additionalData) {
2221
+ super(message);
2222
+ this.additionalData = additionalData;
2223
+ this.type = 'antifraud';
2224
+ }
2225
+ }
2226
+
2227
+ class InvalidArgumentError extends CustomError {
2228
+ constructor(message) {
2229
+ super(message);
2230
+ }
2231
+ }
2232
+
2233
+ class NotFoundError extends CustomError {
2234
+ constructor(message) {
2235
+ super(message);
2236
+ }
2237
+ }
2238
+
2239
+ class PaymentError extends CustomError {
2240
+ constructor(message, additionalData) {
2241
+ super(message);
2242
+ this.additionalData = additionalData;
2243
+ this.type = 'payment';
2244
+ }
2245
+ }
2246
+
2247
+ class RequiredArgumentError extends CustomError {
2248
+ constructor(args) {
2249
+ super(`Required arguments: ${args.join(', ')}`);
2250
+ this.args = args;
2251
+ this.arguments = args;
2252
+ }
2253
+ }
2254
+
2255
+ class StockLimitError extends BusinessError {
2256
+ constructor(message, additionalData) {
2257
+ super(message, additionalData);
2258
+ this.type = 'stock-limit';
2259
+ }
2260
+ }
2261
+
2262
+ class StockOutError extends BusinessError {
2263
+ constructor(message, additionalData) {
2264
+ super(message, additionalData);
2265
+ this.type = 'stock-out';
2266
+ }
2267
+ }
2268
+
2269
+ class AntifraudBankSlipService {
2270
+ constructor(orderBlockedRepository) {
2271
+ this.orderBlockedRepository = orderBlockedRepository;
2272
+ this.MAX_ORDER_VALUE = 5000;
2273
+ }
2274
+ async validate(checkout) {
2275
+ var _a, _b;
2276
+ if (checkout.totalPrice && checkout.totalPrice > this.MAX_ORDER_VALUE && !((_a = checkout.user) === null || _a === void 0 ? void 0 : _a.isSubscriber)) {
2277
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Boleto not authorized', 'Boleto', 'day');
2278
+ throw new FraudValidationError('Boleto não autorizado para cliente não assinante', {
2279
+ checkoutId: checkout.id,
2280
+ userEmail: checkout.user.email,
2281
+ info: {
2282
+ isSubscriber: (_b = checkout.user) === null || _b === void 0 ? void 0 : _b.isSubscriber,
2283
+ subtotal: checkout.subTotalPrice,
2284
+ total: checkout.totalPrice,
2285
+ },
2286
+ });
2287
+ }
2288
+ return true;
2289
+ }
2290
+ }
2291
+
2292
+ class AntifraudCardService {
2293
+ constructor(orderRepository, orderBlockedRepository) {
2294
+ this.orderRepository = orderRepository;
2295
+ this.orderBlockedRepository = orderBlockedRepository;
2296
+ this.LIMIT_ORDERS_DAY = 2;
2297
+ this.LIMIT_ORDERS_WEEK = 7;
2298
+ this.LIMIT_BLOCKED_ORDERS_DAY = 5;
2299
+ }
2300
+ async validate(checkout, card) {
2301
+ var _a, _b;
2302
+ if (!(await this.verifyBlockedOrderAttempts(checkout, card)))
2303
+ throw new FraudValidationError('Cliente com mais de 5 compras negadas/bloqueadas no dia', {
2304
+ checkoutId: checkout.id,
2305
+ userEmail: checkout.user.email,
2306
+ info: {
2307
+ isSubscriber: (_a = checkout.user) === null || _a === void 0 ? void 0 : _a.isSubscriber,
2308
+ subtotal: checkout.subTotalPrice,
2309
+ total: checkout.totalPrice,
2310
+ },
2311
+ });
2312
+ if (!(await this.verifyDayAndWeekOrders(checkout, card)))
2313
+ throw new FraudValidationError('Cliente tentando comprar mais de 2 vezes no dia ou 7 vezes na semana', {
2314
+ checkoutId: checkout.id,
2315
+ userEmail: checkout.user.email,
2316
+ info: {
2317
+ isSubscriber: (_b = checkout.user) === null || _b === void 0 ? void 0 : _b.isSubscriber,
2318
+ subtotal: checkout.subTotalPrice,
2319
+ total: checkout.totalPrice,
2320
+ },
2321
+ });
2322
+ return true;
2323
+ }
2324
+ async verifyBlockedOrderAttempts(checkout, card) {
2325
+ var _a, _b, _c, _d;
2326
+ const day = `${format(new Date(), 'yyyy-MM-dd')}T00:00:00`;
2327
+ const endOfDay = `${format(new Date(), 'yyyy-MM-dd')}T23:59:59`;
2328
+ const ordersBlockedWithCpf = await this.orderBlockedRepository
2329
+ .find({
2330
+ filters: {
2331
+ customer: { cpf: { operator: Where.EQUALS, value: (_a = checkout.user) === null || _a === void 0 ? void 0 : _a.cpf } },
2332
+ ['date']: [
2333
+ { operator: Where.GTE, value: new Date(day) },
2334
+ { operator: Where.LTE, value: new Date(endOfDay) },
2335
+ ],
2336
+ },
2337
+ })
2338
+ .then((data) => data.data);
2339
+ const ordersBlockedWithEmail = await this.orderBlockedRepository
2340
+ .find({
2341
+ filters: {
2342
+ customer: { email: { operator: Where.EQUALS, value: (_b = checkout.user) === null || _b === void 0 ? void 0 : _b.email } },
2343
+ ['date']: [
2344
+ { operator: Where.GTE, value: new Date(day) },
2345
+ { operator: Where.LTE, value: new Date(endOfDay) },
2346
+ ],
2347
+ },
2348
+ })
2349
+ .then((data) => data.data);
2350
+ const ordersBlockedWithCep = await this.orderBlockedRepository
2351
+ .find({
2352
+ filters: {
2353
+ customer: { shippingAddress: { zip: { operator: Where.EQUALS, value: (_c = checkout.shippingAddress) === null || _c === void 0 ? void 0 : _c.zip } } },
2354
+ ['date']: [
2355
+ { operator: Where.GTE, value: new Date(day) },
2356
+ { operator: Where.LTE, value: new Date(endOfDay) },
2357
+ ],
2358
+ },
2359
+ })
2360
+ .then((data) => data.data);
2361
+ const ordersBlockedWithPhone = await this.orderBlockedRepository
2362
+ .find({
2363
+ filters: {
2364
+ customer: { phoneNumber: { operator: Where.EQUALS, value: (_d = checkout.user) === null || _d === void 0 ? void 0 : _d.phone } },
2365
+ ['date']: [
2366
+ { operator: Where.GTE, value: new Date(day) },
2367
+ { operator: Where.LTE, value: new Date(endOfDay) },
2368
+ ],
2369
+ },
2370
+ })
2371
+ .then((data) => data.data);
2372
+ const blockedUniqueEmails = ordersBlockedWithEmail.filter((e) => {
2373
+ var _a;
2374
+ return e.customer.cpf !== ((_a = checkout.user) === null || _a === void 0 ? void 0 : _a.cpf);
2375
+ });
2376
+ const blockedUniqueCeps = ordersBlockedWithCep.filter((e) => {
2377
+ var _a, _b;
2378
+ return e.customer.cpf !== ((_a = checkout.user) === null || _a === void 0 ? void 0 : _a.cpf) && e.customer.email !== ((_b = checkout.user) === null || _b === void 0 ? void 0 : _b.email);
2379
+ });
2380
+ const blockedUniquePhone = ordersBlockedWithPhone.filter((e) => {
2381
+ var _a, _b, _c, _d, _e, _f;
2382
+ return (e.customer.cpf !== ((_a = checkout.user) === null || _a === void 0 ? void 0 : _a.cpf) &&
2383
+ e.customer.email !== ((_b = checkout.user) === null || _b === void 0 ? void 0 : _b.email) &&
2384
+ ((_d = (_c = e.customer.shippingAddress) === null || _c === void 0 ? void 0 : _c.zip) === null || _d === void 0 ? void 0 : _d.toString()) !== ((_f = (_e = checkout.shippingAddress) === null || _e === void 0 ? void 0 : _e.zip) === null || _f === void 0 ? void 0 : _f.toString()));
2385
+ });
2386
+ const blockedAttempts = ordersBlockedWithCpf
2387
+ .concat(blockedUniqueEmails)
2388
+ .concat(blockedUniqueCeps)
2389
+ .concat(blockedUniquePhone);
2390
+ if (blockedAttempts.length >= this.LIMIT_BLOCKED_ORDERS_DAY) {
2391
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'More than 5 attempts have failed', 'Failed attempts', 'day', card || null);
2392
+ return false;
2393
+ }
2394
+ return true;
2395
+ }
2396
+ async verifyDayAndWeekOrders(checkout, card) {
2397
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2398
+ const ordersPerDay = await this.validateOrdersByRange((_a = checkout.user) === null || _a === void 0 ? void 0 : _a.cpf, (_b = checkout.user) === null || _b === void 0 ? void 0 : _b.email, (_c = checkout.user) === null || _c === void 0 ? void 0 : _c.phone, (_d = checkout.shippingAddress) === null || _d === void 0 ? void 0 : _d.zip, card, this.getDateRange('day'));
2399
+ for (const key in ordersPerDay) {
2400
+ if (ordersPerDay[key] > this.LIMIT_ORDERS_DAY) {
2401
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Order limit', key, 'day');
2402
+ return false;
2403
+ }
2404
+ }
2405
+ const ordersPerWeek = await this.validateOrdersByRange((_e = checkout.user) === null || _e === void 0 ? void 0 : _e.cpf, (_f = checkout.user) === null || _f === void 0 ? void 0 : _f.email, (_g = checkout.user) === null || _g === void 0 ? void 0 : _g.phone, (_h = checkout.shippingAddress) === null || _h === void 0 ? void 0 : _h.zip, card, this.getDateRange('week'));
2406
+ for (const key in ordersPerWeek) {
2407
+ if (ordersPerDay[key] > this.LIMIT_ORDERS_WEEK) {
2408
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Order limit', key, 'week');
2409
+ return false;
2410
+ }
2411
+ }
2412
+ return true;
2413
+ }
2414
+ async validateOrdersByRange(cpf, email, phone, zip, card, range) {
2415
+ const ordersCpf = await this.countOrdersByField('user', 'cpf', cpf, range);
2416
+ const ordersByEmail = await this.countOrdersByField('user', 'email', email, range);
2417
+ const ordersByPhone = await this.countOrdersByField('user', 'phone', phone, range);
2418
+ const ordersByZip = await this.countOrdersByField('shippingAddress', 'zip', zip, range);
2419
+ return {
2420
+ cpf: ordersCpf,
2421
+ email: ordersByEmail,
2422
+ phone: ordersByPhone,
2423
+ zip: ordersByZip,
2424
+ };
2425
+ }
2426
+ async countOrdersByField(property, field, value, range) {
2427
+ const filters = {
2428
+ [property]: {
2429
+ [field]: value,
2430
+ },
2431
+ ['createdAt']: [
2432
+ { operator: Where.GTE, value: range.firstDate },
2433
+ { operator: Where.LTE, value: range.lastDate },
2434
+ ],
2435
+ };
2436
+ const docs = await (await this.orderRepository.find({ filters })).count;
2437
+ return docs;
2438
+ }
2439
+ getDateRange(range = 'day') {
2440
+ switch (range) {
2441
+ case 'day':
2442
+ return {
2443
+ firstDate: startOfDay(new Date()).getTime(),
2444
+ lastDate: endOfDay(new Date()).getTime(),
2445
+ };
2446
+ case 'week':
2447
+ return {
2448
+ firstDate: startOfDay(subDays(new Date(), 7)).getTime(),
2449
+ lastDate: endOfDay(new Date()).getTime(),
2450
+ };
2451
+ default:
2452
+ return {
2453
+ firstDate: startOfDay(new Date()).getTime(),
2454
+ lastDate: endOfDay(new Date()).getTime(),
2455
+ };
2456
+ }
2457
+ }
2458
+ }
2459
+
2460
+ class AntifraudGlampointsService {
2461
+ constructor() { }
2462
+ async validate(checkout) {
2463
+ return true;
2464
+ }
2465
+ }
2466
+
2467
+ class AntifraudPixService {
2468
+ constructor() { }
2469
+ async validate(checkout) {
2470
+ return true;
2471
+ }
2472
+ }
2473
+
2474
+ class GlampointsPaymentService {
2475
+ constructor(glamCredentials, paymentRepository) {
2476
+ this.glamCredentials = glamCredentials;
2477
+ this.paymentRepository = paymentRepository;
2478
+ }
2479
+ async pay(checkout) {
2480
+ const payment = await this.paymentRepository.create(Payment.toInstance({
2481
+ createdAt: new Date(),
2482
+ updatedAt: new Date(),
2483
+ userId: checkout.user.id,
2484
+ checkoutId: checkout.id,
2485
+ totalPrice: checkout.totalPrice,
2486
+ paymentProvider: 'glampoints',
2487
+ transaction: {
2488
+ amount: 0,
2489
+ acquirer_response_code: '0000',
2490
+ acquirer_name: 'glampoints',
2491
+ authorized_amount: 0,
2492
+ capture_method: 'ecommerce',
2493
+ installments: 1,
2494
+ cost: 0,
2495
+ paid_amount: 0,
2496
+ paid_at: new Date().toISOString(),
2497
+ payment_method: 'glampoints',
2498
+ referer: 'api_key',
2499
+ refunded_amount: 0,
2500
+ status: 'paid',
2501
+ status_reason: 'acquirer',
2502
+ date_created: new Date().toISOString(),
2503
+ },
2504
+ }));
2505
+ return payment;
2506
+ }
2507
+ async rewardByOrder(order, user) {
2508
+ var _a;
2509
+ try {
2510
+ const points = order.lineItems.filter((item) => !item.isGift).reduce((acc, li) => acc + li.quantity, 0);
2511
+ const hasGlambeauty = (_a = order.lineItems) === null || _a === void 0 ? void 0 : _a.some((doc) => doc.brand && doc.brand.toUpperCase() === 'GLAM BEAUTY');
2512
+ const result = await axios({
2513
+ method: 'POST',
2514
+ url: `${this.glamCredentials.baseUrl}/integration/win/reward`,
2515
+ headers: {
2516
+ 'Content-Type': 'application/json',
2517
+ Authorization: `Bearer ${this.glamCredentials.integrationToken}`,
2518
+ Origin: 'https://cloudfunctions.b4a.com.br',
2519
+ },
2520
+ timeout: 60000,
2521
+ data: JSON.stringify({
2522
+ personId: user.id,
2523
+ rewardType: 50,
2524
+ referenceId: 0,
2525
+ referenceName: `Compra - ${points} produto(s)`,
2526
+ points,
2527
+ productId: '',
2528
+ token: this.glamCredentials.integrationToken,
2529
+ orderId: order.id,
2530
+ orderNumber: order.orderNumber,
2531
+ glambeauty: hasGlambeauty,
2532
+ }),
2533
+ });
2534
+ console.info('[rewards - rewardByOrder] reward success:', JSON.stringify(result));
2535
+ return result.data;
2536
+ }
2537
+ catch (err) {
2538
+ console.log(err);
2539
+ console.error('[rewards - rewardByOrder] reward request error', JSON.stringify(err));
2540
+ }
2541
+ }
2542
+ async negativateRewardByOrderId(order) {
2543
+ try {
2544
+ const result = await axios({
2545
+ method: 'POST',
2546
+ url: `${this.glamCredentials.baseUrl}/integration/negativate/reward`,
2547
+ headers: {
2548
+ 'Content-Type': 'application/json',
2549
+ Authorization: `Bearer ${this.glamCredentials.integrationToken}`,
2550
+ Origin: 'https://cloudfunctions.b4a.com.br',
2551
+ },
2552
+ timeout: 60000,
2553
+ data: JSON.stringify({
2554
+ rewardType: 51,
2555
+ referenceName: `Pedido #${order.id} cancelado`,
2556
+ token: '$2a$12$2DAPE64UUWAo4TT/1eQ9TOJO40b5z2jdomOJG3X7LeexwOHYtPydW',
2557
+ orderId: order.id,
2558
+ orderNumber: order.orderNumber,
2559
+ }),
2560
+ });
2561
+ return result;
2562
+ }
2563
+ catch (error) {
2564
+ return error;
2565
+ }
2566
+ }
2567
+ }
2568
+
2278
2569
  class RoundProductPricesHelper {
2279
2570
  static roundProductPrices(product) {
2280
2571
  product.price.price = Number(product.price.price.toFixed(2));
@@ -2295,6 +2586,12 @@ class LogDocument extends BaseModel {
2295
2586
  }
2296
2587
  }
2297
2588
 
2589
+ class Sequence extends BaseModel {
2590
+ static get identifiersFields() {
2591
+ return ['id'];
2592
+ }
2593
+ }
2594
+
2298
2595
  var FilterType;
2299
2596
  (function (FilterType) {
2300
2597
  FilterType["ACCESSORY_IMPORTANCE"] = "accessoryImportance";
@@ -2433,29 +2730,82 @@ class ShopSettings extends BaseModel {
2433
2730
  }
2434
2731
  }
2435
2732
 
2436
- class InvalidArgumentError extends CustomError {
2437
- constructor(message) {
2438
- super(message);
2733
+ class AdyenCardAxiosAdapter {
2734
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
2735
+ this.credentials = credentials;
2736
+ this.paymentRepository = paymentRepository;
2737
+ this.orderBlockedRepository = orderBlockedRepository;
2439
2738
  }
2440
- }
2441
-
2442
- class RequiredArgumentError extends CustomError {
2443
- constructor(args) {
2444
- super(`Required arguments: ${args.join(', ')}`);
2445
- this.args = args;
2446
- this.arguments = args;
2739
+ createCardHash(bu) {
2740
+ throw new Error('Method not implemented.');
2447
2741
  }
2448
- }
2449
-
2450
- class NotFoundError extends CustomError {
2451
- constructor(message) {
2452
- super(message);
2742
+ async pay(checkout, card) {
2743
+ try {
2744
+ const result = await axios({
2745
+ method: 'POST',
2746
+ url: this.credentials.URL_TRANSACTION,
2747
+ headers: {
2748
+ 'x-api-key': this.credentials.API_KEY,
2749
+ 'content-type': 'application/json',
2750
+ },
2751
+ data: this.createCardPayment(checkout, card),
2752
+ });
2753
+ if (result.data.resultCode !== 'Authorised') {
2754
+ this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
2755
+ return Promise.reject(new PaymentError(`Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito`, {
2756
+ checkoutId: checkout.id,
2757
+ userEmail: checkout.user.email,
2758
+ info: result.data,
2759
+ }));
2760
+ }
2761
+ const payment = await this.paymentRepository.create(Payment.toInstance({
2762
+ createdAt: new Date(),
2763
+ updatedAt: new Date(),
2764
+ userId: checkout.user.id,
2765
+ checkoutId: checkout.id,
2766
+ totalPrice: checkout.totalPrice,
2767
+ paymentProvider: 'adyen',
2768
+ transaction: Object.assign(Object.assign({}, result.data), { status: 'paid' }),
2769
+ }));
2770
+ return payment;
2771
+ }
2772
+ catch (error) {
2773
+ throw new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', {
2774
+ checkoutId: checkout.id,
2775
+ userEmail: checkout.user.email,
2776
+ info: error.message,
2777
+ });
2778
+ }
2453
2779
  }
2454
- }
2455
-
2456
- class DuplicatedResultsError extends CustomError {
2457
- constructor(message) {
2458
- super(message);
2780
+ createCardPayment(checkout, card) {
2781
+ return {
2782
+ amount: {
2783
+ currency: 'BRL',
2784
+ value: ((checkout === null || checkout === void 0 ? void 0 : checkout.totalPrice) || 0) * 100,
2785
+ },
2786
+ paymentMethod: {
2787
+ type: 'scheme',
2788
+ storedPaymentMethodId: card.cardId,
2789
+ },
2790
+ reference: checkout.id,
2791
+ shopperInteraction: 'Ecommerce',
2792
+ merchantAccount: this.credentials.MERCHANT_ACCOUNT,
2793
+ shopperReference: checkout.user.id,
2794
+ recurringProcessingModel: 'CardOnFile',
2795
+ returnUrl: this.credentials.URL_POSTBACK,
2796
+ installments: {
2797
+ value: card.installments,
2798
+ },
2799
+ };
2800
+ }
2801
+ addCard() {
2802
+ throw new Error('Method not implemented.');
2803
+ }
2804
+ getCardByToken(token) {
2805
+ throw new Error('Method not implemented.');
2806
+ }
2807
+ createTransaction(info) {
2808
+ throw new Error('Method not implemented.');
2459
2809
  }
2460
2810
  }
2461
2811
 
@@ -3308,9 +3658,6 @@ class ProductFirestoreRepository extends withCrudFirestore(withHelpers(withFires
3308
3658
  async fetchPaginatedReviews() {
3309
3659
  return Promise.resolve([]);
3310
3660
  }
3311
- productVariantFullReport() {
3312
- return;
3313
- }
3314
3661
  }
3315
3662
  __decorate([
3316
3663
  Log(),
@@ -3360,6 +3707,17 @@ class LogFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore
3360
3707
  }
3361
3708
  }
3362
3709
 
3710
+ class SequenceFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3711
+ constructor({ firestore, interceptors }) {
3712
+ super({
3713
+ firestore,
3714
+ collectionName: 'sequences',
3715
+ model: Sequence,
3716
+ interceptors,
3717
+ });
3718
+ }
3719
+ }
3720
+
3363
3721
  class HomeFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3364
3722
  constructor({ firestore, interceptors }) {
3365
3723
  super({
@@ -3600,11 +3958,7 @@ class OrderBlockedFirestoreRepository extends withCrudFirestore(withHelpers(with
3600
3958
  limiteRange,
3601
3959
  type,
3602
3960
  card,
3603
- checkout: {
3604
- id: checkout.id,
3605
- shop: checkout.shop,
3606
- total: checkout.totalPrice,
3607
- },
3961
+ checkout,
3608
3962
  date: new Date(),
3609
3963
  }));
3610
3964
  }
@@ -5895,56 +6249,6 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
5895
6249
  });
5896
6250
  return data && data[0] && this.bindReviewToModel(data[0]);
5897
6251
  }
5898
- async productVariantFullReport() {
5899
- const fields = [
5900
- 'id',
5901
- 'name',
5902
- 'description',
5903
- 'slug',
5904
- 'sku',
5905
- 'ean',
5906
- 'cest',
5907
- 'ncm',
5908
- 'has_variants',
5909
- 'is_variant',
5910
- 'grade',
5911
- 'type',
5912
- 'is_kit',
5913
- 'tags',
5914
- 'published',
5915
- 'stock',
5916
- 'brand',
5917
- 'brand_description',
5918
- 'images',
5919
- 'miniatures',
5920
- 'video',
5921
- 'weight',
5922
- 'cost_price',
5923
- 'full_price',
5924
- 'price',
5925
- 'subscriber_discount_percentage',
5926
- 'subscriber_price',
5927
- 'how_to_use',
5928
- 'who_must_use',
5929
- 'differentials',
5930
- 'ingredients',
5931
- 'purpose',
5932
- 'filters',
5933
- 'category_id',
5934
- 'outlet',
5935
- 'label',
5936
- 'group',
5937
- 'validity',
5938
- 'gender',
5939
- 'shopping_count',
5940
- 'rating',
5941
- 'reviews_total',
5942
- 'created_at',
5943
- 'updated_at',
5944
- ];
5945
- const { product_variant_report_query: data } = await this.query('product_variant_report_query', fields);
5946
- return data;
5947
- }
5948
6252
  }
5949
6253
  __decorate([
5950
6254
  Log(),
@@ -6501,6 +6805,315 @@ __decorate([
6501
6805
  __metadata("design:returntype", Promise)
6502
6806
  ], WishlistHasuraGraphQLRepository.prototype, "findBfluOrGlamgirlWishlists", null);
6503
6807
 
6808
+ class PagarmeBankSlipAxiosAdapter {
6809
+ constructor(credentials, paymentRepository) {
6810
+ this.credentials = credentials;
6811
+ this.paymentRepository = paymentRepository;
6812
+ }
6813
+ async pay(checkout) {
6814
+ try {
6815
+ const payload = this.createBoletoPayment(checkout);
6816
+ const result = await axios({
6817
+ method: 'POST',
6818
+ url: `${this.credentials.URL}/transactions`,
6819
+ data: this.createBoletoPayment(checkout),
6820
+ });
6821
+ console.log('[PAGARME BOLETO DATA TO SEND]', payload);
6822
+ if (result.data.status !== PagarmePaymentStatus['Em processamento']) {
6823
+ return Promise.reject(new PaymentError(`Houve uma falha ao gerar o boleto. Tente novamente`, {
6824
+ checkoutId: checkout.id,
6825
+ userEmail: checkout.user.email,
6826
+ info: result.data,
6827
+ }));
6828
+ }
6829
+ const payment = await this.paymentRepository.create({
6830
+ createdAt: new Date(),
6831
+ updatedAt: new Date(),
6832
+ userId: checkout.user.id,
6833
+ checkoutId: checkout.id,
6834
+ totalPrice: checkout.totalPrice,
6835
+ paymentProvider: 'pagarMe',
6836
+ transaction: result.data,
6837
+ });
6838
+ return payment;
6839
+ }
6840
+ catch (error) {
6841
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
6842
+ checkoutId: checkout.id,
6843
+ userEmail: checkout.user.email,
6844
+ info: error.response.data,
6845
+ });
6846
+ }
6847
+ }
6848
+ async getBoletoTransaction(paymentId) {
6849
+ try {
6850
+ const { data } = await axios({
6851
+ method: 'GET',
6852
+ url: `${this.credentials.URL}/transactions/${paymentId}`,
6853
+ data: {
6854
+ api_key: this.credentials.API_KEY,
6855
+ },
6856
+ });
6857
+ return data;
6858
+ }
6859
+ catch (error) {
6860
+ throw new BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
6861
+ paymentId,
6862
+ info: error.response.data,
6863
+ });
6864
+ }
6865
+ }
6866
+ createBoletoPayment(checkout) {
6867
+ return {
6868
+ api_key: this.credentials.API_KEY,
6869
+ amount: Math.floor(checkout.totalPrice * 100),
6870
+ boleto_rules: ['strict_expiration_date'],
6871
+ boleto_instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
6872
+ boleto_expiration_date: format(addDays(new Date(), 3), 'yyyy-MM-dd'),
6873
+ payment_method: 'boleto',
6874
+ postback_url: this.credentials.URL_POSTBACK,
6875
+ customer: {
6876
+ external_id: checkout.user.id,
6877
+ type: 'individual',
6878
+ country: 'br',
6879
+ name: checkout.user.displayName,
6880
+ documents: [
6881
+ {
6882
+ type: 'cpf',
6883
+ number: checkout.user.cpf,
6884
+ },
6885
+ ],
6886
+ },
6887
+ };
6888
+ }
6889
+ }
6890
+
6891
+ class PagarmeCardAxiosAdapter {
6892
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
6893
+ this.credentials = credentials;
6894
+ this.paymentRepository = paymentRepository;
6895
+ this.orderBlockedRepository = orderBlockedRepository;
6896
+ }
6897
+ async pay(checkout, card) {
6898
+ var _a;
6899
+ try {
6900
+ const payload = this.createCardPayment(checkout, card);
6901
+ const result = await axios({
6902
+ method: 'POST',
6903
+ url: `${this.credentials.URL}/transactions`,
6904
+ data: payload,
6905
+ });
6906
+ console.log('[PAGARME CARD DATA TO SEND]', payload);
6907
+ if (result.data.status !== PagarmePaymentStatus.Pago) {
6908
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
6909
+ return Promise.reject(new PaymentError(`Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito`, {
6910
+ checkoutId: checkout.id,
6911
+ userEmail: checkout.user.email,
6912
+ info: result.data,
6913
+ }));
6914
+ }
6915
+ const payment = await this.paymentRepository.create({
6916
+ createdAt: new Date(),
6917
+ updatedAt: new Date(),
6918
+ userId: checkout.user.id,
6919
+ checkoutId: checkout.id,
6920
+ totalPrice: checkout.totalPrice,
6921
+ paymentProvider: PaymentProviders.PAGARME,
6922
+ transaction: Object.assign(Object.assign({}, result.data), { paidAt: new Date() }),
6923
+ });
6924
+ return payment;
6925
+ }
6926
+ catch (error) {
6927
+ throw new PaymentError('Seu pagamento com cartão não foi autorizado. Para não perder seus produtos, pague com PIX ou outro cartão de crédito', {
6928
+ checkoutId: checkout.id,
6929
+ userEmail: checkout.user.email,
6930
+ info: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data,
6931
+ });
6932
+ }
6933
+ }
6934
+ async addCard(card) {
6935
+ try {
6936
+ const { data } = await axios({
6937
+ method: 'POST',
6938
+ url: `${this.credentials.URL}/cards`,
6939
+ data: {
6940
+ api_key: this.credentials.API_KEY,
6941
+ card_number: card.number,
6942
+ card_expiration_date: card.expirationDate.replace('/', ''),
6943
+ card_holder_name: card.name,
6944
+ card_cvv: card.cvv,
6945
+ },
6946
+ });
6947
+ return data;
6948
+ }
6949
+ catch (error) {
6950
+ throw new BusinessError('Houve uma falha adicionar o cartão', {
6951
+ info: error.response.data,
6952
+ });
6953
+ }
6954
+ }
6955
+ async createCardHash(bu) {
6956
+ const key = bu === BusinessUnitEnum.SHOP ? this.credentials.SHOP_API_KEY : this.credentials.SUBSCRIPTION_API_KEY;
6957
+ try {
6958
+ const { data } = await axios({
6959
+ method: 'GET',
6960
+ headers: {
6961
+ 'content-type': 'application/json',
6962
+ },
6963
+ url: `${this.credentials.URL}/transactions/card_hash_key`,
6964
+ data: JSON.stringify({
6965
+ api_key: key,
6966
+ }),
6967
+ });
6968
+ return data;
6969
+ }
6970
+ catch (error) {
6971
+ throw new BusinessError('Houve uma falha gerar o hash', {
6972
+ info: error.response.data,
6973
+ });
6974
+ }
6975
+ }
6976
+ async getCardByToken(id) {
6977
+ try {
6978
+ const { data } = await axios({
6979
+ method: 'POST',
6980
+ url: `${this.credentials.URL}/cards/${id}`,
6981
+ data: {
6982
+ api_key: this.credentials.API_KEY,
6983
+ },
6984
+ });
6985
+ return data;
6986
+ }
6987
+ catch (error) {
6988
+ throw new BusinessError('Houve uma falha buscar o cartão com id: ' + id, {
6989
+ info: error.response.data,
6990
+ });
6991
+ }
6992
+ }
6993
+ async createTransaction(info) {
6994
+ try {
6995
+ const { data } = await axios({
6996
+ method: 'POST',
6997
+ url: `${this.credentials.URL}/transactions`,
6998
+ data: Object.assign(Object.assign({}, info), { api_key: this.credentials.API_KEY }),
6999
+ });
7000
+ return data;
7001
+ }
7002
+ catch (error) {
7003
+ throw new BusinessError('Houve uma falha ao criar a transação', {
7004
+ info: error.response.data,
7005
+ });
7006
+ }
7007
+ }
7008
+ createCardPayment(checkout, card) {
7009
+ var _a, _b, _c, _d, _e, _f;
7010
+ return {
7011
+ api_key: this.credentials.API_KEY,
7012
+ amount: Math.floor(checkout.totalPrice * 100),
7013
+ card_id: card.cardId,
7014
+ payment_method: 'credit_card',
7015
+ installments: card.installments,
7016
+ soft_descriptor: checkout.shop === Shops.GLAMSHOP ? 'Glam' : "Men's Market",
7017
+ customer: {
7018
+ external_id: checkout.user.id,
7019
+ name: checkout.user.displayName,
7020
+ type: 'individual',
7021
+ country: 'br',
7022
+ email: checkout.user.email,
7023
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
7024
+ documents: [
7025
+ {
7026
+ type: 'cpf',
7027
+ number: checkout.user.cpf,
7028
+ },
7029
+ ],
7030
+ },
7031
+ billing: {
7032
+ name: checkout.user.displayName,
7033
+ address: {
7034
+ country: 'br',
7035
+ state: checkout.billingAddress ? checkout.billingAddress.state : (_a = checkout.shippingAddress) === null || _a === void 0 ? void 0 : _a.state,
7036
+ city: checkout.billingAddress ? checkout.billingAddress.city : (_b = checkout.shippingAddress) === null || _b === void 0 ? void 0 : _b.city,
7037
+ neighborhood: checkout.billingAddress ? checkout.billingAddress.district : (_c = checkout.shippingAddress) === null || _c === void 0 ? void 0 : _c.district,
7038
+ street: checkout.billingAddress ? checkout.billingAddress.street : (_d = checkout.shippingAddress) === null || _d === void 0 ? void 0 : _d.street,
7039
+ street_number: checkout.billingAddress ? checkout.billingAddress.number : (_e = checkout.shippingAddress) === null || _e === void 0 ? void 0 : _e.number,
7040
+ zipcode: checkout.billingAddress
7041
+ ? checkout.billingAddress.zip.replace('-', '')
7042
+ : (_f = checkout.shippingAddress) === null || _f === void 0 ? void 0 : _f.zip.replace('-', ''),
7043
+ },
7044
+ },
7045
+ items: checkout.lineItems.map((item) => {
7046
+ return {
7047
+ id: item.id,
7048
+ title: checkout.user.isSubscriber ? `${item.name} - ASSINANTE` : item.name,
7049
+ unit_price: Math.floor(item.pricePaid * 100),
7050
+ quantity: item.quantity,
7051
+ tangible: true,
7052
+ };
7053
+ }),
7054
+ };
7055
+ }
7056
+ }
7057
+
7058
+ class PagarmePixAxiosAdapter {
7059
+ constructor(credentials, paymentRepository) {
7060
+ this.credentials = credentials;
7061
+ this.paymentRepository = paymentRepository;
7062
+ }
7063
+ async pay(checkout) {
7064
+ var _a;
7065
+ try {
7066
+ const payload = this.createPixPayment(checkout);
7067
+ const result = await axios({
7068
+ method: 'POST',
7069
+ url: `${this.credentials.URL}/transactions`,
7070
+ data: payload,
7071
+ });
7072
+ console.log('[PAGARME PIX DATA TO SEND]', payload);
7073
+ const payment = await this.paymentRepository.create({
7074
+ createdAt: new Date(),
7075
+ updatedAt: new Date(),
7076
+ userId: checkout.user.id,
7077
+ checkoutId: checkout.id,
7078
+ totalPrice: checkout.totalPrice,
7079
+ paymentProvider: 'pagarMe',
7080
+ transaction: result.data,
7081
+ });
7082
+ return payment;
7083
+ }
7084
+ catch (error) {
7085
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
7086
+ checkoutId: checkout.id,
7087
+ userEmail: checkout.user.email,
7088
+ info: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data,
7089
+ });
7090
+ }
7091
+ }
7092
+ createPixPayment(checkout) {
7093
+ return {
7094
+ payment_method: 'pix',
7095
+ amount: Math.floor(checkout.totalPrice * 100),
7096
+ api_key: this.credentials.API_KEY,
7097
+ postback_url: this.credentials.URL_POSTBACK,
7098
+ pix_expiration_date: format(addDays(new Date(), 1), 'yyyy-MM-dd'),
7099
+ customer: {
7100
+ external_id: checkout.user.id,
7101
+ type: 'individual',
7102
+ country: 'br',
7103
+ name: checkout.user.displayName,
7104
+ email: checkout.user.email.trim(),
7105
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
7106
+ documents: [
7107
+ {
7108
+ type: 'cpf',
7109
+ number: checkout.user.cpf,
7110
+ },
7111
+ ],
7112
+ },
7113
+ };
7114
+ }
7115
+ }
7116
+
6504
7117
  class VertexAxiosAdapter {
6505
7118
  constructor(config) {
6506
7119
  this.config = config;
@@ -6654,4 +7267,4 @@ class ProductsVertexSearch {
6654
7267
  }
6655
7268
  }
6656
7269
 
6657
- export { AccessoryImportances, Address, Area, Authentication, AuthenticationFirebaseAuthService, AxiosAdapter, Base, BaseModel, BeardProblems, BeardSizes, BeautyProductImportances, BeautyProfile, BeautyQuestionsHelper, BillingStatus, BodyProblems, BodyShapes, BodyTattoos, Buy2Win, Buy2WinFirestoreRepository, Campaign, CampaignBanner, CampaignDashboard, CampaignDashboardFirestoreRepository, CampaignHashtag, CampaignHashtagFirestoreRepository, Category, CategoryCollectionChildren, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryFilter, CategoryFilterHasuraGraphQLRepository, CategoryFirestoreRepository, CategoryHasuraGraphQL, CategoryHasuraGraphQLRepository, CategoryProduct, CategoryProductHasuraGraphQLRepository, Checkout, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, ClassNameHelper, ConnectBaseDocumentSnapshot, ConnectCollectionService, ConnectDocumentService, ConnectFirestoreService, Coupon, CouponCategories, CouponCategory, CouponChannels, CouponFirestoreRepository, CouponOldCategories, CouponSubtypes, CouponTypes, Debug, DebugDecoratorHelper, DebugHelper, DebugNamespaces, DuplicatedResultsError, Edition, EditionStatus, Exclusivities, FaceSkinOilinesses, FaceSkinProblems, FaceSkinTones, FamilyIncomes, Filter, FilterHasuraGraphQLRepository, FilterOption, FilterOptionHasuraGraphQLRepository, FilterType, FirebaseFileUploaderService, FragranceImportances, GenderDestination, HairColors, HairProblems, HairStrands, HairTypes, Home, HomeFirestoreRepository, InvalidArgumentError, KitProduct, KitProductHasuraGraphQL, Lead, LeadFirestoreRepository, LegacyOrderFirestoreRepository, LineItem, Log, LogDocument, LogFirestoreRepository, Logger, NotFoundError, OfficePosition, Order, OrderBlocked, OrderBlockedFirestoreRepository, OrderFirestoreRepository, OrderStatus, Payment, PaymentFirestoreRepository, PaymentType, PersonTypes, Plans, Product, ProductFirestoreRepository, ProductHasuraGraphQL, ProductHasuraGraphQLRepository, ProductLabelEnum, ProductReviews, ProductReviewsHasuraGraphQLRepository, ProductSpents, ProductStockNotification, ProductStockNotificationHasuraGraphQLRepository, ProductVariantFirestoreRepository, ProductsIndex, ProductsVertexSearch, QuestionsFilters, RecoveryPassword, ReflectHelper, Register, RegisterFirebaseAuthService, RequiredArgumentError, RoundProductPricesHelper, ShippingMethod, ShopMenu, ShopMenuFirestoreRepository, ShopPageName, ShopSettings, ShopSettingsFirestoreRepository, Shops, SignInMethods, SignOut, Status, Subscription, SubscriptionEditionFirestoreRepository, SubscriptionFirestoreRepository, SubscriptionMaterialization, SubscriptionMaterializationFirestoreRepository, SubscriptionPayment, SubscriptionPaymentFirestoreRepository, SubscriptionPlan, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionSummary, SubscriptionSummaryFirestoreRepository, Trace, UnauthorizedError, UpdateOptionActions, UpdateUserImage, User, UserAddress, UserAddressFirestoreRepository, UserAlreadyRegisteredError, UserBeautyProfileFirestoreRepository, UserFirestoreRepository, UserPaymentMethod, UserPaymentMethodFirestoreRepository, UserType, Variant, VariantHasuraGraphQL, VariantHasuraGraphQLRepository, VertexAxiosAdapter, WeakPasswordError, Where, Wishlist, WishlistHasuraGraphQLRepository, WishlistLogType, is, isDebuggable, isUUID, parseDateTime, withCreateFirestore, withCreateHasuraGraphQL, withCrudFirestore, withCrudHasuraGraphQL, withDeleteFirestore, withDeleteHasuraGraphQL, withFindFirestore, withFindHasuraGraphQL, withFirestore, withGetFirestore, withGetHasuraGraphQL, withHasuraGraphQL, withHelpers, withSubCollection, withUpdateFirestore, withUpdateHasuraGraphQL };
7270
+ export { AccessoryImportances, Address, AdyenCardAxiosAdapter, AdyenPaymentMethodFactory, AntifraudBankSlipService, AntifraudCardService, AntifraudGlampointsService, AntifraudPixService, AntifraudProviderFactory, AntifraudProviders, Area, Authentication, AuthenticationFirebaseAuthService, AxiosAdapter, Base, BaseModel, BeardProblems, BeardSizes, BeautyProductImportances, BeautyProfile, BeautyQuestionsHelper, BillingStatus, BodyProblems, BodyShapes, BodyTattoos, BusinessError, BusinessUnitEnum, Buy2Win, Buy2WinFirestoreRepository, Campaign, CampaignBanner, CampaignDashboard, CampaignDashboardFirestoreRepository, CampaignHashtag, CampaignHashtagFirestoreRepository, Category, CategoryCollectionChildren, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryFilter, CategoryFilterHasuraGraphQLRepository, CategoryFirestoreRepository, CategoryHasuraGraphQL, CategoryHasuraGraphQLRepository, CategoryProduct, CategoryProductHasuraGraphQLRepository, Checkout, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, ClassNameHelper, ConnectBaseDocumentSnapshot, ConnectCollectionService, ConnectDocumentService, ConnectFirestoreService, Coupon, CouponCategories, CouponCategory, CouponChannels, CouponFirestoreRepository, CouponOldCategories, CouponSubtypes, CouponTypes, Debug, DebugDecoratorHelper, DebugHelper, DebugNamespaces, DuplicatedResultsError, Edition, EditionStatus, Exclusivities, FaceSkinOilinesses, FaceSkinProblems, FaceSkinTones, FamilyIncomes, Filter, FilterHasuraGraphQLRepository, FilterOption, FilterOptionHasuraGraphQLRepository, FilterType, FirebaseFileUploaderService, FragranceImportances, FraudValidationError, GenderDestination, GlampointsPaymentMethodFactory, GlampointsPaymentService, HairColors, HairProblems, HairStrands, HairTypes, Home, HomeFirestoreRepository, InvalidArgumentError, KitProduct, KitProductHasuraGraphQL, Lead, LeadFirestoreRepository, LegacyOrderFirestoreRepository, LineItem, Log, LogDocument, LogFirestoreRepository, Logger, NotFoundError, OfficePosition, Order, OrderBlocked, OrderBlockedFirestoreRepository, OrderBlockedType, OrderFirestoreRepository, OrderStatus, PagarmeBankSlipAxiosAdapter, PagarmeCardAxiosAdapter, PagarmePaymentMethodFactory, PagarmePaymentStatus, PagarmePixAxiosAdapter, Payment, PaymentError, PaymentFirestoreRepository, PaymentMethods, PaymentProviderFactory, PaymentProviders, PaymentTransaction, PaymentType, PersonTypes, Plans, Product, ProductFirestoreRepository, ProductHasuraGraphQL, ProductHasuraGraphQLRepository, ProductLabelEnum, ProductReviews, ProductReviewsHasuraGraphQLRepository, ProductSpents, ProductStockNotification, ProductStockNotificationHasuraGraphQLRepository, ProductVariantFirestoreRepository, ProductsIndex, ProductsVertexSearch, QuestionsFilters, RecoveryPassword, ReflectHelper, Register, RegisterFirebaseAuthService, RequiredArgumentError, RoundProductPricesHelper, Sequence, SequenceFirestoreRepository, ShippingMethod, ShopMenu, ShopMenuFirestoreRepository, ShopPageName, ShopSettings, ShopSettingsFirestoreRepository, Shops, SignInMethods, SignOut, Status, StockLimitError, StockOutError, Subscription, SubscriptionEditionFirestoreRepository, SubscriptionFirestoreRepository, SubscriptionMaterialization, SubscriptionMaterializationFirestoreRepository, SubscriptionPayment, SubscriptionPaymentFirestoreRepository, SubscriptionPlan, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionSummary, SubscriptionSummaryFirestoreRepository, Trace, UnauthorizedError, UpdateOptionActions, UpdateUserImage, User, UserAddress, UserAddressFirestoreRepository, UserAlreadyRegisteredError, UserBeautyProfileFirestoreRepository, UserFirestoreRepository, UserPaymentMethod, UserPaymentMethodFirestoreRepository, UserType, Variant, VariantHasuraGraphQL, VariantHasuraGraphQLRepository, VertexAxiosAdapter, WeakPasswordError, Where, Wishlist, WishlistHasuraGraphQLRepository, WishlistLogType, is, isDebuggable, isUUID, parseDateTime, withCreateFirestore, withCreateHasuraGraphQL, withCrudFirestore, withCrudHasuraGraphQL, withDeleteFirestore, withDeleteHasuraGraphQL, withFindFirestore, withFindHasuraGraphQL, withFirestore, withGetFirestore, withGetHasuraGraphQL, withHasuraGraphQL, withHelpers, withSubCollection, withUpdateFirestore, withUpdateHasuraGraphQL };