Skip to content

Commit

Permalink
Merge pull request #118 from soat-fiap/put_usecases_back
Browse files Browse the repository at this point in the history
putting usecases back to update order payment and status
  • Loading branch information
italopessoa authored Jul 18, 2024
2 parents cf03e37 + ff6a3c5 commit 3d5c91d
Show file tree
Hide file tree
Showing 15 changed files with 83 additions and 114 deletions.
32 changes: 3 additions & 29 deletions src/FIAP.TechChallenge.ByteMeBurger.Api/DomainEventsHandler.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using System.Diagnostics.CodeAnalysis;
using FIAP.TechChallenge.ByteMeBurger.Domain.Events;
using FIAP.TechChallenge.ByteMeBurger.Domain.Interfaces;
using FIAP.TechChallenge.ByteMeBurger.Domain.ValueObjects;
using Microsoft.Extensions.Caching.Hybrid;

namespace FIAP.TechChallenge.ByteMeBurger.Api;
Expand All @@ -14,16 +12,11 @@ public class DomainEventsHandler : IDisposable
{
private readonly ILogger<DomainEventsHandler> _logger;
private readonly HybridCache _cache;
private readonly IOrderService _orderService;

public DomainEventsHandler(ILogger<DomainEventsHandler> logger, HybridCache cache, IServiceProvider serviceProvider)
public DomainEventsHandler(ILogger<DomainEventsHandler> logger, HybridCache cache)
{
_logger = logger;
_cache = cache;
using (var scope = serviceProvider.CreateScope())
{
_orderService = scope.ServiceProvider.GetRequiredService<IOrderService>();
}

DomainEventTrigger.ProductCreated += OnProductCreated;
DomainEventTrigger.ProductDeleted += OnProductDeleted;
Expand All @@ -48,19 +41,10 @@ private void OnOrderStatusChanged(object? sender, OrderStatusChanged e)
e.Payload.OldStatus, e.Payload.NewStatus, e.Payload.OrderId);
}

private async void OnOrderPaymentConfirmed(object? sender, OrderPaymentConfirmed e)
private void OnOrderPaymentConfirmed(object? sender, OrderPaymentConfirmed e)
{
_logger.LogInformation("Order: {OrderId} payment confirmed", e.Payload);
InvalidateOrderCache(e.Payload.OrderId);
try
{
await _orderService.UpdateStatusAsync(e.Payload.OrderId, OrderStatus.Received);
}
catch (Exception exception)
{
_logger.LogError(exception, "Error updating order status {OrderId}", e.Payload.OrderId);
throw;
}
}

private void OnOrderCreated(object? sender, OrderCreated e)
Expand All @@ -85,20 +69,10 @@ private void OnProductCreated(object? sender, ProductCreated e)
_logger.LogInformation("Product created: {@Product}", e.Payload);
}

private async void OnPaymentCreated(object? sender, PaymentCreated e)
private void OnPaymentCreated(object? sender, PaymentCreated e)
{
_logger.LogInformation("Payment {PaymentId} created for Order: {OrderId}", e.Payload.OrderId,
e.Payload.Id.Value);

try
{
await _orderService.UpdateOrderPaymentAsync(e.Payload.OrderId, e.Payload.Id);
}
catch (Exception exception)
{
_logger.LogError(exception, "Error updating order payment {OrderId}", e.Payload.OrderId);
throw;
}
}

private void InvalidateOrderCache(Guid orderId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
"MySql": "Server=localhost;Database=restaurant1;Uid=italo;Pwd=italo123@;Port=3306"
},
"MercadoPago": {
"WebhookSecret": "",
"AccessToken": "",
"NotificationUrl": ""
"WebhookSecret": "1232",
"AccessToken": "123",
"NotificationUrl": "1232"
},
"HybridCache": {
"Expiration": "01:00:00",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,19 @@ public class PaymentService : IPaymentService
private readonly IUpdatePaymentStatusUseCase _updatePaymentStatusUseCase;
private readonly IPaymentRepository _paymentRepository;
private readonly IPaymentGatewayFactoryMethod _paymentGatewayFactory;
private readonly IUpdateOrderPaymentUseCase _updateOrderPaymentUseCase;

public PaymentService(ICreatePaymentUseCase createOrderPaymentUseCase,
IUpdatePaymentStatusUseCase updatePaymentStatusUseCase,
IPaymentRepository paymentRepository,
IPaymentGatewayFactoryMethod paymentGatewayFactory)
IPaymentGatewayFactoryMethod paymentGatewayFactory,
IUpdateOrderPaymentUseCase updateOrderPaymentUseCase)
{
_createOrderPaymentUseCase = createOrderPaymentUseCase;
_updatePaymentStatusUseCase = updatePaymentStatusUseCase;
_paymentRepository = paymentRepository;
_paymentGatewayFactory = paymentGatewayFactory;
_updateOrderPaymentUseCase = updateOrderPaymentUseCase;
}

public async Task<Payment> CreateOrderPaymentAsync(CreateOrderPaymentRequestDto command)
Expand All @@ -31,6 +34,7 @@ public async Task<Payment> CreateOrderPaymentAsync(CreateOrderPaymentRequestDto
return null;

await _paymentRepository.SaveAsync(payment);
await _updateOrderPaymentUseCase.Execute(payment.OrderId, payment.Id);
return payment;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using FIAP.TechChallenge.ByteMeBurger.Application.UseCases.Orders;
using FIAP.TechChallenge.ByteMeBurger.Domain.Events;
using FIAP.TechChallenge.ByteMeBurger.Domain.Interfaces;
using FIAP.TechChallenge.ByteMeBurger.Domain.ValueObjects;
Expand All @@ -7,10 +8,13 @@ namespace FIAP.TechChallenge.ByteMeBurger.Application.UseCases.Payment;
public class UpdatePaymentStatusUseCase : IUpdatePaymentStatusUseCase
{
private readonly IPaymentRepository _paymentRepository;
private readonly IUpdateOrderStatusUseCase _updateOrderStatusUseCase;

public UpdatePaymentStatusUseCase(IPaymentRepository paymentRepository)
public UpdatePaymentStatusUseCase(IUpdateOrderStatusUseCase updateOrderStatusUseCase,
IPaymentRepository paymentRepository)
{
_paymentRepository = paymentRepository;
_updateOrderStatusUseCase = updateOrderStatusUseCase;
}

public async Task<bool> Execute(Domain.Entities.Payment? payment, PaymentStatus status)
Expand All @@ -28,6 +32,8 @@ and not PaymentStatus.Cancelled
if (paymentStatusUpdated && payment.IsApproved())
{
DomainEventTrigger.RaisePaymentConfirmed(payment);
// TODO change to eventual consistency. use events to update order status
await _updateOrderStatusUseCase.Execute(payment.OrderId, OrderStatus.Received);
}

return paymentStatusUpdated;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
using System.Data;
using Dapper;
using FIAP.TechChallenge.ByteMeBurger.Domain.Base;
using FIAP.TechChallenge.ByteMeBurger.Domain.Entities;
using FIAP.TechChallenge.ByteMeBurger.Domain.Interfaces;
using FIAP.TechChallenge.ByteMeBurger.Persistence.Dto;
using Microsoft.Extensions.Logging;

namespace FIAP.TechChallenge.ByteMeBurger.Persistence.Repository;

public class CustomerRepositoryDapper(IDbContext context, ILogger<CustomerRepositoryDapper> logger)
public class CustomerRepositoryDapper(IDbConnection dbConnection, ILogger<CustomerRepositoryDapper> logger)
: ICustomerRepository
{

private readonly IDbConnection _dbConnection = context.CreateConnection();

public async Task<Customer?> FindByCpfAsync(string cpf)
{
logger.LogInformation("Finding customer by CPF: {Cpf}", cpf);
var customerDto = await _dbConnection.QuerySingleOrDefaultAsync<CustomerDto>(
var customerDto = await dbConnection.QuerySingleOrDefaultAsync<CustomerDto>(
Constants.GetCustomerByCpfQuery,
new { Cpf = cpf });

Expand All @@ -33,7 +30,7 @@ public async Task<Customer> CreateAsync(Customer customer)
{
logger.LogInformation("Creating customer with CPF: {Cpf}", customer.Cpf);
var param = (CustomerDto)customer;
var rowsAffected = await _dbConnection.ExecuteAsync(
var rowsAffected = await dbConnection.ExecuteAsync(
Constants.InsertCustomerQuery,
param);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,18 @@

namespace FIAP.TechChallenge.ByteMeBurger.Persistence.Repository;

public class OrderRepositoryDapper(IDbContext context, ILogger<OrderRepositoryDapper> logger)
public class OrderRepositoryDapper(IDbConnection dbConnection, ILogger<OrderRepositoryDapper> logger)
: IOrderRepository
{

private readonly IDbConnection _dbConnection = context.CreateConnection();

public async Task<Order> CreateAsync(Order order)
{
logger.LogInformation("Persisting order {OrderId}", order.Id);
var transaction = _dbConnection.BeginTransaction();
var transaction = dbConnection.BeginTransaction();
{
try
{
await _dbConnection.ExecuteAsync(
await dbConnection.ExecuteAsync(
Constants.InsertOrderQuery,
new
{
Expand All @@ -34,7 +32,7 @@ await _dbConnection.ExecuteAsync(
order.Created,
TrackingCode = order.TrackingCode.Value
});
await _dbConnection.ExecuteAsync(Constants.InsertOrderItemsQuery, order.OrderItems);
await dbConnection.ExecuteAsync(Constants.InsertOrderItemsQuery, order.OrderItems);

transaction.Commit();
logger.LogInformation("Order {OrderId} persisted", order.Id);
Expand All @@ -55,7 +53,7 @@ public async Task<ReadOnlyCollection<Order>> GetAllAsync()
var ordersDictionary = new Dictionary<Guid, Order>();


await _dbConnection.QueryAsync<OrderListDto, CustomerDto, PaymentDto?, OrderItemDto, Order>(
await dbConnection.QueryAsync<OrderListDto, CustomerDto, PaymentDto?, OrderItemDto, Order>(
Constants.GetAllOrdersQuery,
(orderListDto, customerDto, paymentDao, orderItemDto) =>
{
Expand Down Expand Up @@ -94,7 +92,7 @@ public async Task<ReadOnlyCollection<Order>> GetAllAsync()
logger.LogInformation("Getting order {OrderId} from database", orderId);
var ordersDictionary = new Dictionary<Guid, Order>();

await _dbConnection.QueryAsync<OrderListDto, Guid?, CustomerDto, OrderItemDto, Order>(
await dbConnection.QueryAsync<OrderListDto, Guid?, CustomerDto, OrderItemDto, Order>(
Constants.GetOrderByIdQuery,
(orderListDto, paymentId, customerDto, orderItemDto) =>
{
Expand Down Expand Up @@ -132,7 +130,7 @@ public async Task<bool> UpdateOrderStatusAsync(Order order)
logger.LogInformation("Updating order {OrderId} status to {OrderStatus}", order.Id, order.Status);
try
{
var updated = await _dbConnection.ExecuteAsync(
var updated = await dbConnection.ExecuteAsync(
Constants.UpdateOrderStatusQuery,
new
{
Expand All @@ -159,7 +157,7 @@ public async Task<bool> UpdateOrderPaymentAsync(Order order)
logger.LogInformation("Updating order {OrderId} Payment {PaymentId}", order.Id, order.PaymentId.Value);
try
{
var updated = await _dbConnection.ExecuteAsync(
var updated = await dbConnection.ExecuteAsync(
Constants.UpdateOrderPaymentIdQuery,
new
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,23 @@
namespace FIAP.TechChallenge.ByteMeBurger.Persistence.Repository;

public class PaymentRepositoryDapper(
IDbContext context,
IDbConnection dbConnection,
ILogger<PaymentRepositoryDapper> logger)
: IPaymentRepository
{
private readonly IDbConnection _dbConnection = context.CreateConnection();

public async Task<Payment> SaveAsync(Payment payment)
{
logger.LogInformation("Persisting Payment {PaymentId} for Order {OrderId}", payment.Id.Value,
payment.OrderId);

var transaction = _dbConnection.BeginTransaction();
var transaction = dbConnection.BeginTransaction();
{
try
{
var paymentDao = new PaymentDto(payment.Id.Value, payment.OrderId, (int)payment.Status,
(int)payment.PaymentType, payment.Amount, payment.ExternalReference, payment.Created, null);
await _dbConnection.ExecuteAsync(Constants.InsertPaymentQuery, paymentDao);
await dbConnection.ExecuteAsync(Constants.InsertPaymentQuery, paymentDao);

transaction.Commit();

Expand All @@ -48,7 +47,7 @@ public async Task<Payment> SaveAsync(Payment payment)
{
logger.LogInformation("Getting Payment {PaymentId}", paymentId.Value);

var paymentDao = await _dbConnection.QuerySingleOrDefaultAsync<PaymentDto>(
var paymentDao = await dbConnection.QuerySingleOrDefaultAsync<PaymentDto>(
Constants.GetPaymentQuery,
param: new { Id = paymentId.Value }
);
Expand Down Expand Up @@ -76,7 +75,7 @@ public async Task<Payment> SaveAsync(Payment payment)
logger.LogInformation("Getting {PaymentType} Payment by ExternalReference {ExternalReference}",
paymentType.ToString(), externalReference);

var paymentDao = await _dbConnection.QuerySingleOrDefaultAsync<PaymentDto>(
var paymentDao = await dbConnection.QuerySingleOrDefaultAsync<PaymentDto>(
Constants.GetPaymentByExternalReferenceQuery,
param: new
{
Expand Down Expand Up @@ -108,7 +107,7 @@ public async Task<bool> UpdatePaymentStatusAsync(Payment payment)
{
logger.LogInformation("Updating Payment {PaymentId} status", payment.Id.Value);

var updated = await _dbConnection.ExecuteAsync(
var updated = await dbConnection.ExecuteAsync(
Constants.UpdatePaymentStatusQuery,
new
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,14 @@

namespace FIAP.TechChallenge.ByteMeBurger.Persistence.Repository;

public class ProductRepositoryDapper(IDbContext context, ILogger<ProductRepositoryDapper> logger)
public class ProductRepositoryDapper(IDbConnection dbConnection, ILogger<ProductRepositoryDapper> logger)
: IProductRepository
{
private readonly IDbConnection _dbConnection = context.CreateConnection();

public async Task<Product?> FindByIdAsync(Guid id)
{
logger.LogInformation("Finding product {ProductId}", id);
var productDto = await _dbConnection.QuerySingleOrDefaultAsync<ProductDto>(
var productDto = await dbConnection.QuerySingleOrDefaultAsync<ProductDto>(
"SELECT * FROM Products WHERE Id=@Id",
param: new { Id = id });

Expand All @@ -35,7 +34,7 @@ public async Task<Product> CreateAsync(Product product)
{
logger.LogInformation("Creating product with name: {ProductName}", product.Name);
var param = (ProductDto)product;
var affectedRows = await _dbConnection.ExecuteAsync(Constants.InsertProductQuery, param);
var affectedRows = await dbConnection.ExecuteAsync(Constants.InsertProductQuery, param);

if (affectedRows > 0)
{
Expand All @@ -52,7 +51,7 @@ public async Task<Product> CreateAsync(Product product)
public async Task<bool> DeleteAsync(Guid productId)
{
logger.LogInformation("Deleting product {ProductId}", productId);
var affectedRows = await _dbConnection.ExecuteAsync(Constants.DeleteProductQuery,
var affectedRows = await dbConnection.ExecuteAsync(Constants.DeleteProductQuery,
new { Id = productId });

if (affectedRows == 1)
Expand All @@ -70,7 +69,7 @@ public async Task<bool> DeleteAsync(Guid productId)
public async Task<ReadOnlyCollection<Product>> GetAll()
{
logger.LogInformation("Getting all products");
var productDtoList = await _dbConnection.QueryAsync<ProductDto>(
var productDtoList = await dbConnection.QueryAsync<ProductDto>(
"SELECT * FROM Products");

logger.LogInformation("Retrieved {Count} products", productDtoList.Count());
Expand All @@ -82,7 +81,7 @@ public async Task<ReadOnlyCollection<Product>> GetAll()
public async Task<ReadOnlyCollection<Product>> FindByCategory(ProductCategory category)
{
logger.LogInformation("Finding products by category: {ProductCategory}", category);
var productDtoList = await _dbConnection.QueryAsync<ProductDto>(
var productDtoList = await dbConnection.QueryAsync<ProductDto>(
"SELECT * FROM Products WHERE Category = @Category",
param: new { Category = (int)category });

Expand All @@ -93,7 +92,7 @@ public async Task<ReadOnlyCollection<Product>> FindByCategory(ProductCategory ca
public async Task<bool> UpdateAsync(Product product)
{
logger.LogInformation("Updating product with ID: {ProductId}", product.Id);
var affectedRows = await _dbConnection.ExecuteAsync(
var affectedRows = await dbConnection.ExecuteAsync(
Constants.UpdateProductQuery,
(ProductDto)product);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Data;
using System.Data.Common;
using System.Diagnostics.CodeAnalysis;
using FIAP.TechChallenge.ByteMeBurger.Domain.Base;
using FIAP.TechChallenge.ByteMeBurger.Domain.Interfaces;
using FIAP.TechChallenge.ByteMeBurger.Persistence.Repository;
using Microsoft.Extensions.Configuration;
Expand All @@ -15,16 +14,15 @@ public static class ServiceExtensions
{
public static void ConfigurePersistenceApp(this IServiceCollection services, IConfiguration configuration)
{
services.AddSingleton<IDbContext, MySqlDbContext>();
// services.AddScoped<IDbConnection>(_ =>
// {
// DbProviderFactories.RegisterFactory("MySql.Data.MySqlClient", MySqlClientFactory.Instance);
// var providerFactory = DbProviderFactories.GetFactory("MySql.Data.MySqlClient");
// var conn = providerFactory.CreateConnection();
// conn.ConnectionString = configuration.GetConnectionString("MySql");
// // conn.Open();
// return conn;
// });
services.AddScoped<IDbConnection>(_ =>
{
DbProviderFactories.RegisterFactory("MySql.Data.MySqlClient", MySqlClientFactory.Instance);
var providerFactory = DbProviderFactories.GetFactory("MySql.Data.MySqlClient");
var conn = providerFactory.CreateConnection();
conn.ConnectionString = configuration.GetConnectionString("MySql");
conn.Open();
return conn;
});

services.AddScoped<IOrderRepository, OrderRepositoryDapper>()
.AddScoped<ICustomerRepository, CustomerRepositoryDapper>()
Expand Down
Loading

0 comments on commit 3d5c91d

Please sign in to comment.