feat: Add initial PromotionService solution structure including domain, API, and test projects.

This commit is contained in:
Ho Ngoc Hai
2026-01-17 21:28:29 +07:00
parent 2fa92bb52c
commit 803f510d07
69 changed files with 4096 additions and 0 deletions

View File

@@ -529,6 +529,57 @@ services:
- "traefik.http.services.mission-service.loadbalancer.healthcheck.path=/health/live"
- "traefik.http.services.mission-service.loadbalancer.healthcheck.interval=10s"
# Promotion Service .NET - Voucher, Gift Card, Campaign Management
promotion-service-net:
build:
context: ../../services/promotion-service-net
dockerfile: Dockerfile
image: goodgo/promotion-service-net:latest
container_name: promotion-service-net-local
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=http://+:8080
# EN: Database - Neon PostgreSQL
# VI: Cơ sở dữ liệu - Neon PostgreSQL
- ConnectionStrings__DefaultConnection=Host=ep-holy-glitter-a4hongg7-pooler.us-east-1.aws.neon.tech;Port=5432;Database=promotion_service;Username=neondb_owner;Password=npg_Ssfy6HKO0cXI;SSL Mode=Require
# EN: IAM Service Communication
# VI: Giao tiếp IAM Service
- IamService__BaseUrl=http://iam-service-net:8080
- IamService__ServiceName=promotion-service
# EN: Wallet Service Communication
# VI: Giao tiếp Wallet Service
- WalletService__BaseUrl=http://wallet-service-net:8080
# EN: JWT Configuration
# VI: Cấu hình JWT
- Jwt__Authority=http://iam-service-net:8080
- Jwt__Audience=goodgo-api
- Jwt__RequireHttpsMetadata=false
ports:
- "5008:8080"
depends_on:
iam-service-net:
condition: service_healthy
wallet-service-net:
condition: service_healthy
traefik:
condition: service_started
networks:
- microservices-network
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health/live"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
labels:
- "traefik.enable=true"
- "traefik.http.routers.promotion-service.rule=PathPrefix(`/api/v1/campaigns`) || PathPrefix(`/api/v1/vouchers`) || PathPrefix(`/api/v1/admin/campaigns`) || PathPrefix(`/api/v1/admin/vouchers`)"
- "traefik.http.routers.promotion-service.entrypoints=web"
- "traefik.http.services.promotion-service.loadbalancer.server.port=8080"
- "traefik.http.services.promotion-service.loadbalancer.healthcheck.path=/health/live"
- "traefik.http.services.promotion-service.loadbalancer.healthcheck.interval=10s"
# Jaeger - Distributed Tracing
# jaeger:

View File

@@ -0,0 +1,22 @@
<Project>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591;CA2017</NoWarn>
</PropertyGroup>
<PropertyGroup>
<Authors>GoodGo Team</Authors>
<Company>GoodGo</Company>
<Copyright>© 2026 GoodGo. All rights reserved.</Copyright>
<RepositoryType>git</RepositoryType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="All" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,66 @@
# Build stage / Giai đoạn build
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
# EN: Copy project files for layer caching
# VI: Sao chép các file project để tận dụng layer caching
COPY ["src/PromotionService.API/PromotionService.API.csproj", "src/PromotionService.API/"]
COPY ["src/PromotionService.Domain/PromotionService.Domain.csproj", "src/PromotionService.Domain/"]
COPY ["src/PromotionService.Infrastructure/PromotionService.Infrastructure.csproj", "src/PromotionService.Infrastructure/"]
COPY ["Directory.Build.props", "./"]
# EN: Restore dependencies
# VI: Khôi phục dependencies
RUN dotnet restore "src/PromotionService.API/PromotionService.API.csproj"
# EN: Copy all source code
# VI: Sao chép toàn bộ source code
COPY src/ ./src/
# EN: Build the application
# VI: Build ứng dụng
WORKDIR "/src/src/PromotionService.API"
RUN dotnet build "PromotionService.API.csproj" -c Release -o /app/build --no-restore
# Publish stage / Giai đoạn publish
FROM build AS publish
RUN dotnet publish "PromotionService.API.csproj" -c Release -o /app/publish /p:UseAppHost=false --no-restore
# Runtime stage / Giai đoạn runtime
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final
WORKDIR /app
# EN: Create non-root user for security
# VI: Tạo user non-root cho bảo mật
RUN groupadd -g 1001 dotnetuser && \
useradd -u 1001 -g dotnetuser -s /bin/sh dotnetuser
# EN: Copy published application
# VI: Sao chép ứng dụng đã publish
COPY --from=publish /app/publish .
# EN: Change ownership to non-root user
# VI: Thay đổi quyền sở hữu sang user non-root
RUN chown -R dotnetuser:dotnetuser /app
# EN: Switch to non-root user
# VI: Chuyển sang user non-root
USER dotnetuser
# EN: Expose port
# VI: Mở cổng
EXPOSE 8080
# EN: Set environment variables
# VI: Thiết lập biến môi trường
ENV ASPNETCORE_URLS=http://+:8080
ENV ASPNETCORE_ENVIRONMENT=Production
# EN: Health check
# VI: Kiểm tra health
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD curl -f http://localhost:8080/health/live || exit 1
# EN: Start the application
# VI: Khởi động ứng dụng
ENTRYPOINT ["dotnet", "PromotionService.API.dll"]

View File

@@ -0,0 +1,11 @@
<Solution>
<Folder Name="/src/">
<Project Path="src/PromotionService.API/PromotionService.API.csproj" />
<Project Path="src/PromotionService.Domain/PromotionService.Domain.csproj" />
<Project Path="src/PromotionService.Infrastructure/PromotionService.Infrastructure.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/PromotionService.FunctionalTests/PromotionService.FunctionalTests.csproj" />
<Project Path="tests/PromotionService.UnitTests/PromotionService.UnitTests.csproj" />
</Folder>
</Solution>

View File

@@ -0,0 +1,72 @@
version: '3.8'
# EN: Docker Compose for local development
# VI: Docker Compose cho phát triển local
services:
myservice-api:
build:
context: .
dockerfile: Dockerfile
container_name: myservice-api
ports:
- "5000:8080"
environment:
- ASPNETCORE_ENVIRONMENT=Development
- DATABASE_URL=Host=postgres;Port=5432;Database=myservice_db;Username=postgres;Password=postgres
- REDIS_URL=redis:6379
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
networks:
- myservice-network
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health/live"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s
postgres:
image: postgres:16-alpine
container_name: myservice-postgres
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: myservice_db
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- myservice-network
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5
redis:
image: redis:7-alpine
container_name: myservice-redis
ports:
- "6379:6379"
volumes:
- redis_data:/data
networks:
- myservice-network
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
volumes:
postgres_data:
redis_data:
networks:
myservice-network:
driver: bridge

View File

@@ -0,0 +1,7 @@
{
"sdk": {
"version": "10.0.101",
"rollForward": "latestMinor",
"allowPrerelease": false
}
}

View File

@@ -0,0 +1,58 @@
using System.Diagnostics;
using MediatR;
namespace PromotionService.API.Application.Behaviors;
/// <summary>
/// EN: MediatR behavior for logging request handling.
/// VI: MediatR behavior để logging việc xử lý request.
/// </summary>
/// <typeparam name="TRequest">EN: Request type / VI: Loại request</typeparam>
/// <typeparam name="TResponse">EN: Response type / VI: Loại response</typeparam>
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;
public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
var requestName = typeof(TRequest).Name;
_logger.LogInformation(
"Handling {RequestName} / Đang xử lý {RequestName}",
requestName);
var stopwatch = Stopwatch.StartNew();
try
{
var response = await next();
stopwatch.Stop();
_logger.LogInformation(
"Handled {RequestName} in {ElapsedMs}ms / Đã xử lý {RequestName} trong {ElapsedMs}ms",
requestName, stopwatch.ElapsedMilliseconds);
return response;
}
catch (Exception ex)
{
stopwatch.Stop();
_logger.LogError(ex,
"Error handling {RequestName} after {ElapsedMs}ms / Lỗi xử lý {RequestName} sau {ElapsedMs}ms",
requestName, stopwatch.ElapsedMilliseconds);
throw;
}
}
}

View File

@@ -0,0 +1,84 @@
using MediatR;
using Microsoft.EntityFrameworkCore;
using PromotionService.Infrastructure;
namespace PromotionService.API.Application.Behaviors;
/// <summary>
/// EN: MediatR behavior for handling database transactions.
/// VI: MediatR behavior để xử lý database transactions.
/// </summary>
/// <typeparam name="TRequest">EN: Request type / VI: Loại request</typeparam>
/// <typeparam name="TResponse">EN: Response type / VI: Loại response</typeparam>
public class TransactionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly PromotionServiceContext _dbContext;
private readonly ILogger<TransactionBehavior<TRequest, TResponse>> _logger;
public TransactionBehavior(
PromotionServiceContext dbContext,
ILogger<TransactionBehavior<TRequest, TResponse>> logger)
{
_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
var requestName = typeof(TRequest).Name;
// EN: Skip transaction for queries (read operations)
// VI: Bỏ qua transaction cho queries (các thao tác đọc)
if (requestName.EndsWith("Query"))
{
return await next();
}
// EN: Skip if already in a transaction
// VI: Bỏ qua nếu đã trong transaction
if (_dbContext.HasActiveTransaction)
{
return await next();
}
var strategy = _dbContext.Database.CreateExecutionStrategy();
return await strategy.ExecuteAsync(async () =>
{
await using var transaction = await _dbContext.BeginTransactionAsync();
_logger.LogInformation(
"Begin transaction {TransactionId} for {RequestName} / Bắt đầu transaction {TransactionId} cho {RequestName}",
transaction?.TransactionId, requestName);
try
{
var response = await next();
if (transaction != null)
{
await _dbContext.CommitTransactionAsync(transaction);
_logger.LogInformation(
"Committed transaction {TransactionId} for {RequestName} / Đã commit transaction {TransactionId} cho {RequestName}",
transaction.TransactionId, requestName);
}
return response;
}
catch (Exception ex)
{
_logger.LogError(ex,
"Error during transaction {TransactionId} for {RequestName} / Lỗi trong transaction {TransactionId} cho {RequestName}",
transaction?.TransactionId, requestName);
_dbContext.RollbackTransaction();
throw;
}
});
}
}

View File

@@ -0,0 +1,63 @@
using FluentValidation;
using MediatR;
namespace PromotionService.API.Application.Behaviors;
/// <summary>
/// EN: MediatR behavior for FluentValidation integration.
/// VI: MediatR behavior để tích hợp FluentValidation.
/// </summary>
/// <typeparam name="TRequest">EN: Request type / VI: Loại request</typeparam>
/// <typeparam name="TResponse">EN: Response type / VI: Loại response</typeparam>
public class ValidatorBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
private readonly ILogger<ValidatorBehavior<TRequest, TResponse>> _logger;
public ValidatorBehavior(
IEnumerable<IValidator<TRequest>> validators,
ILogger<ValidatorBehavior<TRequest, TResponse>> logger)
{
_validators = validators ?? throw new ArgumentNullException(nameof(validators));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
var requestName = typeof(TRequest).Name;
if (!_validators.Any())
{
return await next();
}
_logger.LogDebug(
"Validating {RequestName} / Đang validate {RequestName}",
requestName);
var context = new ValidationContext<TRequest>(request);
var validationResults = await Task.WhenAll(
_validators.Select(v => v.ValidateAsync(context, cancellationToken)));
var failures = validationResults
.SelectMany(r => r.Errors)
.Where(f => f != null)
.ToList();
if (failures.Count != 0)
{
_logger.LogWarning(
"Validation failed for {RequestName} with {ErrorCount} errors / Validation thất bại cho {RequestName} với {ErrorCount} lỗi",
requestName, failures.Count);
throw new ValidationException(failures);
}
return await next();
}
}

View File

@@ -0,0 +1,14 @@
using MediatR;
namespace PromotionService.API.Application.Commands;
/// <summary>
/// EN: Command to change status of a Sample.
/// VI: Command để thay đổi trạng thái của Sample.
/// </summary>
/// <param name="SampleId">EN: Sample ID / VI: ID sample</param>
/// <param name="NewStatus">EN: New status (activate, complete, cancel) / VI: Trạng thái mới (activate, complete, cancel)</param>
public record ChangeSampleStatusCommand(
Guid SampleId,
string NewStatus
) : IRequest<bool>;

View File

@@ -0,0 +1,70 @@
using MediatR;
using PromotionService.Domain.AggregatesModel.SampleAggregate;
namespace PromotionService.API.Application.Commands;
/// <summary>
/// EN: Handler for ChangeSampleStatusCommand.
/// VI: Handler cho ChangeSampleStatusCommand.
/// </summary>
public class ChangeSampleStatusCommandHandler : IRequestHandler<ChangeSampleStatusCommand, bool>
{
private readonly ISampleRepository _sampleRepository;
private readonly ILogger<ChangeSampleStatusCommandHandler> _logger;
public ChangeSampleStatusCommandHandler(
ISampleRepository sampleRepository,
ILogger<ChangeSampleStatusCommandHandler> logger)
{
_sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<bool> Handle(
ChangeSampleStatusCommand request,
CancellationToken cancellationToken)
{
_logger.LogInformation(
"Changing status of sample {SampleId} to {NewStatus} / Thay đổi trạng thái sample {SampleId} thành {NewStatus}",
request.SampleId, request.NewStatus);
// EN: Get existing sample / VI: Lấy sample đã tồn tại
var sample = await _sampleRepository.GetAsync(request.SampleId);
if (sample is null)
{
_logger.LogWarning(
"Sample {SampleId} not found / Sample {SampleId} không tìm thấy",
request.SampleId);
return false;
}
// EN: Change status based on action / VI: Thay đổi trạng thái dựa trên action
switch (request.NewStatus.ToLowerInvariant())
{
case "activate":
sample.Activate();
break;
case "complete":
sample.Complete();
break;
case "cancel":
sample.Cancel();
break;
default:
_logger.LogWarning(
"Invalid status action: {NewStatus} / Action trạng thái không hợp lệ: {NewStatus}",
request.NewStatus);
return false;
}
// EN: Save changes / VI: Lưu thay đổi
await _sampleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
_logger.LogInformation(
"Sample {SampleId} status changed to {NewStatus} / Trạng thái sample {SampleId} đã đổi thành {NewStatus}",
request.SampleId, request.NewStatus);
return true;
}
}

View File

@@ -0,0 +1,21 @@
using MediatR;
namespace PromotionService.API.Application.Commands;
/// <summary>
/// EN: Command to create a new Sample.
/// VI: Command để tạo một Sample mới.
/// </summary>
/// <param name="Name">EN: Sample name / VI: Tên sample</param>
/// <param name="Description">EN: Optional description / VI: Mô tả tùy chọn</param>
public record CreateSampleCommand(
string Name,
string? Description
) : IRequest<CreateSampleCommandResult>;
/// <summary>
/// EN: Result of CreateSampleCommand.
/// VI: Kết quả của CreateSampleCommand.
/// </summary>
/// <param name="Id">EN: Created sample ID / VI: ID sample đã tạo</param>
public record CreateSampleCommandResult(Guid Id);

View File

@@ -0,0 +1,46 @@
using MediatR;
using PromotionService.Domain.AggregatesModel.SampleAggregate;
namespace PromotionService.API.Application.Commands;
/// <summary>
/// EN: Handler for CreateSampleCommand.
/// VI: Handler cho CreateSampleCommand.
/// </summary>
public class CreateSampleCommandHandler : IRequestHandler<CreateSampleCommand, CreateSampleCommandResult>
{
private readonly ISampleRepository _sampleRepository;
private readonly ILogger<CreateSampleCommandHandler> _logger;
public CreateSampleCommandHandler(
ISampleRepository sampleRepository,
ILogger<CreateSampleCommandHandler> logger)
{
_sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<CreateSampleCommandResult> Handle(
CreateSampleCommand request,
CancellationToken cancellationToken)
{
_logger.LogInformation(
"Creating new sample with name: {Name} / Tạo sample mới với tên: {Name}",
request.Name);
// EN: Create domain entity / VI: Tạo domain entity
var sample = new Sample(request.Name, request.Description);
// EN: Add to repository / VI: Thêm vào repository
_sampleRepository.Add(sample);
// EN: Save changes (dispatches domain events) / VI: Lưu thay đổi (dispatch domain events)
await _sampleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
_logger.LogInformation(
"Sample created successfully with ID: {SampleId} / Sample đã tạo thành công với ID: {SampleId}",
sample.Id);
return new CreateSampleCommandResult(sample.Id);
}
}

View File

@@ -0,0 +1,10 @@
using MediatR;
namespace PromotionService.API.Application.Commands;
/// <summary>
/// EN: Command to delete a Sample.
/// VI: Command để xóa một Sample.
/// </summary>
/// <param name="SampleId">EN: Sample ID to delete / VI: ID sample cần xóa</param>
public record DeleteSampleCommand(Guid SampleId) : IRequest<bool>;

View File

@@ -0,0 +1,54 @@
using MediatR;
using PromotionService.Domain.AggregatesModel.SampleAggregate;
namespace PromotionService.API.Application.Commands;
/// <summary>
/// EN: Handler for DeleteSampleCommand.
/// VI: Handler cho DeleteSampleCommand.
/// </summary>
public class DeleteSampleCommandHandler : IRequestHandler<DeleteSampleCommand, bool>
{
private readonly ISampleRepository _sampleRepository;
private readonly ILogger<DeleteSampleCommandHandler> _logger;
public DeleteSampleCommandHandler(
ISampleRepository sampleRepository,
ILogger<DeleteSampleCommandHandler> logger)
{
_sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<bool> Handle(
DeleteSampleCommand request,
CancellationToken cancellationToken)
{
_logger.LogInformation(
"Deleting sample {SampleId} / Xóa sample {SampleId}",
request.SampleId);
// EN: Get existing sample / VI: Lấy sample đã tồn tại
var sample = await _sampleRepository.GetAsync(request.SampleId);
if (sample is null)
{
_logger.LogWarning(
"Sample {SampleId} not found / Sample {SampleId} không tìm thấy",
request.SampleId);
return false;
}
// EN: Delete sample / VI: Xóa sample
_sampleRepository.Delete(sample);
// EN: Save changes / VI: Lưu thay đổi
await _sampleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
_logger.LogInformation(
"Sample {SampleId} deleted successfully / Sample {SampleId} đã xóa thành công",
request.SampleId);
return true;
}
}

View File

@@ -0,0 +1,16 @@
using MediatR;
namespace PromotionService.API.Application.Commands;
/// <summary>
/// EN: Command to update an existing Sample.
/// VI: Command để cập nhật một Sample đã tồn tại.
/// </summary>
/// <param name="SampleId">EN: Sample ID to update / VI: ID sample cần cập nhật</param>
/// <param name="Name">EN: New name / VI: Tên mới</param>
/// <param name="Description">EN: New description / VI: Mô tả mới</param>
public record UpdateSampleCommand(
Guid SampleId,
string Name,
string? Description
) : IRequest<bool>;

View File

@@ -0,0 +1,54 @@
using MediatR;
using PromotionService.Domain.AggregatesModel.SampleAggregate;
namespace PromotionService.API.Application.Commands;
/// <summary>
/// EN: Handler for UpdateSampleCommand.
/// VI: Handler cho UpdateSampleCommand.
/// </summary>
public class UpdateSampleCommandHandler : IRequestHandler<UpdateSampleCommand, bool>
{
private readonly ISampleRepository _sampleRepository;
private readonly ILogger<UpdateSampleCommandHandler> _logger;
public UpdateSampleCommandHandler(
ISampleRepository sampleRepository,
ILogger<UpdateSampleCommandHandler> logger)
{
_sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<bool> Handle(
UpdateSampleCommand request,
CancellationToken cancellationToken)
{
_logger.LogInformation(
"Updating sample {SampleId} / Cập nhật sample {SampleId}",
request.SampleId);
// EN: Get existing sample / VI: Lấy sample đã tồn tại
var sample = await _sampleRepository.GetAsync(request.SampleId);
if (sample is null)
{
_logger.LogWarning(
"Sample {SampleId} not found / Sample {SampleId} không tìm thấy",
request.SampleId);
return false;
}
// EN: Update sample using domain method / VI: Cập nhật sample sử dụng domain method
sample.Update(request.Name, request.Description);
// EN: Save changes / VI: Lưu thay đổi
await _sampleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
_logger.LogInformation(
"Sample {SampleId} updated successfully / Sample {SampleId} đã cập nhật thành công",
request.SampleId);
return true;
}
}

View File

@@ -0,0 +1,23 @@
using MediatR;
namespace PromotionService.API.Application.Queries;
/// <summary>
/// EN: Query to get a Sample by ID.
/// VI: Query để lấy một Sample theo ID.
/// </summary>
/// <param name="SampleId">EN: Sample ID / VI: ID sample</param>
public record GetSampleQuery(Guid SampleId) : IRequest<SampleViewModel?>;
/// <summary>
/// EN: Sample view model for API responses.
/// VI: Sample view model cho API responses.
/// </summary>
public record SampleViewModel(
Guid Id,
string Name,
string? Description,
string Status,
DateTime CreatedAt,
DateTime? UpdatedAt
);

View File

@@ -0,0 +1,39 @@
using MediatR;
using PromotionService.Domain.AggregatesModel.SampleAggregate;
namespace PromotionService.API.Application.Queries;
/// <summary>
/// EN: Handler for GetSampleQuery.
/// VI: Handler cho GetSampleQuery.
/// </summary>
public class GetSampleQueryHandler : IRequestHandler<GetSampleQuery, SampleViewModel?>
{
private readonly ISampleRepository _sampleRepository;
public GetSampleQueryHandler(ISampleRepository sampleRepository)
{
_sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository));
}
public async Task<SampleViewModel?> Handle(
GetSampleQuery request,
CancellationToken cancellationToken)
{
var sample = await _sampleRepository.GetAsync(request.SampleId);
if (sample is null)
{
return null;
}
return new SampleViewModel(
sample.Id,
sample.Name,
sample.Description,
sample.Status.Name,
sample.CreatedAt,
sample.UpdatedAt
);
}
}

View File

@@ -0,0 +1,9 @@
using MediatR;
namespace PromotionService.API.Application.Queries;
/// <summary>
/// EN: Query to get all Samples.
/// VI: Query để lấy tất cả Samples.
/// </summary>
public record GetSamplesQuery : IRequest<IEnumerable<SampleViewModel>>;

View File

@@ -0,0 +1,34 @@
using MediatR;
using PromotionService.Domain.AggregatesModel.SampleAggregate;
namespace PromotionService.API.Application.Queries;
/// <summary>
/// EN: Handler for GetSamplesQuery.
/// VI: Handler cho GetSamplesQuery.
/// </summary>
public class GetSamplesQueryHandler : IRequestHandler<GetSamplesQuery, IEnumerable<SampleViewModel>>
{
private readonly ISampleRepository _sampleRepository;
public GetSamplesQueryHandler(ISampleRepository sampleRepository)
{
_sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository));
}
public async Task<IEnumerable<SampleViewModel>> Handle(
GetSamplesQuery request,
CancellationToken cancellationToken)
{
var samples = await _sampleRepository.GetAllAsync();
return samples.Select(sample => new SampleViewModel(
sample.Id,
sample.Name,
sample.Description,
sample.Status.Name,
sample.CreatedAt,
sample.UpdatedAt
));
}
}

View File

@@ -0,0 +1,25 @@
using FluentValidation;
using PromotionService.API.Application.Commands;
namespace PromotionService.API.Application.Validations;
/// <summary>
/// EN: Validator for CreateSampleCommand.
/// VI: Validator cho CreateSampleCommand.
/// </summary>
public class CreateSampleCommandValidator : AbstractValidator<CreateSampleCommand>
{
public CreateSampleCommandValidator()
{
RuleFor(x => x.Name)
.NotEmpty()
.WithMessage("Name is required / Tên là bắt buộc")
.MaximumLength(200)
.WithMessage("Name must be less than 200 characters / Tên phải ít hơn 200 ký tự");
RuleFor(x => x.Description)
.MaximumLength(1000)
.WithMessage("Description must be less than 1000 characters / Mô tả phải ít hơn 1000 ký tự")
.When(x => x.Description != null);
}
}

View File

@@ -0,0 +1,29 @@
using FluentValidation;
using PromotionService.API.Application.Commands;
namespace PromotionService.API.Application.Validations;
/// <summary>
/// EN: Validator for UpdateSampleCommand.
/// VI: Validator cho UpdateSampleCommand.
/// </summary>
public class UpdateSampleCommandValidator : AbstractValidator<UpdateSampleCommand>
{
public UpdateSampleCommandValidator()
{
RuleFor(x => x.SampleId)
.NotEmpty()
.WithMessage("Sample ID is required / ID sample là bắt buộc");
RuleFor(x => x.Name)
.NotEmpty()
.WithMessage("Name is required / Tên là bắt buộc")
.MaximumLength(200)
.WithMessage("Name must be less than 200 characters / Tên phải ít hơn 200 ký tự");
RuleFor(x => x.Description)
.MaximumLength(1000)
.WithMessage("Description must be less than 1000 characters / Mô tả phải ít hơn 1000 ký tự")
.When(x => x.Description != null);
}
}

View File

@@ -0,0 +1,200 @@
using Asp.Versioning;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using PromotionService.API.Application.Commands;
using PromotionService.API.Application.Queries;
namespace PromotionService.API.Controllers;
/// <summary>
/// EN: Controller for Sample CRUD operations using CQRS pattern.
/// VI: Controller cho các thao tác CRUD Sample sử dụng pattern CQRS.
/// </summary>
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[Produces("application/json")]
public class SamplesController : ControllerBase
{
private readonly IMediator _mediator;
private readonly ILogger<SamplesController> _logger;
public SamplesController(IMediator mediator, ILogger<SamplesController> logger)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
/// <summary>
/// EN: Get all samples.
/// VI: Lấy tất cả samples.
/// </summary>
/// <returns>EN: List of samples / VI: Danh sách samples</returns>
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<SampleViewModel>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetSamples()
{
var samples = await _mediator.Send(new GetSamplesQuery());
return Ok(new { success = true, data = samples });
}
/// <summary>
/// EN: Get a sample by ID.
/// VI: Lấy một sample theo ID.
/// </summary>
/// <param name="id">EN: Sample ID / VI: ID sample</param>
/// <returns>EN: Sample details / VI: Chi tiết sample</returns>
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(SampleViewModel), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetSample(Guid id)
{
var sample = await _mediator.Send(new GetSampleQuery(id));
if (sample is null)
{
return NotFound(new
{
success = false,
error = new
{
code = "SAMPLE_NOT_FOUND",
message = $"Sample with ID {id} not found / Sample với ID {id} không tìm thấy"
}
});
}
return Ok(new { success = true, data = sample });
}
/// <summary>
/// EN: Create a new sample.
/// VI: Tạo một sample mới.
/// </summary>
/// <param name="request">EN: Create request / VI: Request tạo</param>
/// <returns>EN: Created sample ID / VI: ID sample đã tạo</returns>
[HttpPost]
[ProducesResponseType(typeof(CreateSampleCommandResult), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> CreateSample([FromBody] CreateSampleRequest request)
{
var command = new CreateSampleCommand(request.Name, request.Description);
var result = await _mediator.Send(command);
return CreatedAtAction(
nameof(GetSample),
new { id = result.Id },
new { success = true, data = result });
}
/// <summary>
/// EN: Update an existing sample.
/// VI: Cập nhật một sample đã tồn tại.
/// </summary>
/// <param name="id">EN: Sample ID / VI: ID sample</param>
/// <param name="request">EN: Update request / VI: Request cập nhật</param>
/// <returns>EN: Success status / VI: Trạng thái thành công</returns>
[HttpPut("{id:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> UpdateSample(Guid id, [FromBody] UpdateSampleRequest request)
{
var command = new UpdateSampleCommand(id, request.Name, request.Description);
var result = await _mediator.Send(command);
if (!result)
{
return NotFound(new
{
success = false,
error = new
{
code = "SAMPLE_NOT_FOUND",
message = $"Sample with ID {id} not found / Sample với ID {id} không tìm thấy"
}
});
}
return Ok(new { success = true, message = "Sample updated successfully / Sample đã cập nhật thành công" });
}
/// <summary>
/// EN: Delete a sample.
/// VI: Xóa một sample.
/// </summary>
/// <param name="id">EN: Sample ID / VI: ID sample</param>
/// <returns>EN: Success status / VI: Trạng thái thành công</returns>
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> DeleteSample(Guid id)
{
var command = new DeleteSampleCommand(id);
var result = await _mediator.Send(command);
if (!result)
{
return NotFound(new
{
success = false,
error = new
{
code = "SAMPLE_NOT_FOUND",
message = $"Sample with ID {id} not found / Sample với ID {id} không tìm thấy"
}
});
}
return NoContent();
}
/// <summary>
/// EN: Change sample status.
/// VI: Thay đổi trạng thái sample.
/// </summary>
/// <param name="id">EN: Sample ID / VI: ID sample</param>
/// <param name="request">EN: Status change request / VI: Request thay đổi trạng thái</param>
/// <returns>EN: Success status / VI: Trạng thái thành công</returns>
[HttpPatch("{id:guid}/status")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> ChangeSampleStatus(Guid id, [FromBody] ChangeStatusRequest request)
{
var command = new ChangeSampleStatusCommand(id, request.Status);
var result = await _mediator.Send(command);
if (!result)
{
return BadRequest(new
{
success = false,
error = new
{
code = "STATUS_CHANGE_FAILED",
message = "Failed to change sample status / Thay đổi trạng thái sample thất bại"
}
});
}
return Ok(new { success = true, message = "Sample status changed successfully / Trạng thái sample đã thay đổi thành công" });
}
}
/// <summary>
/// EN: Request model for creating a sample.
/// VI: Model request để tạo sample.
/// </summary>
public record CreateSampleRequest(string Name, string? Description);
/// <summary>
/// EN: Request model for updating a sample.
/// VI: Model request để cập nhật sample.
/// </summary>
public record UpdateSampleRequest(string Name, string? Description);
/// <summary>
/// EN: Request model for changing sample status.
/// VI: Model request để thay đổi trạng thái sample.
/// </summary>
public record ChangeStatusRequest(string Status);

View File

@@ -0,0 +1,144 @@
using Asp.Versioning;
using FluentValidation;
using Hellang.Middleware.ProblemDetails;
using PromotionService.API.Application.Behaviors;
using PromotionService.Infrastructure;
using Serilog;
// EN: Configure Serilog early / VI: Cấu hình Serilog sớm
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();
try
{
Log.Information("Starting PromotionService API / Khởi động PromotionService API");
var builder = WebApplication.CreateBuilder(args);
// EN: Configure Serilog / VI: Cấu hình Serilog
builder.Host.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.WriteTo.Console());
// EN: Add Infrastructure services / VI: Thêm Infrastructure services
builder.Services.AddInfrastructure(builder.Configuration);
// EN: Add MediatR with behaviors / VI: Thêm MediatR với behaviors
builder.Services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblyContaining<Program>();
cfg.AddOpenBehavior(typeof(LoggingBehavior<,>));
cfg.AddOpenBehavior(typeof(ValidatorBehavior<,>));
cfg.AddOpenBehavior(typeof(TransactionBehavior<,>));
});
// EN: Add FluentValidation / VI: Thêm FluentValidation
builder.Services.AddValidatorsFromAssemblyContaining<Program>();
// EN: Add API versioning / VI: Thêm API versioning
builder.Services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
options.ApiVersionReader = ApiVersionReader.Combine(
new UrlSegmentApiVersionReader(),
new HeaderApiVersionReader("X-Api-Version"));
})
.AddApiExplorer(options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
// EN: Add controllers / VI: Thêm controllers
builder.Services.AddControllers();
// EN: Add ProblemDetails middleware (RFC 7807) / VI: Thêm ProblemDetails middleware
builder.Services.AddProblemDetails(options =>
{
options.IncludeExceptionDetails = (ctx, ex) =>
builder.Environment.IsDevelopment();
});
// EN: Add Swagger / VI: Thêm Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new()
{
Title = "PromotionService API",
Version = "v1",
Description = "PromotionService microservice API / API microservice PromotionService"
});
});
// EN: Add health checks / VI: Thêm health checks
builder.Services.AddHealthChecks()
.AddNpgSql(
builder.Configuration.GetConnectionString("DefaultConnection")
?? builder.Configuration["DATABASE_URL"]
?? "",
name: "postgresql",
tags: ["db", "postgresql"]);
// EN: Add CORS / VI: Thêm CORS
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
var app = builder.Build();
// EN: Configure middleware pipeline / VI: Cấu hình middleware pipeline
app.UseSerilogRequestLogging();
app.UseProblemDetails();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "PromotionService API v1");
c.RoutePrefix = "swagger";
});
}
app.UseCors();
app.UseRouting();
// EN: Map health check endpoints / VI: Map health check endpoints
app.MapHealthChecks("/health");
app.MapHealthChecks("/health/live", new()
{
Predicate = _ => false // EN: Just checks app is running / VI: Chỉ kiểm tra app đang chạy
});
app.MapHealthChecks("/health/ready");
// EN: Map controllers / VI: Map controllers
app.MapControllers();
// EN: Run the application / VI: Chạy ứng dụng
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly / Ứng dụng kết thúc bất ngờ");
throw;
}
finally
{
Log.CloseAndFlush();
}
// EN: Make Program class accessible for integration tests
// VI: Làm cho class Program có thể truy cập cho integration tests
public partial class Program { }

View File

@@ -0,0 +1,43 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<AssemblyName>PromotionService.API</AssemblyName>
<RootNamespace>PromotionService.API</RootNamespace>
<Description>Web API layer with CQRS pattern</Description>
<UserSecretsId>myservice-api</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<!-- EN: MediatR for CQRS / VI: MediatR cho CQRS -->
<PackageReference Include="MediatR" Version="12.4.1" />
<!-- EN: FluentValidation for request validation / VI: FluentValidation cho validation request -->
<PackageReference Include="FluentValidation" Version="11.11.0" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.11.0" />
<!-- EN: Swagger/OpenAPI / VI: Swagger/OpenAPI -->
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
<!-- EN: API Versioning / VI: API Versioning -->
<PackageReference Include="Asp.Versioning.Mvc" Version="8.1.0" />
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.1.0" />
<!-- EN: Health checks / VI: Health checks -->
<PackageReference Include="AspNetCore.HealthChecks.NpgSql" Version="8.0.2" />
<PackageReference Include="AspNetCore.HealthChecks.Redis" Version="8.0.1" />
<!-- EN: Problem Details (RFC 7807) / VI: Problem Details (RFC 7807) -->
<PackageReference Include="Hellang.Middleware.ProblemDetails" Version="6.5.1" />
<!-- EN: Serilog for structured logging / VI: Serilog cho structured logging -->
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.Seq" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PromotionService.Domain\PromotionService.Domain.csproj" />
<ProjectReference Include="..\PromotionService.Infrastructure\PromotionService.Infrastructure.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,15 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,19 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft.AspNetCore": "Information",
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
}
},
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Information",
"Microsoft.EntityFrameworkCore.Database.Command": "Information",
"System": "Information"
}
}
}
}

View File

@@ -0,0 +1,46 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore": "Warning"
}
},
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.EntityFrameworkCore": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}"
}
}
],
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithThreadId"
]
},
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Port=5432;Database=myservice_db;Username=postgres;Password=postgres"
},
"Redis": {
"ConnectionString": "localhost:6379"
},
"Jwt": {
"Secret": "your-super-secret-key-min-32-characters",
"Issuer": "goodgo-platform",
"Audience": "goodgo-services",
"AccessTokenExpiryMinutes": 15,
"RefreshTokenExpiryDays": 7
},
"AllowedHosts": "*"
}

View File

@@ -0,0 +1,31 @@
namespace PromotionService.Domain.AggregatesModel.CampaignAggregate;
using PromotionService.Domain.SeedWork;
/// <summary>
/// EN: How the user acquires the voucher.
/// VI: Cách người dùng nhận voucher.
/// </summary>
public class AcquisitionType : Enumeration
{
/// <summary>
/// EN: Free voucher (giveaway).
/// VI: Voucher miễn phí (tặng).
/// </summary>
public static readonly AcquisitionType Free = new(1, nameof(Free));
/// <summary>
/// EN: Exchange with loyalty points.
/// VI: Đổi bằng điểm thưởng.
/// </summary>
public static readonly AcquisitionType ExchangePoints = new(2, nameof(ExchangePoints));
/// <summary>
/// EN: Purchase with currency.
/// VI: Mua bằng tiền tệ.
/// </summary>
public static readonly AcquisitionType Purchase = new(3, nameof(Purchase));
protected AcquisitionType() : base(0, "Unknown") { }
public AcquisitionType(int id, string name) : base(id, name) { }
}

View File

@@ -0,0 +1,25 @@
namespace PromotionService.Domain.AggregatesModel.CampaignAggregate;
using PromotionService.Domain.SeedWork;
/// <summary>
/// EN: Type of backing asset for the voucher.
/// VI: Loại tài sản đảm bảo cho voucher.
/// </summary>
public class AssetType : Enumeration
{
/// <summary>
/// EN: Currency (VND, USD, etc.)
/// VI: Tiền tệ (VND, USD, v.v.)
/// </summary>
public static readonly AssetType Currency = new(1, nameof(Currency));
/// <summary>
/// EN: Points (PPoint).
/// VI: Điểm (PPoint).
/// </summary>
public static readonly AssetType Point = new(2, nameof(Point));
protected AssetType() : base(0, "Unknown") { }
public AssetType(int id, string name) : base(id, name) { }
}

View File

@@ -0,0 +1,434 @@
namespace PromotionService.Domain.AggregatesModel.CampaignAggregate;
using PromotionService.Domain.Events;
using PromotionService.Domain.Exceptions;
using PromotionService.Domain.SeedWork;
/// <summary>
/// EN: Campaign Aggregate Root - represents a marketing campaign with vouchers.
/// VI: Campaign Aggregate Root - đại diện cho một chiến dịch marketing với voucher.
/// </summary>
public class Campaign : Entity, IAggregateRoot
{
private readonly List<Voucher> _vouchers = new();
/// <summary>
/// EN: ID of the merchant who owns the campaign.
/// VI: ID của merchant sở hữu chiến dịch.
/// </summary>
public Guid MerchantId { get; private set; }
/// <summary>
/// EN: Campaign name.
/// VI: Tên chiến dịch.
/// </summary>
public string Name { get; private set; } = null!;
/// <summary>
/// EN: Campaign description.
/// VI: Mô tả chiến dịch.
/// </summary>
public string? Description { get; private set; }
#region Backing Asset (What the voucher contains)
/// <summary>
/// EN: Type of backing asset (Currency or Point).
/// VI: Loại tài sản đảm bảo (Tiền tệ hoặc Điểm).
/// </summary>
public AssetType BackingAssetType { get; private set; } = null!;
public int BackingAssetTypeId { get; private set; }
/// <summary>
/// EN: Currency/Point code (e.g., VND, USD, PPoint).
/// VI: Mã tiền tệ/điểm (ví dụ: VND, USD, PPoint).
/// </summary>
public string BackingAssetCode { get; private set; } = null!;
/// <summary>
/// EN: Face value of each voucher.
/// VI: Mệnh giá của mỗi voucher.
/// </summary>
public decimal FaceValue { get; private set; }
#endregion
#region Acquisition (How user gets the voucher)
/// <summary>
/// EN: How user acquires the voucher (Free, ExchangePoints, Purchase).
/// VI: Cách người dùng nhận voucher (Miễn phí, Đổi điểm, Mua).
/// </summary>
public AcquisitionType AcquisitionType { get; private set; } = null!;
public int AcquisitionTypeId { get; private set; }
/// <summary>
/// EN: Price to acquire (points or currency amount).
/// VI: Giá để nhận (số điểm hoặc số tiền).
/// </summary>
public decimal AcquisitionPrice { get; private set; }
#endregion
#region Escrow (Wallet Service Hold)
/// <summary>
/// EN: Hold ID from Wallet Service for escrow.
/// VI: ID giữ từ Wallet Service cho ký quỹ.
/// </summary>
public Guid? EscrowHoldId { get; private set; }
/// <summary>
/// EN: Wallet ID that provides the escrow.
/// VI: ID ví cung cấp ký quỹ.
/// </summary>
public Guid? EscrowWalletId { get; private set; }
/// <summary>
/// EN: Total amount held in escrow.
/// VI: Tổng số tiền ký quỹ.
/// </summary>
public decimal EscrowAmount { get; private set; }
#endregion
#region Campaign Limits
/// <summary>
/// EN: Total number of vouchers to issue.
/// VI: Tổng số voucher phát hành.
/// </summary>
public int TotalVouchers { get; private set; }
/// <summary>
/// EN: Number of vouchers already issued (claimed).
/// VI: Số voucher đã phát hành (đã nhận).
/// </summary>
public int IssuedVouchers { get; private set; }
/// <summary>
/// EN: Maximum vouchers per user (0 = unlimited).
/// VI: Số voucher tối đa mỗi người dùng (0 = không giới hạn).
/// </summary>
public int MaxPerUser { get; private set; }
/// <summary>
/// EN: Campaign start date.
/// VI: Ngày bắt đầu chiến dịch.
/// </summary>
public DateTime StartDate { get; private set; }
/// <summary>
/// EN: Campaign end date.
/// VI: Ngày kết thúc chiến dịch.
/// </summary>
public DateTime EndDate { get; private set; }
/// <summary>
/// EN: Voucher validity days after claiming.
/// VI: Số ngày voucher có hiệu lực sau khi nhận.
/// </summary>
public int VoucherValidityDays { get; private set; }
#endregion
#region Status
/// <summary>
/// EN: Current campaign status.
/// VI: Trạng thái chiến dịch hiện tại.
/// </summary>
public CampaignStatus Status { get; private set; } = null!;
public int StatusId { get; private set; }
/// <summary>
/// EN: Timestamp of creation.
/// VI: Thời điểm tạo.
/// </summary>
public DateTime CreatedAt { get; private set; }
/// <summary>
/// EN: Timestamp of last update.
/// VI: Thời điểm cập nhật cuối.
/// </summary>
public DateTime UpdatedAt { get; private set; }
#endregion
/// <summary>
/// EN: Collection of vouchers in this campaign.
/// VI: Danh sách voucher trong chiến dịch này.
/// </summary>
public IReadOnlyCollection<Voucher> Vouchers => _vouchers.AsReadOnly();
// EF Core constructor
protected Campaign() { }
/// <summary>
/// EN: Create a new campaign.
/// VI: Tạo chiến dịch mới.
/// </summary>
public Campaign(
Guid merchantId,
string name,
string? description,
AssetType backingAssetType,
string backingAssetCode,
decimal faceValue,
AcquisitionType acquisitionType,
decimal acquisitionPrice,
int totalVouchers,
DateTime startDate,
DateTime endDate,
int voucherValidityDays = 30,
int maxPerUser = 1)
{
if (string.IsNullOrWhiteSpace(name))
throw new PromotionDomainException("Campaign name is required");
if (faceValue <= 0)
throw new PromotionDomainException("Face value must be greater than zero");
if (totalVouchers <= 0)
throw new PromotionDomainException("Total vouchers must be greater than zero");
if (endDate <= startDate)
throw new PromotionDomainException("End date must be after start date");
if (acquisitionType != AcquisitionType.Free && acquisitionPrice <= 0)
throw new PromotionDomainException("Acquisition price is required for non-free campaigns");
Id = Guid.NewGuid();
MerchantId = merchantId;
Name = name;
Description = description;
BackingAssetType = backingAssetType;
BackingAssetTypeId = backingAssetType.Id;
BackingAssetCode = backingAssetCode;
FaceValue = faceValue;
AcquisitionType = acquisitionType;
AcquisitionTypeId = acquisitionType.Id;
AcquisitionPrice = acquisitionPrice;
TotalVouchers = totalVouchers;
IssuedVouchers = 0;
MaxPerUser = maxPerUser;
StartDate = startDate;
EndDate = endDate;
VoucherValidityDays = voucherValidityDays;
Status = CampaignStatus.Draft;
StatusId = Status.Id;
CreatedAt = DateTime.UtcNow;
UpdatedAt = DateTime.UtcNow;
// Calculate escrow amount
EscrowAmount = faceValue * totalVouchers;
AddDomainEvent(new CampaignCreatedDomainEvent(Id, merchantId, name));
}
#region Escrow Management
/// <summary>
/// EN: Set the escrow hold ID after Wallet Service confirms the hold.
/// VI: Đặt ID giữ ký quỹ sau khi Wallet Service xác nhận giữ.
/// </summary>
public void SetEscrowHold(Guid walletId, Guid holdId)
{
if (Status != CampaignStatus.Draft)
throw new PromotionDomainException("Can only set escrow on draft campaigns");
EscrowWalletId = walletId;
EscrowHoldId = holdId;
UpdatedAt = DateTime.UtcNow;
}
#endregion
#region Lifecycle Methods
/// <summary>
/// EN: Activate the campaign (make it live).
/// VI: Kích hoạt chiến dịch (đưa vào hoạt động).
/// </summary>
public void Activate()
{
if (Status != CampaignStatus.Draft && Status != CampaignStatus.Paused)
throw new PromotionDomainException($"Cannot activate campaign in {Status.Name} status");
if (!EscrowHoldId.HasValue)
throw new PromotionDomainException("Escrow must be set before activating");
Status = CampaignStatus.Active;
StatusId = Status.Id;
UpdatedAt = DateTime.UtcNow;
AddDomainEvent(new CampaignActivatedDomainEvent(Id, MerchantId));
}
/// <summary>
/// EN: Pause the campaign (temporarily stop).
/// VI: Tạm dừng chiến dịch (dừng tạm thời).
/// </summary>
public void Pause()
{
if (Status != CampaignStatus.Active)
throw new PromotionDomainException("Can only pause active campaigns");
Status = CampaignStatus.Paused;
StatusId = Status.Id;
UpdatedAt = DateTime.UtcNow;
}
/// <summary>
/// EN: Cancel the campaign (release escrow).
/// VI: Hủy chiến dịch (giải phóng ký quỹ).
/// </summary>
public void Cancel()
{
if (Status == CampaignStatus.Completed || Status == CampaignStatus.Cancelled)
throw new PromotionDomainException($"Cannot cancel campaign in {Status.Name} status");
Status = CampaignStatus.Cancelled;
StatusId = Status.Id;
UpdatedAt = DateTime.UtcNow;
AddDomainEvent(new CampaignCancelledDomainEvent(Id, MerchantId, EscrowHoldId));
}
/// <summary>
/// EN: Complete the campaign (normal end).
/// VI: Hoàn thành chiến dịch (kết thúc bình thường).
/// </summary>
public void Complete()
{
if (Status != CampaignStatus.Active && Status != CampaignStatus.Paused)
throw new PromotionDomainException($"Cannot complete campaign in {Status.Name} status");
Status = CampaignStatus.Completed;
StatusId = Status.Id;
UpdatedAt = DateTime.UtcNow;
}
#endregion
#region Voucher Management
/// <summary>
/// EN: Generate voucher codes for this campaign.
/// VI: Tạo mã voucher cho chiến dịch này.
/// </summary>
public void GenerateVouchers(int count)
{
if (Status != CampaignStatus.Draft)
throw new PromotionDomainException("Can only generate vouchers for draft campaigns");
if (_vouchers.Count + count > TotalVouchers)
throw new PromotionDomainException($"Cannot generate {count} vouchers. Maximum is {TotalVouchers}");
for (int i = 0; i < count; i++)
{
var code = GenerateVoucherCode();
var voucher = new Voucher(Id, code, FaceValue, VoucherValidityDays);
_vouchers.Add(voucher);
}
UpdatedAt = DateTime.UtcNow;
}
/// <summary>
/// EN: Issue a voucher to a user (claim).
/// VI: Phát voucher cho người dùng (nhận).
/// </summary>
public Voucher IssueVoucher(Guid userId)
{
if (Status != CampaignStatus.Active)
throw new CampaignNotActiveException(Id);
if (DateTime.UtcNow < StartDate || DateTime.UtcNow > EndDate)
throw new PromotionDomainException("Campaign is not within active date range");
// Check max per user
if (MaxPerUser > 0)
{
var userVoucherCount = _vouchers.Count(v => v.OwnerId == userId);
if (userVoucherCount >= MaxPerUser)
throw new PromotionDomainException($"User already has maximum {MaxPerUser} vouchers from this campaign");
}
// Find available voucher
var voucher = _vouchers.FirstOrDefault(v => v.Status == VoucherStatus.Available);
if (voucher == null)
throw new PromotionDomainException("No available vouchers in this campaign");
voucher.Claim(userId, VoucherValidityDays);
IssuedVouchers++;
UpdatedAt = DateTime.UtcNow;
AddDomainEvent(new VoucherClaimedDomainEvent(voucher.Id, Id, userId, voucher.Code));
return voucher;
}
/// <summary>
/// EN: Get a specific voucher by code.
/// VI: Lấy voucher theo mã.
/// </summary>
public Voucher? GetVoucherByCode(string code)
{
return _vouchers.FirstOrDefault(v => v.Code.Equals(code, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// EN: Get vouchers for a specific user.
/// VI: Lấy voucher của người dùng.
/// </summary>
public IEnumerable<Voucher> GetUserVouchers(Guid userId)
{
return _vouchers.Where(v => v.OwnerId == userId);
}
private string GenerateVoucherCode()
{
// Format: PREFIX-RANDOM (e.g., CAMP-A1B2C3)
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
var code = new string(Enumerable.Repeat(chars, 6)
.Select(s => s[random.Next(s.Length)]).ToArray());
// Ensure uniqueness
while (_vouchers.Any(v => v.Code == $"V{code}"))
{
code = new string(Enumerable.Repeat(chars, 6)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
return $"V{code}";
}
#endregion
#region Statistics
/// <summary>
/// EN: Get available voucher count.
/// VI: Lấy số voucher còn lại.
/// </summary>
public int AvailableVoucherCount => _vouchers.Count(v => v.Status == VoucherStatus.Available);
/// <summary>
/// EN: Get claimed voucher count.
/// VI: Lấy số voucher đã nhận.
/// </summary>
public int ClaimedVoucherCount => _vouchers.Count(v => v.Status != VoucherStatus.Available);
/// <summary>
/// EN: Get redeemed voucher count.
/// VI: Lấy số voucher đã sử dụng.
/// </summary>
public int RedeemedVoucherCount => _vouchers.Count(v =>
v.Status == VoucherStatus.PartiallyRedeemed || v.Status == VoucherStatus.FullyRedeemed);
/// <summary>
/// EN: Get total redeemed value.
/// VI: Lấy tổng giá trị đã sử dụng.
/// </summary>
public decimal TotalRedeemedValue => _vouchers.Sum(v => v.FaceValue - v.RemainingValue);
#endregion
}

View File

@@ -0,0 +1,43 @@
namespace PromotionService.Domain.AggregatesModel.CampaignAggregate;
using PromotionService.Domain.SeedWork;
/// <summary>
/// EN: Status of the marketing campaign.
/// VI: Trạng thái của chiến dịch marketing.
/// </summary>
public class CampaignStatus : Enumeration
{
/// <summary>
/// EN: Draft - campaign is being prepared.
/// VI: Nháp - chiến dịch đang được chuẩn bị.
/// </summary>
public static readonly CampaignStatus Draft = new(1, nameof(Draft));
/// <summary>
/// EN: Active - campaign is running, vouchers can be claimed.
/// VI: Hoạt động - chiến dịch đang chạy, voucher có thể được nhận.
/// </summary>
public static readonly CampaignStatus Active = new(2, nameof(Active));
/// <summary>
/// EN: Paused - campaign is temporarily stopped.
/// VI: Tạm dừng - chiến dịch tạm thời dừng.
/// </summary>
public static readonly CampaignStatus Paused = new(3, nameof(Paused));
/// <summary>
/// EN: Completed - campaign has ended normally.
/// VI: Hoàn thành - chiến dịch đã kết thúc bình thường.
/// </summary>
public static readonly CampaignStatus Completed = new(4, nameof(Completed));
/// <summary>
/// EN: Cancelled - campaign was cancelled, escrow released.
/// VI: Hủy bỏ - chiến dịch bị hủy, escrow được giải phóng.
/// </summary>
public static readonly CampaignStatus Cancelled = new(5, nameof(Cancelled));
protected CampaignStatus() : base(0, "Unknown") { }
public CampaignStatus(int id, string name) : base(id, name) { }
}

View File

@@ -0,0 +1,52 @@
namespace PromotionService.Domain.AggregatesModel.CampaignAggregate;
using PromotionService.Domain.SeedWork;
/// <summary>
/// EN: Repository interface for Campaign aggregate.
/// VI: Interface repository cho Campaign aggregate.
/// </summary>
public interface ICampaignRepository : IRepository<Campaign>
{
/// <summary>
/// EN: Get campaign by ID with vouchers.
/// VI: Lấy chiến dịch theo ID với voucher.
/// </summary>
Task<Campaign?> GetByIdAsync(Guid id);
/// <summary>
/// EN: Get campaigns by merchant ID.
/// VI: Lấy chiến dịch theo ID merchant.
/// </summary>
Task<IEnumerable<Campaign>> GetByMerchantIdAsync(Guid merchantId);
/// <summary>
/// EN: Get active campaigns.
/// VI: Lấy các chiến dịch đang hoạt động.
/// </summary>
Task<IEnumerable<Campaign>> GetActiveAsync();
/// <summary>
/// EN: Get voucher by code across all campaigns.
/// VI: Lấy voucher theo mã trên tất cả chiến dịch.
/// </summary>
Task<Voucher?> GetVoucherByCodeAsync(string code);
/// <summary>
/// EN: Get vouchers owned by a user.
/// VI: Lấy voucher thuộc về người dùng.
/// </summary>
Task<IEnumerable<Voucher>> GetUserVouchersAsync(Guid userId);
/// <summary>
/// EN: Add a new campaign.
/// VI: Thêm chiến dịch mới.
/// </summary>
Campaign Add(Campaign campaign);
/// <summary>
/// EN: Update an existing campaign.
/// VI: Cập nhật chiến dịch hiện có.
/// </summary>
void Update(Campaign campaign);
}

View File

@@ -0,0 +1,199 @@
namespace PromotionService.Domain.AggregatesModel.CampaignAggregate;
using PromotionService.Domain.Exceptions;
using PromotionService.Domain.SeedWork;
/// <summary>
/// EN: Voucher entity representing a single voucher in a campaign.
/// VI: Entity voucher đại diện cho một voucher trong chiến dịch.
/// </summary>
public class Voucher : Entity
{
/// <summary>
/// EN: Campaign ID this voucher belongs to.
/// VI: ID chiến dịch voucher này thuộc về.
/// </summary>
public Guid CampaignId { get; private set; }
/// <summary>
/// EN: Unique voucher code.
/// VI: Mã voucher duy nhất.
/// </summary>
public string Code { get; private set; } = null!;
/// <summary>
/// EN: User ID who owns this voucher (null if unclaimed).
/// VI: ID người dùng sở hữu voucher này (null nếu chưa nhận).
/// </summary>
public Guid? OwnerId { get; private set; }
/// <summary>
/// EN: Original face value of voucher.
/// VI: Mệnh giá gốc của voucher.
/// </summary>
public decimal FaceValue { get; private set; }
/// <summary>
/// EN: Remaining value (after partial redemptions).
/// VI: Giá trị còn lại (sau khi sử dụng một phần).
/// </summary>
public decimal RemainingValue { get; private set; }
/// <summary>
/// EN: Voucher status.
/// VI: Trạng thái voucher.
/// </summary>
public VoucherStatus Status { get; private set; } = null!;
public int StatusId { get; private set; }
/// <summary>
/// EN: When the voucher was claimed by a user.
/// VI: Thời điểm voucher được nhận bởi người dùng.
/// </summary>
public DateTime? ClaimedAt { get; private set; }
/// <summary>
/// EN: When the voucher expires.
/// VI: Thời điểm voucher hết hạn.
/// </summary>
public DateTime? ExpiresAt { get; private set; }
/// <summary>
/// EN: When the voucher was last redeemed.
/// VI: Thời điểm voucher được sử dụng lần cuối.
/// </summary>
public DateTime? RedeemedAt { get; private set; }
/// <summary>
/// EN: Creation timestamp.
/// VI: Thời điểm tạo.
/// </summary>
public DateTime CreatedAt { get; private set; }
/// <summary>
/// EN: Last update timestamp.
/// VI: Thời điểm cập nhật cuối.
/// </summary>
public DateTime UpdatedAt { get; private set; }
// EF Core constructor
protected Voucher() { }
/// <summary>
/// EN: Create a new voucher.
/// VI: Tạo voucher mới.
/// </summary>
public Voucher(Guid campaignId, string code, decimal faceValue, int validityDays)
{
if (string.IsNullOrWhiteSpace(code))
throw new PromotionDomainException("Voucher code is required");
if (faceValue <= 0)
throw new PromotionDomainException("Face value must be greater than zero");
Id = Guid.NewGuid();
CampaignId = campaignId;
Code = code;
FaceValue = faceValue;
RemainingValue = faceValue;
Status = VoucherStatus.Available;
StatusId = Status.Id;
CreatedAt = DateTime.UtcNow;
UpdatedAt = DateTime.UtcNow;
}
/// <summary>
/// EN: Claim the voucher for a user.
/// VI: Nhận voucher cho người dùng.
/// </summary>
public void Claim(Guid userId, int validityDays)
{
if (Status != VoucherStatus.Available)
throw new VoucherAlreadyClaimedException(Id, Code);
OwnerId = userId;
Status = VoucherStatus.Claimed;
StatusId = Status.Id;
ClaimedAt = DateTime.UtcNow;
ExpiresAt = DateTime.UtcNow.AddDays(validityDays);
UpdatedAt = DateTime.UtcNow;
}
/// <summary>
/// EN: Redeem a portion of the voucher value.
/// VI: Sử dụng một phần giá trị voucher.
/// </summary>
/// <param name="amount">Amount to redeem / Số tiền sử dụng</param>
/// <returns>Actual amount deducted / Số tiền thực tế bị trừ</returns>
public decimal Redeem(decimal amount)
{
ValidateCanRedeem();
if (amount <= 0)
throw new PromotionDomainException("Redeem amount must be greater than zero");
// Calculate actual amount (cannot exceed remaining)
var actualAmount = Math.Min(amount, RemainingValue);
RemainingValue -= actualAmount;
RedeemedAt = DateTime.UtcNow;
UpdatedAt = DateTime.UtcNow;
// Update status
Status = RemainingValue == 0 ? VoucherStatus.FullyRedeemed : VoucherStatus.PartiallyRedeemed;
StatusId = Status.Id;
return actualAmount;
}
/// <summary>
/// EN: Mark voucher as expired.
/// VI: Đánh dấu voucher hết hạn.
/// </summary>
public void Expire()
{
if (Status == VoucherStatus.FullyRedeemed)
return; // Already fully used
Status = VoucherStatus.Expired;
StatusId = Status.Id;
UpdatedAt = DateTime.UtcNow;
}
/// <summary>
/// EN: Check if voucher is valid for redemption.
/// VI: Kiểm tra voucher có hợp lệ để sử dụng.
/// </summary>
public bool IsValidForRedemption()
{
return (Status == VoucherStatus.Claimed || Status == VoucherStatus.PartiallyRedeemed)
&& RemainingValue > 0
&& (!ExpiresAt.HasValue || ExpiresAt.Value > DateTime.UtcNow);
}
/// <summary>
/// EN: Check if voucher has expired.
/// VI: Kiểm tra voucher đã hết hạn chưa.
/// </summary>
public bool IsExpired => ExpiresAt.HasValue && DateTime.UtcNow > ExpiresAt.Value;
private void ValidateCanRedeem()
{
if (Status == VoucherStatus.Available)
throw new PromotionDomainException("Voucher has not been claimed yet");
if (Status == VoucherStatus.FullyRedeemed)
throw new PromotionDomainException("Voucher has already been fully redeemed");
if (Status == VoucherStatus.Expired)
throw new VoucherExpiredException(Id, Code);
if (IsExpired)
{
Expire();
throw new VoucherExpiredException(Id, Code);
}
if (RemainingValue <= 0)
throw new InsufficientVoucherValueException(Id, 0, 0);
}
}

View File

@@ -0,0 +1,43 @@
namespace PromotionService.Domain.AggregatesModel.CampaignAggregate;
using PromotionService.Domain.SeedWork;
/// <summary>
/// EN: Status of a voucher in its lifecycle.
/// VI: Trạng thái của voucher trong vòng đời.
/// </summary>
public class VoucherStatus : Enumeration
{
/// <summary>
/// EN: Available - voucher is not claimed yet.
/// VI: Sẵn sàng - voucher chưa được nhận.
/// </summary>
public static readonly VoucherStatus Available = new(1, nameof(Available));
/// <summary>
/// EN: Claimed - voucher is owned by a user.
/// VI: Đã nhận - voucher thuộc về người dùng.
/// </summary>
public static readonly VoucherStatus Claimed = new(2, nameof(Claimed));
/// <summary>
/// EN: Partially redeemed - some value has been used.
/// VI: Đã dùng một phần - một phần giá trị đã được sử dụng.
/// </summary>
public static readonly VoucherStatus PartiallyRedeemed = new(3, nameof(PartiallyRedeemed));
/// <summary>
/// EN: Fully redeemed - all value has been used.
/// VI: Đã dùng hết - toàn bộ giá trị đã được sử dụng.
/// </summary>
public static readonly VoucherStatus FullyRedeemed = new(4, nameof(FullyRedeemed));
/// <summary>
/// EN: Expired - voucher has expired without full use.
/// VI: Hết hạn - voucher đã hết hạn mà chưa dùng hết.
/// </summary>
public static readonly VoucherStatus Expired = new(5, nameof(Expired));
protected VoucherStatus() : base(0, "Unknown") { }
public VoucherStatus(int id, string name) : base(id, name) { }
}

View File

@@ -0,0 +1,34 @@
namespace PromotionService.Domain.AggregatesModel.RedemptionAggregate;
using PromotionService.Domain.SeedWork;
/// <summary>
/// EN: Repository interface for Redemption aggregate.
/// VI: Interface repository cho Redemption aggregate.
/// </summary>
public interface IRedemptionRepository : IRepository<Redemption>
{
/// <summary>
/// EN: Get redemptions by voucher ID.
/// VI: Lấy các lần sử dụng theo ID voucher.
/// </summary>
Task<IEnumerable<Redemption>> GetByVoucherIdAsync(Guid voucherId);
/// <summary>
/// EN: Get redemptions by user ID.
/// VI: Lấy các lần sử dụng theo ID người dùng.
/// </summary>
Task<IEnumerable<Redemption>> GetByUserIdAsync(Guid userId);
/// <summary>
/// EN: Get redemptions by campaign ID.
/// VI: Lấy các lần sử dụng theo ID chiến dịch.
/// </summary>
Task<IEnumerable<Redemption>> GetByCampaignIdAsync(Guid campaignId);
/// <summary>
/// EN: Add a new redemption.
/// VI: Thêm lần sử dụng mới.
/// </summary>
Redemption Add(Redemption redemption);
}

View File

@@ -0,0 +1,92 @@
namespace PromotionService.Domain.AggregatesModel.RedemptionAggregate;
using PromotionService.Domain.SeedWork;
/// <summary>
/// EN: Redemption Aggregate Root - records voucher redemption history.
/// VI: Redemption Aggregate Root - ghi lại lịch sử sử dụng voucher.
/// </summary>
public class Redemption : Entity, IAggregateRoot
{
/// <summary>
/// EN: ID of the voucher that was redeemed.
/// VI: ID của voucher được sử dụng.
/// </summary>
public Guid VoucherId { get; private set; }
/// <summary>
/// EN: ID of the campaign.
/// VI: ID của chiến dịch.
/// </summary>
public Guid CampaignId { get; private set; }
/// <summary>
/// EN: ID of the user who redeemed.
/// VI: ID của người dùng sử dụng.
/// </summary>
public Guid UserId { get; private set; }
/// <summary>
/// EN: Order ID if linked to an order.
/// VI: ID đơn hàng nếu liên kết với đơn hàng.
/// </summary>
public Guid? OrderId { get; private set; }
/// <summary>
/// EN: Amount used from the voucher.
/// VI: Số tiền sử dụng từ voucher.
/// </summary>
public decimal AmountUsed { get; private set; }
/// <summary>
/// EN: Amount refunded to merchant (surplus).
/// VI: Số tiền hoàn lại cho merchant (dư).
/// </summary>
public decimal AmountRefunded { get; private set; }
/// <summary>
/// EN: Execution reference from Wallet Service.
/// VI: Tham chiếu thực thi từ Wallet Service.
/// </summary>
public string? ExecutionReference { get; private set; }
/// <summary>
/// EN: When the redemption occurred.
/// VI: Thời điểm sử dụng.
/// </summary>
public DateTime RedeemedAt { get; private set; }
/// <summary>
/// EN: Creation timestamp.
/// VI: Thời điểm tạo.
/// </summary>
public DateTime CreatedAt { get; private set; }
// EF Core constructor
protected Redemption() { }
/// <summary>
/// EN: Create a redemption record.
/// VI: Tạo bản ghi sử dụng.
/// </summary>
public Redemption(
Guid voucherId,
Guid campaignId,
Guid userId,
Guid? orderId,
decimal amountUsed,
decimal amountRefunded,
string? executionReference = null)
{
Id = Guid.NewGuid();
VoucherId = voucherId;
CampaignId = campaignId;
UserId = userId;
OrderId = orderId;
AmountUsed = amountUsed;
AmountRefunded = amountRefunded;
ExecutionReference = executionReference;
RedeemedAt = DateTime.UtcNow;
CreatedAt = DateTime.UtcNow;
}
}

View File

@@ -0,0 +1,61 @@
using PromotionService.Domain.SeedWork;
namespace PromotionService.Domain.AggregatesModel.SampleAggregate;
/// <summary>
/// EN: Repository interface for Sample aggregate.
/// VI: Interface repository cho Sample aggregate.
/// </summary>
/// <remarks>
/// EN: Following repository pattern, this interface defines the contract
/// for data access operations on Sample aggregate.
/// VI: Theo pattern repository, interface này định nghĩa contract
/// cho các thao tác truy cập dữ liệu trên Sample aggregate.
/// </remarks>
public interface ISampleRepository : IRepository<Sample>
{
/// <summary>
/// EN: Get a sample by its ID.
/// VI: Lấy một sample theo ID.
/// </summary>
/// <param name="sampleId">EN: The sample ID / VI: ID của sample</param>
/// <returns>EN: The sample or null if not found / VI: Sample hoặc null nếu không tìm thấy</returns>
Task<Sample?> GetAsync(Guid sampleId);
/// <summary>
/// EN: Get all samples.
/// VI: Lấy tất cả samples.
/// </summary>
/// <returns>EN: List of samples / VI: Danh sách samples</returns>
Task<IEnumerable<Sample>> GetAllAsync();
/// <summary>
/// EN: Add a new sample.
/// VI: Thêm một sample mới.
/// </summary>
/// <param name="sample">EN: The sample to add / VI: Sample cần thêm</param>
/// <returns>EN: The added sample / VI: Sample đã thêm</returns>
Sample Add(Sample sample);
/// <summary>
/// EN: Update an existing sample.
/// VI: Cập nhật một sample đã tồn tại.
/// </summary>
/// <param name="sample">EN: The sample to update / VI: Sample cần cập nhật</param>
void Update(Sample sample);
/// <summary>
/// EN: Delete a sample.
/// VI: Xóa một sample.
/// </summary>
/// <param name="sample">EN: The sample to delete / VI: Sample cần xóa</param>
void Delete(Sample sample);
/// <summary>
/// EN: Get samples by status.
/// VI: Lấy samples theo trạng thái.
/// </summary>
/// <param name="statusId">EN: The status ID / VI: ID trạng thái</param>
/// <returns>EN: List of samples with given status / VI: Danh sách samples với trạng thái cho trước</returns>
Task<IEnumerable<Sample>> GetByStatusAsync(int statusId);
}

View File

@@ -0,0 +1,158 @@
using PromotionService.Domain.Events;
using PromotionService.Domain.Exceptions;
using PromotionService.Domain.SeedWork;
namespace PromotionService.Domain.AggregatesModel.SampleAggregate;
/// <summary>
/// EN: Sample aggregate root demonstrating DDD patterns.
/// VI: Sample aggregate root minh họa các pattern DDD.
/// </summary>
public class Sample : Entity, IAggregateRoot
{
// EN: Private fields for encapsulation
// VI: Fields private để đóng gói
private string _name = null!;
private string? _description;
private SampleStatus _status = null!;
private DateTime _createdAt;
private DateTime? _updatedAt;
/// <summary>
/// EN: Sample name (required).
/// VI: Tên sample (bắt buộc).
/// </summary>
public string Name => _name;
/// <summary>
/// EN: Optional description.
/// VI: Mô tả tùy chọn.
/// </summary>
public string? Description => _description;
/// <summary>
/// EN: Current status.
/// VI: Trạng thái hiện tại.
/// </summary>
public SampleStatus Status => _status;
/// <summary>
/// EN: Status ID for EF Core mapping.
/// VI: ID trạng thái cho EF Core mapping.
/// </summary>
public int StatusId { get; private set; }
/// <summary>
/// EN: Creation timestamp.
/// VI: Thời gian tạo.
/// </summary>
public DateTime CreatedAt => _createdAt;
/// <summary>
/// EN: Last update timestamp.
/// VI: Thời gian cập nhật cuối.
/// </summary>
public DateTime? UpdatedAt => _updatedAt;
/// <summary>
/// EN: Private constructor for EF Core.
/// VI: Constructor private cho EF Core.
/// </summary>
protected Sample()
{
}
/// <summary>
/// EN: Create a new Sample with required information.
/// VI: Tạo một Sample mới với thông tin bắt buộc.
/// </summary>
/// <param name="name">EN: Sample name / VI: Tên sample</param>
/// <param name="description">EN: Optional description / VI: Mô tả tùy chọn</param>
public Sample(string name, string? description = null) : this()
{
if (string.IsNullOrWhiteSpace(name))
throw new SampleDomainException("Sample name cannot be empty");
Id = Guid.NewGuid();
_name = name;
_description = description;
_status = SampleStatus.Draft;
StatusId = SampleStatus.Draft.Id;
_createdAt = DateTime.UtcNow;
// EN: Add domain event for creation
// VI: Thêm domain event cho việc tạo
AddDomainEvent(new SampleCreatedDomainEvent(this));
}
/// <summary>
/// EN: Update sample information.
/// VI: Cập nhật thông tin sample.
/// </summary>
public void Update(string name, string? description)
{
if (string.IsNullOrWhiteSpace(name))
throw new SampleDomainException("Sample name cannot be empty");
if (_status == SampleStatus.Cancelled)
throw new SampleDomainException("Cannot update a cancelled sample");
_name = name;
_description = description;
_updatedAt = DateTime.UtcNow;
}
/// <summary>
/// EN: Activate the sample.
/// VI: Kích hoạt sample.
/// </summary>
public void Activate()
{
if (_status != SampleStatus.Draft)
throw new SampleDomainException("Only draft samples can be activated");
var previousStatus = _status;
_status = SampleStatus.Active;
StatusId = SampleStatus.Active.Id;
_updatedAt = DateTime.UtcNow;
AddDomainEvent(new SampleStatusChangedDomainEvent(Id, previousStatus, _status));
}
/// <summary>
/// EN: Complete the sample.
/// VI: Hoàn thành sample.
/// </summary>
public void Complete()
{
if (_status != SampleStatus.Active)
throw new SampleDomainException("Only active samples can be completed");
var previousStatus = _status;
_status = SampleStatus.Completed;
StatusId = SampleStatus.Completed.Id;
_updatedAt = DateTime.UtcNow;
AddDomainEvent(new SampleStatusChangedDomainEvent(Id, previousStatus, _status));
}
/// <summary>
/// EN: Cancel the sample.
/// VI: Hủy sample.
/// </summary>
public void Cancel()
{
if (_status == SampleStatus.Completed)
throw new SampleDomainException("Cannot cancel a completed sample");
if (_status == SampleStatus.Cancelled)
throw new SampleDomainException("Sample is already cancelled");
var previousStatus = _status;
_status = SampleStatus.Cancelled;
StatusId = SampleStatus.Cancelled.Id;
_updatedAt = DateTime.UtcNow;
AddDomainEvent(new SampleStatusChangedDomainEvent(Id, previousStatus, _status));
}
}

View File

@@ -0,0 +1,77 @@
using PromotionService.Domain.SeedWork;
namespace PromotionService.Domain.AggregatesModel.SampleAggregate;
/// <summary>
/// EN: Sample status enumeration following type-safe enum pattern.
/// VI: Enumeration trạng thái Sample theo pattern enum an toàn kiểu.
/// </summary>
public class SampleStatus : Enumeration
{
/// <summary>
/// EN: Draft status - initial state
/// VI: Trạng thái nháp - trạng thái ban đầu
/// </summary>
public static SampleStatus Draft = new(1, nameof(Draft));
/// <summary>
/// EN: Active status - ready for use
/// VI: Trạng thái hoạt động - sẵn sàng sử dụng
/// </summary>
public static SampleStatus Active = new(2, nameof(Active));
/// <summary>
/// EN: Completed status - finished processing
/// VI: Trạng thái hoàn thành - đã xử lý xong
/// </summary>
public static SampleStatus Completed = new(3, nameof(Completed));
/// <summary>
/// EN: Cancelled status - cancelled by user
/// VI: Trạng thái đã hủy - bị hủy bởi người dùng
/// </summary>
public static SampleStatus Cancelled = new(4, nameof(Cancelled));
public SampleStatus(int id, string name) : base(id, name)
{
}
/// <summary>
/// EN: Get all available statuses.
/// VI: Lấy tất cả các trạng thái có sẵn.
/// </summary>
public static IEnumerable<SampleStatus> List() => GetAll<SampleStatus>();
/// <summary>
/// EN: Parse status from name.
/// VI: Parse trạng thái từ tên.
/// </summary>
public static SampleStatus FromName(string name)
{
var status = List().SingleOrDefault(s =>
string.Equals(s.Name, name, StringComparison.CurrentCultureIgnoreCase));
if (status is null)
{
throw new ArgumentException($"Possible values for SampleStatus: {string.Join(",", List().Select(s => s.Name))}");
}
return status;
}
/// <summary>
/// EN: Parse status from ID.
/// VI: Parse trạng thái từ ID.
/// </summary>
public static SampleStatus From(int id)
{
var status = List().SingleOrDefault(s => s.Id == id);
if (status is null)
{
throw new ArgumentException($"Possible values for SampleStatus: {string.Join(",", List().Select(s => s.Name))}");
}
return status;
}
}

View File

@@ -0,0 +1,50 @@
namespace PromotionService.Domain.Events;
using MediatR;
/// <summary>
/// EN: Event raised when a new campaign is created.
/// VI: Sự kiện được phát ra khi chiến dịch mới được tạo.
/// </summary>
public record CampaignCreatedDomainEvent(
Guid CampaignId,
Guid MerchantId,
string CampaignName) : INotification;
/// <summary>
/// EN: Event raised when a campaign is activated.
/// VI: Sự kiện được phát ra khi chiến dịch được kích hoạt.
/// </summary>
public record CampaignActivatedDomainEvent(
Guid CampaignId,
Guid MerchantId) : INotification;
/// <summary>
/// EN: Event raised when a campaign is cancelled.
/// VI: Sự kiện được phát ra khi chiến dịch bị hủy.
/// </summary>
public record CampaignCancelledDomainEvent(
Guid CampaignId,
Guid MerchantId,
Guid? EscrowHoldId) : INotification;
/// <summary>
/// EN: Event raised when a voucher is claimed by a user.
/// VI: Sự kiện được phát ra khi voucher được nhận bởi người dùng.
/// </summary>
public record VoucherClaimedDomainEvent(
Guid VoucherId,
Guid CampaignId,
Guid UserId,
string VoucherCode) : INotification;
/// <summary>
/// EN: Event raised when a voucher is redeemed.
/// VI: Sự kiện được phát ra khi voucher được sử dụng.
/// </summary>
public record VoucherRedeemedDomainEvent(
Guid VoucherId,
Guid CampaignId,
Guid UserId,
decimal AmountUsed,
decimal AmountRefunded) : INotification;

View File

@@ -0,0 +1,22 @@
using MediatR;
using PromotionService.Domain.AggregatesModel.SampleAggregate;
namespace PromotionService.Domain.Events;
/// <summary>
/// EN: Domain event raised when a new Sample is created.
/// VI: Domain event được phát ra khi một Sample mới được tạo.
/// </summary>
public class SampleCreatedDomainEvent : INotification
{
/// <summary>
/// EN: The newly created sample.
/// VI: Sample mới được tạo.
/// </summary>
public Sample Sample { get; }
public SampleCreatedDomainEvent(Sample sample)
{
Sample = sample;
}
}

View File

@@ -0,0 +1,39 @@
using MediatR;
using PromotionService.Domain.AggregatesModel.SampleAggregate;
namespace PromotionService.Domain.Events;
/// <summary>
/// EN: Domain event raised when Sample status changes.
/// VI: Domain event được phát ra khi trạng thái Sample thay đổi.
/// </summary>
public class SampleStatusChangedDomainEvent : INotification
{
/// <summary>
/// EN: The sample ID.
/// VI: ID của sample.
/// </summary>
public Guid SampleId { get; }
/// <summary>
/// EN: Previous status before the change.
/// VI: Trạng thái trước khi thay đổi.
/// </summary>
public SampleStatus PreviousStatus { get; }
/// <summary>
/// EN: New status after the change.
/// VI: Trạng thái mới sau khi thay đổi.
/// </summary>
public SampleStatus NewStatus { get; }
public SampleStatusChangedDomainEvent(
Guid sampleId,
SampleStatus previousStatus,
SampleStatus newStatus)
{
SampleId = sampleId;
PreviousStatus = previousStatus;
NewStatus = newStatus;
}
}

View File

@@ -0,0 +1,21 @@
namespace PromotionService.Domain.Exceptions;
/// <summary>
/// EN: Base exception for domain errors.
/// VI: Exception cơ sở cho các lỗi domain.
/// </summary>
public class DomainException : Exception
{
public DomainException()
{
}
public DomainException(string message) : base(message)
{
}
public DomainException(string message, Exception innerException)
: base(message, innerException)
{
}
}

View File

@@ -0,0 +1,80 @@
namespace PromotionService.Domain.Exceptions;
/// <summary>
/// EN: Base exception for Promotion domain errors.
/// VI: Exception cơ sở cho lỗi domain Promotion.
/// </summary>
public class PromotionDomainException : Exception
{
public PromotionDomainException() { }
public PromotionDomainException(string message) : base(message) { }
public PromotionDomainException(string message, Exception innerException) : base(message, innerException) { }
}
/// <summary>
/// EN: Exception when trying to operate on a non-active campaign.
/// VI: Exception khi cố thao tác trên chiến dịch không hoạt động.
/// </summary>
public class CampaignNotActiveException : PromotionDomainException
{
public Guid CampaignId { get; }
public CampaignNotActiveException(Guid campaignId)
: base($"Campaign {campaignId} is not active")
{
CampaignId = campaignId;
}
}
/// <summary>
/// EN: Exception when a voucher has already been claimed.
/// VI: Exception khi voucher đã được nhận.
/// </summary>
public class VoucherAlreadyClaimedException : PromotionDomainException
{
public Guid VoucherId { get; }
public string VoucherCode { get; }
public VoucherAlreadyClaimedException(Guid voucherId, string code)
: base($"Voucher {code} has already been claimed")
{
VoucherId = voucherId;
VoucherCode = code;
}
}
/// <summary>
/// EN: Exception when a voucher has expired.
/// VI: Exception khi voucher đã hết hạn.
/// </summary>
public class VoucherExpiredException : PromotionDomainException
{
public Guid VoucherId { get; }
public string VoucherCode { get; }
public VoucherExpiredException(Guid voucherId, string code)
: base($"Voucher {code} has expired")
{
VoucherId = voucherId;
VoucherCode = code;
}
}
/// <summary>
/// EN: Exception when voucher has insufficient value for redemption.
/// VI: Exception khi voucher không đủ giá trị để sử dụng.
/// </summary>
public class InsufficientVoucherValueException : PromotionDomainException
{
public Guid VoucherId { get; }
public decimal RemainingValue { get; }
public decimal RequestedAmount { get; }
public InsufficientVoucherValueException(Guid voucherId, decimal remaining, decimal requested)
: base($"Voucher has insufficient value. Remaining: {remaining}, Requested: {requested}")
{
VoucherId = voucherId;
RemainingValue = remaining;
RequestedAmount = requested;
}
}

View File

@@ -0,0 +1,21 @@
namespace PromotionService.Domain.Exceptions;
/// <summary>
/// EN: Exception for Sample aggregate domain errors.
/// VI: Exception cho các lỗi domain của Sample aggregate.
/// </summary>
public class SampleDomainException : DomainException
{
public SampleDomainException()
{
}
public SampleDomainException(string message) : base(message)
{
}
public SampleDomainException(string message, Exception innerException)
: base(message, innerException)
{
}
}

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>PromotionService.Domain</AssemblyName>
<RootNamespace>PromotionService.Domain</RootNamespace>
<Description>Domain layer containing core business logic and entities</Description>
</PropertyGroup>
<ItemGroup>
<!-- EN: MediatR for domain events / VI: MediatR cho domain events -->
<PackageReference Include="MediatR.Contracts" Version="2.0.1" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,102 @@
using MediatR;
namespace PromotionService.Domain.SeedWork;
/// <summary>
/// EN: Base class for all domain entities.
/// VI: Lớp cơ sở cho tất cả các entity trong domain.
/// </summary>
public abstract class Entity
{
private int? _requestedHashCode;
private Guid _id;
private List<INotification> _domainEvents = new();
/// <summary>
/// EN: Unique identifier for the entity.
/// VI: Định danh duy nhất cho entity.
/// </summary>
public virtual Guid Id
{
get => _id;
protected set => _id = value;
}
/// <summary>
/// EN: Domain events raised by this entity.
/// VI: Các domain event được phát ra bởi entity này.
/// </summary>
public IReadOnlyCollection<INotification> DomainEvents => _domainEvents.AsReadOnly();
/// <summary>
/// EN: Add a domain event to be dispatched.
/// VI: Thêm một domain event để dispatch.
/// </summary>
public void AddDomainEvent(INotification eventItem)
{
_domainEvents.Add(eventItem);
}
/// <summary>
/// EN: Remove a domain event.
/// VI: Xóa một domain event.
/// </summary>
public void RemoveDomainEvent(INotification eventItem)
{
_domainEvents.Remove(eventItem);
}
/// <summary>
/// EN: Clear all domain events.
/// VI: Xóa tất cả domain events.
/// </summary>
public void ClearDomainEvents()
{
_domainEvents.Clear();
}
/// <summary>
/// EN: Check if entity is transient (not persisted yet).
/// VI: Kiểm tra xem entity có phải là transient (chưa lưu) không.
/// </summary>
public bool IsTransient()
{
return Id == default;
}
public override bool Equals(object? obj)
{
if (obj is not Entity item)
return false;
if (ReferenceEquals(this, item))
return true;
if (GetType() != item.GetType())
return false;
if (item.IsTransient() || IsTransient())
return false;
return item.Id == Id;
}
public override int GetHashCode()
{
if (IsTransient())
return base.GetHashCode();
_requestedHashCode ??= Id.GetHashCode() ^ 31;
return _requestedHashCode.Value;
}
public static bool operator ==(Entity? left, Entity? right)
{
return left?.Equals(right) ?? right is null;
}
public static bool operator !=(Entity? left, Entity? right)
{
return !(left == right);
}
}

View File

@@ -0,0 +1,95 @@
using System.Reflection;
namespace PromotionService.Domain.SeedWork;
/// <summary>
/// EN: Base class for enumeration classes (type-safe enum pattern).
/// VI: Lớp cơ sở cho các lớp enumeration (pattern enum an toàn kiểu).
/// </summary>
/// <remarks>
/// EN: This provides a type-safe alternative to enums with additional functionality
/// like validation, parsing, and rich behavior.
/// VI: Cung cấp một thay thế an toàn kiểu cho enums với các chức năng bổ sung
/// như validation, parsing, và hành vi phong phú.
/// </remarks>
public abstract class Enumeration : IComparable
{
/// <summary>
/// EN: The name of the enumeration value.
/// VI: Tên của giá trị enumeration.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// EN: The unique identifier of the enumeration value.
/// VI: Định danh duy nhất của giá trị enumeration.
/// </summary>
public int Id { get; private set; }
protected Enumeration(int id, string name) => (Id, Name) = (id, name);
public override string ToString() => Name;
/// <summary>
/// EN: Get all enumeration values of a given type.
/// VI: Lấy tất cả các giá trị enumeration của một kiểu cho trước.
/// </summary>
public static IEnumerable<T> GetAll<T>() where T : Enumeration =>
typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)
.Select(f => f.GetValue(null))
.Cast<T>();
public override bool Equals(object? obj)
{
if (obj is not Enumeration otherValue)
return false;
var typeMatches = GetType() == obj.GetType();
var valueMatches = Id.Equals(otherValue.Id);
return typeMatches && valueMatches;
}
public override int GetHashCode() => Id.GetHashCode();
/// <summary>
/// EN: Get absolute difference between two enumeration values.
/// VI: Lấy sự khác biệt tuyệt đối giữa hai giá trị enumeration.
/// </summary>
public static int AbsoluteDifference(Enumeration firstValue, Enumeration secondValue)
{
return Math.Abs(firstValue.Id - secondValue.Id);
}
/// <summary>
/// EN: Parse an integer ID to the corresponding enumeration value.
/// VI: Parse một ID integer thành giá trị enumeration tương ứng.
/// </summary>
public static T FromValue<T>(int value) where T : Enumeration
{
var matchingItem = Parse<T, int>(value, "value", item => item.Id == value);
return matchingItem;
}
/// <summary>
/// EN: Parse a display name to the corresponding enumeration value.
/// VI: Parse một tên hiển thị thành giá trị enumeration tương ứng.
/// </summary>
public static T FromDisplayName<T>(string displayName) where T : Enumeration
{
var matchingItem = Parse<T, string>(displayName, "display name", item => item.Name == displayName);
return matchingItem;
}
private static T Parse<T, TValue>(TValue value, string description, Func<T, bool> predicate) where T : Enumeration
{
var matchingItem = GetAll<T>().FirstOrDefault(predicate);
if (matchingItem is null)
throw new InvalidOperationException($"'{value}' is not a valid {description} in {typeof(T)}");
return matchingItem;
}
public int CompareTo(object? other) => Id.CompareTo(((Enumeration)other!).Id);
}

View File

@@ -0,0 +1,15 @@
namespace PromotionService.Domain.SeedWork;
/// <summary>
/// EN: Marker interface for aggregate roots.
/// VI: Interface đánh dấu cho aggregate roots.
/// </summary>
/// <remarks>
/// EN: Aggregate roots are the entry points to aggregates and are the only objects
/// that outside code should hold references to.
/// VI: Aggregate roots là điểm vào của aggregates và là đối tượng duy nhất
/// mà code bên ngoài nên giữ tham chiếu đến.
/// </remarks>
public interface IAggregateRoot
{
}

View File

@@ -0,0 +1,15 @@
namespace PromotionService.Domain.SeedWork;
/// <summary>
/// EN: Generic repository interface for aggregate roots.
/// VI: Interface repository generic cho aggregate roots.
/// </summary>
/// <typeparam name="T">EN: The aggregate root type / VI: Kiểu aggregate root</typeparam>
public interface IRepository<T> where T : IAggregateRoot
{
/// <summary>
/// EN: The unit of work for this repository.
/// VI: Unit of work cho repository này.
/// </summary>
IUnitOfWork UnitOfWork { get; }
}

View File

@@ -0,0 +1,30 @@
namespace PromotionService.Domain.SeedWork;
/// <summary>
/// EN: Unit of Work pattern interface.
/// VI: Interface cho Unit of Work pattern.
/// </summary>
/// <remarks>
/// EN: Maintains a list of objects affected by a business transaction
/// and coordinates the writing out of changes.
/// VI: Duy trì danh sách các đối tượng bị ảnh hưởng bởi một transaction nghiệp vụ
/// và điều phối việc ghi các thay đổi.
/// </remarks>
public interface IUnitOfWork : IDisposable
{
/// <summary>
/// EN: Save all changes made in this unit of work.
/// VI: Lưu tất cả các thay đổi được thực hiện trong unit of work này.
/// </summary>
/// <param name="cancellationToken">EN: Cancellation token / VI: Token hủy</param>
/// <returns>EN: Number of entities written / VI: Số entity đã ghi</returns>
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
/// <summary>
/// EN: Save all changes and dispatch domain events.
/// VI: Lưu tất cả thay đổi và dispatch domain events.
/// </summary>
/// <param name="cancellationToken">EN: Cancellation token / VI: Token hủy</param>
/// <returns>EN: True if successful / VI: True nếu thành công</returns>
Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default);
}

View File

@@ -0,0 +1,53 @@
namespace PromotionService.Domain.SeedWork;
/// <summary>
/// EN: Base class for Value Objects following DDD patterns.
/// VI: Lớp cơ sở cho Value Objects theo mẫu DDD.
/// </summary>
/// <remarks>
/// EN: Value objects are immutable and compared by their values, not identity.
/// VI: Value objects là bất biến và được so sánh theo giá trị, không phải định danh.
/// </remarks>
public abstract class ValueObject
{
/// <summary>
/// EN: Get the atomic values that make up this value object.
/// VI: Lấy các giá trị nguyên tử tạo nên value object này.
/// </summary>
protected abstract IEnumerable<object?> GetEqualityComponents();
public override bool Equals(object? obj)
{
if (obj is null || obj.GetType() != GetType())
return false;
var other = (ValueObject)obj;
return GetEqualityComponents().SequenceEqual(other.GetEqualityComponents());
}
public override int GetHashCode()
{
return GetEqualityComponents()
.Select(x => x?.GetHashCode() ?? 0)
.Aggregate((x, y) => x ^ y);
}
public static bool operator ==(ValueObject? left, ValueObject? right)
{
return left?.Equals(right) ?? right is null;
}
public static bool operator !=(ValueObject? left, ValueObject? right)
{
return !(left == right);
}
/// <summary>
/// EN: Create a copy of this value object with modifications.
/// VI: Tạo bản sao của value object này với các thay đổi.
/// </summary>
protected ValueObject GetCopy()
{
return (ValueObject)MemberwiseClone();
}
}

View File

@@ -0,0 +1,57 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using PromotionService.Domain.AggregatesModel.SampleAggregate;
using PromotionService.Infrastructure.Idempotency;
using PromotionService.Infrastructure.Repositories;
namespace PromotionService.Infrastructure;
/// <summary>
/// EN: Dependency injection extensions for Infrastructure layer.
/// VI: Extensions dependency injection cho lớp Infrastructure.
/// </summary>
public static class DependencyInjection
{
/// <summary>
/// EN: Add infrastructure services to the DI container.
/// VI: Thêm các services infrastructure vào DI container.
/// </summary>
public static IServiceCollection AddInfrastructure(
this IServiceCollection services,
IConfiguration configuration)
{
// EN: Add DbContext with PostgreSQL / VI: Thêm DbContext với PostgreSQL
services.AddDbContext<PromotionServiceContext>(options =>
{
var connectionString = configuration.GetConnectionString("DefaultConnection")
?? configuration["DATABASE_URL"]
?? throw new InvalidOperationException("Connection string not configured");
options.UseNpgsql(connectionString, npgsqlOptions =>
{
npgsqlOptions.MigrationsAssembly(typeof(PromotionServiceContext).Assembly.FullName);
npgsqlOptions.EnableRetryOnFailure(
maxRetryCount: 5,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorCodesToAdd: null);
});
// EN: Enable sensitive data logging in development only
// VI: Chỉ bật sensitive data logging trong development
if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
{
options.EnableSensitiveDataLogging();
options.EnableDetailedErrors();
}
});
// EN: Register repositories / VI: Đăng ký repositories
services.AddScoped<ISampleRepository, SampleRepository>();
// EN: Register idempotency services / VI: Đăng ký idempotency services
services.AddScoped<IRequestManager, RequestManager>();
return services;
}
}

View File

@@ -0,0 +1,61 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using PromotionService.Domain.AggregatesModel.SampleAggregate;
namespace PromotionService.Infrastructure.EntityConfigurations;
/// <summary>
/// EN: EF Core configuration for Sample entity.
/// VI: Cấu hình EF Core cho entity Sample.
/// </summary>
public class SampleEntityTypeConfiguration : IEntityTypeConfiguration<Sample>
{
public void Configure(EntityTypeBuilder<Sample> builder)
{
// EN: Table name / VI: Tên bảng
builder.ToTable("samples");
// EN: Primary key / VI: Khóa chính
builder.HasKey(s => s.Id);
// EN: Ignore domain events (not persisted)
// VI: Bỏ qua domain events (không lưu)
builder.Ignore(s => s.DomainEvents);
// EN: Properties / VI: Các thuộc tính
builder.Property(s => s.Id)
.HasColumnName("id")
.IsRequired();
builder.Property<string>("_name")
.HasColumnName("name")
.HasMaxLength(200)
.IsRequired();
builder.Property<string?>("_description")
.HasColumnName("description")
.HasMaxLength(1000);
builder.Property<DateTime>("_createdAt")
.HasColumnName("created_at")
.IsRequired();
builder.Property<DateTime?>("_updatedAt")
.HasColumnName("updated_at");
// EN: Status relationship / VI: Quan hệ với Status
builder.Property(s => s.StatusId)
.HasColumnName("status_id")
.IsRequired();
builder.HasOne(s => s.Status)
.WithMany()
.HasForeignKey(s => s.StatusId)
.OnDelete(DeleteBehavior.Restrict);
// EN: Indexes / VI: Các index
builder.HasIndex("_name");
builder.HasIndex(s => s.StatusId);
builder.HasIndex("_createdAt");
}
}

View File

@@ -0,0 +1,39 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using PromotionService.Domain.AggregatesModel.SampleAggregate;
namespace PromotionService.Infrastructure.EntityConfigurations;
/// <summary>
/// EN: EF Core configuration for SampleStatus enumeration.
/// VI: Cấu hình EF Core cho enumeration SampleStatus.
/// </summary>
public class SampleStatusEntityTypeConfiguration : IEntityTypeConfiguration<SampleStatus>
{
public void Configure(EntityTypeBuilder<SampleStatus> builder)
{
// EN: Table name / VI: Tên bảng
builder.ToTable("sample_statuses");
// EN: Primary key / VI: Khóa chính
builder.HasKey(s => s.Id);
builder.Property(s => s.Id)
.HasColumnName("id")
.ValueGeneratedNever()
.IsRequired();
builder.Property(s => s.Name)
.HasColumnName("name")
.HasMaxLength(50)
.IsRequired();
// EN: Seed initial data / VI: Seed dữ liệu ban đầu
builder.HasData(
SampleStatus.Draft,
SampleStatus.Active,
SampleStatus.Completed,
SampleStatus.Cancelled
);
}
}

View File

@@ -0,0 +1,26 @@
namespace PromotionService.Infrastructure.Idempotency;
/// <summary>
/// EN: Entity for tracking client requests to ensure idempotency.
/// VI: Entity để theo dõi các requests từ client đảm bảo idempotency.
/// </summary>
public class ClientRequest
{
/// <summary>
/// EN: Unique request identifier.
/// VI: Định danh request duy nhất.
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// EN: Name of the command/request type.
/// VI: Tên của loại command/request.
/// </summary>
public string Name { get; set; } = null!;
/// <summary>
/// EN: Timestamp when the request was received.
/// VI: Thời điểm request được nhận.
/// </summary>
public DateTime Time { get; set; }
}

View File

@@ -0,0 +1,24 @@
namespace PromotionService.Infrastructure.Idempotency;
/// <summary>
/// EN: Interface for managing client request idempotency.
/// VI: Interface để quản lý idempotency của client requests.
/// </summary>
public interface IRequestManager
{
/// <summary>
/// EN: Check if a request with the given ID exists.
/// VI: Kiểm tra xem request với ID cho trước có tồn tại không.
/// </summary>
/// <param name="id">EN: Request ID / VI: ID của request</param>
/// <returns>EN: True if exists / VI: True nếu tồn tại</returns>
Task<bool> ExistAsync(Guid id);
/// <summary>
/// EN: Create a new request record for tracking.
/// VI: Tạo bản ghi request mới để theo dõi.
/// </summary>
/// <typeparam name="T">EN: Command type / VI: Loại command</typeparam>
/// <param name="id">EN: Request ID / VI: ID của request</param>
Task CreateRequestForCommandAsync<T>(Guid id);
}

View File

@@ -0,0 +1,45 @@
using Microsoft.EntityFrameworkCore;
namespace PromotionService.Infrastructure.Idempotency;
/// <summary>
/// EN: Implementation of request manager for idempotency.
/// VI: Triển khai request manager cho idempotency.
/// </summary>
public class RequestManager : IRequestManager
{
private readonly PromotionServiceContext _context;
public RequestManager(PromotionServiceContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
/// <inheritdoc/>
public async Task<bool> ExistAsync(Guid id)
{
var request = await _context
.FindAsync<ClientRequest>(id);
return request != null;
}
/// <inheritdoc/>
public async Task CreateRequestForCommandAsync<T>(Guid id)
{
var exists = await ExistAsync(id);
var request = exists
? throw new InvalidOperationException($"Request with {id} already exists")
: new ClientRequest
{
Id = id,
Name = typeof(T).Name,
Time = DateTime.UtcNow
};
_context.Add(request);
await _context.SaveChangesAsync();
}
}

View File

@@ -0,0 +1,160 @@
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using PromotionService.Domain.AggregatesModel.SampleAggregate;
using PromotionService.Domain.SeedWork;
using PromotionService.Infrastructure.EntityConfigurations;
namespace PromotionService.Infrastructure;
/// <summary>
/// EN: EF Core DbContext for PromotionService.
/// VI: EF Core DbContext cho PromotionService.
/// </summary>
public class PromotionServiceContext : DbContext, IUnitOfWork
{
private readonly IMediator _mediator;
private IDbContextTransaction? _currentTransaction;
/// <summary>
/// EN: Samples table.
/// VI: Bảng Samples.
/// </summary>
public DbSet<Sample> Samples => Set<Sample>();
/// <summary>
/// EN: Read-only access to current transaction.
/// VI: Truy cập chỉ đọc đến transaction hiện tại.
/// </summary>
public IDbContextTransaction? CurrentTransaction => _currentTransaction;
/// <summary>
/// EN: Check if there is an active transaction.
/// VI: Kiểm tra xem có transaction đang hoạt động không.
/// </summary>
public bool HasActiveTransaction => _currentTransaction != null;
public PromotionServiceContext(DbContextOptions<PromotionServiceContext> options) : base(options)
{
_mediator = null!;
}
public PromotionServiceContext(DbContextOptions<PromotionServiceContext> options, IMediator mediator) : base(options)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
System.Diagnostics.Debug.WriteLine("PromotionServiceContext::ctor - " + GetHashCode());
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// EN: Apply entity configurations
// VI: Áp dụng các cấu hình entity
modelBuilder.ApplyConfiguration(new SampleEntityTypeConfiguration());
modelBuilder.ApplyConfiguration(new SampleStatusEntityTypeConfiguration());
}
/// <summary>
/// EN: Save entities and dispatch domain events.
/// VI: Lưu entities và dispatch domain events.
/// </summary>
public async Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default)
{
// EN: Dispatch domain events before saving (side effects)
// VI: Dispatch domain events trước khi lưu (side effects)
await DispatchDomainEventsAsync();
// EN: Save changes to database
// VI: Lưu thay đổi vào database
await base.SaveChangesAsync(cancellationToken);
return true;
}
/// <summary>
/// EN: Begin a new transaction if none is active.
/// VI: Bắt đầu một transaction mới nếu không có transaction nào đang hoạt động.
/// </summary>
public async Task<IDbContextTransaction?> BeginTransactionAsync()
{
if (_currentTransaction != null) return null;
_currentTransaction = await Database.BeginTransactionAsync(System.Data.IsolationLevel.ReadCommitted);
return _currentTransaction;
}
/// <summary>
/// EN: Commit the current transaction.
/// VI: Commit transaction hiện tại.
/// </summary>
public async Task CommitTransactionAsync(IDbContextTransaction transaction)
{
ArgumentNullException.ThrowIfNull(transaction);
if (transaction != _currentTransaction)
throw new InvalidOperationException($"Transaction {transaction.TransactionId} is not current");
try
{
await SaveChangesAsync();
await transaction.CommitAsync();
}
catch
{
RollbackTransaction();
throw;
}
finally
{
if (_currentTransaction != null)
{
_currentTransaction.Dispose();
_currentTransaction = null;
}
}
}
/// <summary>
/// EN: Rollback the current transaction.
/// VI: Rollback transaction hiện tại.
/// </summary>
public void RollbackTransaction()
{
try
{
_currentTransaction?.Rollback();
}
finally
{
if (_currentTransaction != null)
{
_currentTransaction.Dispose();
_currentTransaction = null;
}
}
}
/// <summary>
/// EN: Dispatch all domain events from tracked entities.
/// VI: Dispatch tất cả domain events từ các entities đang được track.
/// </summary>
private async Task DispatchDomainEventsAsync()
{
var domainEntities = ChangeTracker
.Entries<Entity>()
.Where(x => x.Entity.DomainEvents.Any())
.ToList();
var domainEvents = domainEntities
.SelectMany(x => x.Entity.DomainEvents)
.ToList();
domainEntities.ForEach(entity => entity.Entity.ClearDomainEvents());
foreach (var domainEvent in domainEvents)
{
await _mediator.Publish(domainEvent);
}
}
}

View File

@@ -0,0 +1,36 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>PromotionService.Infrastructure</AssemblyName>
<RootNamespace>PromotionService.Infrastructure</RootNamespace>
<Description>Infrastructure layer for data access and external services</Description>
</PropertyGroup>
<ItemGroup>
<!-- EN: Entity Framework Core with PostgreSQL / VI: Entity Framework Core với PostgreSQL -->
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<!-- EN: MediatR for dispatching domain events / VI: MediatR để dispatch domain events -->
<PackageReference Include="MediatR" Version="12.4.1" />
<!-- EN: Dapper for read-optimized queries / VI: Dapper cho queries tối ưu đọc -->
<PackageReference Include="Dapper" Version="2.1.35" />
<!-- EN: Resilience with Polly / VI: Resilience với Polly -->
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="9.0.0" />
<PackageReference Include="Polly" Version="8.5.0" />
<!-- EN: Redis cache / VI: Redis cache -->
<PackageReference Include="StackExchange.Redis" Version="2.8.16" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PromotionService.Domain\PromotionService.Domain.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,72 @@
using Microsoft.EntityFrameworkCore;
using PromotionService.Domain.AggregatesModel.SampleAggregate;
using PromotionService.Domain.SeedWork;
namespace PromotionService.Infrastructure.Repositories;
/// <summary>
/// EN: Repository implementation for Sample aggregate.
/// VI: Triển khai repository cho Sample aggregate.
/// </summary>
public class SampleRepository : ISampleRepository
{
private readonly PromotionServiceContext _context;
/// <summary>
/// EN: Unit of work for transaction management.
/// VI: Unit of work cho quản lý transaction.
/// </summary>
public IUnitOfWork UnitOfWork => _context;
public SampleRepository(PromotionServiceContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
/// <inheritdoc/>
public async Task<Sample?> GetAsync(Guid sampleId)
{
var sample = await _context.Samples
.Include(s => s.Status)
.FirstOrDefaultAsync(s => s.Id == sampleId);
return sample;
}
/// <inheritdoc/>
public async Task<IEnumerable<Sample>> GetAllAsync()
{
return await _context.Samples
.Include(s => s.Status)
.OrderByDescending(s => s.CreatedAt)
.ToListAsync();
}
/// <inheritdoc/>
public Sample Add(Sample sample)
{
return _context.Samples.Add(sample).Entity;
}
/// <inheritdoc/>
public void Update(Sample sample)
{
_context.Entry(sample).State = EntityState.Modified;
}
/// <inheritdoc/>
public void Delete(Sample sample)
{
_context.Samples.Remove(sample);
}
/// <inheritdoc/>
public async Task<IEnumerable<Sample>> GetByStatusAsync(int statusId)
{
return await _context.Samples
.Include(s => s.Status)
.Where(s => s.StatusId == statusId)
.OrderByDescending(s => s.CreatedAt)
.ToListAsync();
}
}

View File

@@ -0,0 +1,80 @@
using System.Net;
using System.Net.Http.Json;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
namespace PromotionService.FunctionalTests.Controllers;
/// <summary>
/// EN: Functional tests for Samples API endpoints.
/// VI: Functional tests cho các endpoints API Samples.
/// </summary>
public class SamplesControllerTests : IClassFixture<CustomWebApplicationFactory>
{
private readonly HttpClient _client;
public SamplesControllerTests(CustomWebApplicationFactory factory)
{
_client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
}
[Fact]
public async Task GetSamples_ShouldReturnOkWithEmptyList()
{
// Act
var response = await _client.GetAsync("/api/v1/samples");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var content = await response.Content.ReadFromJsonAsync<ApiResponse<List<object>>>();
content?.Success.Should().BeTrue();
}
[Fact]
public async Task CreateSample_WithValidData_ShouldReturnCreated()
{
// Arrange
var request = new { Name = "Test Sample", Description = "Test Description" };
// Act
var response = await _client.PostAsJsonAsync("/api/v1/samples", request);
// Assert
response.StatusCode.Should().Be(HttpStatusCode.Created);
var content = await response.Content.ReadFromJsonAsync<ApiResponse<CreateSampleResult>>();
content?.Success.Should().BeTrue();
content?.Data?.Id.Should().NotBeEmpty();
}
[Fact]
public async Task GetSample_WithInvalidId_ShouldReturnNotFound()
{
// Arrange
var invalidId = Guid.NewGuid();
// Act
var response = await _client.GetAsync($"/api/v1/samples/{invalidId}");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
[Fact]
public async Task HealthCheck_ShouldReturnHealthy()
{
// Act
var response = await _client.GetAsync("/health/live");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
}
// EN: Helper DTOs for deserialization
// VI: Helper DTOs để deserialize
private record ApiResponse<T>(bool Success, T? Data);
private record CreateSampleResult(Guid Id);
}

View File

@@ -0,0 +1,56 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using PromotionService.Infrastructure;
namespace PromotionService.FunctionalTests;
/// <summary>
/// EN: Custom WebApplicationFactory for functional tests.
/// VI: WebApplicationFactory tùy chỉnh cho functional tests.
/// </summary>
public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Testing");
builder.ConfigureServices(services =>
{
// EN: Remove the existing DbContext registration
// VI: Xóa đăng ký DbContext hiện tại
var descriptor = services.SingleOrDefault(
d => d.ServiceType == typeof(DbContextOptions<PromotionServiceContext>));
if (descriptor != null)
{
services.Remove(descriptor);
}
// EN: Remove DbContext service
// VI: Xóa DbContext service
var dbContextDescriptor = services.SingleOrDefault(
d => d.ServiceType == typeof(PromotionServiceContext));
if (dbContextDescriptor != null)
{
services.Remove(dbContextDescriptor);
}
// EN: Add in-memory database for testing
// VI: Thêm in-memory database để test
services.AddDbContext<PromotionServiceContext>(options =>
{
options.UseInMemoryDatabase("TestDatabase_" + Guid.NewGuid().ToString());
});
// EN: Ensure database is created with seed data
// VI: Đảm bảo database được tạo với seed data
var sp = services.BuildServiceProvider();
using var scope = sp.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<PromotionServiceContext>();
db.Database.EnsureCreated();
});
}
}

View File

@@ -0,0 +1,38 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>PromotionService.FunctionalTests</AssemblyName>
<RootNamespace>PromotionService.FunctionalTests</RootNamespace>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<!-- EN: Test framework / VI: Test framework -->
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<!-- EN: Integration testing / VI: Integration testing -->
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.0" />
<PackageReference Include="FluentAssertions" Version="6.12.2" />
<!-- EN: Test containers for database / VI: Test containers cho database -->
<PackageReference Include="Testcontainers.PostgreSql" Version="4.1.0" />
<!-- EN: Coverage / VI: Coverage -->
<PackageReference Include="coverlet.collector" Version="6.0.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\PromotionService.API\PromotionService.API.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,65 @@
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Moq;
using PromotionService.API.Application.Commands;
using PromotionService.Domain.AggregatesModel.SampleAggregate;
using PromotionService.Domain.SeedWork;
using Xunit;
namespace PromotionService.UnitTests.Application;
/// <summary>
/// EN: Unit tests for CreateSampleCommandHandler.
/// VI: Unit tests cho CreateSampleCommandHandler.
/// </summary>
public class CreateSampleCommandHandlerTests
{
private readonly Mock<ISampleRepository> _mockRepository;
private readonly Mock<ILogger<CreateSampleCommandHandler>> _mockLogger;
private readonly CreateSampleCommandHandler _handler;
public CreateSampleCommandHandlerTests()
{
_mockRepository = new Mock<ISampleRepository>();
_mockLogger = new Mock<ILogger<CreateSampleCommandHandler>>();
var mockUnitOfWork = new Mock<IUnitOfWork>();
mockUnitOfWork.Setup(u => u.SaveEntitiesAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(true);
_mockRepository.SetupGet(r => r.UnitOfWork).Returns(mockUnitOfWork.Object);
_handler = new CreateSampleCommandHandler(_mockRepository.Object, _mockLogger.Object);
}
[Fact]
public async Task Handle_WithValidCommand_ShouldCreateSampleAndReturnId()
{
// Arrange
var command = new CreateSampleCommand("Test Sample", "Test Description");
_mockRepository.Setup(r => r.Add(It.IsAny<Sample>()))
.Returns((Sample s) => s);
// Act
var result = await _handler.Handle(command, CancellationToken.None);
// Assert
result.Should().NotBeNull();
result.Id.Should().NotBeEmpty();
_mockRepository.Verify(r => r.Add(It.IsAny<Sample>()), Times.Once);
}
[Fact]
public async Task Handle_WithValidCommand_ShouldCallSaveEntities()
{
// Arrange
var command = new CreateSampleCommand("Test Sample", null);
// Act
await _handler.Handle(command, CancellationToken.None);
// Assert
_mockRepository.Verify(r => r.UnitOfWork.SaveEntitiesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
}

View File

@@ -0,0 +1,151 @@
using FluentAssertions;
using PromotionService.Domain.AggregatesModel.SampleAggregate;
using PromotionService.Domain.Exceptions;
using Xunit;
namespace PromotionService.UnitTests.Domain;
/// <summary>
/// EN: Unit tests for Sample aggregate.
/// VI: Unit tests cho Sample aggregate.
/// </summary>
public class SampleAggregateTests
{
[Fact]
public void CreateSample_WithValidName_ShouldCreateWithDraftStatus()
{
// Arrange
var name = "Test Sample";
var description = "Test Description";
// Act
var sample = new Sample(name, description);
// Assert
sample.Name.Should().Be(name);
sample.Description.Should().Be(description);
sample.Status.Should().Be(SampleStatus.Draft);
sample.Id.Should().NotBeEmpty();
sample.DomainEvents.Should().ContainSingle(); // SampleCreatedDomainEvent
}
[Fact]
public void CreateSample_WithEmptyName_ShouldThrowException()
{
// Arrange
var name = "";
// Act
var act = () => new Sample(name);
// Assert
act.Should().Throw<SampleDomainException>()
.WithMessage("Sample name cannot be empty");
}
[Fact]
public void Activate_WhenDraft_ShouldChangeToActive()
{
// Arrange
var sample = new Sample("Test Sample");
sample.ClearDomainEvents();
// Act
sample.Activate();
// Assert
sample.Status.Should().Be(SampleStatus.Active);
sample.DomainEvents.Should().ContainSingle(); // SampleStatusChangedDomainEvent
}
[Fact]
public void Activate_WhenNotDraft_ShouldThrowException()
{
// Arrange
var sample = new Sample("Test Sample");
sample.Activate();
// Act
var act = () => sample.Activate();
// Assert
act.Should().Throw<SampleDomainException>()
.WithMessage("Only draft samples can be activated");
}
[Fact]
public void Complete_WhenActive_ShouldChangeToCompleted()
{
// Arrange
var sample = new Sample("Test Sample");
sample.Activate();
sample.ClearDomainEvents();
// Act
sample.Complete();
// Assert
sample.Status.Should().Be(SampleStatus.Completed);
}
[Fact]
public void Cancel_WhenDraftOrActive_ShouldChangeToCancelled()
{
// Arrange
var sample = new Sample("Test Sample");
// Act
sample.Cancel();
// Assert
sample.Status.Should().Be(SampleStatus.Cancelled);
}
[Fact]
public void Cancel_WhenCompleted_ShouldThrowException()
{
// Arrange
var sample = new Sample("Test Sample");
sample.Activate();
sample.Complete();
// Act
var act = () => sample.Cancel();
// Assert
act.Should().Throw<SampleDomainException>()
.WithMessage("Cannot cancel a completed sample");
}
[Fact]
public void Update_WhenNotCancelled_ShouldUpdateNameAndDescription()
{
// Arrange
var sample = new Sample("Original Name", "Original Description");
var newName = "Updated Name";
var newDescription = "Updated Description";
// Act
sample.Update(newName, newDescription);
// Assert
sample.Name.Should().Be(newName);
sample.Description.Should().Be(newDescription);
sample.UpdatedAt.Should().NotBeNull();
}
[Fact]
public void Update_WhenCancelled_ShouldThrowException()
{
// Arrange
var sample = new Sample("Test Sample");
sample.Cancel();
// Act
var act = () => sample.Update("New Name", null);
// Assert
act.Should().Throw<SampleDomainException>()
.WithMessage("Cannot update a cancelled sample");
}
}

View File

@@ -0,0 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>PromotionService.UnitTests</AssemblyName>
<RootNamespace>PromotionService.UnitTests</RootNamespace>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<!-- EN: Test framework / VI: Test framework -->
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<!-- EN: Assertions and mocking / VI: Assertions và mocking -->
<PackageReference Include="FluentAssertions" Version="6.12.2" />
<PackageReference Include="Moq" Version="4.20.72" />
<!-- EN: Coverage / VI: Coverage -->
<PackageReference Include="coverlet.collector" Version="6.0.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\PromotionService.Domain\PromotionService.Domain.csproj" />
<ProjectReference Include="..\..\src\PromotionService.API\PromotionService.API.csproj" />
</ItemGroup>
</Project>