Skip to content
This repository has been archived by the owner on Oct 19, 2024. It is now read-only.

Commit

Permalink
feat(143): Consome msg pagamento confirmado
Browse files Browse the repository at this point in the history
  • Loading branch information
dannevesdantas committed Jun 30, 2024
1 parent 2984b47 commit a1ca2a7
Show file tree
Hide file tree
Showing 8 changed files with 203 additions and 1 deletion.
3 changes: 3 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ services:
NOME_FILA_FALHA_COBRANCA: ${NOME_FILA_FALHA_COBRANCA:-falha-cobranca}
URL_FILA_FALHA_COBRANCA: http://localstack:4566/000000000000/falha-cobranca
REGION_FILA_FALHA_COBRANCA: ${REGION_FILA_FALHA_COBRANCA:-us-east-1}
NOME_FILA_PAGAMENTO_CONFIRMADO: pagamento-confirmado
URL_FILA_PAGAMENTO_CONFIRMADO: http://localstack:4566/000000000000/pagamento-confirmado
REGION_FILA_PAGAMENTO_CONFIRMADO: ${REGION_FILA_PAGAMENTO_CONFIRMADO:-us-east-1}
restart: always
networks:
- rms
Expand Down
15 changes: 15 additions & 0 deletions k8s/production/api/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,21 @@ spec:
secretKeyRef:
name: sqs-fila-falha-cobranca-secret
key: REGION_FILA_FALHA_COBRANCA
- name: NOME_FILA_PAGAMENTO_CONFIRMADO
valueFrom:
secretKeyRef:
name: sqs-fila-pagamento-confirmado-secret
key: NOME_FILA_PAGAMENTO_CONFIRMADO
- name: URL_FILA_PAGAMENTO_CONFIRMADO
valueFrom:
secretKeyRef:
name: sqs-fila-pagamento-confirmado-secret
key: URL_FILA_PAGAMENTO_CONFIRMADO
- name: REGION_FILA_PAGAMENTO_CONFIRMADO
valueFrom:
secretKeyRef:
name: sqs-fila-pagamento-confirmado-secret
key: REGION_FILA_PAGAMENTO_CONFIRMADO
ports:
- containerPort: 3002
resources:
Expand Down
18 changes: 18 additions & 0 deletions k8s/production/api/secret-provider.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,15 @@ spec:
key: URL_FILA_FALHA_COBRANCA
- objectName: REGION_FILA_FALHA_COBRANCA
key: REGION_FILA_FALHA_COBRANCA
- secretName: sqs-fila-pagamento-confirmado-secret # Nome do Secret que será montado automaticamente contendo os segredos do AWS Secrets Manager
type: Opaque
data:
- objectName: NOME_FILA_PAGAMENTO_CONFIRMADO
key: NOME_FILA_PAGAMENTO_CONFIRMADO
- objectName: URL_FILA_PAGAMENTO_CONFIRMADO
key: URL_FILA_PAGAMENTO_CONFIRMADO
- objectName: REGION_FILA_PAGAMENTO_CONFIRMADO
key: REGION_FILA_PAGAMENTO_CONFIRMADO
parameters:
# Informe abaixo no campo objectName os nomes dos Segredos do AWS Secrets Manager que deseja acessar.
# Certifique-se de que as Keys declaradas abaixo existem e estão preenchidas na AWS, caso contrário receberá o erro "Failed to fetch secret from all regions"
Expand Down Expand Up @@ -100,3 +109,12 @@ spec:
objectAlias: "URL_FILA_FALHA_COBRANCA"
- path: "QUEUE_REGION"
objectAlias: "REGION_FILA_FALHA_COBRANCA"
- objectName: "prod/RMS/SQSPagamentoConfirmado"
objectType: "secretsmanager"
jmesPath:
- path: "QUEUE_NAME"
objectAlias: "NOME_FILA_PAGAMENTO_CONFIRMADO"
- path: "QUEUE_URL"
objectAlias: "URL_FILA_PAGAMENTO_CONFIRMADO"
- path: "QUEUE_REGION"
objectAlias: "REGION_FILA_PAGAMENTO_CONFIRMADO"
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ import { IPedidoUseCase } from 'src/domain/pedido/interfaces/pedido.use_case.por
import { messageMock } from 'src/mocks/message.mock';
import { Logger } from '@nestjs/common';
import { AtualizaPedidoDTO } from 'src/presentation/rest/v1/presenters/pedido/pedido.dto';
import { StatusPedido, StatusPagamento } from 'src/domain/pedido/enums/pedido.enum';
import {
StatusPedido,
StatusPagamento,
} from 'src/domain/pedido/enums/pedido.enum';

describe('FalhaCobrancaMessageHandler', () => {
let falhaCobrancaMessageHandler: FalhaCobrancaMessageHandler;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { ConfigService } from '@nestjs/config';
import { Test, TestingModule } from '@nestjs/testing';
import { pedidoDTOMock, pedidoUseCaseMock } from 'src/mocks/pedido.mock';
import { IPedidoUseCase } from 'src/domain/pedido/interfaces/pedido.use_case.port';
import { messageIdMock } from 'src/mocks/message.mock';
import { Logger } from '@nestjs/common';
import { AtualizaPedidoDTO } from 'src/presentation/rest/v1/presenters/pedido/pedido.dto';
import { PagamentoMessageHandler } from './pag_confirmado.handler';
import {
StatusPagamento,
StatusPedido,
} from 'src/domain/pedido/enums/pedido.enum';

describe('PagamentoMessageHandler', () => {
let pagamentoMessageHandler: PagamentoMessageHandler;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
Logger,
PagamentoMessageHandler,
{
provide: IPedidoUseCase,
useValue: pedidoUseCaseMock,
},
{
provide: ConfigService,
useValue: {
get: jest.fn(),
getOrThrow: jest.fn(),
},
},
],
}).compile();

pagamentoMessageHandler = module.get<PagamentoMessageHandler>(
PagamentoMessageHandler,
);
});

afterEach(() => {
jest.clearAllMocks();
});

it('deve consumir mensagem de pagamento confirmado', async () => {
const HTTPResponse = {
mensagem: 'Pedido atualizado com sucesso',
body: pedidoDTOMock,
};
const atualizaPedidoDTO: AtualizaPedidoDTO = {
statusPagamento: StatusPagamento.PAGO,
statusPedido: StatusPedido.EM_PREPARACAO,
};
pedidoUseCaseMock.editarPedido.mockReturnValue(HTTPResponse);

await pagamentoMessageHandler.handleMessage(messageIdMock);

expect(pedidoUseCaseMock.editarPedido).toHaveBeenCalledWith(
pedidoDTOMock.id,
atualizaPedidoDTO,
);
});

it('deve lançar exceção ao consumir mensagem de pagamento confirmado', async () => {
const atualizaPedidoDTO: AtualizaPedidoDTO = {
statusPagamento: StatusPagamento.PAGO,
statusPedido: StatusPedido.EM_PREPARACAO,
};
pedidoUseCaseMock.editarPedido.mockRejectedValue(new Error('Erro'));

await pagamentoMessageHandler.handleMessage(messageIdMock);

expect(pedidoUseCaseMock.editarPedido).toHaveBeenCalledWith(
pedidoDTOMock.id,
atualizaPedidoDTO,
);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { Message } from '@aws-sdk/client-sqs';
import { Inject, Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SqsConsumerEventHandler, SqsMessageHandler } from '@ssut/nestjs-sqs';
import {
StatusPagamento,
StatusPedido,
} from 'src/domain/pedido/enums/pedido.enum';
import { IPedidoUseCase } from 'src/domain/pedido/interfaces/pedido.use_case.port';
import { AtualizaPedidoDTO } from 'src/presentation/rest/v1/presenters/pedido/pedido.dto';

@Injectable()
export class PagamentoMessageHandler {
private _nomeFilaPagamentoConfirmado: string;

constructor(
private readonly logger: Logger,
private configService: ConfigService,
@Inject(IPedidoUseCase)
private readonly pedidoUseCase: IPedidoUseCase,
) {
this._nomeFilaPagamentoConfirmado = this.configService.getOrThrow<string>(
'NOME_FILA_PAGAMENTO_CONFIRMADO',
);
}

@SqsMessageHandler('pagamento-confirmado', false)
public async handleMessage(message: Message) {
this.logger.debug(
`Nova mensagem recebida na fila pagamento-confirmado`,
JSON.stringify(message),
);
try {
const idPedido: string = message.Body;
this.logger.debug(`Confirmando pagamento do pedido ${idPedido}...`);
const atualizaPedidoDTO: AtualizaPedidoDTO = {
statusPagamento: StatusPagamento.PAGO,
statusPedido: StatusPedido.EM_PREPARACAO,
};
this.logger.log(
`O pedido ${idPedido} ${StatusPagamento.PAGO} foi enviado para ${StatusPedido.EM_PREPARACAO}`,
);
await this.pedidoUseCase.editarPedido(idPedido, atualizaPedidoDTO);
} catch (error) {
this.logger.error(
`Ocorreu um erro ao processar a mensagem com MessageId ${message?.MessageId}`,
error,
JSON.stringify(message),
);
}
}

@SqsConsumerEventHandler('pagamento-confirmado', 'processing_error')
public onProcessingError(error: Error, message: Message) {
this.logger.error(
`Ocorreu um erro ao processar a mensagem com MessageId ${message?.MessageId}`,
error,
JSON.stringify(message),
);
}
}
5 changes: 5 additions & 0 deletions src/mocks/message.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,8 @@ import { pedidoDTOMock } from './pedido.mock';
export const messageMock = {
Body: JSON.stringify(pedidoDTOMock),
};

// Mock para simular mensagem de pagamento-confirmado
export const messageIdMock = {
Body: pedidoDTOMock.id,
};
19 changes: 19 additions & 0 deletions src/modules/pedido.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { ConfigModule, ConfigService } from '@nestjs/config';
import { SQSClient } from '@aws-sdk/client-sqs';
import { CobrancaMessageHandler } from 'src/infrastructure/message_handlers/nova_cobranca/nova_cobranca.handler';
import { FalhaCobrancaMessageHandler } from 'src/infrastructure/message_handlers/falha_cobranca/falha_cobranca.handler';
import { PagamentoMessageHandler } from 'src/infrastructure/message_handlers/pagamento_confirmado/pag_confirmado.handler';

@Module({
imports: [
Expand Down Expand Up @@ -75,6 +76,23 @@ import { FalhaCobrancaMessageHandler } from 'src/infrastructure/message_handlers
endpoint: configService.get<string>('LOCALSTACK_ENDPOINT'),
}),
},
{
name: configService.getOrThrow<string>(
'NOME_FILA_PAGAMENTO_CONFIRMADO',
),
queueUrl: configService.getOrThrow<string>(
'URL_FILA_PAGAMENTO_CONFIRMADO',
),
region: configService.getOrThrow<string>(
'REGION_FILA_PAGAMENTO_CONFIRMADO',
),
sqs: new SQSClient({
region: configService.getOrThrow<string>(
'REGION_FILA_PAGAMENTO_CONFIRMADO',
),
endpoint: configService.get<string>('LOCALSTACK_ENDPOINT'),
}),
},
],
producers: [
{
Expand Down Expand Up @@ -103,6 +121,7 @@ import { FalhaCobrancaMessageHandler } from 'src/infrastructure/message_handlers
Logger,
CobrancaMessageHandler,
FalhaCobrancaMessageHandler,
PagamentoMessageHandler,
PedidoUseCase,
{
provide: IPedidoUseCase,
Expand Down

0 comments on commit a1ca2a7

Please sign in to comment.