@infrab4a/connect 4.21.3 → 4.22.0-beta.1

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 +887 -243
  2. package/index.esm.js +866 -248
  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,18 +1,102 @@
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';
9
9
  import { CustomError } from 'ts-custom-error';
10
- import axios from 'axios';
10
+ import axios, { AxiosError } from 'axios';
11
11
  import { signInWithEmailAndPassword, signInWithPopup, GoogleAuthProvider, signInAnonymously, sendPasswordResetEmail, createUserWithEmailAndPassword, sendEmailVerification } from 'firebase/auth';
12
12
  import { deleteField, arrayUnion, arrayRemove, Timestamp, doc, getDoc, updateDoc, setDoc, deleteDoc, collection, limit, getDocs, query, where, orderBy, startAfter, addDoc } from 'firebase/firestore';
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,375 @@ __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.log('[rewards - rewardByOrder] reward success:', order.orderNumber, JSON.stringify(result.data));
2535
+ return result.data;
2536
+ }
2537
+ catch (error) {
2538
+ if (error instanceof AxiosError)
2539
+ console.error('[rewards - rewardByOrder] reward request error', error.response.status, JSON.stringify(error.response.data.message), order.orderNumber);
2540
+ else
2541
+ console.log(JSON.stringify(error));
2542
+ }
2543
+ }
2544
+ async negativateRewardByOrderId(order) {
2545
+ try {
2546
+ const result = await axios({
2547
+ method: 'POST',
2548
+ url: `${this.glamCredentials.baseUrl}/integration/negativate/reward`,
2549
+ headers: {
2550
+ 'Content-Type': 'application/json',
2551
+ Authorization: `Bearer ${this.glamCredentials.integrationToken}`,
2552
+ Origin: 'https://cloudfunctions.b4a.com.br',
2553
+ },
2554
+ timeout: 60000,
2555
+ data: JSON.stringify({
2556
+ rewardType: 51,
2557
+ referenceName: `Pedido #${order.id} cancelado`,
2558
+ token: '$2a$12$2DAPE64UUWAo4TT/1eQ9TOJO40b5z2jdomOJG3X7LeexwOHYtPydW',
2559
+ orderId: order.id,
2560
+ orderNumber: order.orderNumber,
2561
+ }),
2562
+ });
2563
+ return result;
2564
+ }
2565
+ catch (error) {
2566
+ if (error instanceof AxiosError)
2567
+ console.error('[negativateRewardByOrderId] request error', error.response.status, JSON.stringify(error.response.data.message), order.orderNumber);
2568
+ else
2569
+ console.log(JSON.stringify(error));
2570
+ }
2571
+ }
2572
+ }
2573
+
2278
2574
  class RoundProductPricesHelper {
2279
2575
  static roundProductPrices(product) {
2280
2576
  product.price.price = Number(product.price.price.toFixed(2));
@@ -2295,6 +2591,12 @@ class LogDocument extends BaseModel {
2295
2591
  }
2296
2592
  }
2297
2593
 
2594
+ class Sequence extends BaseModel {
2595
+ static get identifiersFields() {
2596
+ return ['id'];
2597
+ }
2598
+ }
2599
+
2298
2600
  var FilterType;
2299
2601
  (function (FilterType) {
2300
2602
  FilterType["ACCESSORY_IMPORTANCE"] = "accessoryImportance";
@@ -2433,29 +2735,82 @@ class ShopSettings extends BaseModel {
2433
2735
  }
2434
2736
  }
2435
2737
 
2436
- class InvalidArgumentError extends CustomError {
2437
- constructor(message) {
2438
- super(message);
2738
+ class AdyenCardAxiosAdapter {
2739
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
2740
+ this.credentials = credentials;
2741
+ this.paymentRepository = paymentRepository;
2742
+ this.orderBlockedRepository = orderBlockedRepository;
2439
2743
  }
2440
- }
2441
-
2442
- class RequiredArgumentError extends CustomError {
2443
- constructor(args) {
2444
- super(`Required arguments: ${args.join(', ')}`);
2445
- this.args = args;
2446
- this.arguments = args;
2744
+ createCardHash(bu) {
2745
+ throw new Error('Method not implemented.');
2447
2746
  }
2448
- }
2449
-
2450
- class NotFoundError extends CustomError {
2451
- constructor(message) {
2452
- super(message);
2747
+ async pay(checkout, card) {
2748
+ try {
2749
+ const result = await axios({
2750
+ method: 'POST',
2751
+ url: this.credentials.URL_TRANSACTION,
2752
+ headers: {
2753
+ 'x-api-key': this.credentials.API_KEY,
2754
+ 'content-type': 'application/json',
2755
+ },
2756
+ data: this.createCardPayment(checkout, card),
2757
+ });
2758
+ if (result.data.resultCode !== 'Authorised') {
2759
+ this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
2760
+ 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`, {
2761
+ checkoutId: checkout.id,
2762
+ userEmail: checkout.user.email,
2763
+ info: result.data,
2764
+ }));
2765
+ }
2766
+ const payment = await this.paymentRepository.create(Payment.toInstance({
2767
+ createdAt: new Date(),
2768
+ updatedAt: new Date(),
2769
+ userId: checkout.user.id,
2770
+ checkoutId: checkout.id,
2771
+ totalPrice: checkout.totalPrice,
2772
+ paymentProvider: 'adyen',
2773
+ transaction: Object.assign(Object.assign({}, result.data), { status: 'paid' }),
2774
+ }));
2775
+ return payment;
2776
+ }
2777
+ catch (error) {
2778
+ 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', {
2779
+ checkoutId: checkout.id,
2780
+ userEmail: checkout.user.email,
2781
+ info: error.message,
2782
+ });
2783
+ }
2453
2784
  }
2454
- }
2455
-
2456
- class DuplicatedResultsError extends CustomError {
2457
- constructor(message) {
2458
- super(message);
2785
+ createCardPayment(checkout, card) {
2786
+ return {
2787
+ amount: {
2788
+ currency: 'BRL',
2789
+ value: ((checkout === null || checkout === void 0 ? void 0 : checkout.totalPrice) || 0) * 100,
2790
+ },
2791
+ paymentMethod: {
2792
+ type: 'scheme',
2793
+ storedPaymentMethodId: card.cardId,
2794
+ },
2795
+ reference: checkout.id,
2796
+ shopperInteraction: 'Ecommerce',
2797
+ merchantAccount: this.credentials.MERCHANT_ACCOUNT,
2798
+ shopperReference: checkout.user.id,
2799
+ recurringProcessingModel: 'CardOnFile',
2800
+ returnUrl: this.credentials.URL_POSTBACK,
2801
+ installments: {
2802
+ value: card.installments,
2803
+ },
2804
+ };
2805
+ }
2806
+ addCard() {
2807
+ throw new Error('Method not implemented.');
2808
+ }
2809
+ getCardByToken(token) {
2810
+ throw new Error('Method not implemented.');
2811
+ }
2812
+ createTransaction(info) {
2813
+ throw new Error('Method not implemented.');
2459
2814
  }
2460
2815
  }
2461
2816
 
@@ -3308,9 +3663,6 @@ class ProductFirestoreRepository extends withCrudFirestore(withHelpers(withFires
3308
3663
  async fetchPaginatedReviews() {
3309
3664
  return Promise.resolve([]);
3310
3665
  }
3311
- productVariantFullReport() {
3312
- return;
3313
- }
3314
3666
  }
3315
3667
  __decorate([
3316
3668
  Log(),
@@ -3360,6 +3712,17 @@ class LogFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore
3360
3712
  }
3361
3713
  }
3362
3714
 
3715
+ class SequenceFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3716
+ constructor({ firestore, interceptors }) {
3717
+ super({
3718
+ firestore,
3719
+ collectionName: 'sequences',
3720
+ model: Sequence,
3721
+ interceptors,
3722
+ });
3723
+ }
3724
+ }
3725
+
3363
3726
  class HomeFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3364
3727
  constructor({ firestore, interceptors }) {
3365
3728
  super({
@@ -3600,11 +3963,7 @@ class OrderBlockedFirestoreRepository extends withCrudFirestore(withHelpers(with
3600
3963
  limiteRange,
3601
3964
  type,
3602
3965
  card,
3603
- checkout: {
3604
- id: checkout.id,
3605
- shop: checkout.shop,
3606
- total: checkout.totalPrice,
3607
- },
3966
+ checkout,
3608
3967
  date: new Date(),
3609
3968
  }));
3610
3969
  }
@@ -5895,56 +6254,6 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
5895
6254
  });
5896
6255
  return data && data[0] && this.bindReviewToModel(data[0]);
5897
6256
  }
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
6257
  }
5949
6258
  __decorate([
5950
6259
  Log(),
@@ -6501,6 +6810,315 @@ __decorate([
6501
6810
  __metadata("design:returntype", Promise)
6502
6811
  ], WishlistHasuraGraphQLRepository.prototype, "findBfluOrGlamgirlWishlists", null);
6503
6812
 
6813
+ class PagarmeBankSlipAxiosAdapter {
6814
+ constructor(credentials, paymentRepository) {
6815
+ this.credentials = credentials;
6816
+ this.paymentRepository = paymentRepository;
6817
+ }
6818
+ async pay(checkout) {
6819
+ try {
6820
+ const payload = this.createBoletoPayment(checkout);
6821
+ const result = await axios({
6822
+ method: 'POST',
6823
+ url: `${this.credentials.URL}/transactions`,
6824
+ data: this.createBoletoPayment(checkout),
6825
+ });
6826
+ console.log('[PAGARME BOLETO DATA TO SEND]', payload);
6827
+ if (result.data.status !== PagarmePaymentStatus['Em processamento']) {
6828
+ return Promise.reject(new PaymentError(`Houve uma falha ao gerar o boleto. Tente novamente`, {
6829
+ checkoutId: checkout.id,
6830
+ userEmail: checkout.user.email,
6831
+ info: result.data,
6832
+ }));
6833
+ }
6834
+ const payment = await this.paymentRepository.create({
6835
+ createdAt: new Date(),
6836
+ updatedAt: new Date(),
6837
+ userId: checkout.user.id,
6838
+ checkoutId: checkout.id,
6839
+ totalPrice: checkout.totalPrice,
6840
+ paymentProvider: 'pagarMe',
6841
+ transaction: result.data,
6842
+ });
6843
+ return payment;
6844
+ }
6845
+ catch (error) {
6846
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
6847
+ checkoutId: checkout.id,
6848
+ userEmail: checkout.user.email,
6849
+ info: error.response.data,
6850
+ });
6851
+ }
6852
+ }
6853
+ async getBoletoTransaction(paymentId) {
6854
+ try {
6855
+ const { data } = await axios({
6856
+ method: 'GET',
6857
+ url: `${this.credentials.URL}/transactions/${paymentId}`,
6858
+ data: {
6859
+ api_key: this.credentials.API_KEY,
6860
+ },
6861
+ });
6862
+ return data;
6863
+ }
6864
+ catch (error) {
6865
+ throw new BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
6866
+ paymentId,
6867
+ info: error.response.data,
6868
+ });
6869
+ }
6870
+ }
6871
+ createBoletoPayment(checkout) {
6872
+ return {
6873
+ api_key: this.credentials.API_KEY,
6874
+ amount: Math.floor(checkout.totalPrice * 100),
6875
+ boleto_rules: ['strict_expiration_date'],
6876
+ boleto_instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
6877
+ boleto_expiration_date: format(addDays(new Date(), 3), 'yyyy-MM-dd'),
6878
+ payment_method: 'boleto',
6879
+ postback_url: this.credentials.URL_POSTBACK,
6880
+ customer: {
6881
+ external_id: checkout.user.id,
6882
+ type: 'individual',
6883
+ country: 'br',
6884
+ name: checkout.user.displayName,
6885
+ documents: [
6886
+ {
6887
+ type: 'cpf',
6888
+ number: checkout.user.cpf,
6889
+ },
6890
+ ],
6891
+ },
6892
+ };
6893
+ }
6894
+ }
6895
+
6896
+ class PagarmeCardAxiosAdapter {
6897
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
6898
+ this.credentials = credentials;
6899
+ this.paymentRepository = paymentRepository;
6900
+ this.orderBlockedRepository = orderBlockedRepository;
6901
+ }
6902
+ async pay(checkout, card) {
6903
+ var _a;
6904
+ try {
6905
+ const payload = this.createCardPayment(checkout, card);
6906
+ const result = await axios({
6907
+ method: 'POST',
6908
+ url: `${this.credentials.URL}/transactions`,
6909
+ data: payload,
6910
+ });
6911
+ console.log('[PAGARME CARD DATA TO SEND]', payload);
6912
+ if (result.data.status !== PagarmePaymentStatus.Pago) {
6913
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
6914
+ 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`, {
6915
+ checkoutId: checkout.id,
6916
+ userEmail: checkout.user.email,
6917
+ info: result.data,
6918
+ }));
6919
+ }
6920
+ const payment = await this.paymentRepository.create({
6921
+ createdAt: new Date(),
6922
+ updatedAt: new Date(),
6923
+ userId: checkout.user.id,
6924
+ checkoutId: checkout.id,
6925
+ totalPrice: checkout.totalPrice,
6926
+ paymentProvider: PaymentProviders.PAGARME,
6927
+ transaction: Object.assign(Object.assign({}, result.data), { paidAt: new Date() }),
6928
+ });
6929
+ return payment;
6930
+ }
6931
+ catch (error) {
6932
+ 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', {
6933
+ checkoutId: checkout.id,
6934
+ userEmail: checkout.user.email,
6935
+ info: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data,
6936
+ });
6937
+ }
6938
+ }
6939
+ async addCard(card) {
6940
+ try {
6941
+ const { data } = await axios({
6942
+ method: 'POST',
6943
+ url: `${this.credentials.URL}/cards`,
6944
+ data: {
6945
+ api_key: this.credentials.API_KEY,
6946
+ card_number: card.number,
6947
+ card_expiration_date: card.expirationDate.replace('/', ''),
6948
+ card_holder_name: card.name,
6949
+ card_cvv: card.cvv,
6950
+ },
6951
+ });
6952
+ return data;
6953
+ }
6954
+ catch (error) {
6955
+ throw new BusinessError('Houve uma falha adicionar o cartão', {
6956
+ info: error.response.data,
6957
+ });
6958
+ }
6959
+ }
6960
+ async createCardHash(bu) {
6961
+ const key = bu === BusinessUnitEnum.SHOP ? this.credentials.SHOP_API_KEY : this.credentials.SUBSCRIPTION_API_KEY;
6962
+ try {
6963
+ const { data } = await axios({
6964
+ method: 'GET',
6965
+ headers: {
6966
+ 'content-type': 'application/json',
6967
+ },
6968
+ url: `${this.credentials.URL}/transactions/card_hash_key`,
6969
+ data: JSON.stringify({
6970
+ api_key: key,
6971
+ }),
6972
+ });
6973
+ return data;
6974
+ }
6975
+ catch (error) {
6976
+ throw new BusinessError('Houve uma falha gerar o hash', {
6977
+ info: error.response.data,
6978
+ });
6979
+ }
6980
+ }
6981
+ async getCardByToken(id) {
6982
+ try {
6983
+ const { data } = await axios({
6984
+ method: 'POST',
6985
+ url: `${this.credentials.URL}/cards/${id}`,
6986
+ data: {
6987
+ api_key: this.credentials.API_KEY,
6988
+ },
6989
+ });
6990
+ return data;
6991
+ }
6992
+ catch (error) {
6993
+ throw new BusinessError('Houve uma falha buscar o cartão com id: ' + id, {
6994
+ info: error.response.data,
6995
+ });
6996
+ }
6997
+ }
6998
+ async createTransaction(info) {
6999
+ try {
7000
+ const { data } = await axios({
7001
+ method: 'POST',
7002
+ url: `${this.credentials.URL}/transactions`,
7003
+ data: Object.assign(Object.assign({}, info), { api_key: this.credentials.API_KEY }),
7004
+ });
7005
+ return data;
7006
+ }
7007
+ catch (error) {
7008
+ throw new BusinessError('Houve uma falha ao criar a transação', {
7009
+ info: error.response.data,
7010
+ });
7011
+ }
7012
+ }
7013
+ createCardPayment(checkout, card) {
7014
+ var _a, _b, _c, _d, _e, _f;
7015
+ return {
7016
+ api_key: this.credentials.API_KEY,
7017
+ amount: Math.floor(checkout.totalPrice * 100),
7018
+ card_id: card.cardId,
7019
+ payment_method: 'credit_card',
7020
+ installments: card.installments,
7021
+ soft_descriptor: checkout.shop === Shops.GLAMSHOP ? 'Glam' : "Men's Market",
7022
+ customer: {
7023
+ external_id: checkout.user.id,
7024
+ name: checkout.user.displayName,
7025
+ type: 'individual',
7026
+ country: 'br',
7027
+ email: checkout.user.email,
7028
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
7029
+ documents: [
7030
+ {
7031
+ type: 'cpf',
7032
+ number: checkout.user.cpf,
7033
+ },
7034
+ ],
7035
+ },
7036
+ billing: {
7037
+ name: checkout.user.displayName,
7038
+ address: {
7039
+ country: 'br',
7040
+ state: checkout.billingAddress ? checkout.billingAddress.state : (_a = checkout.shippingAddress) === null || _a === void 0 ? void 0 : _a.state,
7041
+ city: checkout.billingAddress ? checkout.billingAddress.city : (_b = checkout.shippingAddress) === null || _b === void 0 ? void 0 : _b.city,
7042
+ neighborhood: checkout.billingAddress ? checkout.billingAddress.district : (_c = checkout.shippingAddress) === null || _c === void 0 ? void 0 : _c.district,
7043
+ street: checkout.billingAddress ? checkout.billingAddress.street : (_d = checkout.shippingAddress) === null || _d === void 0 ? void 0 : _d.street,
7044
+ street_number: checkout.billingAddress ? checkout.billingAddress.number : (_e = checkout.shippingAddress) === null || _e === void 0 ? void 0 : _e.number,
7045
+ zipcode: checkout.billingAddress
7046
+ ? checkout.billingAddress.zip.replace('-', '')
7047
+ : (_f = checkout.shippingAddress) === null || _f === void 0 ? void 0 : _f.zip.replace('-', ''),
7048
+ },
7049
+ },
7050
+ items: checkout.lineItems.map((item) => {
7051
+ return {
7052
+ id: item.id,
7053
+ title: checkout.user.isSubscriber ? `${item.name} - ASSINANTE` : item.name,
7054
+ unit_price: Math.floor(item.pricePaid * 100),
7055
+ quantity: item.quantity,
7056
+ tangible: true,
7057
+ };
7058
+ }),
7059
+ };
7060
+ }
7061
+ }
7062
+
7063
+ class PagarmePixAxiosAdapter {
7064
+ constructor(credentials, paymentRepository) {
7065
+ this.credentials = credentials;
7066
+ this.paymentRepository = paymentRepository;
7067
+ }
7068
+ async pay(checkout) {
7069
+ var _a;
7070
+ try {
7071
+ const payload = this.createPixPayment(checkout);
7072
+ const result = await axios({
7073
+ method: 'POST',
7074
+ url: `${this.credentials.URL}/transactions`,
7075
+ data: payload,
7076
+ });
7077
+ console.log('[PAGARME PIX DATA TO SEND]', payload);
7078
+ const payment = await this.paymentRepository.create({
7079
+ createdAt: new Date(),
7080
+ updatedAt: new Date(),
7081
+ userId: checkout.user.id,
7082
+ checkoutId: checkout.id,
7083
+ totalPrice: checkout.totalPrice,
7084
+ paymentProvider: 'pagarMe',
7085
+ transaction: result.data,
7086
+ });
7087
+ return payment;
7088
+ }
7089
+ catch (error) {
7090
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
7091
+ checkoutId: checkout.id,
7092
+ userEmail: checkout.user.email,
7093
+ info: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data,
7094
+ });
7095
+ }
7096
+ }
7097
+ createPixPayment(checkout) {
7098
+ return {
7099
+ payment_method: 'pix',
7100
+ amount: Math.floor(checkout.totalPrice * 100),
7101
+ api_key: this.credentials.API_KEY,
7102
+ postback_url: this.credentials.URL_POSTBACK,
7103
+ pix_expiration_date: format(addDays(new Date(), 1), 'yyyy-MM-dd'),
7104
+ customer: {
7105
+ external_id: checkout.user.id,
7106
+ type: 'individual',
7107
+ country: 'br',
7108
+ name: checkout.user.displayName,
7109
+ email: checkout.user.email.trim(),
7110
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
7111
+ documents: [
7112
+ {
7113
+ type: 'cpf',
7114
+ number: checkout.user.cpf,
7115
+ },
7116
+ ],
7117
+ },
7118
+ };
7119
+ }
7120
+ }
7121
+
6504
7122
  class VertexAxiosAdapter {
6505
7123
  constructor(config) {
6506
7124
  this.config = config;
@@ -6654,4 +7272,4 @@ class ProductsVertexSearch {
6654
7272
  }
6655
7273
  }
6656
7274
 
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 };
7275
+ 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 };