Add two basic CQRS commands/queries
This commit is contained in:
@@ -6,11 +6,6 @@
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Products\Commands\" />
|
||||
<Folder Include="Products\Queries\" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AutoMapper" Version="14.0.0" />
|
||||
<PackageReference Include="FluentValidation" Version="12.0.0-preview1" />
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
using MediatR;
|
||||
using Printbase.Application.Products.Dtos;
|
||||
|
||||
namespace Printbase.Application.Products.Commands.CreateProduct;
|
||||
|
||||
public class CreateProductCommand : IRequest<ProductDto>
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string? Description { get; set; }
|
||||
public Guid TypeId { get; set; }
|
||||
public List<CreateProductVariantDto>? Variants { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using MediatR;
|
||||
using Printbase.Application.Products.Dtos;
|
||||
using Printbase.Domain.Entities.Products;
|
||||
using Printbase.Domain.Repositories;
|
||||
|
||||
namespace Printbase.Application.Products.Commands.CreateProduct;
|
||||
|
||||
public class CreateProductCommandHandler(
|
||||
IProductRepository productRepository,
|
||||
IProductVariantRepository variantRepository,
|
||||
IProductTypeRepository typeRepository)
|
||||
: IRequestHandler<CreateProductCommand, ProductDto>
|
||||
{
|
||||
private readonly IProductRepository _productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
|
||||
private readonly IProductVariantRepository _variantRepository = variantRepository ?? throw new ArgumentNullException(nameof(variantRepository));
|
||||
private readonly IProductTypeRepository _typeRepository = typeRepository ?? throw new ArgumentNullException(nameof(typeRepository));
|
||||
|
||||
public async Task<ProductDto> Handle(CreateProductCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var productType = await _typeRepository.GetByIdAsync(request.TypeId, includeRelations: true, cancellationToken);
|
||||
if (productType == null)
|
||||
{
|
||||
throw new ArgumentException($"Product type with ID {request.TypeId} not found");
|
||||
}
|
||||
|
||||
var product = new Product
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = request.Name,
|
||||
Description = request.Description,
|
||||
TypeId = request.TypeId,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
IsActive = true
|
||||
};
|
||||
|
||||
var createdProduct = await _productRepository.AddAsync(product, cancellationToken);
|
||||
|
||||
var productVariants = new List<ProductVariant>();
|
||||
if (request.Variants != null && request.Variants.Count != 0)
|
||||
{
|
||||
foreach (var variant in request.Variants.Select(variantDto => new ProductVariant
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
ProductId = createdProduct.Id,
|
||||
Color = variantDto.Color,
|
||||
Size = variantDto.Size,
|
||||
Price = variantDto.Price,
|
||||
Discount = variantDto.Discount,
|
||||
Stock = variantDto.Stock,
|
||||
SKU = variantDto.SKU ?? GenerateSku(createdProduct.Name, variantDto.Color, variantDto.Size),
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
IsActive = true
|
||||
}))
|
||||
{
|
||||
var createdVariant = await _variantRepository.AddAsync(variant, cancellationToken);
|
||||
productVariants.Add(createdVariant);
|
||||
}
|
||||
}
|
||||
|
||||
var productDto = new ProductDto
|
||||
{
|
||||
Id = createdProduct.Id,
|
||||
Name = createdProduct.Name,
|
||||
Description = createdProduct.Description,
|
||||
TypeId = createdProduct.TypeId,
|
||||
TypeName = productType.Name,
|
||||
GroupName = productType.Group.Name,
|
||||
CreatedAt = createdProduct.CreatedAt,
|
||||
IsActive = createdProduct.IsActive,
|
||||
Variants = productVariants.Select(v => new ProductVariantDto
|
||||
{
|
||||
Id = v.Id,
|
||||
Color = v.Color,
|
||||
Size = v.Size,
|
||||
Price = v.Price,
|
||||
Discount = v.Discount,
|
||||
Stock = v.Stock,
|
||||
SKU = v.SKU,
|
||||
IsActive = v.IsActive
|
||||
}).ToList()
|
||||
};
|
||||
|
||||
return productDto;
|
||||
}
|
||||
|
||||
private static string GenerateSku(string productName, string? color, string? size)
|
||||
{
|
||||
var prefix = productName.Length >= 3 ? productName[..3].ToUpper() : productName.ToUpper();
|
||||
var colorPart = !string.IsNullOrEmpty(color) ? color[..Math.Min(3, color.Length)].ToUpper() : "XXX";
|
||||
var sizePart = !string.IsNullOrEmpty(size) ? size.ToUpper() : "OS";
|
||||
var randomPart = new Random().Next(100, 999).ToString();
|
||||
|
||||
return $"{prefix}-{colorPart}-{sizePart}-{randomPart}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace Printbase.Application.Products.Commands.CreateProduct;
|
||||
|
||||
public class CreateProductVariantDto
|
||||
{
|
||||
public string? Color { get; set; }
|
||||
public string? Size { get; set; }
|
||||
public decimal Price { get; set; }
|
||||
public decimal? Discount { get; set; }
|
||||
public int Stock { get; set; }
|
||||
public string? SKU { get; set; }
|
||||
}
|
||||
15
src/Printbase.Application/Products/Dtos/ProductDto.cs
Normal file
15
src/Printbase.Application/Products/Dtos/ProductDto.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
namespace Printbase.Application.Products.Dtos;
|
||||
|
||||
public class ProductDto
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string? Description { get; set; }
|
||||
public Guid TypeId { get; set; }
|
||||
public string TypeName { get; set; } = string.Empty;
|
||||
public string GroupName { get; set; } = string.Empty;
|
||||
public ICollection<ProductVariantDto>? Variants { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime? UpdatedAt { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
}
|
||||
14
src/Printbase.Application/Products/Dtos/ProductVariantDto.cs
Normal file
14
src/Printbase.Application/Products/Dtos/ProductVariantDto.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
namespace Printbase.Application.Products.Dtos;
|
||||
|
||||
public class ProductVariantDto
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string? Color { get; set; }
|
||||
public string? Size { get; set; }
|
||||
public decimal Price { get; set; }
|
||||
public decimal? Discount { get; set; }
|
||||
public decimal DiscountedPrice => Discount is > 0 ? Price - Price * Discount.Value / 100m : Price;
|
||||
public int Stock { get; set; }
|
||||
public string? SKU { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using MediatR;
|
||||
using Printbase.Application.Products.Dtos;
|
||||
|
||||
namespace Printbase.Application.Products.Queries;
|
||||
|
||||
public class GetProductByIdQuery(Guid id, bool includeVariants = true) : IRequest<ProductDto?>
|
||||
{
|
||||
public Guid Id { get; } = id;
|
||||
public bool IncludeVariants { get; } = includeVariants;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using AutoMapper;
|
||||
using MediatR;
|
||||
using Printbase.Application.Products.Dtos;
|
||||
using Printbase.Domain.Repositories;
|
||||
|
||||
namespace Printbase.Application.Products.Queries.GetProductById;
|
||||
|
||||
public class GetProductByIdQueryHandler(IProductRepository productRepository, IMapper mapper)
|
||||
: IRequestHandler<GetProductByIdQuery, ProductDto?>
|
||||
{
|
||||
private readonly IProductRepository _productRepository = productRepository
|
||||
?? throw new ArgumentNullException(nameof(productRepository));
|
||||
private readonly IMapper _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
|
||||
|
||||
public async Task<ProductDto?> Handle(GetProductByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var product = await _productRepository.GetByIdAsync(request.Id, includeRelations: true, cancellationToken);
|
||||
|
||||
if (product == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var productDto = new ProductDto
|
||||
{
|
||||
Id = product.Id,
|
||||
Name = product.Name,
|
||||
Description = product.Description,
|
||||
TypeId = product.TypeId,
|
||||
TypeName = product.Type.Name,
|
||||
GroupName = product.Type.Group.Name,
|
||||
CreatedAt = product.CreatedAt,
|
||||
UpdatedAt = product.UpdatedAt,
|
||||
IsActive = product.IsActive
|
||||
};
|
||||
|
||||
if (request.IncludeVariants)
|
||||
{
|
||||
productDto.Variants = product.Variants
|
||||
.Select(v => new ProductVariantDto
|
||||
{
|
||||
Id = v.Id,
|
||||
Color = v.Color,
|
||||
Size = v.Size,
|
||||
Price = v.Price,
|
||||
Discount = v.Discount,
|
||||
Stock = v.Stock,
|
||||
SKU = v.SKU,
|
||||
IsActive = v.IsActive
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
|
||||
return productDto;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using AutoMapper;
|
||||
using Printbase.Application.Products.Commands.CreateProduct;
|
||||
using Printbase.Application.Products.Dtos;
|
||||
using Printbase.Domain.Entities.Products;
|
||||
using Printbase.Infrastructure.DbEntities.Products;
|
||||
|
||||
@@ -9,43 +11,65 @@ public class ProductMappingProfile : Profile
|
||||
public ProductMappingProfile()
|
||||
{
|
||||
CreateMap<ProductDbEntity, Product>()
|
||||
.ForMember(dest => dest.Type,
|
||||
opt => opt.MapFrom(src => src.Type))
|
||||
.ForMember(dest => dest.Variants,
|
||||
opt => opt.MapFrom(src => src.Variants));
|
||||
.ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.Type))
|
||||
.ForMember(dest => dest.Variants, opt => opt.MapFrom(src => src.Variants));
|
||||
|
||||
CreateMap<Product, ProductDbEntity>()
|
||||
.ForMember(dest => dest.Type,
|
||||
opt => opt.Ignore()) // in repo
|
||||
.ForMember(dest => dest.Variants,
|
||||
opt => opt.Ignore()); // in repo
|
||||
.ForMember(dest => dest.Type, opt => opt.Ignore()) // Handle in repository
|
||||
.ForMember(dest => dest.Variants, opt => opt.Ignore()); // Handle in repository
|
||||
|
||||
// ProductVariant mapping
|
||||
CreateMap<ProductVariantDbEntity, ProductVariant>()
|
||||
.ForMember(dest => dest.Product,
|
||||
opt => opt.MapFrom(src => src.Product));
|
||||
.ForMember(dest => dest.Product, opt => opt.MapFrom(src => src.Product));
|
||||
|
||||
CreateMap<ProductVariant, ProductVariantDbEntity>()
|
||||
.ForMember(dest => dest.Product,
|
||||
opt => opt.Ignore()); // in repo
|
||||
.ForMember(dest => dest.Product, opt => opt.Ignore()); // Handle in repository
|
||||
|
||||
// ProductType mapping
|
||||
CreateMap<ProductTypeDbEntity, ProductType>()
|
||||
.ForMember(dest => dest.Group,
|
||||
opt => opt.MapFrom(src => src.Group))
|
||||
.ForMember(dest => dest.Products,
|
||||
opt => opt.MapFrom(src => src.Products));
|
||||
.ForMember(dest => dest.Group, opt => opt.MapFrom(src => src.Group))
|
||||
.ForMember(dest => dest.Products, opt => opt.MapFrom(src => src.Products));
|
||||
|
||||
CreateMap<ProductType, ProductTypeDbEntity>()
|
||||
.ForMember(dest => dest.Group,
|
||||
opt => opt.Ignore()) // in repo
|
||||
.ForMember(dest => dest.Products,
|
||||
opt => opt.Ignore()); // in repo
|
||||
.ForMember(dest => dest.Group, opt => opt.Ignore()) // Handle in repository
|
||||
.ForMember(dest => dest.Products, opt => opt.Ignore()); // Handle in repository
|
||||
|
||||
// ProductGroup mapping
|
||||
CreateMap<ProductGroupDbEntity, ProductGroup>()
|
||||
.ForMember(dest => dest.Types,
|
||||
opt => opt.MapFrom(src => src.Types));
|
||||
.ForMember(dest => dest.Types, opt => opt.MapFrom(src => src.Types));
|
||||
|
||||
CreateMap<ProductGroup, ProductGroupDbEntity>()
|
||||
.ForMember(dest => dest.Types,
|
||||
opt => opt.Ignore()); // in repo
|
||||
.ForMember(dest => dest.Types, opt => opt.Ignore()); // Handle in repository
|
||||
|
||||
// Domain <-> DTO mappings
|
||||
|
||||
// Product to DTO mapping
|
||||
CreateMap<Product, ProductDto>()
|
||||
.ForMember(dest => dest.TypeName, opt => opt.MapFrom(src => src.Type.Name))
|
||||
.ForMember(dest => dest.GroupName, opt => opt.MapFrom(src => src.Type.Group.Name))
|
||||
.ForMember(dest => dest.Variants, opt => opt.MapFrom(src => src.Variants));
|
||||
|
||||
// ProductVariant to DTO mapping
|
||||
CreateMap<ProductVariant, ProductVariantDto>();
|
||||
|
||||
// Command to Domain mappings
|
||||
|
||||
// CreateProductCommand to Product mapping
|
||||
CreateMap<CreateProductCommand, Product>()
|
||||
.ForMember(dest => dest.Id, opt => opt.Ignore())
|
||||
.ForMember(dest => dest.Type, opt => opt.Ignore())
|
||||
.ForMember(dest => dest.Variants, opt => opt.Ignore())
|
||||
.ForMember(dest => dest.CreatedAt, opt => opt.Ignore())
|
||||
.ForMember(dest => dest.UpdatedAt, opt => opt.Ignore())
|
||||
.ForMember(dest => dest.IsActive, opt => opt.Ignore());
|
||||
|
||||
// CreateProductVariantDto to ProductVariant mapping
|
||||
CreateMap<CreateProductVariantDto, ProductVariant>()
|
||||
.ForMember(dest => dest.Id, opt => opt.Ignore())
|
||||
.ForMember(dest => dest.ProductId, opt => opt.Ignore())
|
||||
.ForMember(dest => dest.Product, opt => opt.Ignore())
|
||||
.ForMember(dest => dest.CreatedAt, opt => opt.Ignore())
|
||||
.ForMember(dest => dest.UpdatedAt, opt => opt.Ignore())
|
||||
.ForMember(dest => dest.IsActive, opt => opt.Ignore());
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Printbase.Application\Printbase.Application.csproj" />
|
||||
<ProjectReference Include="..\Printbase.Domain\Printbase.Domain.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
50
src/Printbase.WebApi/Controllers/ProductsController.cs
Normal file
50
src/Printbase.WebApi/Controllers/ProductsController.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Printbase.Application.Products.Commands.CreateProduct;
|
||||
using Printbase.Application.Products.Queries;
|
||||
|
||||
namespace Printbase.WebApi.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class ProductsController(IMediator mediator) : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
|
||||
|
||||
[HttpGet("{id}")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetProductById(Guid id, [FromQuery] bool includeVariants = true)
|
||||
{
|
||||
var query = new GetProductByIdQuery(id, includeVariants);
|
||||
var result = await _mediator.Send(query);
|
||||
|
||||
if (result == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[ProducesResponseType(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> CreateProduct([FromBody] CreateProductCommand command)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
{
|
||||
return BadRequest(ModelState);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var result = await _mediator.Send(command);
|
||||
return CreatedAtAction(nameof(GetProductById), new { id = result.Id }, result);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
return BadRequest(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user