@infrab4a/connect 4.1.2-beta.1 → 4.1.2-beta.11

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 (38) hide show
  1. package/index.cjs.js +574 -47
  2. package/index.esm.js +563 -48
  3. package/package.json +2 -1
  4. package/src/domain/shopping/enums/index.d.ts +2 -0
  5. package/src/domain/shopping/enums/payment-methods.enum.d.ts +5 -0
  6. package/src/domain/shopping/enums/payment-providers.enum.d.ts +4 -0
  7. package/src/domain/shopping/factories/adyen-payment-method.factory.d.ts +8 -0
  8. package/src/domain/shopping/factories/base-payment-method.factory.d.ts +7 -0
  9. package/src/domain/shopping/factories/glampoints-payment-method.factory.d.ts +8 -0
  10. package/src/domain/shopping/factories/index.d.ts +4 -0
  11. package/src/domain/shopping/factories/pagarme-payment-method.factory.d.ts +10 -0
  12. package/src/domain/shopping/factories/payment-provider.factory.d.ts +14 -0
  13. package/src/domain/shopping/index.d.ts +2 -0
  14. package/src/domain/shopping/interfaces/index.d.ts +6 -0
  15. package/src/domain/shopping/interfaces/payment-method-factory.interface.d.ts +14 -0
  16. package/src/domain/shopping/interfaces/payment-provider-bank-slip.interface.d.ts +5 -0
  17. package/src/domain/shopping/interfaces/payment-provider-card.interface.d.ts +6 -0
  18. package/src/domain/shopping/interfaces/payment-provider-glampoints.interface.d.ts +5 -0
  19. package/src/domain/shopping/interfaces/payment-provider-pix.interface.d.ts +5 -0
  20. package/src/domain/shopping/interfaces/payment-provider.interface.d.ts +6 -0
  21. package/src/domain/shopping/models/index.d.ts +2 -0
  22. package/src/domain/shopping/models/order.d.ts +2 -2
  23. package/src/domain/shopping/models/payment.d.ts +7 -61
  24. package/src/domain/shopping/models/payment.transaction.d.ts +66 -0
  25. package/src/domain/shopping/models/types/index.d.ts +4 -4
  26. package/src/domain/shopping/services/adyen-card-payment.service.d.ts +28 -0
  27. package/src/domain/shopping/services/antifraude.service.d.ts +19 -0
  28. package/src/domain/shopping/services/glampoints-payment.service.d.ts +4 -0
  29. package/src/domain/shopping/services/index.d.ts +6 -0
  30. package/src/domain/shopping/services/pagarme-bank-slip-payment.service.d.ts +8 -0
  31. package/src/domain/shopping/services/pagarme-card-payment.service.d.ts +10 -0
  32. package/src/domain/shopping/services/pagarme-pix-payment.service.d.ts +8 -0
  33. package/src/domain/shopping/types/adyen-credentials.type.d.ts +6 -0
  34. package/src/domain/shopping/types/index.d.ts +5 -0
  35. package/src/domain/shopping/types/pagarme-credentials.type.d.ts +5 -0
  36. package/src/domain/shopping/types/payment-card-info.type.d.ts +4 -0
  37. package/src/domain/shopping/types/payment-method.type.d.ts +2 -0
  38. package/src/domain/shopping/types/payment-provider.type.d.ts +2 -0
package/index.esm.js CHANGED
@@ -12,6 +12,34 @@ import axios from 'axios';
12
12
  import { collection, getDoc, doc, where, orderBy, getDocs, query, startAfter, startAt, limit, addDoc, setDoc, deleteField, arrayUnion, arrayRemove, deleteDoc, Timestamp } from 'firebase/firestore';
13
13
  import { signInWithEmailAndPassword, signInWithPopup, GoogleAuthProvider, signInAnonymously, sendPasswordResetEmail, createUserWithEmailAndPassword, sendEmailVerification } from 'firebase/auth';
14
14
  import { mutation, query as query$1 } from 'gql-query-builder';
15
+ import * as moment from 'moment';
16
+
17
+ class BasePaymentMethodFactory {
18
+ constructor(methods) {
19
+ this.methods = methods;
20
+ }
21
+ build(method) {
22
+ return this.methods[method];
23
+ }
24
+ }
25
+
26
+ class AdyenPaymentMethodFactory extends BasePaymentMethodFactory {
27
+ }
28
+
29
+ class GlampointsPaymentMethodFactory extends BasePaymentMethodFactory {
30
+ }
31
+
32
+ class PagarmePaymentMethodFactory extends BasePaymentMethodFactory {
33
+ }
34
+
35
+ class PaymentProviderFactory {
36
+ constructor(paymentProviders) {
37
+ this.paymentProviders = paymentProviders;
38
+ }
39
+ build(provider) {
40
+ return this.paymentProviders[provider];
41
+ }
42
+ }
15
43
 
16
44
  class BaseModel {
17
45
  get identifier() {
@@ -474,171 +502,178 @@ class Edition extends BaseModel {
474
502
  }
475
503
  }
476
504
 
477
- class Payment extends BaseModel {
478
- static get identifiersFields() {
479
- return ['id'];
480
- }
505
+ class PaymentTransaction extends BaseModel {
481
506
  }
482
507
  __decorate([
483
508
  Expose({ name: 'refuse_reason' }),
484
509
  __metadata("design:type", String)
485
- ], Payment.prototype, "refuseReason", void 0);
510
+ ], PaymentTransaction.prototype, "refuseReason", void 0);
486
511
  __decorate([
487
512
  Expose({ name: 'status_reason' }),
488
513
  __metadata("design:type", String)
489
- ], Payment.prototype, "statusReason", void 0);
514
+ ], PaymentTransaction.prototype, "statusReason", void 0);
490
515
  __decorate([
491
516
  Expose({ name: 'acquirer_response_code' }),
492
517
  __metadata("design:type", String)
493
- ], Payment.prototype, "acquirerResponseCode", void 0);
518
+ ], PaymentTransaction.prototype, "acquirerResponseCode", void 0);
494
519
  __decorate([
495
520
  Expose({ name: 'acquirer_name' }),
496
521
  __metadata("design:type", String)
497
- ], Payment.prototype, "acquirerName", void 0);
522
+ ], PaymentTransaction.prototype, "acquirerName", void 0);
498
523
  __decorate([
499
524
  Expose({ name: 'acquirer_id' }),
500
525
  __metadata("design:type", String)
501
- ], Payment.prototype, "acquirerId", void 0);
526
+ ], PaymentTransaction.prototype, "acquirerId", void 0);
502
527
  __decorate([
503
528
  Expose({ name: 'authorization_code' }),
504
529
  __metadata("design:type", String)
505
- ], Payment.prototype, "authorizationCode", void 0);
530
+ ], PaymentTransaction.prototype, "authorizationCode", void 0);
506
531
  __decorate([
507
532
  Expose({ name: 'soft_descriptor' }),
508
533
  __metadata("design:type", String)
509
- ], Payment.prototype, "softDescriptor", void 0);
534
+ ], PaymentTransaction.prototype, "softDescriptor", void 0);
510
535
  __decorate([
511
536
  Expose({ name: 'date_created' }),
512
537
  __metadata("design:type", String)
513
- ], Payment.prototype, "dateCreated", void 0);
538
+ ], PaymentTransaction.prototype, "dateCreated", void 0);
514
539
  __decorate([
515
540
  Expose({ name: 'date_updated' }),
516
541
  __metadata("design:type", String)
517
- ], Payment.prototype, "dateUpdated", void 0);
542
+ ], PaymentTransaction.prototype, "dateUpdated", void 0);
518
543
  __decorate([
519
544
  Expose({ name: 'authorized_amount' }),
520
545
  __metadata("design:type", Number)
521
- ], Payment.prototype, "authorizedAmount", void 0);
546
+ ], PaymentTransaction.prototype, "authorizedAmount", void 0);
522
547
  __decorate([
523
548
  Expose({ name: 'paid_amount' }),
524
549
  __metadata("design:type", Number)
525
- ], Payment.prototype, "paidAmount", void 0);
550
+ ], PaymentTransaction.prototype, "paidAmount", void 0);
526
551
  __decorate([
527
552
  Expose({ name: 'refunded_amount' }),
528
553
  __metadata("design:type", Number)
529
- ], Payment.prototype, "refundedAmount", void 0);
554
+ ], PaymentTransaction.prototype, "refundedAmount", void 0);
530
555
  __decorate([
531
556
  Expose({ name: 'card_holder_name' }),
532
557
  __metadata("design:type", String)
533
- ], Payment.prototype, "cardHolderName", void 0);
558
+ ], PaymentTransaction.prototype, "cardHolderName", void 0);
534
559
  __decorate([
535
560
  Expose({ name: 'card_last_digits' }),
536
561
  __metadata("design:type", String)
537
- ], Payment.prototype, "cardLastDigits", void 0);
562
+ ], PaymentTransaction.prototype, "cardLastDigits", void 0);
538
563
  __decorate([
539
564
  Expose({ name: 'card_first_digits' }),
540
565
  __metadata("design:type", String)
541
- ], Payment.prototype, "cardFirstDigits", void 0);
566
+ ], PaymentTransaction.prototype, "cardFirstDigits", void 0);
542
567
  __decorate([
543
568
  Expose({ name: 'card_brand' }),
544
569
  __metadata("design:type", String)
545
- ], Payment.prototype, "cardBrand", void 0);
570
+ ], PaymentTransaction.prototype, "cardBrand", void 0);
546
571
  __decorate([
547
572
  Expose({ name: 'card_pin_mode' }),
548
573
  __metadata("design:type", String)
549
- ], Payment.prototype, "cardPinMode", void 0);
574
+ ], PaymentTransaction.prototype, "cardPinMode", void 0);
550
575
  __decorate([
551
576
  Expose({ name: 'card_magstripe_fallback' }),
552
577
  __metadata("design:type", Boolean)
553
- ], Payment.prototype, "cardMagstripeFallback", void 0);
578
+ ], PaymentTransaction.prototype, "cardMagstripeFallback", void 0);
554
579
  __decorate([
555
580
  Expose({ name: 'cvm_pin' }),
556
581
  __metadata("design:type", Boolean)
557
- ], Payment.prototype, "cvmPin", void 0);
582
+ ], PaymentTransaction.prototype, "cvmPin", void 0);
558
583
  __decorate([
559
584
  Expose({ name: 'postback_url' }),
560
585
  __metadata("design:type", String)
561
- ], Payment.prototype, "postbackUrl", void 0);
586
+ ], PaymentTransaction.prototype, "postbackUrl", void 0);
562
587
  __decorate([
563
588
  Expose({ name: 'payment_method' }),
564
589
  __metadata("design:type", String)
565
- ], Payment.prototype, "paymentMethod", void 0);
590
+ ], PaymentTransaction.prototype, "paymentMethod", void 0);
566
591
  __decorate([
567
592
  Expose({ name: 'capture_method' }),
568
593
  __metadata("design:type", String)
569
- ], Payment.prototype, "captureMethod", void 0);
594
+ ], PaymentTransaction.prototype, "captureMethod", void 0);
570
595
  __decorate([
571
596
  Expose({ name: 'antifraud_score' }),
572
597
  __metadata("design:type", String)
573
- ], Payment.prototype, "antifraudScore", void 0);
598
+ ], PaymentTransaction.prototype, "antifraudScore", void 0);
574
599
  __decorate([
575
600
  Expose({ name: 'boleto_url' }),
576
601
  __metadata("design:type", String)
577
- ], Payment.prototype, "boletoUrl", void 0);
602
+ ], PaymentTransaction.prototype, "boletoUrl", void 0);
578
603
  __decorate([
579
604
  Expose({ name: 'boleto_barcode' }),
580
605
  __metadata("design:type", String)
581
- ], Payment.prototype, "boletoBarcode", void 0);
606
+ ], PaymentTransaction.prototype, "boletoBarcode", void 0);
582
607
  __decorate([
583
608
  Expose({ name: 'boleto_expiration_date' }),
584
609
  __metadata("design:type", String)
585
- ], Payment.prototype, "boletoExpirationDate", void 0);
610
+ ], PaymentTransaction.prototype, "boletoExpirationDate", void 0);
586
611
  __decorate([
587
612
  Expose({ name: 'subscription_id' }),
588
613
  __metadata("design:type", String)
589
- ], Payment.prototype, "subscriptionId", void 0);
614
+ ], PaymentTransaction.prototype, "subscriptionId", void 0);
590
615
  __decorate([
591
616
  Expose({ name: 'split_rules' }),
592
617
  __metadata("design:type", String)
593
- ], Payment.prototype, "splitRules", void 0);
618
+ ], PaymentTransaction.prototype, "splitRules", void 0);
594
619
  __decorate([
595
620
  Expose({ name: 'antifraud_metadata' }),
596
621
  __metadata("design:type", Object)
597
- ], Payment.prototype, "antifraudMetadata", void 0);
622
+ ], PaymentTransaction.prototype, "antifraudMetadata", void 0);
598
623
  __decorate([
599
624
  Expose({ name: 'reference_key' }),
600
625
  __metadata("design:type", String)
601
- ], Payment.prototype, "referenceKey", void 0);
626
+ ], PaymentTransaction.prototype, "referenceKey", void 0);
602
627
  __decorate([
603
628
  Expose({ name: 'local_transaction_id' }),
604
629
  __metadata("design:type", String)
605
- ], Payment.prototype, "localTransactionId", void 0);
630
+ ], PaymentTransaction.prototype, "localTransactionId", void 0);
606
631
  __decorate([
607
632
  Expose({ name: 'local_time' }),
608
633
  __metadata("design:type", String)
609
- ], Payment.prototype, "localTime", void 0);
634
+ ], PaymentTransaction.prototype, "localTime", void 0);
610
635
  __decorate([
611
636
  Expose({ name: 'fraud_covered' }),
612
637
  __metadata("design:type", Boolean)
613
- ], Payment.prototype, "fraudCovered", void 0);
638
+ ], PaymentTransaction.prototype, "fraudCovered", void 0);
614
639
  __decorate([
615
640
  Expose({ name: 'fraud_reimbursed' }),
616
641
  __metadata("design:type", String)
617
- ], Payment.prototype, "fraudReimbursed", void 0);
642
+ ], PaymentTransaction.prototype, "fraudReimbursed", void 0);
618
643
  __decorate([
619
644
  Expose({ name: 'order_id' }),
620
645
  __metadata("design:type", String)
621
- ], Payment.prototype, "orderId", void 0);
646
+ ], PaymentTransaction.prototype, "orderId", void 0);
622
647
  __decorate([
623
648
  Expose({ name: 'risk_level' }),
624
649
  __metadata("design:type", String)
625
- ], Payment.prototype, "riskLevel", void 0);
650
+ ], PaymentTransaction.prototype, "riskLevel", void 0);
626
651
  __decorate([
627
652
  Expose({ name: 'receipt_url' }),
628
653
  __metadata("design:type", String)
629
- ], Payment.prototype, "receiptUrl", void 0);
654
+ ], PaymentTransaction.prototype, "receiptUrl", void 0);
630
655
  __decorate([
631
656
  Expose({ name: 'private_label' }),
632
657
  __metadata("design:type", String)
633
- ], Payment.prototype, "privateLabel", void 0);
658
+ ], PaymentTransaction.prototype, "privateLabel", void 0);
634
659
  __decorate([
635
660
  Expose({ name: 'pix_qr_code' }),
636
661
  __metadata("design:type", String)
637
- ], Payment.prototype, "pixQrCode", void 0);
662
+ ], PaymentTransaction.prototype, "pixQrCode", void 0);
638
663
  __decorate([
639
664
  Expose({ name: 'pix_expiration_date' }),
640
665
  __metadata("design:type", String)
641
- ], Payment.prototype, "pixExpirationDate", void 0);
666
+ ], PaymentTransaction.prototype, "pixExpirationDate", void 0);
667
+
668
+ class Payment extends BaseModel {
669
+ static get identifiersFields() {
670
+ return ['id'];
671
+ }
672
+ }
673
+ __decorate([
674
+ Type(() => PaymentTransaction),
675
+ __metadata("design:type", PaymentTransaction)
676
+ ], Payment.prototype, "transaction", void 0);
642
677
 
643
678
  class SubscriptionPayment extends BaseModel {
644
679
  static get identifiersFields() {
@@ -2204,8 +2239,8 @@ var OrderStatus;
2204
2239
  class Order extends Checkout {
2205
2240
  }
2206
2241
  __decorate([
2207
- Type(() => Payment),
2208
- __metadata("design:type", Payment)
2242
+ Type(() => PaymentTransaction),
2243
+ __metadata("design:type", PaymentTransaction)
2209
2244
  ], Order.prototype, "payment", void 0);
2210
2245
 
2211
2246
  class OrderBlocked extends BaseModel {
@@ -2236,6 +2271,486 @@ __decorate([
2236
2271
  __metadata("design:type", Coupon)
2237
2272
  ], CheckoutSubscription.prototype, "coupon", void 0);
2238
2273
 
2274
+ class AdyenCardService {
2275
+ constructor(credentials) {
2276
+ this.credentials = credentials;
2277
+ }
2278
+ async pay(checkout, card) {
2279
+ try {
2280
+ const result = await axios({
2281
+ method: 'POST',
2282
+ url: this.credentials.URL_TRANSACTION,
2283
+ headers: {
2284
+ 'x-api-key': this.credentials.API_KEY,
2285
+ 'content-type': 'application/json',
2286
+ },
2287
+ data: this.createCardPayment(checkout, card),
2288
+ });
2289
+ if (result.data.resultCode !== 'Authorised') {
2290
+ this.checkoutAntiFraudService.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
2291
+ return Promise.reject(new Error(`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`));
2292
+ }
2293
+ const payment = {
2294
+ createdAt: new Date(),
2295
+ updatedAt: new Date(),
2296
+ userId: checkout.user.id,
2297
+ checkoutId: checkout.id,
2298
+ totalPrice: checkout.totalPrice,
2299
+ transaction: Object.assign(Object.assign({}, result.data), { status: 'paid' }),
2300
+ };
2301
+ return payment;
2302
+ }
2303
+ catch (error) { }
2304
+ }
2305
+ createCardPayment(checkout, card) {
2306
+ return {
2307
+ amount: {
2308
+ currency: 'BRL',
2309
+ value: ((checkout === null || checkout === void 0 ? void 0 : checkout.totalPrice) || 0) * 100,
2310
+ },
2311
+ paymentMethod: {
2312
+ type: 'scheme',
2313
+ storedPaymentMethodId: card.cardId,
2314
+ },
2315
+ reference: checkout.id,
2316
+ shopperInteraction: 'Ecommerce',
2317
+ merchantAccount: this.credentials.MERCHANT_ACCOUNT,
2318
+ shopperReference: checkout.user.id,
2319
+ recurringProcessingModel: 'CardOnFile',
2320
+ returnUrl: this.credentials.URL_POSTBACK,
2321
+ installments: {
2322
+ value: card.installments,
2323
+ },
2324
+ };
2325
+ }
2326
+ addCard() {
2327
+ throw new Error('Method not implemented.');
2328
+ }
2329
+ }
2330
+
2331
+ class CheckoutAntiFraudService {
2332
+ constructor(orderRepository, orderBlockedRepository) {
2333
+ this.orderRepository = orderRepository;
2334
+ this.orderBlockedRepository = orderBlockedRepository;
2335
+ this.LIMIT_ORDERS_DAY = 2;
2336
+ this.LIMIT_ORDERS_WEEK = 7;
2337
+ this.LIMIT_BLOCKED_ORDERS_DAY = 5;
2338
+ }
2339
+ async validAntiFraud(checkout, boleto, pix, card) {
2340
+ if (this.couponValidation(checkout))
2341
+ return false;
2342
+ if (pix)
2343
+ return true;
2344
+ if (boleto && !this.verifyBoletoOrder(checkout))
2345
+ return false;
2346
+ if (card && !(await this.verifyBlockedOrderAttempts(checkout, card)))
2347
+ return false;
2348
+ if (card && !(await this.verifyDayAndWeekOrders(checkout, card)))
2349
+ return false;
2350
+ return true;
2351
+ }
2352
+ couponValidation(checkout) {
2353
+ var _a, _b;
2354
+ if (((_a = checkout.coupon) === null || _a === void 0 ? void 0 : _a.nickname) === 'FALHADEPAGAMENTO') {
2355
+ console.error(`Falha de pagamento com cupom. CheckoutId: ${JSON.stringify({
2356
+ checkoutId: checkout.id,
2357
+ user: checkout.user.id,
2358
+ coupon: (_b = checkout.coupon) === null || _b === void 0 ? void 0 : _b.nickname,
2359
+ })}`);
2360
+ return false;
2361
+ }
2362
+ return true;
2363
+ }
2364
+ async verifyDayAndWeekOrders(checkout, card) {
2365
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2366
+ 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'));
2367
+ for (const key in ordersPerDay) {
2368
+ if (ordersPerDay[key] > this.LIMIT_ORDERS_DAY) {
2369
+ await this.createBlockedOrderOrPayment(checkout, 'Order limit', key, 'day');
2370
+ return false;
2371
+ }
2372
+ }
2373
+ 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'));
2374
+ for (const key in ordersPerWeek) {
2375
+ if (ordersPerDay[key] > this.LIMIT_ORDERS_WEEK) {
2376
+ await this.createBlockedOrderOrPayment(checkout, 'Order limit', key, 'week');
2377
+ return false;
2378
+ }
2379
+ }
2380
+ return true;
2381
+ }
2382
+ async validateOrdersByRange(cpf, email, phone, zip, card, range) {
2383
+ const ordersCpf = await this.countOrdersByField('user', 'cpf', cpf, range);
2384
+ const ordersByEmail = await this.countOrdersByField('user', 'email', email, range);
2385
+ const ordersByPhone = await this.countOrdersByField('user', 'phone', phone, range);
2386
+ const ordersByZip = await this.countOrdersByField('shippingAddress', 'zip', zip, range);
2387
+ return {
2388
+ cpf: ordersCpf,
2389
+ email: ordersByEmail,
2390
+ phone: ordersByPhone,
2391
+ zip: ordersByZip,
2392
+ };
2393
+ }
2394
+ async countOrdersByField(property, field, value, range) {
2395
+ const filters = {
2396
+ [property]: {
2397
+ [field]: value,
2398
+ },
2399
+ ['createdAt']: [
2400
+ { operator: Where.GTE, value: range.firstDate },
2401
+ { operator: Where.LTE, value: range.lastDate },
2402
+ ],
2403
+ };
2404
+ const docs = await (await this.orderRepository.find({ filters })).count;
2405
+ return docs;
2406
+ }
2407
+ async verifyBoletoOrder(checkout) {
2408
+ var _a;
2409
+ const maxOrderValue = 5000;
2410
+ if (checkout.totalPrice && checkout.totalPrice > maxOrderValue && !((_a = checkout.user) === null || _a === void 0 ? void 0 : _a.isSubscriber)) {
2411
+ await this.createBlockedOrderOrPayment(checkout, 'Boleto not authorized', 'Boleto', 'day');
2412
+ return false;
2413
+ }
2414
+ return true;
2415
+ }
2416
+ async verifyBlockedOrderAttempts(checkout, card) {
2417
+ var _a, _b, _c, _d;
2418
+ const day = `${moment().format('YYYY-MM-DD')}T00:00:00`;
2419
+ const endOfDay = `${moment().format('YYYY-MM-DD')}T23:59:59`;
2420
+ const ordersBlockedWithCpf = await this.orderBlockedRepository
2421
+ .find({
2422
+ filters: {
2423
+ customer: { cpf: { operator: Where.EQUALS, value: (_a = checkout.user) === null || _a === void 0 ? void 0 : _a.cpf } },
2424
+ date: [
2425
+ { operator: Where.GTE, value: new Date(day) },
2426
+ { operator: Where.LTE, value: new Date(endOfDay) },
2427
+ ],
2428
+ },
2429
+ })
2430
+ .then((data) => data.data);
2431
+ const ordersBlockedWithEmail = await this.orderBlockedRepository
2432
+ .find({
2433
+ filters: {
2434
+ customer: { email: { operator: Where.EQUALS, value: (_b = checkout.user) === null || _b === void 0 ? void 0 : _b.email } },
2435
+ date: [
2436
+ { operator: Where.GTE, value: new Date(day) },
2437
+ { operator: Where.LTE, value: new Date(endOfDay) },
2438
+ ],
2439
+ },
2440
+ })
2441
+ .then((data) => data.data);
2442
+ const ordersBlockedWithCep = await this.orderBlockedRepository
2443
+ .find({
2444
+ filters: {
2445
+ customer: { shippingAddress: { zip: { operator: Where.EQUALS, value: (_c = checkout.shippingAddress) === null || _c === void 0 ? void 0 : _c.zip } } },
2446
+ date: [
2447
+ { operator: Where.GTE, value: new Date(day) },
2448
+ { operator: Where.LTE, value: new Date(endOfDay) },
2449
+ ],
2450
+ },
2451
+ })
2452
+ .then((data) => data.data);
2453
+ const ordersBlockedWithPhone = await this.orderBlockedRepository
2454
+ .find({
2455
+ filters: {
2456
+ customer: { phoneNumber: { operator: Where.EQUALS, value: (_d = checkout.user) === null || _d === void 0 ? void 0 : _d.phone } },
2457
+ date: [
2458
+ { operator: Where.GTE, value: new Date(day) },
2459
+ { operator: Where.LTE, value: new Date(endOfDay) },
2460
+ ],
2461
+ },
2462
+ })
2463
+ .then((data) => data.data);
2464
+ const blockedUniqueEmails = ordersBlockedWithEmail.filter((e) => {
2465
+ var _a;
2466
+ return e.customer.cpf !== ((_a = checkout.user) === null || _a === void 0 ? void 0 : _a.cpf);
2467
+ });
2468
+ const blockedUniqueCeps = ordersBlockedWithCep.filter((e) => {
2469
+ var _a, _b;
2470
+ 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);
2471
+ });
2472
+ const blockedUniquePhone = ordersBlockedWithPhone.filter((e) => {
2473
+ var _a, _b, _c, _d, _e, _f;
2474
+ return (e.customer.cpf !== ((_a = checkout.user) === null || _a === void 0 ? void 0 : _a.cpf) &&
2475
+ e.customer.email !== ((_b = checkout.user) === null || _b === void 0 ? void 0 : _b.email) &&
2476
+ ((_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()));
2477
+ });
2478
+ const blockedAttempts = ordersBlockedWithCpf
2479
+ .concat(blockedUniqueEmails)
2480
+ .concat(blockedUniqueCeps)
2481
+ .concat(blockedUniquePhone);
2482
+ if (blockedAttempts.length >= this.LIMIT_BLOCKED_ORDERS_DAY) {
2483
+ await this.createBlockedOrderOrPayment(checkout, 'More than 5 attempts have failed', 'Failed attempts', 'day', card || null);
2484
+ return false;
2485
+ }
2486
+ return true;
2487
+ }
2488
+ async createBlockedOrderOrPayment(checkout, blockType, type, limiteRange, card = null) {
2489
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2490
+ const paymentBlocked = {
2491
+ customer: {
2492
+ name: ((_a = checkout.user) === null || _a === void 0 ? void 0 : _a.displayName) || '',
2493
+ cpf: ((_b = checkout.user) === null || _b === void 0 ? void 0 : _b.cpf) || '',
2494
+ id: (_c = checkout.user) === null || _c === void 0 ? void 0 : _c.id,
2495
+ email: ((_d = checkout.user) === null || _d === void 0 ? void 0 : _d.email) || '',
2496
+ phoneNumber: '+55' + ((_e = checkout.user) === null || _e === void 0 ? void 0 : _e.phone),
2497
+ isSubscriber: (_f = checkout.user) === null || _f === void 0 ? void 0 : _f.isSubscriber,
2498
+ subscriptionPlan: ((_g = checkout.user) === null || _g === void 0 ? void 0 : _g.subscriptionPlan) || '',
2499
+ shippingAddress: Object.assign(Object.assign({}, checkout.shippingAddress), { zip: this.formatZip((_h = checkout.shippingAddress) === null || _h === void 0 ? void 0 : _h.zip) }),
2500
+ },
2501
+ blockType,
2502
+ limiteRange,
2503
+ type,
2504
+ card,
2505
+ checkout: {
2506
+ id: checkout.id,
2507
+ shop: checkout.shop,
2508
+ total: checkout.totalPrice,
2509
+ },
2510
+ date: new Date(),
2511
+ };
2512
+ await this.orderBlockedRepository.create(paymentBlocked);
2513
+ }
2514
+ getDateRange(range = 'day') {
2515
+ switch (range) {
2516
+ case 'day':
2517
+ return {
2518
+ firstDate: moment().startOf('D').valueOf(),
2519
+ lastDate: moment().endOf('D').valueOf(),
2520
+ };
2521
+ case 'week':
2522
+ return {
2523
+ firstDate: moment().subtract(7, 'd').startOf('D').valueOf(),
2524
+ lastDate: moment().endOf('D').valueOf(),
2525
+ };
2526
+ default:
2527
+ return {
2528
+ firstDate: moment().startOf('D').valueOf(),
2529
+ lastDate: moment().endOf('D').valueOf(),
2530
+ };
2531
+ }
2532
+ }
2533
+ formatZip(zip) {
2534
+ if (zip.length === 8)
2535
+ return zip.substring(0, 5) + '-' + zip.substring(5, 8);
2536
+ return zip;
2537
+ }
2538
+ }
2539
+
2540
+ class GlampointsPaymentService {
2541
+ pay(checkout) {
2542
+ const payment = {
2543
+ createdAt: new Date(),
2544
+ updatedAt: new Date(),
2545
+ userId: checkout.user.id,
2546
+ checkoutId: checkout.id,
2547
+ totalPrice: checkout.totalPrice,
2548
+ transaction: {
2549
+ amount: 0,
2550
+ acquirerResponseCode: '0000',
2551
+ acquirerName: 'glampoints',
2552
+ authorizedAmount: 0,
2553
+ captureMethod: 'ecommerce',
2554
+ installments: 1,
2555
+ cost: 0,
2556
+ paidAmount: 0,
2557
+ paymentMethod: 'glampoints',
2558
+ referer: 'api_key',
2559
+ refundedAmount: 0,
2560
+ status: 'paid',
2561
+ statusReason: 'acquirer',
2562
+ },
2563
+ };
2564
+ return Promise.resolve(payment);
2565
+ }
2566
+ }
2567
+
2568
+ class PagarmeBankSlipService {
2569
+ constructor(credentials) {
2570
+ this.credentials = credentials;
2571
+ }
2572
+ async pay(checkout) {
2573
+ try {
2574
+ const result = await axios({
2575
+ method: 'POST',
2576
+ url: this.credentials.URL_TRANSACTION,
2577
+ data: this.createBoletoPayment(checkout),
2578
+ });
2579
+ if (result.data.status !== 'processing') {
2580
+ console.log('Erro ao gerar o boleto para o checkout: ');
2581
+ return Promise.reject(new Error(`Erro ao gerar o boleto para o checkout: ${checkout.id}`));
2582
+ }
2583
+ const payment = {
2584
+ createdAt: new Date(),
2585
+ updatedAt: new Date(),
2586
+ userId: checkout.user.id,
2587
+ checkoutId: checkout.id,
2588
+ totalPrice: checkout.totalPrice,
2589
+ transaction: result.data,
2590
+ };
2591
+ return payment;
2592
+ }
2593
+ catch (error) {
2594
+ console.log(error);
2595
+ }
2596
+ }
2597
+ createBoletoPayment(checkout) {
2598
+ return {
2599
+ api_key: this.credentials.API_KEY,
2600
+ amount: Math.floor(checkout.totalPrice * 100),
2601
+ boleto_rules: ['strict_expiration_date'],
2602
+ boleto_instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
2603
+ boleto_expiration_date: moment().add(3, 'day').format('YYYY-MM-DD'),
2604
+ payment_method: 'boleto',
2605
+ postback_url: this.credentials.URL_POSTBACK,
2606
+ customer: {
2607
+ external_id: checkout.user.id,
2608
+ type: 'individual',
2609
+ country: 'br',
2610
+ name: checkout.user.displayName,
2611
+ documents: [
2612
+ {
2613
+ type: 'cpf',
2614
+ number: checkout.user.cpf,
2615
+ },
2616
+ ],
2617
+ },
2618
+ };
2619
+ }
2620
+ }
2621
+
2622
+ class PagarmeCardService {
2623
+ constructor(credentials) {
2624
+ this.credentials = credentials;
2625
+ }
2626
+ async pay(checkout, card) {
2627
+ try {
2628
+ const result = await axios({
2629
+ method: 'POST',
2630
+ url: this.credentials.URL_TRANSACTION,
2631
+ data: this.createCardPayment(checkout, card),
2632
+ });
2633
+ if (result.data.status !== 'paid') {
2634
+ this.checkoutAntiFraudService.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
2635
+ return Promise.reject(new Error(`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`));
2636
+ }
2637
+ const payment = {
2638
+ createdAt: new Date(),
2639
+ updatedAt: new Date(),
2640
+ userId: checkout.user.id,
2641
+ checkoutId: checkout.id,
2642
+ totalPrice: checkout.totalPrice,
2643
+ transaction: result.data,
2644
+ };
2645
+ return payment;
2646
+ }
2647
+ catch (error) {
2648
+ console.log(error);
2649
+ }
2650
+ }
2651
+ addCard() {
2652
+ throw new Error('Method not implemented.');
2653
+ }
2654
+ createCardPayment(checkout, card) {
2655
+ var _a, _b, _c, _d, _e, _f;
2656
+ return {
2657
+ api_key: this.credentials.API_KEY,
2658
+ amount: Math.floor(checkout.totalPrice * 100),
2659
+ card_id: card.cardId,
2660
+ payment_method: 'credit_card',
2661
+ installments: card.installments,
2662
+ soft_descriptor: checkout.shop,
2663
+ customer: {
2664
+ external_id: checkout.user.id,
2665
+ name: checkout.user.displayName,
2666
+ type: 'individual',
2667
+ country: 'br',
2668
+ email: checkout.user.email,
2669
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
2670
+ documents: [
2671
+ {
2672
+ type: 'cpf',
2673
+ number: checkout.user.cpf,
2674
+ },
2675
+ ],
2676
+ },
2677
+ billing: {
2678
+ name: checkout.user.displayName,
2679
+ address: {
2680
+ country: 'br',
2681
+ state: checkout.billingAddress ? checkout.billingAddress.state : (_a = checkout.shippingAddress) === null || _a === void 0 ? void 0 : _a.state,
2682
+ city: checkout.billingAddress ? checkout.billingAddress.city : (_b = checkout.shippingAddress) === null || _b === void 0 ? void 0 : _b.city,
2683
+ neighborhood: checkout.billingAddress ? checkout.billingAddress.district : (_c = checkout.shippingAddress) === null || _c === void 0 ? void 0 : _c.district,
2684
+ street: checkout.billingAddress ? checkout.billingAddress.street : (_d = checkout.shippingAddress) === null || _d === void 0 ? void 0 : _d.street,
2685
+ street_number: checkout.billingAddress ? checkout.billingAddress.number : (_e = checkout.shippingAddress) === null || _e === void 0 ? void 0 : _e.number,
2686
+ zipcode: checkout.billingAddress
2687
+ ? checkout.billingAddress.zip.replace('-', '')
2688
+ : (_f = checkout.shippingAddress) === null || _f === void 0 ? void 0 : _f.zip.replace('-', ''),
2689
+ },
2690
+ },
2691
+ items: checkout.lineItems.map((item) => {
2692
+ return {
2693
+ id: item.id,
2694
+ title: checkout.user.isSubscriber ? `${item.name} - ASSINANTE` : item.name,
2695
+ unit_price: Math.floor(item.pricePaid * 100),
2696
+ quantity: item.quantity,
2697
+ tangible: true,
2698
+ };
2699
+ }),
2700
+ };
2701
+ }
2702
+ }
2703
+
2704
+ class PagarmePixService {
2705
+ constructor(credentials) {
2706
+ this.credentials = credentials;
2707
+ }
2708
+ async pay(checkout) {
2709
+ try {
2710
+ const result = await axios({
2711
+ method: 'POST',
2712
+ url: this.credentials.URL_TRANSACTION,
2713
+ data: this.createPixPayment(checkout),
2714
+ });
2715
+ const payment = {
2716
+ createdAt: new Date(),
2717
+ updatedAt: new Date(),
2718
+ userId: checkout.user.id,
2719
+ checkoutId: checkout.id,
2720
+ totalPrice: checkout.totalPrice,
2721
+ transaction: result.data,
2722
+ };
2723
+ return payment;
2724
+ }
2725
+ catch (error) {
2726
+ console.log(error);
2727
+ }
2728
+ }
2729
+ createPixPayment(checkout) {
2730
+ return {
2731
+ payment_method: 'pix',
2732
+ amount: Math.floor(checkout.totalPrice * 100),
2733
+ api_key: this.credentials.API_KEY,
2734
+ postback_url: this.credentials.URL_POSTBACK,
2735
+ pix_expiration_date: moment().add(1, 'day').format('YYYY-MM-DD'),
2736
+ customer: {
2737
+ external_id: checkout.user.id,
2738
+ type: 'individual',
2739
+ country: 'br',
2740
+ name: checkout.user.displayName,
2741
+ email: checkout.user.email.trim(),
2742
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
2743
+ documents: [
2744
+ {
2745
+ type: 'cpf',
2746
+ number: checkout.user.cpf,
2747
+ },
2748
+ ],
2749
+ },
2750
+ };
2751
+ }
2752
+ }
2753
+
2239
2754
  class RoundProductPricesHelper {
2240
2755
  static roundProductPrices(product) {
2241
2756
  product.price.price = Number(product.price.price.toFixed(2));
@@ -2770,7 +3285,7 @@ const withFindFirestore = (MixinBase) => {
2770
3285
  const collection = this.collection(this.buildCollectionPathForFind(find.filters));
2771
3286
  const enableCount = (_b = (_a = find === null || find === void 0 ? void 0 : find.options) === null || _a === void 0 ? void 0 : _a.enableCount) !== null && _b !== void 0 ? _b : true;
2772
3287
  const intercepted = await ((_d = (_c = this.interceptors) === null || _c === void 0 ? void 0 : _c.request) === null || _d === void 0 ? void 0 : _d.call(_c, { find }));
2773
- const { filters, limits, orderBy } = intercepted.find || find;
3288
+ const { filters, limits, orderBy } = (intercepted === null || intercepted === void 0 ? void 0 : intercepted.find) || find;
2774
3289
  const queries = this.makeFirestoreWhere(filters || {});
2775
3290
  const ordination = this.makeFirestoreOrderBy(filters, orderBy);
2776
3291
  const offsets = await this.defineLimits(filters, limits);
@@ -5544,4 +6059,4 @@ class WishlistHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5544
6059
  }
5545
6060
  }
5546
6061
 
5547
- 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, Coupon, CouponFirestoreRepository, CouponSubtypes, CouponTypes, Debug, DebugDecoratorHelper, DebugHelper, DebugNamespaces, DuplicatedResultsError, Edition, EditionStatus, Exclusivities, FaceSkinOilinesses, FaceSkinProblems, FaceSkinTones, FamilyIncomes, Filter, FilterHasuraGraphQLRepository, FilterOption, FilterOptionHasuraGraphQLRepository, FilterType, FragranceImportances, GenderDestination, HairColors, HairProblems, HairStrands, HairTypes, Home, HomeFirestoreRepository, InvalidArgumentError, KitProduct, KitProductHasuraGraphQL, Lead, LeadFirestoreRepository, LegacyOrderFirestoreRepository, LineItem, Log, Logger, NotFoundError, OfficePosition, Order, OrderBlocked, OrderBlockedFirestoreRepository, OrderFirestoreRepository, OrderStatus, Payment, PaymentFirestoreRepository, PaymentType, Product, ProductFirestoreRepository, ProductHasuraGraphQL, ProductHasuraGraphQLRepository, ProductSpents, ProductVariantFirestoreRepository, ProductsIndex, QuestionsFilters, RecoveryPassword, ReflectHelper, Register, RegisterFirebaseAuthService, RequiredArgumentError, RoundProductPricesHelper, Sequence, SequenceFirestoreRepository, ShippingMethod, ShopMenu, ShopMenuFirestoreRepository, ShopPageName, ShopSettings, ShopSettingsFirestoreRepository, Shops, SignInMethods, SignOut, Status, Subscription, SubscriptionEditionFirestoreRepository, SubscriptionFirestoreRepository, SubscriptionPayment, SubscriptionPaymentFirestoreRepository, SubscriptionPlan, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, Trace, UnauthorizedError, UpdateOptionActions, User, UserAddress, UserAddressFirestoreRepository, UserAlreadyRegisteredError, UserBeautyProfileFirestoreRepository, UserFirestoreRepository, UserPaymentMethod, UserPaymentMethodFirestoreRepository, UserType, Variant, VariantHasuraGraphQL, VariantHasuraGraphQLRepository, WeakPasswordError, Where, Wishlist, WishlistHasuraGraphQLRepository, is, isDebuggable, isUUID, parseDateTime, withCreateFirestore, withCreateHasuraGraphQL, withCrudFirestore, withCrudHasuraGraphQL, withDeleteFirestore, withDeleteHasuraGraphQL, withFindFirestore, withFindHasuraGraphQL, withFirestore, withGetFirestore, withGetHasuraGraphQL, withHasuraGraphQL, withHelpers, withSubCollection, withUpdateFirestore, withUpdateHasuraGraphQL };
6062
+ export { AccessoryImportances, Address, AdyenCardService, AdyenPaymentMethodFactory, 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, CheckoutAntiFraudService, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, ClassNameHelper, Coupon, CouponFirestoreRepository, CouponSubtypes, CouponTypes, Debug, DebugDecoratorHelper, DebugHelper, DebugNamespaces, DuplicatedResultsError, Edition, EditionStatus, Exclusivities, FaceSkinOilinesses, FaceSkinProblems, FaceSkinTones, FamilyIncomes, Filter, FilterHasuraGraphQLRepository, FilterOption, FilterOptionHasuraGraphQLRepository, FilterType, FragranceImportances, GenderDestination, GlampointsPaymentMethodFactory, GlampointsPaymentService, HairColors, HairProblems, HairStrands, HairTypes, Home, HomeFirestoreRepository, InvalidArgumentError, KitProduct, KitProductHasuraGraphQL, Lead, LeadFirestoreRepository, LegacyOrderFirestoreRepository, LineItem, Log, Logger, NotFoundError, OfficePosition, Order, OrderBlocked, OrderBlockedFirestoreRepository, OrderFirestoreRepository, OrderStatus, PagarmeBankSlipService, PagarmeCardService, PagarmePaymentMethodFactory, PagarmePixService, Payment, PaymentFirestoreRepository, PaymentProviderFactory, PaymentTransaction, PaymentType, Product, ProductFirestoreRepository, ProductHasuraGraphQL, ProductHasuraGraphQLRepository, ProductSpents, ProductVariantFirestoreRepository, ProductsIndex, QuestionsFilters, RecoveryPassword, ReflectHelper, Register, RegisterFirebaseAuthService, RequiredArgumentError, RoundProductPricesHelper, Sequence, SequenceFirestoreRepository, ShippingMethod, ShopMenu, ShopMenuFirestoreRepository, ShopPageName, ShopSettings, ShopSettingsFirestoreRepository, Shops, SignInMethods, SignOut, Status, Subscription, SubscriptionEditionFirestoreRepository, SubscriptionFirestoreRepository, SubscriptionPayment, SubscriptionPaymentFirestoreRepository, SubscriptionPlan, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, Trace, UnauthorizedError, UpdateOptionActions, User, UserAddress, UserAddressFirestoreRepository, UserAlreadyRegisteredError, UserBeautyProfileFirestoreRepository, UserFirestoreRepository, UserPaymentMethod, UserPaymentMethodFirestoreRepository, UserType, Variant, VariantHasuraGraphQL, VariantHasuraGraphQLRepository, WeakPasswordError, Where, Wishlist, WishlistHasuraGraphQLRepository, is, isDebuggable, isUUID, parseDateTime, withCreateFirestore, withCreateHasuraGraphQL, withCrudFirestore, withCrudHasuraGraphQL, withDeleteFirestore, withDeleteHasuraGraphQL, withFindFirestore, withFindHasuraGraphQL, withFirestore, withGetFirestore, withGetHasuraGraphQL, withHasuraGraphQL, withHelpers, withSubCollection, withUpdateFirestore, withUpdateHasuraGraphQL };