@infrab4a/connect 4.17.2-beta.1 → 4.18.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 (62) hide show
  1. package/index.cjs.js +751 -83
  2. package/index.esm.js +728 -86
  3. package/package.json +1 -1
  4. package/src/domain/general/models/index.d.ts +1 -0
  5. package/src/domain/general/models/sequences.d.ts +9 -0
  6. package/src/domain/general/repositories/index.d.ts +1 -0
  7. package/src/domain/general/repositories/sequences.repository.d.ts +4 -0
  8. package/src/domain/shopping/enums/antifraud-providers.enum.d.ts +6 -0
  9. package/src/domain/shopping/enums/index.d.ts +3 -0
  10. package/src/domain/shopping/enums/payment-methods.enum.d.ts +6 -0
  11. package/src/domain/shopping/enums/payment-providers.enum.d.ts +5 -0
  12. package/src/domain/shopping/factories/adyen-payment-method.factory.d.ts +8 -0
  13. package/src/domain/shopping/factories/antifraud-provider.factory.d.ts +15 -0
  14. package/src/domain/shopping/factories/base-payment-method.factory.d.ts +7 -0
  15. package/src/domain/shopping/factories/glampoints-payment-method.factory.d.ts +8 -0
  16. package/src/domain/shopping/factories/index.d.ts +5 -0
  17. package/src/domain/shopping/factories/pagarme-payment-method.factory.d.ts +10 -0
  18. package/src/domain/shopping/factories/payment-provider.factory.d.ts +15 -0
  19. package/src/domain/shopping/index.d.ts +4 -0
  20. package/src/domain/shopping/interfaces/antifraud-method-factory.interface.d.ts +11 -0
  21. package/src/domain/shopping/interfaces/antifraud-provider.interface.d.ts +5 -0
  22. package/src/domain/shopping/interfaces/index.d.ts +7 -0
  23. package/src/domain/shopping/interfaces/payment-method-factory.interface.d.ts +14 -0
  24. package/src/domain/shopping/interfaces/payment-provider-bank-slip.interface.d.ts +5 -0
  25. package/src/domain/shopping/interfaces/payment-provider-card.interface.d.ts +7 -0
  26. package/src/domain/shopping/interfaces/payment-provider-glampoints.interface.d.ts +5 -0
  27. package/src/domain/shopping/interfaces/payment-provider-pix.interface.d.ts +5 -0
  28. package/src/domain/shopping/models/index.d.ts +1 -0
  29. package/src/domain/shopping/models/order.d.ts +2 -2
  30. package/src/domain/shopping/models/payment-transaction.d.ts +67 -0
  31. package/src/domain/shopping/models/payment.d.ts +10 -63
  32. package/src/domain/shopping/models/types/index.d.ts +4 -4
  33. package/src/domain/shopping/services/adyen-card-payment.service.d.ts +13 -0
  34. package/src/domain/shopping/services/antifraud-bankslip.service.d.ts +9 -0
  35. package/src/domain/shopping/services/antifraud-card.service.d.ts +18 -0
  36. package/src/domain/shopping/services/antifraud-glampoints.service.d.ts +6 -0
  37. package/src/domain/shopping/services/antifraud-pix.service.d.ts +6 -0
  38. package/src/domain/shopping/services/glampoints-payment.service.d.ts +8 -0
  39. package/src/domain/shopping/services/index.d.ts +9 -0
  40. package/src/domain/shopping/services/pagarme-bank-slip-payment.service.d.ts +11 -0
  41. package/src/domain/shopping/services/pagarme-card-payment.service.d.ts +13 -0
  42. package/src/domain/shopping/services/pagarme-pix-payment.service.d.ts +11 -0
  43. package/src/domain/shopping/types/adyen-credentials.type.d.ts +6 -0
  44. package/src/domain/shopping/types/antifraud-provider.type.d.ts +2 -0
  45. package/src/domain/shopping/types/index.d.ts +5 -0
  46. package/src/domain/shopping/types/pagarme-credentials.type.d.ts +5 -0
  47. package/src/domain/shopping/types/payment-method.type.d.ts +2 -0
  48. package/src/domain/shopping/types/payment-provider.type.d.ts +2 -0
  49. package/src/errors/business.error.d.ts +7 -0
  50. package/src/errors/fraud-validation.error.d.ts +7 -0
  51. package/src/errors/index.d.ts +7 -2
  52. package/src/errors/payment.error.d.ts +7 -0
  53. package/src/errors/stock-limit.error.d.ts +5 -0
  54. package/src/errors/stock-out.error.d.ts +5 -0
  55. package/src/errors/types/checkout-additional-data-erro.type.d.ts +5 -0
  56. package/src/errors/types/index.d.ts +1 -0
  57. package/src/infra/firebase/firestore/repositories/general/index.d.ts +1 -0
  58. package/src/infra/firebase/firestore/repositories/general/sequences-firestore.repository.d.ts +7 -0
  59. package/src/infra/firebase/firestore/repositories/shopping/index.d.ts +1 -1
  60. package/src/infra/firebase/firestore/repositories/shopping/order-blocked-firestore.repository.d.ts +9 -0
  61. package/src/infra/hasura-graphql/mixins/with-find-hasura-graphql.mixin.d.ts +0 -1
  62. package/src/utils/index.d.ts +2 -2
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
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';
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,65 @@ 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 PaymentMethods;
25
+ (function (PaymentMethods) {
26
+ PaymentMethods["CARD"] = "card";
27
+ PaymentMethods["BANKSLIP"] = "bankSlip";
28
+ PaymentMethods["PIX"] = "pix";
29
+ PaymentMethods["POINTS"] = "glampoints";
30
+ })(PaymentMethods || (PaymentMethods = {}));
31
+
32
+ var PaymentProviders;
33
+ (function (PaymentProviders) {
34
+ PaymentProviders["PAGARME"] = "pagarMe";
35
+ PaymentProviders["ADYEN"] = "adyen";
36
+ PaymentProviders["GLAMPOINTS"] = "glampoints";
37
+ })(PaymentProviders || (PaymentProviders = {}));
38
+
39
+ class BasePaymentMethodFactory {
40
+ constructor(methods) {
41
+ this.methods = methods;
42
+ }
43
+ build(method) {
44
+ return this.methods[method];
45
+ }
46
+ }
47
+
48
+ class AdyenPaymentMethodFactory extends BasePaymentMethodFactory {
49
+ }
50
+
51
+ class AntifraudProviderFactory {
52
+ constructor(antifraudProviders) {
53
+ this.antifraudProviders = antifraudProviders;
54
+ }
55
+ build(provider) {
56
+ return this.antifraudProviders[provider];
57
+ }
58
+ }
59
+
60
+ class GlampointsPaymentMethodFactory extends BasePaymentMethodFactory {
61
+ }
62
+
63
+ class PagarmePaymentMethodFactory extends BasePaymentMethodFactory {
64
+ }
65
+
66
+ class PaymentProviderFactory {
67
+ constructor(paymentProviders) {
68
+ this.paymentProviders = paymentProviders;
69
+ }
70
+ build(provider) {
71
+ return this.paymentProviders[provider];
72
+ }
73
+ }
74
+
16
75
  class BaseModel {
17
76
  get identifier() {
18
77
  const fields = this.constructor.identifiersFields.filter((field) => field !== 'identifier');
@@ -559,175 +618,182 @@ var Status;
559
618
  Status["CANCELLED"] = "Cancelado";
560
619
  })(Status || (Status = {}));
561
620
 
562
- class Payment extends BaseModel {
563
- static get identifiersFields() {
564
- return ['id'];
565
- }
621
+ class PaymentTransaction extends BaseModel {
566
622
  }
567
623
  __decorate([
568
624
  Expose({ name: 'refuse_reason' }),
569
625
  __metadata("design:type", String)
570
- ], Payment.prototype, "refuseReason", void 0);
626
+ ], PaymentTransaction.prototype, "refuseReason", void 0);
571
627
  __decorate([
572
628
  Expose({ name: 'status_reason' }),
573
629
  __metadata("design:type", String)
574
- ], Payment.prototype, "statusReason", void 0);
630
+ ], PaymentTransaction.prototype, "statusReason", void 0);
575
631
  __decorate([
576
632
  Expose({ name: 'acquirer_response_code' }),
577
633
  __metadata("design:type", String)
578
- ], Payment.prototype, "acquirerResponseCode", void 0);
634
+ ], PaymentTransaction.prototype, "acquirerResponseCode", void 0);
579
635
  __decorate([
580
636
  Expose({ name: 'acquirer_name' }),
581
637
  __metadata("design:type", String)
582
- ], Payment.prototype, "acquirerName", void 0);
638
+ ], PaymentTransaction.prototype, "acquirerName", void 0);
583
639
  __decorate([
584
640
  Expose({ name: 'acquirer_id' }),
585
641
  __metadata("design:type", String)
586
- ], Payment.prototype, "acquirerId", void 0);
642
+ ], PaymentTransaction.prototype, "acquirerId", void 0);
587
643
  __decorate([
588
644
  Expose({ name: 'authorization_code' }),
589
645
  __metadata("design:type", String)
590
- ], Payment.prototype, "authorizationCode", void 0);
646
+ ], PaymentTransaction.prototype, "authorizationCode", void 0);
591
647
  __decorate([
592
648
  Expose({ name: 'soft_descriptor' }),
593
649
  __metadata("design:type", String)
594
- ], Payment.prototype, "softDescriptor", void 0);
650
+ ], PaymentTransaction.prototype, "softDescriptor", void 0);
595
651
  __decorate([
596
652
  Expose({ name: 'date_created' }),
597
653
  __metadata("design:type", String)
598
- ], Payment.prototype, "dateCreated", void 0);
654
+ ], PaymentTransaction.prototype, "dateCreated", void 0);
599
655
  __decorate([
600
656
  Expose({ name: 'date_updated' }),
601
657
  __metadata("design:type", String)
602
- ], Payment.prototype, "dateUpdated", void 0);
658
+ ], PaymentTransaction.prototype, "dateUpdated", void 0);
603
659
  __decorate([
604
660
  Expose({ name: 'authorized_amount' }),
605
661
  __metadata("design:type", Number)
606
- ], Payment.prototype, "authorizedAmount", void 0);
662
+ ], PaymentTransaction.prototype, "authorizedAmount", void 0);
607
663
  __decorate([
608
664
  Expose({ name: 'paid_amount' }),
609
665
  __metadata("design:type", Number)
610
- ], Payment.prototype, "paidAmount", void 0);
666
+ ], PaymentTransaction.prototype, "paidAmount", void 0);
611
667
  __decorate([
612
668
  Expose({ name: 'paid_at' }),
613
669
  __metadata("design:type", String)
614
- ], Payment.prototype, "paidAt", void 0);
670
+ ], PaymentTransaction.prototype, "paidAt", void 0);
615
671
  __decorate([
616
672
  Expose({ name: 'refunded_amount' }),
617
673
  __metadata("design:type", Number)
618
- ], Payment.prototype, "refundedAmount", void 0);
674
+ ], PaymentTransaction.prototype, "refundedAmount", void 0);
619
675
  __decorate([
620
676
  Expose({ name: 'card_holder_name' }),
621
677
  __metadata("design:type", String)
622
- ], Payment.prototype, "cardHolderName", void 0);
678
+ ], PaymentTransaction.prototype, "cardHolderName", void 0);
623
679
  __decorate([
624
680
  Expose({ name: 'card_last_digits' }),
625
681
  __metadata("design:type", String)
626
- ], Payment.prototype, "cardLastDigits", void 0);
682
+ ], PaymentTransaction.prototype, "cardLastDigits", void 0);
627
683
  __decorate([
628
684
  Expose({ name: 'card_first_digits' }),
629
685
  __metadata("design:type", String)
630
- ], Payment.prototype, "cardFirstDigits", void 0);
686
+ ], PaymentTransaction.prototype, "cardFirstDigits", void 0);
631
687
  __decorate([
632
688
  Expose({ name: 'card_brand' }),
633
689
  __metadata("design:type", String)
634
- ], Payment.prototype, "cardBrand", void 0);
690
+ ], PaymentTransaction.prototype, "cardBrand", void 0);
635
691
  __decorate([
636
692
  Expose({ name: 'card_pin_mode' }),
637
693
  __metadata("design:type", String)
638
- ], Payment.prototype, "cardPinMode", void 0);
694
+ ], PaymentTransaction.prototype, "cardPinMode", void 0);
639
695
  __decorate([
640
696
  Expose({ name: 'card_magstripe_fallback' }),
641
697
  __metadata("design:type", Boolean)
642
- ], Payment.prototype, "cardMagstripeFallback", void 0);
698
+ ], PaymentTransaction.prototype, "cardMagstripeFallback", void 0);
643
699
  __decorate([
644
700
  Expose({ name: 'cvm_pin' }),
645
701
  __metadata("design:type", Boolean)
646
- ], Payment.prototype, "cvmPin", void 0);
702
+ ], PaymentTransaction.prototype, "cvmPin", void 0);
647
703
  __decorate([
648
704
  Expose({ name: 'postback_url' }),
649
705
  __metadata("design:type", String)
650
- ], Payment.prototype, "postbackUrl", void 0);
706
+ ], PaymentTransaction.prototype, "postbackUrl", void 0);
651
707
  __decorate([
652
708
  Expose({ name: 'payment_method' }),
653
709
  __metadata("design:type", String)
654
- ], Payment.prototype, "paymentMethod", void 0);
710
+ ], PaymentTransaction.prototype, "paymentMethod", void 0);
655
711
  __decorate([
656
712
  Expose({ name: 'capture_method' }),
657
713
  __metadata("design:type", String)
658
- ], Payment.prototype, "captureMethod", void 0);
714
+ ], PaymentTransaction.prototype, "captureMethod", void 0);
659
715
  __decorate([
660
716
  Expose({ name: 'antifraud_score' }),
661
717
  __metadata("design:type", String)
662
- ], Payment.prototype, "antifraudScore", void 0);
718
+ ], PaymentTransaction.prototype, "antifraudScore", void 0);
663
719
  __decorate([
664
720
  Expose({ name: 'boleto_url' }),
665
721
  __metadata("design:type", String)
666
- ], Payment.prototype, "boletoUrl", void 0);
722
+ ], PaymentTransaction.prototype, "boletoUrl", void 0);
667
723
  __decorate([
668
724
  Expose({ name: 'boleto_barcode' }),
669
725
  __metadata("design:type", String)
670
- ], Payment.prototype, "boletoBarcode", void 0);
726
+ ], PaymentTransaction.prototype, "boletoBarcode", void 0);
671
727
  __decorate([
672
728
  Expose({ name: 'boleto_expiration_date' }),
673
729
  __metadata("design:type", String)
674
- ], Payment.prototype, "boletoExpirationDate", void 0);
730
+ ], PaymentTransaction.prototype, "boletoExpirationDate", void 0);
675
731
  __decorate([
676
732
  Expose({ name: 'subscription_id' }),
677
733
  __metadata("design:type", String)
678
- ], Payment.prototype, "subscriptionId", void 0);
734
+ ], PaymentTransaction.prototype, "subscriptionId", void 0);
679
735
  __decorate([
680
736
  Expose({ name: 'split_rules' }),
681
737
  __metadata("design:type", String)
682
- ], Payment.prototype, "splitRules", void 0);
738
+ ], PaymentTransaction.prototype, "splitRules", void 0);
683
739
  __decorate([
684
740
  Expose({ name: 'antifraud_metadata' }),
685
741
  __metadata("design:type", Object)
686
- ], Payment.prototype, "antifraudMetadata", void 0);
742
+ ], PaymentTransaction.prototype, "antifraudMetadata", void 0);
687
743
  __decorate([
688
744
  Expose({ name: 'reference_key' }),
689
745
  __metadata("design:type", String)
690
- ], Payment.prototype, "referenceKey", void 0);
746
+ ], PaymentTransaction.prototype, "referenceKey", void 0);
691
747
  __decorate([
692
748
  Expose({ name: 'local_transaction_id' }),
693
749
  __metadata("design:type", String)
694
- ], Payment.prototype, "localTransactionId", void 0);
750
+ ], PaymentTransaction.prototype, "localTransactionId", void 0);
695
751
  __decorate([
696
752
  Expose({ name: 'local_time' }),
697
753
  __metadata("design:type", String)
698
- ], Payment.prototype, "localTime", void 0);
754
+ ], PaymentTransaction.prototype, "localTime", void 0);
699
755
  __decorate([
700
756
  Expose({ name: 'fraud_covered' }),
701
757
  __metadata("design:type", Boolean)
702
- ], Payment.prototype, "fraudCovered", void 0);
758
+ ], PaymentTransaction.prototype, "fraudCovered", void 0);
703
759
  __decorate([
704
760
  Expose({ name: 'fraud_reimbursed' }),
705
761
  __metadata("design:type", String)
706
- ], Payment.prototype, "fraudReimbursed", void 0);
762
+ ], PaymentTransaction.prototype, "fraudReimbursed", void 0);
707
763
  __decorate([
708
764
  Expose({ name: 'order_id' }),
709
765
  __metadata("design:type", String)
710
- ], Payment.prototype, "orderId", void 0);
766
+ ], PaymentTransaction.prototype, "orderId", void 0);
711
767
  __decorate([
712
768
  Expose({ name: 'risk_level' }),
713
769
  __metadata("design:type", String)
714
- ], Payment.prototype, "riskLevel", void 0);
770
+ ], PaymentTransaction.prototype, "riskLevel", void 0);
715
771
  __decorate([
716
772
  Expose({ name: 'receipt_url' }),
717
773
  __metadata("design:type", String)
718
- ], Payment.prototype, "receiptUrl", void 0);
774
+ ], PaymentTransaction.prototype, "receiptUrl", void 0);
719
775
  __decorate([
720
776
  Expose({ name: 'private_label' }),
721
777
  __metadata("design:type", String)
722
- ], Payment.prototype, "privateLabel", void 0);
778
+ ], PaymentTransaction.prototype, "privateLabel", void 0);
723
779
  __decorate([
724
780
  Expose({ name: 'pix_qr_code' }),
725
781
  __metadata("design:type", String)
726
- ], Payment.prototype, "pixQrCode", void 0);
782
+ ], PaymentTransaction.prototype, "pixQrCode", void 0);
727
783
  __decorate([
728
784
  Expose({ name: 'pix_expiration_date' }),
729
785
  __metadata("design:type", String)
730
- ], Payment.prototype, "pixExpirationDate", void 0);
786
+ ], PaymentTransaction.prototype, "pixExpirationDate", void 0);
787
+
788
+ class Payment extends BaseModel {
789
+ static get identifiersFields() {
790
+ return ['id'];
791
+ }
792
+ }
793
+ __decorate([
794
+ Type(() => PaymentTransaction),
795
+ __metadata("design:type", PaymentTransaction)
796
+ ], Payment.prototype, "transaction", void 0);
731
797
 
732
798
  class SubscriptionPayment extends BaseModel {
733
799
  static get identifiersFields() {
@@ -2191,8 +2257,8 @@ var OrderStatus;
2191
2257
  class Order extends Checkout {
2192
2258
  }
2193
2259
  __decorate([
2194
- Type(() => Payment),
2195
- __metadata("design:type", Payment)
2260
+ Type(() => PaymentTransaction),
2261
+ __metadata("design:type", PaymentTransaction)
2196
2262
  ], Order.prototype, "payment", void 0);
2197
2263
 
2198
2264
  class OrderBlocked extends BaseModel {
@@ -2223,6 +2289,592 @@ __decorate([
2223
2289
  __metadata("design:type", Coupon)
2224
2290
  ], CheckoutSubscription.prototype, "coupon", void 0);
2225
2291
 
2292
+ class BusinessError extends CustomError {
2293
+ constructor(message, additionalData, type = '') {
2294
+ super(message);
2295
+ this.additionalData = additionalData;
2296
+ this.type = type;
2297
+ }
2298
+ }
2299
+
2300
+ class DuplicatedResultsError extends CustomError {
2301
+ constructor(message) {
2302
+ super(message);
2303
+ }
2304
+ }
2305
+
2306
+ class FraudValidationError extends CustomError {
2307
+ constructor(message, additionalData) {
2308
+ super(message);
2309
+ this.additionalData = additionalData;
2310
+ this.type = 'antifraud';
2311
+ }
2312
+ }
2313
+
2314
+ class InvalidArgumentError extends CustomError {
2315
+ constructor(message) {
2316
+ super(message);
2317
+ }
2318
+ }
2319
+
2320
+ class NotFoundError extends CustomError {
2321
+ constructor(message) {
2322
+ super(message);
2323
+ }
2324
+ }
2325
+
2326
+ class PaymentError extends CustomError {
2327
+ constructor(message, additionalData) {
2328
+ super(message);
2329
+ this.additionalData = additionalData;
2330
+ this.type = 'payment';
2331
+ }
2332
+ }
2333
+
2334
+ class RequiredArgumentError extends CustomError {
2335
+ constructor(args) {
2336
+ super(`Required arguments: ${args.join(', ')}`);
2337
+ this.args = args;
2338
+ this.arguments = args;
2339
+ }
2340
+ }
2341
+
2342
+ class StockLimitError extends BusinessError {
2343
+ constructor(message, additionalData) {
2344
+ super(message, additionalData);
2345
+ this.type = 'stock-limit';
2346
+ }
2347
+ }
2348
+
2349
+ class StockOutError extends BusinessError {
2350
+ constructor(message, additionalData) {
2351
+ super(message, additionalData);
2352
+ this.type = 'stock-out';
2353
+ }
2354
+ }
2355
+
2356
+ class AdyenCardService {
2357
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
2358
+ this.credentials = credentials;
2359
+ this.paymentRepository = paymentRepository;
2360
+ this.orderBlockedRepository = orderBlockedRepository;
2361
+ }
2362
+ async pay(checkout, card) {
2363
+ try {
2364
+ const result = await axios({
2365
+ method: 'POST',
2366
+ url: this.credentials.URL_TRANSACTION,
2367
+ headers: {
2368
+ 'x-api-key': this.credentials.API_KEY,
2369
+ 'content-type': 'application/json',
2370
+ },
2371
+ data: this.createCardPayment(checkout, card),
2372
+ });
2373
+ if (result.data.resultCode !== 'Authorised') {
2374
+ this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
2375
+ 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`, {
2376
+ checkoutId: checkout.id,
2377
+ userEmail: checkout.user.email,
2378
+ info: result.data,
2379
+ }));
2380
+ }
2381
+ const payment = await this.paymentRepository.create(Payment.toInstance({
2382
+ createdAt: new Date(),
2383
+ updatedAt: new Date(),
2384
+ userId: checkout.user.id,
2385
+ checkoutId: checkout.id,
2386
+ totalPrice: checkout.totalPrice,
2387
+ paymentProvider: 'adyen',
2388
+ transaction: Object.assign(Object.assign({}, result.data), { status: 'paid' }),
2389
+ }));
2390
+ return payment;
2391
+ }
2392
+ catch (error) {
2393
+ 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', {
2394
+ checkoutId: checkout.id,
2395
+ userEmail: checkout.user.email,
2396
+ info: error.message,
2397
+ });
2398
+ }
2399
+ }
2400
+ createCardPayment(checkout, card) {
2401
+ return {
2402
+ amount: {
2403
+ currency: 'BRL',
2404
+ value: ((checkout === null || checkout === void 0 ? void 0 : checkout.totalPrice) || 0) * 100,
2405
+ },
2406
+ paymentMethod: {
2407
+ type: 'scheme',
2408
+ storedPaymentMethodId: card.cardId,
2409
+ },
2410
+ reference: checkout.id,
2411
+ shopperInteraction: 'Ecommerce',
2412
+ merchantAccount: this.credentials.MERCHANT_ACCOUNT,
2413
+ shopperReference: checkout.user.id,
2414
+ recurringProcessingModel: 'CardOnFile',
2415
+ returnUrl: this.credentials.URL_POSTBACK,
2416
+ installments: {
2417
+ value: card.installments,
2418
+ },
2419
+ };
2420
+ }
2421
+ addCard() {
2422
+ throw new Error('Method not implemented.');
2423
+ }
2424
+ }
2425
+
2426
+ class AntifraudBankSlipService {
2427
+ constructor(orderBlockedRepository) {
2428
+ this.orderBlockedRepository = orderBlockedRepository;
2429
+ this.MAX_ORDER_VALUE = 5000;
2430
+ }
2431
+ async validate(checkout) {
2432
+ var _a, _b;
2433
+ if (checkout.totalPrice && checkout.totalPrice > this.MAX_ORDER_VALUE && !((_a = checkout.user) === null || _a === void 0 ? void 0 : _a.isSubscriber)) {
2434
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Boleto not authorized', 'Boleto', 'day');
2435
+ throw new FraudValidationError('Boleto não autorizado para cliente não assinante', {
2436
+ checkoutId: checkout.id,
2437
+ userEmail: checkout.user.email,
2438
+ info: {
2439
+ isSubscriber: (_b = checkout.user) === null || _b === void 0 ? void 0 : _b.isSubscriber,
2440
+ subtotal: checkout.subTotalPrice,
2441
+ total: checkout.totalPrice,
2442
+ },
2443
+ });
2444
+ }
2445
+ return true;
2446
+ }
2447
+ }
2448
+
2449
+ class AntifraudCardService {
2450
+ constructor(orderRepository, orderBlockedRepository) {
2451
+ this.orderRepository = orderRepository;
2452
+ this.orderBlockedRepository = orderBlockedRepository;
2453
+ this.LIMIT_ORDERS_DAY = 2;
2454
+ this.LIMIT_ORDERS_WEEK = 7;
2455
+ this.LIMIT_BLOCKED_ORDERS_DAY = 5;
2456
+ }
2457
+ async validate(checkout, card) {
2458
+ var _a, _b;
2459
+ if (!(await this.verifyBlockedOrderAttempts(checkout, card)))
2460
+ throw new FraudValidationError('Cliente com mais de 5 compras negadas/bloqueadas no dia', {
2461
+ checkoutId: checkout.id,
2462
+ userEmail: checkout.user.email,
2463
+ info: {
2464
+ isSubscriber: (_a = checkout.user) === null || _a === void 0 ? void 0 : _a.isSubscriber,
2465
+ subtotal: checkout.subTotalPrice,
2466
+ total: checkout.totalPrice,
2467
+ },
2468
+ });
2469
+ if (!(await this.verifyDayAndWeekOrders(checkout, card)))
2470
+ throw new FraudValidationError('Cliente tentando comprar mais de 2 vezes no dia ou 7 vezes na semana', {
2471
+ checkoutId: checkout.id,
2472
+ userEmail: checkout.user.email,
2473
+ info: {
2474
+ isSubscriber: (_b = checkout.user) === null || _b === void 0 ? void 0 : _b.isSubscriber,
2475
+ subtotal: checkout.subTotalPrice,
2476
+ total: checkout.totalPrice,
2477
+ },
2478
+ });
2479
+ return true;
2480
+ }
2481
+ async verifyBlockedOrderAttempts(checkout, card) {
2482
+ var _a, _b, _c, _d;
2483
+ const day = `${format(new Date(), 'YYYY-MM-DD')}T00:00:00`;
2484
+ const endOfDay = `${format(new Date(), 'YYYY-MM-DD')}T23:59:59`;
2485
+ const ordersBlockedWithCpf = await this.orderBlockedRepository
2486
+ .find({
2487
+ filters: {
2488
+ customer: { cpf: { operator: Where.EQUALS, value: (_a = checkout.user) === null || _a === void 0 ? void 0 : _a.cpf } },
2489
+ date: [
2490
+ { operator: Where.GTE, value: new Date(day) },
2491
+ { operator: Where.LTE, value: new Date(endOfDay) },
2492
+ ],
2493
+ },
2494
+ })
2495
+ .then((data) => data.data);
2496
+ const ordersBlockedWithEmail = await this.orderBlockedRepository
2497
+ .find({
2498
+ filters: {
2499
+ customer: { email: { operator: Where.EQUALS, value: (_b = checkout.user) === null || _b === void 0 ? void 0 : _b.email } },
2500
+ date: [
2501
+ { operator: Where.GTE, value: new Date(day) },
2502
+ { operator: Where.LTE, value: new Date(endOfDay) },
2503
+ ],
2504
+ },
2505
+ })
2506
+ .then((data) => data.data);
2507
+ const ordersBlockedWithCep = await this.orderBlockedRepository
2508
+ .find({
2509
+ filters: {
2510
+ customer: { shippingAddress: { zip: { operator: Where.EQUALS, value: (_c = checkout.shippingAddress) === null || _c === void 0 ? void 0 : _c.zip } } },
2511
+ date: [
2512
+ { operator: Where.GTE, value: new Date(day) },
2513
+ { operator: Where.LTE, value: new Date(endOfDay) },
2514
+ ],
2515
+ },
2516
+ })
2517
+ .then((data) => data.data);
2518
+ const ordersBlockedWithPhone = await this.orderBlockedRepository
2519
+ .find({
2520
+ filters: {
2521
+ customer: { phoneNumber: { operator: Where.EQUALS, value: (_d = checkout.user) === null || _d === void 0 ? void 0 : _d.phone } },
2522
+ date: [
2523
+ { operator: Where.GTE, value: new Date(day) },
2524
+ { operator: Where.LTE, value: new Date(endOfDay) },
2525
+ ],
2526
+ },
2527
+ })
2528
+ .then((data) => data.data);
2529
+ const blockedUniqueEmails = ordersBlockedWithEmail.filter((e) => {
2530
+ var _a;
2531
+ return e.customer.cpf !== ((_a = checkout.user) === null || _a === void 0 ? void 0 : _a.cpf);
2532
+ });
2533
+ const blockedUniqueCeps = ordersBlockedWithCep.filter((e) => {
2534
+ var _a, _b;
2535
+ 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);
2536
+ });
2537
+ const blockedUniquePhone = ordersBlockedWithPhone.filter((e) => {
2538
+ var _a, _b, _c, _d, _e, _f;
2539
+ return (e.customer.cpf !== ((_a = checkout.user) === null || _a === void 0 ? void 0 : _a.cpf) &&
2540
+ e.customer.email !== ((_b = checkout.user) === null || _b === void 0 ? void 0 : _b.email) &&
2541
+ ((_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()));
2542
+ });
2543
+ const blockedAttempts = ordersBlockedWithCpf
2544
+ .concat(blockedUniqueEmails)
2545
+ .concat(blockedUniqueCeps)
2546
+ .concat(blockedUniquePhone);
2547
+ if (blockedAttempts.length >= this.LIMIT_BLOCKED_ORDERS_DAY) {
2548
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'More than 5 attempts have failed', 'Failed attempts', 'day', card || null);
2549
+ return false;
2550
+ }
2551
+ return true;
2552
+ }
2553
+ async verifyDayAndWeekOrders(checkout, card) {
2554
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2555
+ 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'));
2556
+ for (const key in ordersPerDay) {
2557
+ if (ordersPerDay[key] > this.LIMIT_ORDERS_DAY) {
2558
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Order limit', key, 'day');
2559
+ return false;
2560
+ }
2561
+ }
2562
+ 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'));
2563
+ for (const key in ordersPerWeek) {
2564
+ if (ordersPerDay[key] > this.LIMIT_ORDERS_WEEK) {
2565
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Order limit', key, 'week');
2566
+ return false;
2567
+ }
2568
+ }
2569
+ return true;
2570
+ }
2571
+ async validateOrdersByRange(cpf, email, phone, zip, card, range) {
2572
+ const ordersCpf = await this.countOrdersByField('user', 'cpf', cpf, range);
2573
+ const ordersByEmail = await this.countOrdersByField('user', 'email', email, range);
2574
+ const ordersByPhone = await this.countOrdersByField('user', 'phone', phone, range);
2575
+ const ordersByZip = await this.countOrdersByField('shippingAddress', 'zip', zip, range);
2576
+ return {
2577
+ cpf: ordersCpf,
2578
+ email: ordersByEmail,
2579
+ phone: ordersByPhone,
2580
+ zip: ordersByZip,
2581
+ };
2582
+ }
2583
+ async countOrdersByField(property, field, value, range) {
2584
+ const filters = {
2585
+ [property]: {
2586
+ [field]: value,
2587
+ },
2588
+ ['createdAt']: [
2589
+ { operator: Where.GTE, value: range.firstDate },
2590
+ { operator: Where.LTE, value: range.lastDate },
2591
+ ],
2592
+ };
2593
+ const docs = await (await this.orderRepository.find({ filters })).count;
2594
+ return docs;
2595
+ }
2596
+ getDateRange(range = 'day') {
2597
+ switch (range) {
2598
+ case 'day':
2599
+ return {
2600
+ firstDate: startOfDay(new Date()).getTime(),
2601
+ lastDate: endOfDay(new Date()).getTime(),
2602
+ };
2603
+ case 'week':
2604
+ return {
2605
+ firstDate: startOfDay(subDays(new Date(), 7)).getTime(),
2606
+ lastDate: endOfDay(new Date()).getTime(),
2607
+ };
2608
+ default:
2609
+ return {
2610
+ firstDate: startOfDay(new Date()).getTime(),
2611
+ lastDate: endOfDay(new Date()).getTime(),
2612
+ };
2613
+ }
2614
+ }
2615
+ }
2616
+
2617
+ class AntifraudGlampointsService {
2618
+ constructor() { }
2619
+ async validate(checkout) {
2620
+ return true;
2621
+ }
2622
+ }
2623
+
2624
+ class AntifraudPixService {
2625
+ constructor() { }
2626
+ async validate(checkout) {
2627
+ return true;
2628
+ }
2629
+ }
2630
+
2631
+ class GlampointsPaymentService {
2632
+ constructor(paymentRepository) {
2633
+ this.paymentRepository = paymentRepository;
2634
+ }
2635
+ async pay(checkout) {
2636
+ const payment = await this.paymentRepository.create(Payment.toInstance({
2637
+ createdAt: new Date(),
2638
+ updatedAt: new Date(),
2639
+ userId: checkout.user.id,
2640
+ checkoutId: checkout.id,
2641
+ totalPrice: checkout.totalPrice,
2642
+ paymentProvider: 'glampoints',
2643
+ transaction: {
2644
+ amount: 0,
2645
+ acquirerResponseCode: '0000',
2646
+ acquirerName: 'glampoints',
2647
+ authorizedAmount: 0,
2648
+ captureMethod: 'ecommerce',
2649
+ installments: 1,
2650
+ cost: 0,
2651
+ paidAmount: 0,
2652
+ paidAt: new Date().toISOString(),
2653
+ paymentMethod: 'glampoints',
2654
+ referer: 'api_key',
2655
+ refundedAmount: 0,
2656
+ status: 'paid',
2657
+ statusReason: 'acquirer',
2658
+ },
2659
+ }));
2660
+ return payment;
2661
+ }
2662
+ }
2663
+
2664
+ class PagarmeBankSlipService {
2665
+ constructor(credentials, paymentRepository) {
2666
+ this.credentials = credentials;
2667
+ this.paymentRepository = paymentRepository;
2668
+ }
2669
+ async pay(checkout) {
2670
+ try {
2671
+ const result = await axios({
2672
+ method: 'POST',
2673
+ url: this.credentials.URL_TRANSACTION,
2674
+ data: this.createBoletoPayment(checkout),
2675
+ });
2676
+ if (result.data.status !== 'processing') {
2677
+ return Promise.reject(new PaymentError(`Houve uma falha ao gerar o boleto. Tente novamente`, {
2678
+ checkoutId: checkout.id,
2679
+ userEmail: checkout.user.email,
2680
+ info: result.data,
2681
+ }));
2682
+ }
2683
+ const payment = await this.paymentRepository.create(Payment.toInstance({
2684
+ createdAt: new Date(),
2685
+ updatedAt: new Date(),
2686
+ userId: checkout.user.id,
2687
+ checkoutId: checkout.id,
2688
+ totalPrice: checkout.totalPrice,
2689
+ paymentProvider: 'pagarMe',
2690
+ transaction: result.data,
2691
+ }));
2692
+ return payment;
2693
+ }
2694
+ catch (error) {
2695
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
2696
+ checkoutId: checkout.id,
2697
+ userEmail: checkout.user.email,
2698
+ info: error.response.data,
2699
+ });
2700
+ }
2701
+ }
2702
+ createBoletoPayment(checkout) {
2703
+ return {
2704
+ api_key: this.credentials.API_KEY,
2705
+ amount: Math.floor(checkout.totalPrice * 100),
2706
+ boleto_rules: ['strict_expiration_date'],
2707
+ boleto_instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
2708
+ boleto_expiration_date: format(addDays(new Date(), 3), 'yyyy-MM-dd'),
2709
+ payment_method: 'boleto',
2710
+ postback_url: this.credentials.URL_POSTBACK,
2711
+ customer: {
2712
+ external_id: checkout.user.id,
2713
+ type: 'individual',
2714
+ country: 'br',
2715
+ name: checkout.user.displayName,
2716
+ documents: [
2717
+ {
2718
+ type: 'cpf',
2719
+ number: checkout.user.cpf,
2720
+ },
2721
+ ],
2722
+ },
2723
+ };
2724
+ }
2725
+ }
2726
+
2727
+ class PagarmeCardService {
2728
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
2729
+ this.credentials = credentials;
2730
+ this.paymentRepository = paymentRepository;
2731
+ this.orderBlockedRepository = orderBlockedRepository;
2732
+ }
2733
+ async pay(checkout, card) {
2734
+ var _a;
2735
+ try {
2736
+ const result = await axios({
2737
+ method: 'POST',
2738
+ url: this.credentials.URL_TRANSACTION,
2739
+ data: this.createCardPayment(checkout, card),
2740
+ });
2741
+ if (result.data.status !== 'paid') {
2742
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
2743
+ 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`, {
2744
+ checkoutId: checkout.id,
2745
+ userEmail: checkout.user.email,
2746
+ info: result.data,
2747
+ }));
2748
+ }
2749
+ const payment = await this.paymentRepository.create(Payment.toInstance({
2750
+ createdAt: new Date(),
2751
+ updatedAt: new Date(),
2752
+ userId: checkout.user.id,
2753
+ checkoutId: checkout.id,
2754
+ totalPrice: checkout.totalPrice,
2755
+ paymentProvider: PaymentProviders.PAGARME,
2756
+ transaction: Object.assign(Object.assign({}, result.data), { paidAt: new Date() }),
2757
+ }));
2758
+ return payment;
2759
+ }
2760
+ catch (error) {
2761
+ 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', {
2762
+ checkoutId: checkout.id,
2763
+ userEmail: checkout.user.email,
2764
+ info: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data,
2765
+ });
2766
+ }
2767
+ }
2768
+ addCard() {
2769
+ throw new Error('Method not implemented.');
2770
+ }
2771
+ createCardPayment(checkout, card) {
2772
+ var _a, _b, _c, _d, _e, _f;
2773
+ return {
2774
+ api_key: this.credentials.API_KEY,
2775
+ amount: Math.floor(checkout.totalPrice * 100),
2776
+ card_id: card.cardId,
2777
+ payment_method: 'credit_card',
2778
+ installments: card.installments,
2779
+ soft_descriptor: checkout.shop === Shops.GLAMSHOP ? 'Glam' : "Men's Market",
2780
+ customer: {
2781
+ external_id: checkout.user.id,
2782
+ name: checkout.user.displayName,
2783
+ type: 'individual',
2784
+ country: 'br',
2785
+ email: checkout.user.email,
2786
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
2787
+ documents: [
2788
+ {
2789
+ type: 'cpf',
2790
+ number: checkout.user.cpf,
2791
+ },
2792
+ ],
2793
+ },
2794
+ billing: {
2795
+ name: checkout.user.displayName,
2796
+ address: {
2797
+ country: 'br',
2798
+ state: checkout.billingAddress ? checkout.billingAddress.state : (_a = checkout.shippingAddress) === null || _a === void 0 ? void 0 : _a.state,
2799
+ city: checkout.billingAddress ? checkout.billingAddress.city : (_b = checkout.shippingAddress) === null || _b === void 0 ? void 0 : _b.city,
2800
+ neighborhood: checkout.billingAddress ? checkout.billingAddress.district : (_c = checkout.shippingAddress) === null || _c === void 0 ? void 0 : _c.district,
2801
+ street: checkout.billingAddress ? checkout.billingAddress.street : (_d = checkout.shippingAddress) === null || _d === void 0 ? void 0 : _d.street,
2802
+ street_number: checkout.billingAddress ? checkout.billingAddress.number : (_e = checkout.shippingAddress) === null || _e === void 0 ? void 0 : _e.number,
2803
+ zipcode: checkout.billingAddress
2804
+ ? checkout.billingAddress.zip.replace('-', '')
2805
+ : (_f = checkout.shippingAddress) === null || _f === void 0 ? void 0 : _f.zip.replace('-', ''),
2806
+ },
2807
+ },
2808
+ items: checkout.lineItems.map((item) => {
2809
+ return {
2810
+ id: item.id,
2811
+ title: checkout.user.isSubscriber ? `${item.name} - ASSINANTE` : item.name,
2812
+ unit_price: Math.floor(item.pricePaid * 100),
2813
+ quantity: item.quantity,
2814
+ tangible: true,
2815
+ };
2816
+ }),
2817
+ };
2818
+ }
2819
+ }
2820
+
2821
+ class PagarmePixService {
2822
+ constructor(credentials, paymentRepository) {
2823
+ this.credentials = credentials;
2824
+ this.paymentRepository = paymentRepository;
2825
+ }
2826
+ async pay(checkout) {
2827
+ var _a;
2828
+ try {
2829
+ const result = await axios({
2830
+ method: 'POST',
2831
+ url: this.credentials.URL_TRANSACTION,
2832
+ data: this.createPixPayment(checkout),
2833
+ });
2834
+ const payment = await this.paymentRepository.create(Payment.toInstance({
2835
+ createdAt: new Date(),
2836
+ updatedAt: new Date(),
2837
+ userId: checkout.user.id,
2838
+ checkoutId: checkout.id,
2839
+ totalPrice: checkout.totalPrice,
2840
+ paymentProvider: 'pagarMe',
2841
+ transaction: Object.assign(Object.assign({}, result.data), { paidAt: new Date() }),
2842
+ }));
2843
+ return payment;
2844
+ }
2845
+ catch (error) {
2846
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
2847
+ checkoutId: checkout.id,
2848
+ userEmail: checkout.user.email,
2849
+ info: (_a = error.response) === null || _a === void 0 ? void 0 : _a.data,
2850
+ });
2851
+ }
2852
+ }
2853
+ createPixPayment(checkout) {
2854
+ return {
2855
+ payment_method: 'pix',
2856
+ amount: Math.floor(checkout.totalPrice * 100),
2857
+ api_key: this.credentials.API_KEY,
2858
+ postback_url: this.credentials.URL_POSTBACK,
2859
+ pix_expiration_date: format(addDays(new Date(), 1), 'yyyy-MM-dd'),
2860
+ customer: {
2861
+ external_id: checkout.user.id,
2862
+ type: 'individual',
2863
+ country: 'br',
2864
+ name: checkout.user.displayName,
2865
+ email: checkout.user.email.trim(),
2866
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
2867
+ documents: [
2868
+ {
2869
+ type: 'cpf',
2870
+ number: checkout.user.cpf,
2871
+ },
2872
+ ],
2873
+ },
2874
+ };
2875
+ }
2876
+ }
2877
+
2226
2878
  class RoundProductPricesHelper {
2227
2879
  static roundProductPrices(product) {
2228
2880
  product.price.price = Number(product.price.price.toFixed(2));
@@ -2243,6 +2895,12 @@ class LogDocument extends BaseModel {
2243
2895
  }
2244
2896
  }
2245
2897
 
2898
+ class Sequence extends BaseModel {
2899
+ static get identifiersFields() {
2900
+ return ['id'];
2901
+ }
2902
+ }
2903
+
2246
2904
  var FilterType;
2247
2905
  (function (FilterType) {
2248
2906
  FilterType["ACCESSORY_IMPORTANCE"] = "accessoryImportance";
@@ -2381,32 +3039,6 @@ class ShopSettings extends BaseModel {
2381
3039
  }
2382
3040
  }
2383
3041
 
2384
- class InvalidArgumentError extends CustomError {
2385
- constructor(message) {
2386
- super(message);
2387
- }
2388
- }
2389
-
2390
- class RequiredArgumentError extends CustomError {
2391
- constructor(args) {
2392
- super(`Required arguments: ${args.join(', ')}`);
2393
- this.args = args;
2394
- this.arguments = args;
2395
- }
2396
- }
2397
-
2398
- class NotFoundError extends CustomError {
2399
- constructor(message) {
2400
- super(message);
2401
- }
2402
- }
2403
-
2404
- class DuplicatedResultsError extends CustomError {
2405
- constructor(message) {
2406
- super(message);
2407
- }
2408
- }
2409
-
2410
3042
  class AxiosAdapter {
2411
3043
  constructor(config) {
2412
3044
  this.config = config;
@@ -3305,6 +3937,17 @@ class LogFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore
3305
3937
  }
3306
3938
  }
3307
3939
 
3940
+ class SequenceFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3941
+ constructor({ firestore, interceptors }) {
3942
+ super({
3943
+ firestore,
3944
+ collectionName: 'sequences',
3945
+ model: Sequence,
3946
+ interceptors,
3947
+ });
3948
+ }
3949
+ }
3950
+
3308
3951
  class HomeFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3309
3952
  constructor({ firestore, interceptors }) {
3310
3953
  super({
@@ -4446,7 +5089,6 @@ const withFindHasuraGraphQL = (MixinBase) => {
4446
5089
  return class FindHasuraGraphQLMixin extends MixinBase {
4447
5090
  constructor() {
4448
5091
  super(...arguments);
4449
- this.lastDistinct = {};
4450
5092
  this.bindOrderByAttributes = (orderBy, fields) => Object.keys(orderBy).reduce((acc, current) => [
4451
5093
  ...acc,
4452
5094
  {
@@ -4482,10 +5124,9 @@ const withFindHasuraGraphQL = (MixinBase) => {
4482
5124
  });
4483
5125
  }
4484
5126
  async find(params) {
4485
- var _a, _b, _c, _d, _e, _f, _g;
5127
+ var _a, _b, _c, _d, _e, _f, _g, _h;
4486
5128
  this.logger = DebugHelper.from(this, 'find');
4487
5129
  const { filters, limits, orderBy, options } = params || {};
4488
- const tableFiltersNamed = `${this.tableName}:${JSON.stringify(filters)}`;
4489
5130
  const enableCount = (_a = options === null || options === void 0 ? void 0 : options.enableCount) !== null && _a !== void 0 ? _a : true;
4490
5131
  const variablesFilters = isNil(filters)
4491
5132
  ? {}
@@ -4536,8 +5177,8 @@ const withFindHasuraGraphQL = (MixinBase) => {
4536
5177
  },
4537
5178
  ]
4538
5179
  : []),
4539
- ...((!this.lastDistinct[tableFiltersNamed] &&
4540
- ((_c = (_b = params.options) === null || _b === void 0 ? void 0 : _b.distinct) === null || _c === void 0 ? void 0 : _c.map((distinct) => {
5180
+ ...((!((_b = params.limits) === null || _b === void 0 ? void 0 : _b.offset) &&
5181
+ ((_d = (_c = params.options) === null || _c === void 0 ? void 0 : _c.distinct) === null || _d === void 0 ? void 0 : _d.map((distinct) => {
4541
5182
  var _a, _b;
4542
5183
  const distinctOption = (_a = this.fields.find((fieldOption) => fieldOption === distinct)) !== null && _a !== void 0 ? _a : this.fields.find((fieldOption) => Object.keys(fieldOption).shift() === distinct);
4543
5184
  const fieldName = ((_b = Object.values(distinctOption).shift()) === null || _b === void 0 ? void 0 : _b.columnName) || distinct;
@@ -4558,27 +5199,28 @@ const withFindHasuraGraphQL = (MixinBase) => {
4558
5199
  []),
4559
5200
  ]);
4560
5201
  const data = result[this.tableName].map((row) => this.convertDataFromHasura(row));
4561
- return Object.assign(Object.assign(Object.assign({ data, count: enableCount ? result[`${this.tableName}_aggregate`].aggregate.count : Infinity }, (((_d = options === null || options === void 0 ? void 0 : options.minimal) === null || _d === void 0 ? void 0 : _d.length)
5202
+ return Object.assign(Object.assign(Object.assign({ data, count: enableCount ? result[`${this.tableName}_aggregate`].aggregate.count : Infinity }, (((_e = options === null || options === void 0 ? void 0 : options.minimal) === null || _e === void 0 ? void 0 : _e.length)
4562
5203
  ? {
4563
5204
  minimal: options.minimal.reduce((minimals, current) => {
4564
5205
  var _a;
4565
5206
  return (Object.assign(Object.assign({}, minimals), set(minimals, current, result[`${this.tableName}_aggregate`].aggregate.min[((_a = AttributeOptionHelper.FindByAttribute(current.toString().split('.').pop(), this.fields)) === null || _a === void 0 ? void 0 : _a.columnName) || current])));
4566
5207
  }, {}),
4567
5208
  }
4568
- : {})), (((_e = options === null || options === void 0 ? void 0 : options.maximum) === null || _e === void 0 ? void 0 : _e.length)
5209
+ : {})), (((_f = options === null || options === void 0 ? void 0 : options.maximum) === null || _f === void 0 ? void 0 : _f.length)
4569
5210
  ? {
4570
5211
  maximum: options.maximum.reduce((maximums, current) => {
4571
5212
  var _a;
4572
5213
  return (Object.assign(Object.assign({}, maximums), set(maximums, current, result[`${this.tableName}_aggregate`].aggregate.max[((_a = AttributeOptionHelper.FindByAttribute(current.toString().split('.').pop(), this.fields)) === null || _a === void 0 ? void 0 : _a.columnName) || current])));
4573
5214
  }, {}),
4574
5215
  }
4575
- : {})), (((_f = options === null || options === void 0 ? void 0 : options.distinct) === null || _f === void 0 ? void 0 : _f.length) && {
4576
- distinct: (_g = this.lastDistinct[tableFiltersNamed]) !== null && _g !== void 0 ? _g : (this.lastDistinct[tableFiltersNamed] = options === null || options === void 0 ? void 0 : options.distinct.reduce((distinct, current) => {
5216
+ : {})), (!((_g = params.limits) === null || _g === void 0 ? void 0 : _g.offset) &&
5217
+ ((_h = options === null || options === void 0 ? void 0 : options.distinct) === null || _h === void 0 ? void 0 : _h.length) && {
5218
+ distinct: options === null || options === void 0 ? void 0 : options.distinct.reduce((distinct, current) => {
4577
5219
  var _a, _b;
4578
5220
  const distinctOption = (_a = this.fields.find((fieldOption) => fieldOption === current)) !== null && _a !== void 0 ? _a : this.fields.find((fieldOption) => Object.keys(fieldOption).shift() === current);
4579
5221
  const fieldName = ((_b = Object.values(distinctOption).shift()) === null || _b === void 0 ? void 0 : _b.columnName) || current;
4580
5222
  return Object.assign(Object.assign({}, distinct), { [current.toString()]: result[`${this.tableName}_${current.toString()}_distinct`].map((obj) => obj[fieldName]) });
4581
- }, {})),
5223
+ }, {}),
4582
5224
  }));
4583
5225
  }
4584
5226
  };
@@ -6601,4 +7243,4 @@ class ProductsVertexSearch {
6601
7243
  }
6602
7244
  }
6603
7245
 
6604
- 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, Checkout, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, ClassNameHelper, ConnectBaseDocumentSnapshot, ConnectCollectionService, ConnectDocumentService, ConnectFirestoreService, Coupon, CouponCategory, CouponFirestoreRepository, 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, 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 };
7246
+ export { AccessoryImportances, Address, AdyenCardService, AdyenPaymentMethodFactory, AntifraudBankSlipService, AntifraudCardService, AntifraudGlampointsService, AntifraudPixService, AntifraudProviderFactory, AntifraudProviders, Area, Authentication, AuthenticationFirebaseAuthService, AxiosAdapter, Base, BaseModel, BeardProblems, BeardSizes, BeautyProductImportances, BeautyProfile, BeautyQuestionsHelper, BillingStatus, BodyProblems, BodyShapes, BodyTattoos, BusinessError, Buy2Win, Buy2WinFirestoreRepository, Campaign, CampaignBanner, CampaignDashboard, CampaignDashboardFirestoreRepository, CampaignHashtag, CampaignHashtagFirestoreRepository, Category, CategoryCollectionChildren, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryFilter, CategoryFilterHasuraGraphQLRepository, CategoryFirestoreRepository, CategoryHasuraGraphQL, CategoryHasuraGraphQLRepository, Checkout, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, ClassNameHelper, ConnectBaseDocumentSnapshot, ConnectCollectionService, ConnectDocumentService, ConnectFirestoreService, Coupon, CouponCategory, CouponFirestoreRepository, 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, OrderFirestoreRepository, OrderStatus, PagarmeBankSlipService, PagarmeCardService, PagarmePaymentMethodFactory, PagarmePixService, Payment, PaymentError, PaymentFirestoreRepository, PaymentMethods, PaymentProviderFactory, PaymentProviders, PaymentTransaction, PaymentType, PersonTypes, Plans, Product, ProductFirestoreRepository, ProductHasuraGraphQL, ProductHasuraGraphQLRepository, 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 };