Skip to content

Commit

Permalink
fix: Melhorias
Browse files Browse the repository at this point in the history
  • Loading branch information
EduardoPires committed Apr 1, 2022
1 parent 971e0cc commit a6c3014
Show file tree
Hide file tree
Showing 17 changed files with 202 additions and 247 deletions.
Binary file not shown.
Binary file modified src/services/DevStore.Orders.API/Application/DTO/VoucherDTO.cs
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public static void RegisterServices(this IServiceCollection services)
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<IAspNetUser, AspNetUser>();
services.AddScoped<ShoppingCartContext>();
services.AddScoped<ShoppingCart>();
}
}
}
185 changes: 10 additions & 175 deletions src/services/DevStore.ShoppingCart.API/Program.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
using DevStore.ShoppingCart.API;
using DevStore.ShoppingCart.API.Configuration;
using DevStore.ShoppingCart.API.Data;
using DevStore.ShoppingCart.API.Model;
using DevStore.WebAPI.Core.Identity;
using DevStore.WebAPI.Core.User;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;

#region Builder Configuration

Expand Down Expand Up @@ -38,8 +36,6 @@

#region Configure Pipeline

var Errors = new List<string>();

app.UseSwaggerConfiguration();

app.UseApiConfiguration(app.Environment);
Expand All @@ -57,84 +53,32 @@
void MapActions(WebApplication app)
{
app.MapGet("/shopping-cart", [Authorize] async (
ShoppingCartContext context,
IAspNetUser user) =>
await GetShoppingCartClient(context, user) ?? new CustomerShoppingCart())
ShoppingCart cart) => await cart.GetShoppingCart())
.WithName("GetShoppingCart")
.WithTags("ShoppingCart");

app.MapPost("/shopping-cart", [Authorize] async (
ShoppingCartContext context,
IAspNetUser user,
CartItem item) =>
{
var shoppingCart = await GetShoppingCartClient(context, user);
if (shoppingCart == null)
ManageNewCart(context, user, item);
else
ManageCart(context, shoppingCart, item);
if (Errors.Any()) return CustomResponse();
await Persist(context);
return CustomResponse();
})
ShoppingCart cart,
CartItem item) => await cart.AddItem(item))
.ProducesValidationProblem()
.Produces<CartItem>(StatusCodes.Status201Created)
.Produces(StatusCodes.Status400BadRequest)
.WithName("AddItem")
.WithTags("ShoppingCart");

app.MapPut("/shopping-cart/{productId}", [Authorize] async (
ShoppingCartContext context,
IAspNetUser user,
ShoppingCart cart,
Guid productId,
CartItem item) =>
{
var shoppingCart = await GetShoppingCartClient(context, user);
var shoppingCartItem = await GetValidItem(context, productId, shoppingCart, item);
if (shoppingCartItem == null) return CustomResponse();
shoppingCart.UpdateUnit(shoppingCartItem, item.Quantity);
ValidateShoppingCart(shoppingCart);
if (Errors.Any()) return CustomResponse();
context.CartItems.Update(shoppingCartItem);
context.CustomerShoppingCart.Update(shoppingCart);
await Persist(context);
return CustomResponse();
})
CartItem item) => await cart.UpdateItem(productId, item))
.ProducesValidationProblem()
.Produces<CartItem>(StatusCodes.Status204NoContent)
.Produces(StatusCodes.Status400BadRequest)
.WithName("UpdateItem")
.WithTags("ShoppingCart");

app.MapDelete("/shopping-cart/{productId}", [Authorize] async (
ShoppingCartContext context,
IAspNetUser user,
Guid productId) =>
{
var cart = await GetShoppingCartClient(context, user);
var item = await GetValidItem(context, productId, cart);
if (item == null) return CustomResponse();
ValidateShoppingCart(cart);
if (Errors.Any()) return CustomResponse();
cart.RemoveItem(item);
context.CartItems.Remove(item);
context.CustomerShoppingCart.Update(cart);
await Persist(context);
return CustomResponse();
})
ShoppingCart cart,
Guid productId) => await cart.RemoveItem(productId))
.ProducesValidationProblem()
.Produces<CartItem>(StatusCodes.Status204NoContent)
.Produces(StatusCodes.Status400BadRequest)
Expand All @@ -143,122 +87,13 @@ await GetShoppingCartClient(context, user) ?? new CustomerShoppingCart())
.WithTags("ShoppingCart");

app.MapPost("/shopping-cart/apply-voucher", [Authorize] async (
ShoppingCartContext context,
IAspNetUser user,
Voucher voucher) =>
{
var cart = await GetShoppingCartClient(context, user);
cart.ApplyVoucher(voucher);
context.CustomerShoppingCart.Update(cart);
await Persist(context);
return CustomResponse();
})
ShoppingCart cart,
Voucher voucher) => await cart.ApplyVoucher(voucher))
.ProducesValidationProblem()
.Produces<CartItem>(StatusCodes.Status204NoContent)
.Produces(StatusCodes.Status400BadRequest)
.WithName("ApplyVoucher")
.WithTags("ShoppingCart");
}

#endregion

#region Action Methods

async Task<CustomerShoppingCart> GetShoppingCartClient(ShoppingCartContext context, IAspNetUser user)
{
return await context.CustomerShoppingCart
.Include(c => c.Items)
.FirstOrDefaultAsync(c => c.CustomerId == user.GetUserId());
}

void ManageNewCart(ShoppingCartContext context, IAspNetUser user, CartItem item)
{
var cart = new CustomerShoppingCart(user.GetUserId());
cart.AddItem(item);

ValidateShoppingCart(cart);
context.CustomerShoppingCart.Add(cart);
}

void ManageCart(ShoppingCartContext context, CustomerShoppingCart cart, CartItem item)
{
var savedItem = cart.HasItem(item);

cart.AddItem(item);
ValidateShoppingCart(cart);

if (savedItem)
{
context.CartItems.Update(cart.GetProductById(item.ProductId));
}
else
{
context.CartItems.Add(item);
}

context.CustomerShoppingCart.Update(cart);
}

async Task<CartItem> GetValidItem(ShoppingCartContext context, Guid productId, CustomerShoppingCart cart, CartItem item = null)
{
if (item != null && productId != item.ProductId)
{
AddErrorToStack("Current item is not the same sent item");
return null;
}

if (cart == null)
{
AddErrorToStack("Shopping cart not found");
return null;
}

var cartItem = await context.CartItems
.FirstOrDefaultAsync(i => i.ShoppingCartId == cart.Id && i.ProductId == productId);

if (cartItem == null || !cart.HasItem(cartItem))
{
AddErrorToStack("The item is not in cart");
return null;
}

return cartItem;
}

async Task Persist(ShoppingCartContext context)
{
var result = await context.SaveChangesAsync();
if (result <= 0) AddErrorToStack("Error saving data");
}

bool ValidateShoppingCart(CustomerShoppingCart shoppingCart)
{
if (shoppingCart.IsValid()) return true;

shoppingCart.ValidationResult.Errors.ToList().ForEach(e => AddErrorToStack(e.ErrorMessage));
return false;
}

void AddErrorToStack(string error)
{
Errors.Add(error);
}

IResult CustomResponse(object result = null)
{
if (!Errors.Any())
{
return Results.Ok(result);
}

return Results.BadRequest(Results.ValidationProblem(
new Dictionary<string, string[]>
{
{ "Messages", Errors.ToArray() }
}));
}

#endregion
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using DevStore.Core.Messages.Integration;
using DevStore.MessageBus;
using DevStore.ShoppingCart.API.Data;
using Microsoft.EntityFrameworkCore;

namespace DevStore.ShoppingCart.API.Services
Expand Down Expand Up @@ -29,7 +30,7 @@ private void SetSubscribers()
private async Task RemoveShoppingCart(OrderDoneIntegrationEvent message)
{
using var scope = _serviceProvider.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<Data.ShoppingCartContext>();
var context = scope.ServiceProvider.GetRequiredService<ShoppingCartContext>();

var shoppingCart = await context.CustomerShoppingCart
.FirstOrDefaultAsync(c => c.CustomerId == message.CustomerId);
Expand Down

0 comments on commit a6c3014

Please sign in to comment.