@infrab4a/connect-nestjs 1.7.2 → 1.8.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs.d.ts CHANGED
@@ -1 +1 @@
1
- export * from "./src/index";
1
+ export * from "./src\\index";
package/index.cjs.js CHANGED
@@ -5,10 +5,15 @@ Object.defineProperty(exports, '__esModule', { value: true });
5
5
  var elasticsearch = require('@elastic/elasticsearch');
6
6
  var connect = require('@infrab4a/connect');
7
7
  var common = require('@nestjs/common');
8
+ var pagarme = require('pagarme');
8
9
  var discoveryengine = require('@google-cloud/discoveryengine');
9
10
  var v1beta = require('@google-cloud/discoveryengine/build/src/v1beta');
10
11
  var nestjsFirebase = require('nestjs-firebase');
11
12
 
13
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
14
+
15
+ var pagarme__default = /*#__PURE__*/_interopDefaultLegacy(pagarme);
16
+
12
17
  const ES_CONFIG = 'ES_CONFIG';
13
18
 
14
19
  const HASURA_OPTIONS = 'HASURA_OPTIONS';
@@ -290,6 +295,279 @@ class ConnectFirestoreService {
290
295
  }
291
296
  }
292
297
 
298
+ class PagarmeBankSlipAPIService {
299
+ constructor(credentials, paymentRepository) {
300
+ this.credentials = credentials;
301
+ this.paymentRepository = paymentRepository;
302
+ }
303
+ async pay(checkout) {
304
+ try {
305
+ const client = await pagarme__default["default"].client.connect({ api_key: this.credentials.API_KEY });
306
+ const result = client.transactions.create(Object.assign({}, this.createBoletoPayment(checkout)));
307
+ if (result.data.status !== connect.PagarmePaymentStatus['Em processamento']) {
308
+ return Promise.reject(new connect.PaymentError(`Houve uma falha ao gerar o boleto. Tente novamente`, {
309
+ checkoutId: checkout.id,
310
+ userEmail: checkout.user.email,
311
+ info: result.data,
312
+ }));
313
+ }
314
+ const payment = await this.paymentRepository.create(connect.Payment.toInstance({
315
+ createdAt: new Date(),
316
+ updatedAt: new Date(),
317
+ userId: checkout.user.id,
318
+ checkoutId: checkout.id,
319
+ totalPrice: checkout.totalPrice,
320
+ paymentProvider: 'pagarMe',
321
+ transaction: result.data,
322
+ }));
323
+ return payment;
324
+ }
325
+ catch (error) {
326
+ throw new connect.PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
327
+ checkoutId: checkout.id,
328
+ userEmail: checkout.user.email,
329
+ info: error,
330
+ });
331
+ }
332
+ }
333
+ async getBoletoTransaction(paymentId) {
334
+ try {
335
+ const client = await pagarme__default["default"].client.connect({ api_key: this.credentials.API_KEY });
336
+ const result = client.transactions.find({ id: paymentId });
337
+ return result;
338
+ }
339
+ catch (error) {
340
+ throw new connect.BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
341
+ paymentId,
342
+ info: error,
343
+ });
344
+ }
345
+ }
346
+ createBoletoPayment(checkout) {
347
+ return {
348
+ api_key: this.credentials.API_KEY,
349
+ amount: Math.floor(checkout.totalPrice * 100),
350
+ boleto_rules: ['strict_expiration_date'],
351
+ boleto_instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
352
+ boleto_expiration_date: connect.format(connect.addDays(new Date(), 3), 'yyyy-MM-dd'),
353
+ payment_method: 'boleto',
354
+ postback_url: this.credentials.URL_POSTBACK,
355
+ customer: {
356
+ external_id: checkout.user.id,
357
+ type: 'individual',
358
+ country: 'br',
359
+ name: checkout.user.displayName,
360
+ documents: [
361
+ {
362
+ type: 'cpf',
363
+ number: checkout.user.cpf,
364
+ },
365
+ ],
366
+ },
367
+ };
368
+ }
369
+ }
370
+
371
+ class PagarmeCardAPIService {
372
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
373
+ this.credentials = credentials;
374
+ this.paymentRepository = paymentRepository;
375
+ this.orderBlockedRepository = orderBlockedRepository;
376
+ }
377
+ async pay(checkout, card) {
378
+ try {
379
+ const client = await pagarme__default["default"].client.connect({ api_key: this.credentials.API_KEY });
380
+ const result = client.transactions.create(Object.assign({}, this.createCardPayment(checkout, card)));
381
+ if (result.data.status !== connect.PagarmePaymentStatus.Pago) {
382
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
383
+ return Promise.reject(new connect.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`, {
384
+ checkoutId: checkout.id,
385
+ userEmail: checkout.user.email,
386
+ info: result.data,
387
+ }));
388
+ }
389
+ const payment = await this.paymentRepository.create(connect.Payment.toInstance({
390
+ createdAt: new Date(),
391
+ updatedAt: new Date(),
392
+ userId: checkout.user.id,
393
+ checkoutId: checkout.id,
394
+ totalPrice: checkout.totalPrice,
395
+ paymentProvider: connect.PaymentProviders.PAGARME,
396
+ transaction: Object.assign(Object.assign({}, result.data), { paidAt: new Date() }),
397
+ }));
398
+ return payment;
399
+ }
400
+ catch (error) {
401
+ throw new connect.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', {
402
+ checkoutId: checkout.id,
403
+ userEmail: checkout.user.email,
404
+ info: error,
405
+ });
406
+ }
407
+ }
408
+ async addCard(card) {
409
+ try {
410
+ const client = await pagarme__default["default"].client.connect({ api_key: this.credentials.API_KEY });
411
+ const result = client.cards.create({
412
+ card_number: card.number,
413
+ card_expiration_date: card.expirationDate.replace('/', ''),
414
+ card_holder_name: card.name,
415
+ card_cvv: card.cvv,
416
+ });
417
+ return result;
418
+ }
419
+ catch (error) {
420
+ throw new connect.BusinessError('Houve uma falha adicionar o cartão', {
421
+ info: error,
422
+ });
423
+ }
424
+ }
425
+ async createCardHash(bu, card) {
426
+ try {
427
+ const client = await pagarme__default["default"].client.connect({ api_key: this.credentials.API_KEY });
428
+ const result = await client.security.encrypt({
429
+ card_number: card.number,
430
+ card_expiration_date: card.expirationDate.replace('/', ''),
431
+ card_holder_name: card.name,
432
+ card_cvv: card.cvv,
433
+ });
434
+ return result;
435
+ }
436
+ catch (error) {
437
+ throw new connect.BusinessError('Houve uma falha ao gerar o hash do cartão', {
438
+ info: error,
439
+ });
440
+ }
441
+ }
442
+ async getCardByToken(id) {
443
+ try {
444
+ const client = await pagarme__default["default"].client.connect({ api_key: this.credentials.API_KEY });
445
+ const result = client.cards.find({
446
+ id,
447
+ });
448
+ return result;
449
+ }
450
+ catch (error) {
451
+ throw new connect.BusinessError('Houve uma falha buscar o cartão com id: ' + id, {
452
+ info: error,
453
+ });
454
+ }
455
+ }
456
+ async createTransaction(data) {
457
+ try {
458
+ const client = await pagarme__default["default"].client.connect({ api_key: this.credentials.API_KEY });
459
+ const result = await client.transactions.create(data);
460
+ return result;
461
+ }
462
+ catch (error) {
463
+ throw new connect.BusinessError('Houve uma falha ao criar a transação', {
464
+ info: error,
465
+ });
466
+ }
467
+ }
468
+ createCardPayment(checkout, card) {
469
+ var _a, _b, _c, _d, _e, _f;
470
+ return {
471
+ api_key: this.credentials.API_KEY,
472
+ amount: Math.floor(checkout.totalPrice * 100),
473
+ card_id: card.cardId,
474
+ payment_method: 'credit_card',
475
+ installments: card.installments,
476
+ soft_descriptor: checkout.shop === connect.Shops.GLAMSHOP ? 'Glam' : "Men's Market",
477
+ customer: {
478
+ external_id: checkout.user.id,
479
+ name: checkout.user.displayName,
480
+ type: 'individual',
481
+ country: 'br',
482
+ email: checkout.user.email,
483
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
484
+ documents: [
485
+ {
486
+ type: 'cpf',
487
+ number: checkout.user.cpf,
488
+ },
489
+ ],
490
+ },
491
+ billing: {
492
+ name: checkout.user.displayName,
493
+ address: {
494
+ country: 'br',
495
+ state: checkout.billingAddress ? checkout.billingAddress.state : (_a = checkout.shippingAddress) === null || _a === void 0 ? void 0 : _a.state,
496
+ city: checkout.billingAddress ? checkout.billingAddress.city : (_b = checkout.shippingAddress) === null || _b === void 0 ? void 0 : _b.city,
497
+ neighborhood: checkout.billingAddress ? checkout.billingAddress.district : (_c = checkout.shippingAddress) === null || _c === void 0 ? void 0 : _c.district,
498
+ street: checkout.billingAddress ? checkout.billingAddress.street : (_d = checkout.shippingAddress) === null || _d === void 0 ? void 0 : _d.street,
499
+ street_number: checkout.billingAddress ? checkout.billingAddress.number : (_e = checkout.shippingAddress) === null || _e === void 0 ? void 0 : _e.number,
500
+ zipcode: checkout.billingAddress
501
+ ? checkout.billingAddress.zip.replace('-', '')
502
+ : (_f = checkout.shippingAddress) === null || _f === void 0 ? void 0 : _f.zip.replace('-', ''),
503
+ },
504
+ },
505
+ items: checkout.lineItems.map((item) => {
506
+ return {
507
+ id: item.id,
508
+ title: checkout.user.isSubscriber ? `${item.name} - ASSINANTE` : item.name,
509
+ unit_price: Math.floor(item.pricePaid * 100),
510
+ quantity: item.quantity,
511
+ tangible: true,
512
+ };
513
+ }),
514
+ };
515
+ }
516
+ }
517
+
518
+ class PagarmePixAPIService {
519
+ constructor(credentials, paymentRepository) {
520
+ this.credentials = credentials;
521
+ this.paymentRepository = paymentRepository;
522
+ }
523
+ async pay(checkout) {
524
+ try {
525
+ const client = await pagarme__default["default"].client.connect({ api_key: this.credentials.API_KEY });
526
+ const result = client.transactions.create(Object.assign({}, this.createPixPayment(checkout)));
527
+ const payment = await this.paymentRepository.create(connect.Payment.toInstance({
528
+ createdAt: new Date(),
529
+ updatedAt: new Date(),
530
+ userId: checkout.user.id,
531
+ checkoutId: checkout.id,
532
+ totalPrice: checkout.totalPrice,
533
+ paymentProvider: 'pagarMe',
534
+ transaction: Object.assign(Object.assign({}, result.data), { paidAt: new Date() }),
535
+ }));
536
+ return payment;
537
+ }
538
+ catch (error) {
539
+ throw new connect.PaymentError('Houve uma falha ao processar pagamento com pix', {
540
+ checkoutId: checkout.id,
541
+ userEmail: checkout.user.email,
542
+ info: error,
543
+ });
544
+ }
545
+ }
546
+ createPixPayment(checkout) {
547
+ return {
548
+ payment_method: 'pix',
549
+ amount: Math.floor(checkout.totalPrice * 100),
550
+ api_key: this.credentials.API_KEY,
551
+ postback_url: this.credentials.URL_POSTBACK,
552
+ pix_expiration_date: connect.format(connect.addDays(new Date(), 1), 'yyyy-MM-dd'),
553
+ customer: {
554
+ external_id: checkout.user.id,
555
+ type: 'individual',
556
+ country: 'br',
557
+ name: checkout.user.displayName,
558
+ email: checkout.user.email.trim(),
559
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
560
+ documents: [
561
+ {
562
+ type: 'cpf',
563
+ number: checkout.user.cpf,
564
+ },
565
+ ],
566
+ },
567
+ };
568
+ }
569
+ }
570
+
293
571
  class ProductVertexHelper {
294
572
  constructor() { }
295
573
  static productMapper(product) {
@@ -709,6 +987,13 @@ exports.NestFirestoreModule = NestFirestoreModule_1 = __decorate([
709
987
  },
710
988
  inject: ['FirestoreOptions'],
711
989
  },
990
+ {
991
+ provide: 'SequenceRepository',
992
+ useFactory: (options) => {
993
+ return new connect.SequenceFirestoreRepository(options);
994
+ },
995
+ inject: ['FirestoreOptions'],
996
+ },
712
997
  ],
713
998
  exports: [
714
999
  'BeautyProfileRepository',
@@ -952,5 +1237,8 @@ exports.ConnectFirestoreService = ConnectFirestoreService;
952
1237
  exports.ES_CONFIG = ES_CONFIG;
953
1238
  exports.FIREBASE_STORAGE = FIREBASE_STORAGE;
954
1239
  exports.HASURA_OPTIONS = HASURA_OPTIONS;
1240
+ exports.PagarmeBankSlipAPIService = PagarmeBankSlipAPIService;
1241
+ exports.PagarmeCardAPIService = PagarmeCardAPIService;
1242
+ exports.PagarmePixAPIService = PagarmePixAPIService;
955
1243
  exports.ProductVertexHelper = ProductVertexHelper;
956
1244
  exports.VERTEX_CONFIG = VERTEX_CONFIG;
package/index.esm.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Client } from '@elastic/elasticsearch';
2
- import { DebugHelper, isEmpty, NotFoundError, ProductsIndex, UserBeautyProfileFirestoreRepository, Buy2WinFirestoreRepository, CategoryFirestoreRepository, CheckoutFirestoreRepository, CheckoutSubscriptionFirestoreRepository, CouponFirestoreRepository, CampaignHashtagFirestoreRepository, CampaignDashboardFirestoreRepository, SubscriptionEditionFirestoreRepository, HomeFirestoreRepository, LeadFirestoreRepository, LegacyOrderFirestoreRepository, ShopMenuFirestoreRepository, OrderFirestoreRepository, PaymentFirestoreRepository, ProductFirestoreRepository, ShopSettingsFirestoreRepository, SubscriptionPaymentFirestoreRepository, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionFirestoreRepository, UserFirestoreRepository, UserAddressFirestoreRepository, UserPaymentMethodFirestoreRepository, SubscriptionMaterializationFirestoreRepository, SubscriptionSummaryFirestoreRepository, ProductVariantFirestoreRepository, OrderBlockedFirestoreRepository, LogFirestoreRepository, CategoryHasuraGraphQLRepository, ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository, ProductReviewsHasuraGraphQLRepository, VariantHasuraGraphQLRepository, ProductStockNotificationHasuraGraphQLRepository, FilterOptionHasuraGraphQLRepository, FilterHasuraGraphQLRepository, CategoryCollectionChildrenHasuraGraphQLRepository, WishlistHasuraGraphQLRepository, ProductsVertexSearch, isNil } from '@infrab4a/connect';
2
+ import { DebugHelper, isEmpty, NotFoundError, PagarmePaymentStatus, PaymentError, Payment, BusinessError, format, addDays, PaymentProviders, Shops, ProductsIndex, UserBeautyProfileFirestoreRepository, Buy2WinFirestoreRepository, CategoryFirestoreRepository, CheckoutFirestoreRepository, CheckoutSubscriptionFirestoreRepository, CouponFirestoreRepository, CampaignHashtagFirestoreRepository, CampaignDashboardFirestoreRepository, SubscriptionEditionFirestoreRepository, HomeFirestoreRepository, LeadFirestoreRepository, LegacyOrderFirestoreRepository, ShopMenuFirestoreRepository, OrderFirestoreRepository, PaymentFirestoreRepository, ProductFirestoreRepository, ShopSettingsFirestoreRepository, SubscriptionPaymentFirestoreRepository, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionFirestoreRepository, UserFirestoreRepository, UserAddressFirestoreRepository, UserPaymentMethodFirestoreRepository, SubscriptionMaterializationFirestoreRepository, SubscriptionSummaryFirestoreRepository, ProductVariantFirestoreRepository, OrderBlockedFirestoreRepository, LogFirestoreRepository, SequenceFirestoreRepository, CategoryHasuraGraphQLRepository, ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository, ProductReviewsHasuraGraphQLRepository, VariantHasuraGraphQLRepository, ProductStockNotificationHasuraGraphQLRepository, FilterOptionHasuraGraphQLRepository, FilterHasuraGraphQLRepository, CategoryCollectionChildrenHasuraGraphQLRepository, WishlistHasuraGraphQLRepository, ProductsVertexSearch, isNil } from '@infrab4a/connect';
3
3
  import { Injectable, Inject, Module } from '@nestjs/common';
4
+ import pagarme from 'pagarme';
4
5
  import { DocumentServiceClient } from '@google-cloud/discoveryengine';
5
6
  import { SearchServiceClient } from '@google-cloud/discoveryengine/build/src/v1beta';
6
7
  import { FirebaseConstants, FirebaseModule } from 'nestjs-firebase';
@@ -286,6 +287,279 @@ class ConnectFirestoreService {
286
287
  }
287
288
  }
288
289
 
290
+ class PagarmeBankSlipAPIService {
291
+ constructor(credentials, paymentRepository) {
292
+ this.credentials = credentials;
293
+ this.paymentRepository = paymentRepository;
294
+ }
295
+ async pay(checkout) {
296
+ try {
297
+ const client = await pagarme.client.connect({ api_key: this.credentials.API_KEY });
298
+ const result = client.transactions.create(Object.assign({}, this.createBoletoPayment(checkout)));
299
+ if (result.data.status !== PagarmePaymentStatus['Em processamento']) {
300
+ return Promise.reject(new PaymentError(`Houve uma falha ao gerar o boleto. Tente novamente`, {
301
+ checkoutId: checkout.id,
302
+ userEmail: checkout.user.email,
303
+ info: result.data,
304
+ }));
305
+ }
306
+ const payment = await this.paymentRepository.create(Payment.toInstance({
307
+ createdAt: new Date(),
308
+ updatedAt: new Date(),
309
+ userId: checkout.user.id,
310
+ checkoutId: checkout.id,
311
+ totalPrice: checkout.totalPrice,
312
+ paymentProvider: 'pagarMe',
313
+ transaction: result.data,
314
+ }));
315
+ return payment;
316
+ }
317
+ catch (error) {
318
+ throw new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
319
+ checkoutId: checkout.id,
320
+ userEmail: checkout.user.email,
321
+ info: error,
322
+ });
323
+ }
324
+ }
325
+ async getBoletoTransaction(paymentId) {
326
+ try {
327
+ const client = await pagarme.client.connect({ api_key: this.credentials.API_KEY });
328
+ const result = client.transactions.find({ id: paymentId });
329
+ return result;
330
+ }
331
+ catch (error) {
332
+ throw new BusinessError('Houve uma falha buscar o boleto com paymentId: ' + paymentId, {
333
+ paymentId,
334
+ info: error,
335
+ });
336
+ }
337
+ }
338
+ createBoletoPayment(checkout) {
339
+ return {
340
+ api_key: this.credentials.API_KEY,
341
+ amount: Math.floor(checkout.totalPrice * 100),
342
+ boleto_rules: ['strict_expiration_date'],
343
+ boleto_instructions: 'Sr. Caixa, NÃO aceitar o pagamento após o vencimento.',
344
+ boleto_expiration_date: format(addDays(new Date(), 3), 'yyyy-MM-dd'),
345
+ payment_method: 'boleto',
346
+ postback_url: this.credentials.URL_POSTBACK,
347
+ customer: {
348
+ external_id: checkout.user.id,
349
+ type: 'individual',
350
+ country: 'br',
351
+ name: checkout.user.displayName,
352
+ documents: [
353
+ {
354
+ type: 'cpf',
355
+ number: checkout.user.cpf,
356
+ },
357
+ ],
358
+ },
359
+ };
360
+ }
361
+ }
362
+
363
+ class PagarmeCardAPIService {
364
+ constructor(credentials, paymentRepository, orderBlockedRepository) {
365
+ this.credentials = credentials;
366
+ this.paymentRepository = paymentRepository;
367
+ this.orderBlockedRepository = orderBlockedRepository;
368
+ }
369
+ async pay(checkout, card) {
370
+ try {
371
+ const client = await pagarme.client.connect({ api_key: this.credentials.API_KEY });
372
+ const result = client.transactions.create(Object.assign({}, this.createCardPayment(checkout, card)));
373
+ if (result.data.status !== PagarmePaymentStatus.Pago) {
374
+ await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
375
+ 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`, {
376
+ checkoutId: checkout.id,
377
+ userEmail: checkout.user.email,
378
+ info: result.data,
379
+ }));
380
+ }
381
+ const payment = await this.paymentRepository.create(Payment.toInstance({
382
+ createdAt: new Date(),
383
+ updatedAt: new Date(),
384
+ userId: checkout.user.id,
385
+ checkoutId: checkout.id,
386
+ totalPrice: checkout.totalPrice,
387
+ paymentProvider: PaymentProviders.PAGARME,
388
+ transaction: Object.assign(Object.assign({}, result.data), { paidAt: new Date() }),
389
+ }));
390
+ return payment;
391
+ }
392
+ catch (error) {
393
+ 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', {
394
+ checkoutId: checkout.id,
395
+ userEmail: checkout.user.email,
396
+ info: error,
397
+ });
398
+ }
399
+ }
400
+ async addCard(card) {
401
+ try {
402
+ const client = await pagarme.client.connect({ api_key: this.credentials.API_KEY });
403
+ const result = client.cards.create({
404
+ card_number: card.number,
405
+ card_expiration_date: card.expirationDate.replace('/', ''),
406
+ card_holder_name: card.name,
407
+ card_cvv: card.cvv,
408
+ });
409
+ return result;
410
+ }
411
+ catch (error) {
412
+ throw new BusinessError('Houve uma falha adicionar o cartão', {
413
+ info: error,
414
+ });
415
+ }
416
+ }
417
+ async createCardHash(bu, card) {
418
+ try {
419
+ const client = await pagarme.client.connect({ api_key: this.credentials.API_KEY });
420
+ const result = await client.security.encrypt({
421
+ card_number: card.number,
422
+ card_expiration_date: card.expirationDate.replace('/', ''),
423
+ card_holder_name: card.name,
424
+ card_cvv: card.cvv,
425
+ });
426
+ return result;
427
+ }
428
+ catch (error) {
429
+ throw new BusinessError('Houve uma falha ao gerar o hash do cartão', {
430
+ info: error,
431
+ });
432
+ }
433
+ }
434
+ async getCardByToken(id) {
435
+ try {
436
+ const client = await pagarme.client.connect({ api_key: this.credentials.API_KEY });
437
+ const result = client.cards.find({
438
+ id,
439
+ });
440
+ return result;
441
+ }
442
+ catch (error) {
443
+ throw new BusinessError('Houve uma falha buscar o cartão com id: ' + id, {
444
+ info: error,
445
+ });
446
+ }
447
+ }
448
+ async createTransaction(data) {
449
+ try {
450
+ const client = await pagarme.client.connect({ api_key: this.credentials.API_KEY });
451
+ const result = await client.transactions.create(data);
452
+ return result;
453
+ }
454
+ catch (error) {
455
+ throw new BusinessError('Houve uma falha ao criar a transação', {
456
+ info: error,
457
+ });
458
+ }
459
+ }
460
+ createCardPayment(checkout, card) {
461
+ var _a, _b, _c, _d, _e, _f;
462
+ return {
463
+ api_key: this.credentials.API_KEY,
464
+ amount: Math.floor(checkout.totalPrice * 100),
465
+ card_id: card.cardId,
466
+ payment_method: 'credit_card',
467
+ installments: card.installments,
468
+ soft_descriptor: checkout.shop === Shops.GLAMSHOP ? 'Glam' : "Men's Market",
469
+ customer: {
470
+ external_id: checkout.user.id,
471
+ name: checkout.user.displayName,
472
+ type: 'individual',
473
+ country: 'br',
474
+ email: checkout.user.email,
475
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
476
+ documents: [
477
+ {
478
+ type: 'cpf',
479
+ number: checkout.user.cpf,
480
+ },
481
+ ],
482
+ },
483
+ billing: {
484
+ name: checkout.user.displayName,
485
+ address: {
486
+ country: 'br',
487
+ state: checkout.billingAddress ? checkout.billingAddress.state : (_a = checkout.shippingAddress) === null || _a === void 0 ? void 0 : _a.state,
488
+ city: checkout.billingAddress ? checkout.billingAddress.city : (_b = checkout.shippingAddress) === null || _b === void 0 ? void 0 : _b.city,
489
+ neighborhood: checkout.billingAddress ? checkout.billingAddress.district : (_c = checkout.shippingAddress) === null || _c === void 0 ? void 0 : _c.district,
490
+ street: checkout.billingAddress ? checkout.billingAddress.street : (_d = checkout.shippingAddress) === null || _d === void 0 ? void 0 : _d.street,
491
+ street_number: checkout.billingAddress ? checkout.billingAddress.number : (_e = checkout.shippingAddress) === null || _e === void 0 ? void 0 : _e.number,
492
+ zipcode: checkout.billingAddress
493
+ ? checkout.billingAddress.zip.replace('-', '')
494
+ : (_f = checkout.shippingAddress) === null || _f === void 0 ? void 0 : _f.zip.replace('-', ''),
495
+ },
496
+ },
497
+ items: checkout.lineItems.map((item) => {
498
+ return {
499
+ id: item.id,
500
+ title: checkout.user.isSubscriber ? `${item.name} - ASSINANTE` : item.name,
501
+ unit_price: Math.floor(item.pricePaid * 100),
502
+ quantity: item.quantity,
503
+ tangible: true,
504
+ };
505
+ }),
506
+ };
507
+ }
508
+ }
509
+
510
+ class PagarmePixAPIService {
511
+ constructor(credentials, paymentRepository) {
512
+ this.credentials = credentials;
513
+ this.paymentRepository = paymentRepository;
514
+ }
515
+ async pay(checkout) {
516
+ try {
517
+ const client = await pagarme.client.connect({ api_key: this.credentials.API_KEY });
518
+ const result = client.transactions.create(Object.assign({}, this.createPixPayment(checkout)));
519
+ const payment = await this.paymentRepository.create(Payment.toInstance({
520
+ createdAt: new Date(),
521
+ updatedAt: new Date(),
522
+ userId: checkout.user.id,
523
+ checkoutId: checkout.id,
524
+ totalPrice: checkout.totalPrice,
525
+ paymentProvider: 'pagarMe',
526
+ transaction: Object.assign(Object.assign({}, result.data), { paidAt: new Date() }),
527
+ }));
528
+ return payment;
529
+ }
530
+ catch (error) {
531
+ throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
532
+ checkoutId: checkout.id,
533
+ userEmail: checkout.user.email,
534
+ info: error,
535
+ });
536
+ }
537
+ }
538
+ createPixPayment(checkout) {
539
+ return {
540
+ payment_method: 'pix',
541
+ amount: Math.floor(checkout.totalPrice * 100),
542
+ api_key: this.credentials.API_KEY,
543
+ postback_url: this.credentials.URL_POSTBACK,
544
+ pix_expiration_date: format(addDays(new Date(), 1), 'yyyy-MM-dd'),
545
+ customer: {
546
+ external_id: checkout.user.id,
547
+ type: 'individual',
548
+ country: 'br',
549
+ name: checkout.user.displayName,
550
+ email: checkout.user.email.trim(),
551
+ phone_numbers: checkout.user.phone ? ['+55' + checkout.user.phone] : '',
552
+ documents: [
553
+ {
554
+ type: 'cpf',
555
+ number: checkout.user.cpf,
556
+ },
557
+ ],
558
+ },
559
+ };
560
+ }
561
+ }
562
+
289
563
  class ProductVertexHelper {
290
564
  constructor() { }
291
565
  static productMapper(product) {
@@ -705,6 +979,13 @@ NestFirestoreModule = NestFirestoreModule_1 = __decorate([
705
979
  },
706
980
  inject: ['FirestoreOptions'],
707
981
  },
982
+ {
983
+ provide: 'SequenceRepository',
984
+ useFactory: (options) => {
985
+ return new SequenceFirestoreRepository(options);
986
+ },
987
+ inject: ['FirestoreOptions'],
988
+ },
708
989
  ],
709
990
  exports: [
710
991
  'BeautyProfileRepository',
@@ -942,4 +1223,4 @@ NestConnectModule = NestConnectModule_1 = __decorate([
942
1223
  Module({})
943
1224
  ], NestConnectModule);
944
1225
 
945
- export { ConnectCollectionService, ConnectDocumentService, ConnectFirestoreService, DiscoveryEngineVertexAdapter, ES_CONFIG, FIREBASE_STORAGE, HASURA_OPTIONS, NativeElasticSearchAdapter, NestConnectModule, NestElasticSeachModule, NestFirestoreModule, NestHasuraGraphQLModule, NestStorageModule, ProductVertexHelper, VERTEX_CONFIG };
1226
+ export { ConnectCollectionService, ConnectDocumentService, ConnectFirestoreService, DiscoveryEngineVertexAdapter, ES_CONFIG, FIREBASE_STORAGE, HASURA_OPTIONS, NativeElasticSearchAdapter, NestConnectModule, NestElasticSeachModule, NestFirestoreModule, NestHasuraGraphQLModule, NestStorageModule, PagarmeBankSlipAPIService, PagarmeCardAPIService, PagarmePixAPIService, ProductVertexHelper, VERTEX_CONFIG };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infrab4a/connect-nestjs",
3
- "version": "1.7.2",
3
+ "version": "1.8.0-beta.1",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org"
6
6
  },
@@ -9,7 +9,7 @@
9
9
  "url": "https://github.com/B4AGroup/b4a-firebase-libs"
10
10
  },
11
11
  "peerDependencies": {
12
- "@infrab4a/connect": "^4.19.0",
12
+ "@infrab4a/connect": "^4.20.0-beta.5",
13
13
  "@nestjs/common": "^10.3.3",
14
14
  "@nestjs/core": "^10.3.3",
15
15
  "firebase-admin": "^12.0.0"
@@ -17,7 +17,8 @@
17
17
  "dependencies": {
18
18
  "@elastic/elasticsearch": "^8.13.1",
19
19
  "@google-cloud/discoveryengine": "^1.14.0",
20
- "nestjs-firebase": "^10.4.0"
20
+ "nestjs-firebase": "^10.4.0",
21
+ "pagarme": "4.35.2"
21
22
  },
22
23
  "exports": {
23
24
  "./package.json": "./package.json",
@@ -1,3 +1,4 @@
1
1
  export * from './elasticsearch';
2
2
  export * from './firebase';
3
+ export * from './pagarme';
3
4
  export * from './vertex-ai';
@@ -0,0 +1 @@
1
+ export * from './services';
@@ -0,0 +1,3 @@
1
+ export * from './pagarme-bank-slip-api.service';
2
+ export * from './pagarme-card-api.service';
3
+ export * from './pagarme-pix-api.service';
@@ -0,0 +1,9 @@
1
+ import { Checkout, PagarmeCredentials, Payment, PaymentProviderBankSlip, PaymentRepository, PaymentTransaction } from '@infrab4a/connect';
2
+ export declare class PagarmeBankSlipAPIService implements PaymentProviderBankSlip {
3
+ private credentials;
4
+ private paymentRepository;
5
+ constructor(credentials: PagarmeCredentials, paymentRepository: PaymentRepository);
6
+ pay(checkout: Checkout): Promise<Payment>;
7
+ getBoletoTransaction(paymentId: number): Promise<PaymentTransaction>;
8
+ private createBoletoPayment;
9
+ }
@@ -0,0 +1,13 @@
1
+ import { BusinessUnitEnum, CardInfo, Checkout, OrderBlockedRepository, PagarMeCard, PagarmeCredentials, Payment, PaymentCardInfo, PaymentProviderCard, PaymentRepository, PaymentTransaction } from '@infrab4a/connect';
2
+ export declare class PagarmeCardAPIService implements PaymentProviderCard<PagarMeCard> {
3
+ private credentials;
4
+ private paymentRepository;
5
+ private orderBlockedRepository;
6
+ constructor(credentials: PagarmeCredentials, paymentRepository: PaymentRepository, orderBlockedRepository: OrderBlockedRepository);
7
+ pay(checkout: Checkout, card: PaymentCardInfo): Promise<Payment>;
8
+ addCard(card: CardInfo): Promise<PagarMeCard>;
9
+ createCardHash(bu: BusinessUnitEnum, card: CardInfo): Promise<string>;
10
+ getCardByToken(id: string): Promise<PagarMeCard>;
11
+ createTransaction(data: any): Promise<PaymentTransaction>;
12
+ private createCardPayment;
13
+ }
@@ -0,0 +1,8 @@
1
+ import { Checkout, PagarmeCredentials, Payment, PaymentProviderPix, PaymentRepository } from '@infrab4a/connect';
2
+ export declare class PagarmePixAPIService implements PaymentProviderPix {
3
+ private credentials;
4
+ private paymentRepository;
5
+ constructor(credentials: PagarmeCredentials, paymentRepository: PaymentRepository);
6
+ pay(checkout: Checkout): Promise<Payment>;
7
+ private createPixPayment;
8
+ }