1+ using JSE . Core . DomainObjects ;
2+ using JSE . Core . Messages . Integration ;
3+ using JSE . MessageBus ;
4+ using JSE . Pedidos . Domain . Pedidos ;
5+
6+ namespace JSE . Pedidos . API . Services
7+ {
8+ public class PedidoIntegrationHandler : BackgroundService
9+ {
10+ private readonly IMessageBus _bus ;
11+ private readonly IServiceProvider _serviceProvider ;
12+
13+ public PedidoIntegrationHandler ( IServiceProvider serviceProvider , IMessageBus bus )
14+ {
15+ _serviceProvider = serviceProvider ;
16+ _bus = bus ;
17+ }
18+ protected override Task ExecuteAsync ( CancellationToken stoppingToken )
19+ {
20+ SetSubscribers ( ) ;
21+ return Task . CompletedTask ;
22+ }
23+
24+ private void SetSubscribers ( )
25+ {
26+ _bus . SubscribeAsync < PedidoCanceladoIntegrationEvent > ( "PedidoCancelado" ,
27+ async request => await CancelarPedido ( request ) ) ;
28+
29+ _bus . SubscribeAsync < PedidoPagoIntegrationEvent > ( "PedidoPago" ,
30+ async request => await FinalizarPedido ( request ) ) ;
31+ }
32+
33+ private async Task CancelarPedido ( PedidoCanceladoIntegrationEvent message )
34+ {
35+ using ( var scope = _serviceProvider . CreateScope ( ) )
36+ {
37+ var pedidoRepository = scope . ServiceProvider . GetRequiredService < IPedidoRepository > ( ) ;
38+
39+ var pedido = await pedidoRepository . ObterPorId ( message . PedidoId ) ;
40+ pedido . CancelarPedido ( ) ;
41+
42+ pedidoRepository . Atualizar ( pedido ) ;
43+
44+ if ( ! await pedidoRepository . UnitOfWork . Commit ( ) )
45+ {
46+ throw new DomainException ( $ "Problemas ao cancelar o pedido { message . PedidoId } ") ;
47+ }
48+ }
49+ }
50+
51+ private async Task FinalizarPedido ( PedidoPagoIntegrationEvent message )
52+ {
53+ using ( var scope = _serviceProvider . CreateScope ( ) )
54+ {
55+ var pedidoRepository = scope . ServiceProvider . GetRequiredService < IPedidoRepository > ( ) ;
56+
57+ var pedido = await pedidoRepository . ObterPorId ( message . PedidoId ) ;
58+ pedido . FinalizarPedido ( ) ;
59+
60+ pedidoRepository . Atualizar ( pedido ) ;
61+
62+ if ( ! await pedidoRepository . UnitOfWork . Commit ( ) )
63+ {
64+ throw new DomainException ( $ "Problemas ao finalizar o pedido { message . PedidoId } ") ;
65+ }
66+ }
67+ }
68+ }
69+ }
0 commit comments