@infrab4a/connect-nestjs 1.11.0 → 1.12.1-alpha.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.
package/index.cjs.js CHANGED
@@ -5,6 +5,7 @@ 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 firestore = require('firebase-admin/firestore');
8
9
  var pagarme = require('pagarme');
9
10
  var discoveryengine = require('@google-cloud/discoveryengine');
10
11
  var v1beta = require('@google-cloud/discoveryengine/build/src/v1beta');
@@ -166,7 +167,7 @@ class ConnectBaseDocumentSnapshot {
166
167
  isNotEmpty() {
167
168
  return this.connectDocumentSnapshot.exists;
168
169
  }
169
- data(options) {
170
+ data(_options) {
170
171
  return this.connectDocumentSnapshot.data();
171
172
  }
172
173
  get(fieldPath) {
@@ -225,13 +226,13 @@ class ConnectCollectionService {
225
226
  return new ConnectDocumentService(newDoc.path, this.firestore).withConverter(this.converter);
226
227
  }
227
228
  async getDocs() {
228
- if (this.startingAt > 0)
229
+ if (this.startingAt)
229
230
  this.limitBy += this.startingAt;
230
231
  let query = this.query ? this.query : this.reference;
231
232
  query = this.orderBy ? query.orderBy(this.orderBy.fieldPath, this.orderBy.directionStr) : query;
232
233
  query = this.limitBy ? query.limit(this.limitBy) : query;
233
234
  return query.get().then((docs) => {
234
- const docsPaginated = this.startingAt > 0 ? docs.docs.slice(this.startingAt, this.limitBy) : docs.docs;
235
+ const docsPaginated = this.startingAt ? docs.docs.slice(this.startingAt, this.limitBy) : docs.docs;
235
236
  return {
236
237
  empty: Boolean(docsPaginated.length),
237
238
  size: docsPaginated.length,
@@ -283,7 +284,7 @@ class ConnectCollectionService {
283
284
  }
284
285
  }
285
286
 
286
- class ConnectFirestoreService {
287
+ exports.ConnectFirestoreService = class ConnectFirestoreService {
287
288
  constructor(firestore) {
288
289
  this.firestore = firestore;
289
290
  }
@@ -293,7 +294,11 @@ class ConnectFirestoreService {
293
294
  getDocument(path) {
294
295
  return new ConnectDocumentService(path, this.firestore);
295
296
  }
296
- }
297
+ };
298
+ exports.ConnectFirestoreService = __decorate([
299
+ common.Injectable(),
300
+ __metadata("design:paramtypes", [firestore.Firestore])
301
+ ], exports.ConnectFirestoreService);
297
302
 
298
303
  class PagarmeBankSlipAPIAdapter {
299
304
  constructor(credentials, paymentRepository) {
@@ -305,10 +310,10 @@ class PagarmeBankSlipAPIAdapter {
305
310
  const client = await pagarme__default["default"].client.connect({ api_key: this.credentials.API_KEY });
306
311
  const payload = this.createBoletoPayment(checkout);
307
312
  const result = await client.transactions.create(payload);
308
- console.log('[PAGARME BOLETO DATA TO SEND]', payload);
309
- console.log('result PagarmeBankSlipAPIAdapter', JSON.stringify(result));
313
+ console.warn('[PAGARME BOLETO DATA TO SEND]', payload);
314
+ console.warn('result PagarmeBankSlipAPIAdapter', JSON.stringify(result));
310
315
  if (result.status !== connect.PagarmePaymentStatus['Em processamento']) {
311
- return Promise.reject(new connect.PaymentError(`Houve uma falha ao gerar o boleto. Tente novamente`, {
316
+ return Promise.reject(new connect.PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
312
317
  checkoutId: checkout.id,
313
318
  userEmail: checkout.user.email,
314
319
  info: result,
@@ -337,7 +342,7 @@ class PagarmeBankSlipAPIAdapter {
337
342
  async getBoletoTransaction(paymentId) {
338
343
  try {
339
344
  const client = await pagarme__default["default"].client.connect({ api_key: this.credentials.API_KEY });
340
- const result = client.transactions.find({ id: paymentId });
345
+ const result = await client.transactions.find({ id: paymentId });
341
346
  return result;
342
347
  }
343
348
  catch (error) {
@@ -380,43 +385,73 @@ class PagarmeCardAPIAdapter {
380
385
  }
381
386
  async pay(checkout, card) {
382
387
  try {
383
- const client = await pagarme__default["default"].client.connect({ api_key: this.credentials.API_KEY });
384
- const payload = this.createCardPayment(checkout, card);
385
- const result = await client.transactions.create(payload);
386
- console.log('[PAGARME CARD DATA TO SEND]', payload);
387
- console.log('result PagarmeCardAPIAdapter', JSON.stringify(result));
388
- if (result.status !== connect.PagarmePaymentStatus.Pago) {
389
- await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
390
- 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`, {
391
- checkoutId: checkout.id,
392
- userEmail: checkout.user.email,
393
- info: result,
394
- }));
395
- }
396
- const payment = await this.paymentRepository.create({
397
- createdAt: new Date(),
398
- updatedAt: new Date(),
399
- userId: checkout.user.id,
400
- checkoutId: checkout.id,
401
- totalPrice: checkout.totalPrice,
402
- paymentProvider: connect.PaymentProviders.PAGARME,
403
- transaction: Object.assign(Object.assign({}, result), { paidAt: new Date() }),
404
- });
405
- return payment;
388
+ const client = await this.createPagarmeClient();
389
+ const transactionResult = await this.executeCardTransaction(client, checkout, card);
390
+ await this.validateTransactionResult(transactionResult, checkout, card);
391
+ return await this.createPaymentRecord(checkout, transactionResult);
406
392
  }
407
393
  catch (error) {
408
- console.error('Error PagarmeCardAPIAdapter', JSON.stringify(error));
409
- 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', {
410
- checkoutId: checkout.id,
411
- userEmail: checkout.user.email,
412
- info: error,
413
- });
394
+ this.handlePaymentError(error, checkout);
395
+ }
396
+ }
397
+ async createPagarmeClient() {
398
+ return await pagarme__default["default"].client.connect({ api_key: this.credentials.API_KEY });
399
+ }
400
+ async executeCardTransaction(client, checkout, card) {
401
+ const payload = this.createCardPayment(checkout, card);
402
+ const result = await client.transactions.create(payload);
403
+ this.logTransactionDetails(payload, result);
404
+ return result;
405
+ }
406
+ logTransactionDetails(payload, result) {
407
+ console.warn('[PAGARME CARD DATA TO SEND]', payload);
408
+ console.warn('result PagarmeCardAPIAdapter', JSON.stringify(result));
409
+ }
410
+ async validateTransactionResult(result, checkout, card) {
411
+ if (result.status !== connect.PagarmePaymentStatus.Pago) {
412
+ await this.handleUnauthorizedPayment(checkout, card, result);
414
413
  }
415
414
  }
415
+ async handleUnauthorizedPayment(checkout, card, result) {
416
+ await this.createBlockedOrderRecord(checkout, card);
417
+ 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', {
418
+ checkoutId: checkout.id,
419
+ userEmail: checkout.user.email,
420
+ info: result,
421
+ });
422
+ }
423
+ async createBlockedOrderRecord(checkout, card) {
424
+ await this.orderBlockedRepository.createBlockedOrderOrPayment({
425
+ checkout,
426
+ blockType: 'Card not authorized',
427
+ type: 'Card',
428
+ limiteRange: 'day',
429
+ card,
430
+ });
431
+ }
432
+ async createPaymentRecord(checkout, transactionResult) {
433
+ return await this.paymentRepository.create({
434
+ createdAt: new Date(),
435
+ updatedAt: new Date(),
436
+ userId: checkout.user.id,
437
+ checkoutId: checkout.id,
438
+ totalPrice: checkout.totalPrice,
439
+ paymentProvider: connect.PaymentProviders.PAGARME,
440
+ transaction: Object.assign(Object.assign({}, transactionResult), { paidAt: new Date() }),
441
+ });
442
+ }
443
+ handlePaymentError(error, checkout) {
444
+ console.error('Error PagarmeCardAPIAdapter', JSON.stringify(error));
445
+ 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', {
446
+ checkoutId: checkout.id,
447
+ userEmail: checkout.user.email,
448
+ info: error,
449
+ });
450
+ }
416
451
  async addCard(card) {
417
452
  try {
418
453
  const client = await pagarme__default["default"].client.connect({ api_key: this.credentials.API_KEY });
419
- const result = client.cards.create({
454
+ const result = await client.cards.create({
420
455
  card_number: card.number,
421
456
  card_expiration_date: card.expirationDate.replace('/', ''),
422
457
  card_holder_name: card.name,
@@ -450,7 +485,7 @@ class PagarmeCardAPIAdapter {
450
485
  async getCardByToken(id) {
451
486
  try {
452
487
  const client = await pagarme__default["default"].client.connect({ api_key: this.credentials.API_KEY });
453
- const result = client.cards.find({
488
+ const result = await client.cards.find({
454
489
  id,
455
490
  });
456
491
  return result;
@@ -534,8 +569,8 @@ class PagarmePixAPIAdapter {
534
569
  const client = await pagarme__default["default"].client.connect({ api_key: this.credentials.API_KEY });
535
570
  const payload = this.createPixPayment(checkout);
536
571
  const result = await client.transactions.create(payload);
537
- console.log('[PAGARME PIX DATA TO SEND]', payload);
538
- console.log('result PagarmePixAPIAdapter', JSON.stringify(result));
572
+ console.warn('[PAGARME PIX DATA TO SEND]', payload);
573
+ console.warn('result PagarmePixAPIAdapter', JSON.stringify(result));
539
574
  const payment = await this.paymentRepository.create({
540
575
  createdAt: new Date(),
541
576
  updatedAt: new Date(),
@@ -548,7 +583,7 @@ class PagarmePixAPIAdapter {
548
583
  return payment;
549
584
  }
550
585
  catch (error) {
551
- console.log('Error PagarmePixAPIAdapter', JSON.stringify(error));
586
+ console.error('Error PagarmePixAPIAdapter', JSON.stringify(error));
552
587
  throw new connect.PaymentError('Houve uma falha ao processar pagamento com pix', {
553
588
  checkoutId: checkout.id,
554
589
  userEmail: checkout.user.email,
@@ -632,8 +667,12 @@ class ProductVertexHelper {
632
667
  exports.DiscoveryEngineVertexAdapter = class DiscoveryEngineVertexAdapter {
633
668
  constructor(configuration) {
634
669
  this.config = configuration;
635
- this.parentEngine = `projects/${this.config.projectId}/locations/${this.config.location}/collections/default_collection/engines/${this.config.dataStoreId}`;
636
- this.parentDataStore = `projects/${this.config.projectId}/locations/${this.config.location}/collections/default_collection/dataStores/${this.config.dataStoreId}/branches/default_branch/documents`;
670
+ this.parentEngine =
671
+ `projects/${this.config.projectId}/locations/${this.config.location}/` +
672
+ `collections/default_collection/engines/${this.config.dataStoreId}`;
673
+ this.parentDataStore =
674
+ `projects/${this.config.projectId}/locations/${this.config.location}/` +
675
+ `collections/default_collection/dataStores/${this.config.dataStoreId}/branches/default_branch/documents`;
637
676
  this.searchClient = new v1beta.SearchServiceClient({
638
677
  apiEndpoint: configuration.apiEndpoint,
639
678
  credentials: configuration.credentials,
@@ -672,7 +711,7 @@ exports.DiscoveryEngineVertexAdapter = class DiscoveryEngineVertexAdapter {
672
711
  const response = await this.documentClient.updateDocument(request);
673
712
  return response;
674
713
  }
675
- async query(term, total, gender) {
714
+ async query(term, total) {
676
715
  const response = (await this.searchClient.search({
677
716
  pageSize: total,
678
717
  query: term,
@@ -706,18 +745,19 @@ exports.DiscoveryEngineVertexAdapter = class DiscoveryEngineVertexAdapter {
706
745
  for (let index = 0; index < products.length; index += batchSize) {
707
746
  const bulkProducts = products.slice(index, index + batchSize);
708
747
  const [operation] = await this.documentClient.importDocuments({
709
- parent: `projects/${this.config.projectId}/locations/${this.config.location}/collections/default_collection/dataStores/${this.config.dataStoreId}/branches/default_branch`,
748
+ parent: `projects/${this.config.projectId}/locations/${this.config.location}/` +
749
+ `collections/default_collection/dataStores/${this.config.dataStoreId}/branches/default_branch`,
710
750
  inlineSource: {
711
751
  documents: bulkProducts,
712
752
  },
713
753
  });
714
754
  total += bulkProducts.length;
715
755
  const [response] = await operation.promise();
716
- console.log(`Imported: ${total} documents`, ((total / products.length) * 100).toFixed(2) + '%', `Erros: `, response.errorSamples ? response.errorSamples : []);
756
+ console.warn(`Imported: ${total} documents`, ((total / products.length) * 100).toFixed(2) + '%', 'Erros: ', response.errorSamples ? response.errorSamples : []);
717
757
  }
718
758
  }
719
759
  catch (error) {
720
- console.log(error);
760
+ console.error(error);
721
761
  }
722
762
  }
723
763
  };
@@ -786,8 +826,8 @@ exports.NestFirestoreModule = NestFirestoreModule_1 = __decorate([
786
826
  common.Module({
787
827
  providers: [
788
828
  {
789
- provide: ConnectFirestoreService,
790
- useFactory: (firebaseAdmin) => new ConnectFirestoreService(firebaseAdmin.firestore),
829
+ provide: exports.ConnectFirestoreService,
830
+ useFactory: (firebaseAdmin) => new exports.ConnectFirestoreService(firebaseAdmin.firestore),
791
831
  inject: [nestjsFirebase.FirebaseConstants.FIREBASE_TOKEN],
792
832
  },
793
833
  {
@@ -795,7 +835,7 @@ exports.NestFirestoreModule = NestFirestoreModule_1 = __decorate([
795
835
  useFactory: (connectFirestoreService) => ({
796
836
  firestore: connectFirestoreService,
797
837
  }),
798
- inject: [ConnectFirestoreService],
838
+ inject: [exports.ConnectFirestoreService],
799
839
  },
800
840
  {
801
841
  provide: 'BeautyProfileRepository',
@@ -860,6 +900,13 @@ exports.NestFirestoreModule = NestFirestoreModule_1 = __decorate([
860
900
  },
861
901
  inject: ['FirestoreOptions', 'SubscriptionRepository'],
862
902
  },
903
+ {
904
+ provide: 'GroupRepository',
905
+ useFactory: (options) => {
906
+ return new connect.GroupFirestoreRepository(options);
907
+ },
908
+ inject: ['FirestoreOptions'],
909
+ },
863
910
  {
864
911
  provide: 'HomeRepository',
865
912
  useFactory: (options) => {
@@ -1018,6 +1065,7 @@ exports.NestFirestoreModule = NestFirestoreModule_1 = __decorate([
1018
1065
  'CampaignHashtagRepository',
1019
1066
  'CampaignDashboardRepository',
1020
1067
  'EditionRepository',
1068
+ 'GroupRepository',
1021
1069
  'HomeRepository',
1022
1070
  'LeadRepository',
1023
1071
  'LegacyOrderRepository',
@@ -1039,7 +1087,7 @@ exports.NestFirestoreModule = NestFirestoreModule_1 = __decorate([
1039
1087
  'SubscriptionMaterializationRepository',
1040
1088
  'SubscriptionSummaryRepository',
1041
1089
  connect.ProductVariantFirestoreRepository,
1042
- ConnectFirestoreService,
1090
+ exports.ConnectFirestoreService,
1043
1091
  ],
1044
1092
  })
1045
1093
  ], exports.NestFirestoreModule);
@@ -1276,7 +1324,6 @@ exports.NestConnectModule = NestConnectModule_1 = __decorate([
1276
1324
 
1277
1325
  exports.ConnectCollectionService = ConnectCollectionService;
1278
1326
  exports.ConnectDocumentService = ConnectDocumentService;
1279
- exports.ConnectFirestoreService = ConnectFirestoreService;
1280
1327
  exports.ES_CONFIG = ES_CONFIG;
1281
1328
  exports.FIREBASE_STORAGE = FIREBASE_STORAGE;
1282
1329
  exports.HASURA_OPTIONS = HASURA_OPTIONS;
package/index.esm.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Client } from '@elastic/elasticsearch';
2
- import { DebugHelper, isEmpty, NotFoundError, PagarmePaymentStatus, PaymentError, 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, ProductReviewHasuraGraphQLRepository, VariantHasuraGraphQLRepository, ProductStockNotificationHasuraGraphQLRepository, FilterOptionHasuraGraphQLRepository, FilterHasuraGraphQLRepository, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryProductHasuraGraphQLRepository, WishlistHasuraGraphQLRepository, ProductErrorsHasuraGraphQLRepository, ProductsVertexSearch, isNil } from '@infrab4a/connect';
2
+ import { DebugHelper, isEmpty, NotFoundError, PagarmePaymentStatus, PaymentError, BusinessError, format, addDays, PaymentProviders, Shops, ProductsIndex, UserBeautyProfileFirestoreRepository, Buy2WinFirestoreRepository, CategoryFirestoreRepository, CheckoutFirestoreRepository, CheckoutSubscriptionFirestoreRepository, CouponFirestoreRepository, CampaignHashtagFirestoreRepository, CampaignDashboardFirestoreRepository, SubscriptionEditionFirestoreRepository, GroupFirestoreRepository, HomeFirestoreRepository, LeadFirestoreRepository, LegacyOrderFirestoreRepository, ShopMenuFirestoreRepository, OrderFirestoreRepository, PaymentFirestoreRepository, ProductFirestoreRepository, ShopSettingsFirestoreRepository, SubscriptionPaymentFirestoreRepository, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionFirestoreRepository, UserFirestoreRepository, UserAddressFirestoreRepository, UserPaymentMethodFirestoreRepository, SubscriptionMaterializationFirestoreRepository, SubscriptionSummaryFirestoreRepository, ProductVariantFirestoreRepository, OrderBlockedFirestoreRepository, LogFirestoreRepository, SequenceFirestoreRepository, CategoryHasuraGraphQLRepository, ProductHasuraGraphQLRepository, CategoryFilterHasuraGraphQLRepository, ProductReviewHasuraGraphQLRepository, VariantHasuraGraphQLRepository, ProductStockNotificationHasuraGraphQLRepository, FilterOptionHasuraGraphQLRepository, FilterHasuraGraphQLRepository, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryProductHasuraGraphQLRepository, WishlistHasuraGraphQLRepository, ProductErrorsHasuraGraphQLRepository, ProductsVertexSearch, isNil } from '@infrab4a/connect';
3
3
  import { Injectable, Inject, Module } from '@nestjs/common';
4
+ import { Firestore } from 'firebase-admin/firestore';
4
5
  import pagarme from 'pagarme';
5
6
  import { DocumentServiceClient } from '@google-cloud/discoveryengine';
6
7
  import { SearchServiceClient } from '@google-cloud/discoveryengine/build/src/v1beta';
@@ -158,7 +159,7 @@ class ConnectBaseDocumentSnapshot {
158
159
  isNotEmpty() {
159
160
  return this.connectDocumentSnapshot.exists;
160
161
  }
161
- data(options) {
162
+ data(_options) {
162
163
  return this.connectDocumentSnapshot.data();
163
164
  }
164
165
  get(fieldPath) {
@@ -217,13 +218,13 @@ class ConnectCollectionService {
217
218
  return new ConnectDocumentService(newDoc.path, this.firestore).withConverter(this.converter);
218
219
  }
219
220
  async getDocs() {
220
- if (this.startingAt > 0)
221
+ if (this.startingAt)
221
222
  this.limitBy += this.startingAt;
222
223
  let query = this.query ? this.query : this.reference;
223
224
  query = this.orderBy ? query.orderBy(this.orderBy.fieldPath, this.orderBy.directionStr) : query;
224
225
  query = this.limitBy ? query.limit(this.limitBy) : query;
225
226
  return query.get().then((docs) => {
226
- const docsPaginated = this.startingAt > 0 ? docs.docs.slice(this.startingAt, this.limitBy) : docs.docs;
227
+ const docsPaginated = this.startingAt ? docs.docs.slice(this.startingAt, this.limitBy) : docs.docs;
227
228
  return {
228
229
  empty: Boolean(docsPaginated.length),
229
230
  size: docsPaginated.length,
@@ -275,7 +276,7 @@ class ConnectCollectionService {
275
276
  }
276
277
  }
277
278
 
278
- class ConnectFirestoreService {
279
+ let ConnectFirestoreService = class ConnectFirestoreService {
279
280
  constructor(firestore) {
280
281
  this.firestore = firestore;
281
282
  }
@@ -285,7 +286,11 @@ class ConnectFirestoreService {
285
286
  getDocument(path) {
286
287
  return new ConnectDocumentService(path, this.firestore);
287
288
  }
288
- }
289
+ };
290
+ ConnectFirestoreService = __decorate([
291
+ Injectable(),
292
+ __metadata("design:paramtypes", [Firestore])
293
+ ], ConnectFirestoreService);
289
294
 
290
295
  class PagarmeBankSlipAPIAdapter {
291
296
  constructor(credentials, paymentRepository) {
@@ -297,10 +302,10 @@ class PagarmeBankSlipAPIAdapter {
297
302
  const client = await pagarme.client.connect({ api_key: this.credentials.API_KEY });
298
303
  const payload = this.createBoletoPayment(checkout);
299
304
  const result = await client.transactions.create(payload);
300
- console.log('[PAGARME BOLETO DATA TO SEND]', payload);
301
- console.log('result PagarmeBankSlipAPIAdapter', JSON.stringify(result));
305
+ console.warn('[PAGARME BOLETO DATA TO SEND]', payload);
306
+ console.warn('result PagarmeBankSlipAPIAdapter', JSON.stringify(result));
302
307
  if (result.status !== PagarmePaymentStatus['Em processamento']) {
303
- return Promise.reject(new PaymentError(`Houve uma falha ao gerar o boleto. Tente novamente`, {
308
+ return Promise.reject(new PaymentError('Houve uma falha ao gerar o boleto. Tente novamente', {
304
309
  checkoutId: checkout.id,
305
310
  userEmail: checkout.user.email,
306
311
  info: result,
@@ -329,7 +334,7 @@ class PagarmeBankSlipAPIAdapter {
329
334
  async getBoletoTransaction(paymentId) {
330
335
  try {
331
336
  const client = await pagarme.client.connect({ api_key: this.credentials.API_KEY });
332
- const result = client.transactions.find({ id: paymentId });
337
+ const result = await client.transactions.find({ id: paymentId });
333
338
  return result;
334
339
  }
335
340
  catch (error) {
@@ -372,43 +377,73 @@ class PagarmeCardAPIAdapter {
372
377
  }
373
378
  async pay(checkout, card) {
374
379
  try {
375
- const client = await pagarme.client.connect({ api_key: this.credentials.API_KEY });
376
- const payload = this.createCardPayment(checkout, card);
377
- const result = await client.transactions.create(payload);
378
- console.log('[PAGARME CARD DATA TO SEND]', payload);
379
- console.log('result PagarmeCardAPIAdapter', JSON.stringify(result));
380
- if (result.status !== PagarmePaymentStatus.Pago) {
381
- await this.orderBlockedRepository.createBlockedOrderOrPayment(checkout, 'Card not authorized', 'Card', 'day', card);
382
- 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`, {
383
- checkoutId: checkout.id,
384
- userEmail: checkout.user.email,
385
- info: result,
386
- }));
387
- }
388
- const payment = await this.paymentRepository.create({
389
- createdAt: new Date(),
390
- updatedAt: new Date(),
391
- userId: checkout.user.id,
392
- checkoutId: checkout.id,
393
- totalPrice: checkout.totalPrice,
394
- paymentProvider: PaymentProviders.PAGARME,
395
- transaction: Object.assign(Object.assign({}, result), { paidAt: new Date() }),
396
- });
397
- return payment;
380
+ const client = await this.createPagarmeClient();
381
+ const transactionResult = await this.executeCardTransaction(client, checkout, card);
382
+ await this.validateTransactionResult(transactionResult, checkout, card);
383
+ return await this.createPaymentRecord(checkout, transactionResult);
398
384
  }
399
385
  catch (error) {
400
- console.error('Error PagarmeCardAPIAdapter', JSON.stringify(error));
401
- 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', {
402
- checkoutId: checkout.id,
403
- userEmail: checkout.user.email,
404
- info: error,
405
- });
386
+ this.handlePaymentError(error, checkout);
387
+ }
388
+ }
389
+ async createPagarmeClient() {
390
+ return await pagarme.client.connect({ api_key: this.credentials.API_KEY });
391
+ }
392
+ async executeCardTransaction(client, checkout, card) {
393
+ const payload = this.createCardPayment(checkout, card);
394
+ const result = await client.transactions.create(payload);
395
+ this.logTransactionDetails(payload, result);
396
+ return result;
397
+ }
398
+ logTransactionDetails(payload, result) {
399
+ console.warn('[PAGARME CARD DATA TO SEND]', payload);
400
+ console.warn('result PagarmeCardAPIAdapter', JSON.stringify(result));
401
+ }
402
+ async validateTransactionResult(result, checkout, card) {
403
+ if (result.status !== PagarmePaymentStatus.Pago) {
404
+ await this.handleUnauthorizedPayment(checkout, card, result);
406
405
  }
407
406
  }
407
+ async handleUnauthorizedPayment(checkout, card, result) {
408
+ await this.createBlockedOrderRecord(checkout, card);
409
+ 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', {
410
+ checkoutId: checkout.id,
411
+ userEmail: checkout.user.email,
412
+ info: result,
413
+ });
414
+ }
415
+ async createBlockedOrderRecord(checkout, card) {
416
+ await this.orderBlockedRepository.createBlockedOrderOrPayment({
417
+ checkout,
418
+ blockType: 'Card not authorized',
419
+ type: 'Card',
420
+ limiteRange: 'day',
421
+ card,
422
+ });
423
+ }
424
+ async createPaymentRecord(checkout, transactionResult) {
425
+ return await this.paymentRepository.create({
426
+ createdAt: new Date(),
427
+ updatedAt: new Date(),
428
+ userId: checkout.user.id,
429
+ checkoutId: checkout.id,
430
+ totalPrice: checkout.totalPrice,
431
+ paymentProvider: PaymentProviders.PAGARME,
432
+ transaction: Object.assign(Object.assign({}, transactionResult), { paidAt: new Date() }),
433
+ });
434
+ }
435
+ handlePaymentError(error, checkout) {
436
+ console.error('Error PagarmeCardAPIAdapter', JSON.stringify(error));
437
+ 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', {
438
+ checkoutId: checkout.id,
439
+ userEmail: checkout.user.email,
440
+ info: error,
441
+ });
442
+ }
408
443
  async addCard(card) {
409
444
  try {
410
445
  const client = await pagarme.client.connect({ api_key: this.credentials.API_KEY });
411
- const result = client.cards.create({
446
+ const result = await client.cards.create({
412
447
  card_number: card.number,
413
448
  card_expiration_date: card.expirationDate.replace('/', ''),
414
449
  card_holder_name: card.name,
@@ -442,7 +477,7 @@ class PagarmeCardAPIAdapter {
442
477
  async getCardByToken(id) {
443
478
  try {
444
479
  const client = await pagarme.client.connect({ api_key: this.credentials.API_KEY });
445
- const result = client.cards.find({
480
+ const result = await client.cards.find({
446
481
  id,
447
482
  });
448
483
  return result;
@@ -526,8 +561,8 @@ class PagarmePixAPIAdapter {
526
561
  const client = await pagarme.client.connect({ api_key: this.credentials.API_KEY });
527
562
  const payload = this.createPixPayment(checkout);
528
563
  const result = await client.transactions.create(payload);
529
- console.log('[PAGARME PIX DATA TO SEND]', payload);
530
- console.log('result PagarmePixAPIAdapter', JSON.stringify(result));
564
+ console.warn('[PAGARME PIX DATA TO SEND]', payload);
565
+ console.warn('result PagarmePixAPIAdapter', JSON.stringify(result));
531
566
  const payment = await this.paymentRepository.create({
532
567
  createdAt: new Date(),
533
568
  updatedAt: new Date(),
@@ -540,7 +575,7 @@ class PagarmePixAPIAdapter {
540
575
  return payment;
541
576
  }
542
577
  catch (error) {
543
- console.log('Error PagarmePixAPIAdapter', JSON.stringify(error));
578
+ console.error('Error PagarmePixAPIAdapter', JSON.stringify(error));
544
579
  throw new PaymentError('Houve uma falha ao processar pagamento com pix', {
545
580
  checkoutId: checkout.id,
546
581
  userEmail: checkout.user.email,
@@ -624,8 +659,12 @@ class ProductVertexHelper {
624
659
  let DiscoveryEngineVertexAdapter = class DiscoveryEngineVertexAdapter {
625
660
  constructor(configuration) {
626
661
  this.config = configuration;
627
- this.parentEngine = `projects/${this.config.projectId}/locations/${this.config.location}/collections/default_collection/engines/${this.config.dataStoreId}`;
628
- this.parentDataStore = `projects/${this.config.projectId}/locations/${this.config.location}/collections/default_collection/dataStores/${this.config.dataStoreId}/branches/default_branch/documents`;
662
+ this.parentEngine =
663
+ `projects/${this.config.projectId}/locations/${this.config.location}/` +
664
+ `collections/default_collection/engines/${this.config.dataStoreId}`;
665
+ this.parentDataStore =
666
+ `projects/${this.config.projectId}/locations/${this.config.location}/` +
667
+ `collections/default_collection/dataStores/${this.config.dataStoreId}/branches/default_branch/documents`;
629
668
  this.searchClient = new SearchServiceClient({
630
669
  apiEndpoint: configuration.apiEndpoint,
631
670
  credentials: configuration.credentials,
@@ -664,7 +703,7 @@ let DiscoveryEngineVertexAdapter = class DiscoveryEngineVertexAdapter {
664
703
  const response = await this.documentClient.updateDocument(request);
665
704
  return response;
666
705
  }
667
- async query(term, total, gender) {
706
+ async query(term, total) {
668
707
  const response = (await this.searchClient.search({
669
708
  pageSize: total,
670
709
  query: term,
@@ -698,18 +737,19 @@ let DiscoveryEngineVertexAdapter = class DiscoveryEngineVertexAdapter {
698
737
  for (let index = 0; index < products.length; index += batchSize) {
699
738
  const bulkProducts = products.slice(index, index + batchSize);
700
739
  const [operation] = await this.documentClient.importDocuments({
701
- parent: `projects/${this.config.projectId}/locations/${this.config.location}/collections/default_collection/dataStores/${this.config.dataStoreId}/branches/default_branch`,
740
+ parent: `projects/${this.config.projectId}/locations/${this.config.location}/` +
741
+ `collections/default_collection/dataStores/${this.config.dataStoreId}/branches/default_branch`,
702
742
  inlineSource: {
703
743
  documents: bulkProducts,
704
744
  },
705
745
  });
706
746
  total += bulkProducts.length;
707
747
  const [response] = await operation.promise();
708
- console.log(`Imported: ${total} documents`, ((total / products.length) * 100).toFixed(2) + '%', `Erros: `, response.errorSamples ? response.errorSamples : []);
748
+ console.warn(`Imported: ${total} documents`, ((total / products.length) * 100).toFixed(2) + '%', 'Erros: ', response.errorSamples ? response.errorSamples : []);
709
749
  }
710
750
  }
711
751
  catch (error) {
712
- console.log(error);
752
+ console.error(error);
713
753
  }
714
754
  }
715
755
  };
@@ -852,6 +892,13 @@ NestFirestoreModule = NestFirestoreModule_1 = __decorate([
852
892
  },
853
893
  inject: ['FirestoreOptions', 'SubscriptionRepository'],
854
894
  },
895
+ {
896
+ provide: 'GroupRepository',
897
+ useFactory: (options) => {
898
+ return new GroupFirestoreRepository(options);
899
+ },
900
+ inject: ['FirestoreOptions'],
901
+ },
855
902
  {
856
903
  provide: 'HomeRepository',
857
904
  useFactory: (options) => {
@@ -1010,6 +1057,7 @@ NestFirestoreModule = NestFirestoreModule_1 = __decorate([
1010
1057
  'CampaignHashtagRepository',
1011
1058
  'CampaignDashboardRepository',
1012
1059
  'EditionRepository',
1060
+ 'GroupRepository',
1013
1061
  'HomeRepository',
1014
1062
  'LeadRepository',
1015
1063
  'LegacyOrderRepository',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@infrab4a/connect-nestjs",
3
- "version": "1.11.0",
3
+ "version": "1.12.1-alpha.0",
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.26.0",
12
+ "@infrab4a/connect": "4.29.1-alpha.0",
13
13
  "@nestjs/common": "^10.3.3",
14
14
  "@nestjs/core": "^10.3.3",
15
15
  "firebase-admin": "^12.0.0"
@@ -1,7 +1,7 @@
1
1
  import { ConnectDocumentData, ConnectDocumentSnapshot, ConnectQuerySnapshot, ConnectSnapshotOptions, ConnectWhereOption } from '@infrab4a/connect';
2
2
  import { ConnectDocumentReference } from './connect-document-reference';
3
3
  export interface ConnectCollectionReference<T extends ConnectDocumentData> {
4
- add(data: Partial<T>, id?: string): Promise<ConnectDocumentReference<T>>;
4
+ add(data: T, id?: string): Promise<ConnectDocumentReference<T>>;
5
5
  where(attribute: string, operator: ConnectWhereOption, value: any): ConnectCollectionReference<T>;
6
6
  order(attribute: string, order: 'asc' | 'desc'): ConnectCollectionReference<T>;
7
7
  limit(quantity: number): ConnectCollectionReference<T>;
@@ -1,5 +1,5 @@
1
- import { Firestore } from 'firebase-admin/firestore';
2
1
  import { ConnectDocumentData, ConnectDocumentSnapshot, ConnectQuerySnapshot, ConnectSnapshotOptions, ConnectWhereOption } from '@infrab4a/connect';
2
+ import { Firestore } from 'firebase-admin/firestore';
3
3
  import { ConnectCollectionReference } from './connect-collection-reference';
4
4
  import { ConnectDocumentReference } from './connect-document-reference';
5
5
  export declare class ConnectCollectionService<T extends ConnectDocumentData> implements ConnectCollectionReference<T> {
@@ -1,10 +1,7 @@
1
+ import { ConnectCollectionReference, ConnectDocumentData, ConnectDocumentReference, ConnectFirestore } from '@infrab4a/connect';
1
2
  import { Firestore } from 'firebase-admin/firestore';
2
- import { ConnectDocumentData } from '@infrab4a/connect';
3
- import { ConnectCollectionReference } from './connect-collection-reference';
4
- import { ConnectDocumentReference } from './connect-document-reference';
5
- import { ConnectFirestore } from './connect-firestore';
6
3
  export declare class ConnectFirestoreService implements ConnectFirestore {
7
- private firestore;
4
+ private readonly firestore;
8
5
  constructor(firestore: Firestore);
9
6
  getCollection<T extends ConnectDocumentData>(path: string): ConnectCollectionReference<T>;
10
7
  getDocument<T extends ConnectDocumentData>(path: string): ConnectDocumentReference<T>;
@@ -7,6 +7,6 @@ export declare class ConnectBaseDocumentSnapshot<T extends ConnectDocumentData =
7
7
  exists: boolean;
8
8
  constructor(connectDocumentSnapshot: DocumentSnapshot<T>);
9
9
  isNotEmpty(): boolean;
10
- data(options?: ConnectSnapshotOptions): T;
10
+ data(_options?: ConnectSnapshotOptions): T;
11
11
  get(fieldPath: string): any;
12
12
  }
@@ -5,6 +5,14 @@ export declare class PagarmeCardAPIAdapter implements PaymentProviderCard<PagarM
5
5
  private orderBlockedRepository;
6
6
  constructor(credentials: PagarmeCredentials, paymentRepository: PaymentRepository, orderBlockedRepository: OrderBlockedRepository);
7
7
  pay(checkout: Checkout, card: PaymentCardInfo): Promise<Payment>;
8
+ private createPagarmeClient;
9
+ private executeCardTransaction;
10
+ private logTransactionDetails;
11
+ private validateTransactionResult;
12
+ private handleUnauthorizedPayment;
13
+ private createBlockedOrderRecord;
14
+ private createPaymentRecord;
15
+ private handlePaymentError;
8
16
  addCard(card: CardInfo): Promise<PagarMeCard>;
9
17
  createCardHash(bu: BusinessUnitEnum, card: CardInfo): Promise<string>;
10
18
  getCardByToken(id: string): Promise<PagarMeCard>;
@@ -8,9 +8,9 @@ export declare class DiscoveryEngineVertexAdapter implements VertexSearchAdapter
8
8
  private searchClient;
9
9
  private documentClient;
10
10
  constructor(configuration: VertexConfig);
11
- save(product: ProductHasuraGraphQL): Promise<[import("@google-cloud/discoveryengine/build/protos/protos").google.cloud.discoveryengine.v1.IDocument, import("@google-cloud/discoveryengine/build/protos/protos").google.cloud.discoveryengine.v1.IUpdateDocumentRequest, {}]>;
12
- update(id: string, data: ProductHasuraGraphQL): Promise<[import("@google-cloud/discoveryengine/build/protos/protos").google.cloud.discoveryengine.v1.IDocument, import("@google-cloud/discoveryengine/build/protos/protos").google.cloud.discoveryengine.v1.IUpdateDocumentRequest, {}]>;
13
- query(term: string, total: number, gender?: string): Promise<ProductSearch[]>;
11
+ save(product: ProductHasuraGraphQL): Promise<any>;
12
+ update(id: string, data: ProductHasuraGraphQL): Promise<any>;
13
+ query(term: string, total: number): Promise<ProductSearch[]>;
14
14
  get(id: string): Promise<any>;
15
15
  delete(id: string): Promise<void>;
16
16
  bulkProducts(products: ProductBulk[]): Promise<void>;