Add two basic CQRS commands/queries

This commit is contained in:
lumijiez
2025-05-05 00:01:30 +03:00
parent d9332cef96
commit 6e1a1b2429
11 changed files with 312 additions and 29 deletions

View File

@@ -6,11 +6,6 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Folder Include="Products\Commands\" />
<Folder Include="Products\Queries\" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" /> <PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="FluentValidation" Version="12.0.0-preview1" /> <PackageReference Include="FluentValidation" Version="12.0.0-preview1" />

View File

@@ -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; }
}

View File

@@ -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}";
}
}

View File

@@ -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; }
}

View 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; }
}

View 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; }
}

View File

@@ -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;
}

View File

@@ -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;
}
}

View File

@@ -1,4 +1,6 @@
using AutoMapper; using AutoMapper;
using Printbase.Application.Products.Commands.CreateProduct;
using Printbase.Application.Products.Dtos;
using Printbase.Domain.Entities.Products; using Printbase.Domain.Entities.Products;
using Printbase.Infrastructure.DbEntities.Products; using Printbase.Infrastructure.DbEntities.Products;
@@ -9,43 +11,65 @@ public class ProductMappingProfile : Profile
public ProductMappingProfile() public ProductMappingProfile()
{ {
CreateMap<ProductDbEntity, Product>() CreateMap<ProductDbEntity, Product>()
.ForMember(dest => dest.Type, .ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.Type))
opt => opt.MapFrom(src => src.Type)) .ForMember(dest => dest.Variants, opt => opt.MapFrom(src => src.Variants));
.ForMember(dest => dest.Variants,
opt => opt.MapFrom(src => src.Variants));
CreateMap<Product, ProductDbEntity>() CreateMap<Product, ProductDbEntity>()
.ForMember(dest => dest.Type, .ForMember(dest => dest.Type, opt => opt.Ignore()) // Handle in repository
opt => opt.Ignore()) // in repo .ForMember(dest => dest.Variants, opt => opt.Ignore()); // Handle in repository
.ForMember(dest => dest.Variants,
opt => opt.Ignore()); // in repo
// ProductVariant mapping
CreateMap<ProductVariantDbEntity, ProductVariant>() CreateMap<ProductVariantDbEntity, ProductVariant>()
.ForMember(dest => dest.Product, .ForMember(dest => dest.Product, opt => opt.MapFrom(src => src.Product));
opt => opt.MapFrom(src => src.Product));
CreateMap<ProductVariant, ProductVariantDbEntity>() CreateMap<ProductVariant, ProductVariantDbEntity>()
.ForMember(dest => dest.Product, .ForMember(dest => dest.Product, opt => opt.Ignore()); // Handle in repository
opt => opt.Ignore()); // in repo
// ProductType mapping
CreateMap<ProductTypeDbEntity, ProductType>() CreateMap<ProductTypeDbEntity, ProductType>()
.ForMember(dest => dest.Group, .ForMember(dest => dest.Group, opt => opt.MapFrom(src => src.Group))
opt => opt.MapFrom(src => src.Group)) .ForMember(dest => dest.Products, opt => opt.MapFrom(src => src.Products));
.ForMember(dest => dest.Products,
opt => opt.MapFrom(src => src.Products));
CreateMap<ProductType, ProductTypeDbEntity>() CreateMap<ProductType, ProductTypeDbEntity>()
.ForMember(dest => dest.Group, .ForMember(dest => dest.Group, opt => opt.Ignore()) // Handle in repository
opt => opt.Ignore()) // in repo .ForMember(dest => dest.Products, opt => opt.Ignore()); // Handle in repository
.ForMember(dest => dest.Products,
opt => opt.Ignore()); // in repo
// ProductGroup mapping
CreateMap<ProductGroupDbEntity, ProductGroup>() CreateMap<ProductGroupDbEntity, ProductGroup>()
.ForMember(dest => dest.Types, .ForMember(dest => dest.Types, opt => opt.MapFrom(src => src.Types));
opt => opt.MapFrom(src => src.Types));
CreateMap<ProductGroup, ProductGroupDbEntity>() CreateMap<ProductGroup, ProductGroupDbEntity>()
.ForMember(dest => dest.Types, .ForMember(dest => dest.Types, opt => opt.Ignore()); // Handle in repository
opt => opt.Ignore()); // in repo
// 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());
} }
} }

View File

@@ -13,6 +13,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Printbase.Application\Printbase.Application.csproj" />
<ProjectReference Include="..\Printbase.Domain\Printbase.Domain.csproj" /> <ProjectReference Include="..\Printbase.Domain\Printbase.Domain.csproj" />
</ItemGroup> </ItemGroup>

View 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);
}
}
}