From 616a8973e4b9b75c060a57910c356409dd9c9379 Mon Sep 17 00:00:00 2001 From: Ho Ngoc Hai Date: Sat, 17 Jan 2026 22:41:40 +0700 Subject: [PATCH] feat: introduce admin API endpoints and handlers for managing campaigns, vouchers, and redemptions. --- services/ads-manager-service-net/.env.example | 40 +++ services/ads-manager-service-net/.gitignore | 75 ++++ .../Directory.Build.props | 22 ++ services/ads-manager-service-net/Dockerfile | 66 ++++ .../ads-manager-service-net/MyService.slnx | 11 + .../docker-compose.yml | 72 ++++ .../docs/en/ARCHITECTURE.md | 271 +++++++++++++++ .../ads-manager-service-net/docs/en/README.md | 265 ++++++++++++++ .../docs/vi/ARCHITECTURE.md | 271 +++++++++++++++ .../ads-manager-service-net/docs/vi/README.md | 265 ++++++++++++++ services/ads-manager-service-net/global.json | 7 + .../Application/Behaviors/LoggingBehavior.cs | 58 ++++ .../Behaviors/TransactionBehavior.cs | 84 +++++ .../Behaviors/ValidatorBehavior.cs | 63 ++++ .../Commands/ChangeSampleStatusCommand.cs | 14 + .../ChangeSampleStatusCommandHandler.cs | 70 ++++ .../Commands/CreateSampleCommand.cs | 21 ++ .../Commands/CreateSampleCommandHandler.cs | 46 +++ .../Commands/DeleteSampleCommand.cs | 10 + .../Commands/DeleteSampleCommandHandler.cs | 54 +++ .../Commands/UpdateSampleCommand.cs | 16 + .../Commands/UpdateSampleCommandHandler.cs | 54 +++ .../Application/Queries/GetSampleQuery.cs | 23 ++ .../Queries/GetSampleQueryHandler.cs | 39 +++ .../Application/Queries/GetSamplesQuery.cs | 9 + .../Queries/GetSamplesQueryHandler.cs | 34 ++ .../CreateSampleCommandValidator.cs | 25 ++ .../UpdateSampleCommandValidator.cs | 29 ++ .../Controllers/SamplesController.cs | 200 +++++++++++ .../src/MyService.API/MyService.API.csproj | 43 +++ .../src/MyService.API/Program.cs | 144 ++++++++ .../Properties/launchSettings.json | 15 + .../appsettings.Development.json | 19 + .../src/MyService.API/appsettings.json | 46 +++ .../SampleAggregate/ISampleRepository.cs | 61 ++++ .../AggregatesModel/SampleAggregate/Sample.cs | 158 +++++++++ .../SampleAggregate/SampleStatus.cs | 77 +++++ .../Events/SampleCreatedDomainEvent.cs | 22 ++ .../Events/SampleStatusChangedDomainEvent.cs | 39 +++ .../Exceptions/DomainException.cs | 21 ++ .../Exceptions/SampleDomainException.cs | 21 ++ .../MyService.Domain/MyService.Domain.csproj | 14 + .../src/MyService.Domain/SeedWork/Entity.cs | 102 ++++++ .../MyService.Domain/SeedWork/Enumeration.cs | 95 +++++ .../SeedWork/IAggregateRoot.cs | 15 + .../MyService.Domain/SeedWork/IRepository.cs | 15 + .../MyService.Domain/SeedWork/IUnitOfWork.cs | 30 ++ .../MyService.Domain/SeedWork/ValueObject.cs | 53 +++ .../DependencyInjection.cs | 57 +++ .../SampleEntityTypeConfiguration.cs | 61 ++++ .../SampleStatusEntityTypeConfiguration.cs | 39 +++ .../Idempotency/ClientRequest.cs | 26 ++ .../Idempotency/IRequestManager.cs | 24 ++ .../Idempotency/RequestManager.cs | 45 +++ .../MyService.Infrastructure.csproj | 36 ++ .../MyServiceContext.cs | 160 +++++++++ .../Repositories/SampleRepository.cs | 72 ++++ .../Controllers/SamplesControllerTests.cs | 80 +++++ .../CustomWebApplicationFactory.cs | 56 +++ .../MyService.FunctionalTests.csproj | 38 ++ .../CreateSampleCommandHandlerTests.cs | 65 ++++ .../Domain/SampleAggregateTests.cs | 151 ++++++++ .../MyService.UnitTests.csproj | 35 ++ .../Commands/AdminCommandHandlers.cs | 159 +++++++++ .../Application/Commands/AdminCommands.cs | 43 +++ .../Application/DTOs/AdminDtos.cs | 126 +++++++ .../Application/Queries/AdminQueries.cs | 68 ++++ .../Application/Queries/AdminQueryHandlers.cs | 309 +++++++++++++++++ .../Admin/AdminCampaignsController.cs | 125 +++++++ .../Admin/AdminRedemptionsController.cs | 89 +++++ .../Admin/AdminVouchersController.cs | 103 ++++++ .../CampaignAggregate/Campaign.cs | 32 ++ .../CampaignAggregate/ICampaignRepository.cs | 6 + .../CampaignAggregate/Voucher.cs | 20 ++ .../Repositories/CampaignRepository.cs | 6 + .../ClaimVoucherCommandHandlerTests.cs | 128 +++++++ .../CreateCampaignCommandHandlerTests.cs | 172 +++++++++ .../Domain/CampaignAggregateTests.cs | 326 ++++++++++++++++++ .../Domain/VoucherEntityTests.cs | 199 +++++++++++ .../PromotionService.UnitTests.csproj | 1 + 80 files changed, 6061 insertions(+) create mode 100644 services/ads-manager-service-net/.env.example create mode 100644 services/ads-manager-service-net/.gitignore create mode 100644 services/ads-manager-service-net/Directory.Build.props create mode 100644 services/ads-manager-service-net/Dockerfile create mode 100644 services/ads-manager-service-net/MyService.slnx create mode 100644 services/ads-manager-service-net/docker-compose.yml create mode 100644 services/ads-manager-service-net/docs/en/ARCHITECTURE.md create mode 100644 services/ads-manager-service-net/docs/en/README.md create mode 100644 services/ads-manager-service-net/docs/vi/ARCHITECTURE.md create mode 100644 services/ads-manager-service-net/docs/vi/README.md create mode 100644 services/ads-manager-service-net/global.json create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Behaviors/LoggingBehavior.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Behaviors/TransactionBehavior.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Behaviors/ValidatorBehavior.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Commands/ChangeSampleStatusCommand.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Commands/ChangeSampleStatusCommandHandler.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Commands/CreateSampleCommand.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Commands/CreateSampleCommandHandler.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Commands/DeleteSampleCommand.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Commands/DeleteSampleCommandHandler.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Commands/UpdateSampleCommand.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Commands/UpdateSampleCommandHandler.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSampleQuery.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSampleQueryHandler.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSamplesQuery.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSamplesQueryHandler.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Validations/CreateSampleCommandValidator.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Application/Validations/UpdateSampleCommandValidator.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Controllers/SamplesController.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/MyService.API.csproj create mode 100644 services/ads-manager-service-net/src/MyService.API/Program.cs create mode 100644 services/ads-manager-service-net/src/MyService.API/Properties/launchSettings.json create mode 100644 services/ads-manager-service-net/src/MyService.API/appsettings.Development.json create mode 100644 services/ads-manager-service-net/src/MyService.API/appsettings.json create mode 100644 services/ads-manager-service-net/src/MyService.Domain/AggregatesModel/SampleAggregate/ISampleRepository.cs create mode 100644 services/ads-manager-service-net/src/MyService.Domain/AggregatesModel/SampleAggregate/Sample.cs create mode 100644 services/ads-manager-service-net/src/MyService.Domain/AggregatesModel/SampleAggregate/SampleStatus.cs create mode 100644 services/ads-manager-service-net/src/MyService.Domain/Events/SampleCreatedDomainEvent.cs create mode 100644 services/ads-manager-service-net/src/MyService.Domain/Events/SampleStatusChangedDomainEvent.cs create mode 100644 services/ads-manager-service-net/src/MyService.Domain/Exceptions/DomainException.cs create mode 100644 services/ads-manager-service-net/src/MyService.Domain/Exceptions/SampleDomainException.cs create mode 100644 services/ads-manager-service-net/src/MyService.Domain/MyService.Domain.csproj create mode 100644 services/ads-manager-service-net/src/MyService.Domain/SeedWork/Entity.cs create mode 100644 services/ads-manager-service-net/src/MyService.Domain/SeedWork/Enumeration.cs create mode 100644 services/ads-manager-service-net/src/MyService.Domain/SeedWork/IAggregateRoot.cs create mode 100644 services/ads-manager-service-net/src/MyService.Domain/SeedWork/IRepository.cs create mode 100644 services/ads-manager-service-net/src/MyService.Domain/SeedWork/IUnitOfWork.cs create mode 100644 services/ads-manager-service-net/src/MyService.Domain/SeedWork/ValueObject.cs create mode 100644 services/ads-manager-service-net/src/MyService.Infrastructure/DependencyInjection.cs create mode 100644 services/ads-manager-service-net/src/MyService.Infrastructure/EntityConfigurations/SampleEntityTypeConfiguration.cs create mode 100644 services/ads-manager-service-net/src/MyService.Infrastructure/EntityConfigurations/SampleStatusEntityTypeConfiguration.cs create mode 100644 services/ads-manager-service-net/src/MyService.Infrastructure/Idempotency/ClientRequest.cs create mode 100644 services/ads-manager-service-net/src/MyService.Infrastructure/Idempotency/IRequestManager.cs create mode 100644 services/ads-manager-service-net/src/MyService.Infrastructure/Idempotency/RequestManager.cs create mode 100644 services/ads-manager-service-net/src/MyService.Infrastructure/MyService.Infrastructure.csproj create mode 100644 services/ads-manager-service-net/src/MyService.Infrastructure/MyServiceContext.cs create mode 100644 services/ads-manager-service-net/src/MyService.Infrastructure/Repositories/SampleRepository.cs create mode 100644 services/ads-manager-service-net/tests/MyService.FunctionalTests/Controllers/SamplesControllerTests.cs create mode 100644 services/ads-manager-service-net/tests/MyService.FunctionalTests/CustomWebApplicationFactory.cs create mode 100644 services/ads-manager-service-net/tests/MyService.FunctionalTests/MyService.FunctionalTests.csproj create mode 100644 services/ads-manager-service-net/tests/MyService.UnitTests/Application/CreateSampleCommandHandlerTests.cs create mode 100644 services/ads-manager-service-net/tests/MyService.UnitTests/Domain/SampleAggregateTests.cs create mode 100644 services/ads-manager-service-net/tests/MyService.UnitTests/MyService.UnitTests.csproj create mode 100644 services/promotion-service-net/src/PromotionService.API/Application/Commands/AdminCommandHandlers.cs create mode 100644 services/promotion-service-net/src/PromotionService.API/Application/Commands/AdminCommands.cs create mode 100644 services/promotion-service-net/src/PromotionService.API/Application/DTOs/AdminDtos.cs create mode 100644 services/promotion-service-net/src/PromotionService.API/Application/Queries/AdminQueries.cs create mode 100644 services/promotion-service-net/src/PromotionService.API/Application/Queries/AdminQueryHandlers.cs create mode 100644 services/promotion-service-net/src/PromotionService.API/Controllers/Admin/AdminCampaignsController.cs create mode 100644 services/promotion-service-net/src/PromotionService.API/Controllers/Admin/AdminRedemptionsController.cs create mode 100644 services/promotion-service-net/src/PromotionService.API/Controllers/Admin/AdminVouchersController.cs create mode 100644 services/promotion-service-net/tests/PromotionService.UnitTests/Application/ClaimVoucherCommandHandlerTests.cs create mode 100644 services/promotion-service-net/tests/PromotionService.UnitTests/Application/CreateCampaignCommandHandlerTests.cs create mode 100644 services/promotion-service-net/tests/PromotionService.UnitTests/Domain/CampaignAggregateTests.cs create mode 100644 services/promotion-service-net/tests/PromotionService.UnitTests/Domain/VoucherEntityTests.cs diff --git a/services/ads-manager-service-net/.env.example b/services/ads-manager-service-net/.env.example new file mode 100644 index 00000000..f9053bc3 --- /dev/null +++ b/services/ads-manager-service-net/.env.example @@ -0,0 +1,40 @@ +# Environment / Môi Trường +ASPNETCORE_ENVIRONMENT=Development + +# Database / Cơ Sở Dữ Liệu +# PostgreSQL connection string (Neon or local) +DATABASE_URL=Host=localhost;Port=5432;Database=myservice_db;Username=postgres;Password=postgres + +# Redis Cache +REDIS_URL=localhost:6379 +REDIS_PASSWORD= + +# JWT Authentication / Xác Thực JWT +JWT_SECRET=your-secret-key-min-32-characters-long-here +JWT_ISSUER=goodgo-platform +JWT_AUDIENCE=goodgo-services +JWT_ACCESS_TOKEN_EXPIRY_MINUTES=15 +JWT_REFRESH_TOKEN_EXPIRY_DAYS=7 + +# API Configuration / Cấu Hình API +API_PORT=5000 +API_BASE_PATH=/api/v1/myservice + +# Observability / Quan Sát +OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 +OTEL_SERVICE_NAME=myservice + +# Logging +LOG_LEVEL=Information +SEQ_URL=http://localhost:5341 + +# Feature Flags +FEATURE_SWAGGER_ENABLED=true +FEATURE_DETAILED_ERRORS=true + +# Rate Limiting +RATE_LIMIT_PERMITS_PER_MINUTE=100 +RATE_LIMIT_QUEUE_LIMIT=10 + +# Health Checks +HEALTHCHECK_TIMEOUT_SECONDS=5 diff --git a/services/ads-manager-service-net/.gitignore b/services/ads-manager-service-net/.gitignore new file mode 100644 index 00000000..84b02a53 --- /dev/null +++ b/services/ads-manager-service-net/.gitignore @@ -0,0 +1,75 @@ +# Build results +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio +.vs/ +*.user +*.userosscache +*.suo +*.userprefs +*.sln.docstates + +# Rider +.idea/ +*.sln.iml + +# Visual Studio Code +.vscode/ + +# NuGet +*.nupkg +*.snupkg +.nuget/ +packages/ +project.lock.json +project.fragment.lock.json + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# Coverage +TestResults/ +*.coverage +*.coveragexml +coverage*.json +coverage*.xml + +# Publish output +publish/ +out/ + +# Environment files +.env +.env.local +.env.*.local +*.env + +# Secrets +appsettings.*.json +!appsettings.json +!appsettings.Development.json + +# macOS +.DS_Store + +# Windows +Thumbs.db +ehthumbs.db + +# JetBrains +*.resharper + +# dotnet tools +.config/dotnet-tools.json + +# Migration scripts (only keep structure) +Migrations/ + +# Temp files +*.tmp +*.temp +~$* diff --git a/services/ads-manager-service-net/Directory.Build.props b/services/ads-manager-service-net/Directory.Build.props new file mode 100644 index 00000000..c3b74373 --- /dev/null +++ b/services/ads-manager-service-net/Directory.Build.props @@ -0,0 +1,22 @@ + + + net10.0 + 14.0 + enable + enable + true + true + $(NoWarn);1591;CA2017 + + + + GoodGo Team + GoodGo + © 2026 GoodGo. All rights reserved. + git + + + + + + diff --git a/services/ads-manager-service-net/Dockerfile b/services/ads-manager-service-net/Dockerfile new file mode 100644 index 00000000..192106ab --- /dev/null +++ b/services/ads-manager-service-net/Dockerfile @@ -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/MyService.API/MyService.API.csproj", "src/MyService.API/"] +COPY ["src/MyService.Domain/MyService.Domain.csproj", "src/MyService.Domain/"] +COPY ["src/MyService.Infrastructure/MyService.Infrastructure.csproj", "src/MyService.Infrastructure/"] +COPY ["Directory.Build.props", "./"] + +# EN: Restore dependencies +# VI: Khôi phục dependencies +RUN dotnet restore "src/MyService.API/MyService.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/MyService.API" +RUN dotnet build "MyService.API.csproj" -c Release -o /app/build --no-restore + +# Publish stage / Giai đoạn publish +FROM build AS publish +RUN dotnet publish "MyService.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", "MyService.API.dll"] diff --git a/services/ads-manager-service-net/MyService.slnx b/services/ads-manager-service-net/MyService.slnx new file mode 100644 index 00000000..1222dbb8 --- /dev/null +++ b/services/ads-manager-service-net/MyService.slnx @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/services/ads-manager-service-net/docker-compose.yml b/services/ads-manager-service-net/docker-compose.yml new file mode 100644 index 00000000..254ceb12 --- /dev/null +++ b/services/ads-manager-service-net/docker-compose.yml @@ -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 diff --git a/services/ads-manager-service-net/docs/en/ARCHITECTURE.md b/services/ads-manager-service-net/docs/en/ARCHITECTURE.md new file mode 100644 index 00000000..9d80ba57 --- /dev/null +++ b/services/ads-manager-service-net/docs/en/ARCHITECTURE.md @@ -0,0 +1,271 @@ +# Architecture Documentation + +> Detailed architecture documentation for the .NET 10 Microservice Template. + +## Architecture Overview + +```mermaid +graph TB + subgraph "API Layer" + C[Controllers] + CMD[Commands] + Q[Queries] + B[Behaviors] + V[Validations] + end + + subgraph "Domain Layer" + AR[Aggregate Roots] + E[Entities] + VO[Value Objects] + DE[Domain Events] + DX[Domain Exceptions] + end + + subgraph "Infrastructure Layer" + DB[(PostgreSQL)] + R[Repositories] + CTX[DbContext] + ID[Idempotency] + end + + C --> CMD + C --> Q + CMD --> B --> V + CMD --> AR + Q --> R + R --> CTX --> DB + AR --> DE + R --> AR + + style C fill:#4a90d9,stroke:#2d5986,color:#fff + style AR fill:#50c878,stroke:#2d8659,color:#fff + style DB fill:#ff6b6b,stroke:#c0392b,color:#fff +``` + +## Layer Responsibilities + +### 1. Domain Layer (MyService.Domain) + +The heart of the application containing pure business logic. This layer: +- Has **ZERO** external dependencies (except MediatR.Contracts for events) +- Contains only POCO classes +- Implements DDD tactical patterns + +#### Components + +| Component | Purpose | +|-----------|---------| +| **SeedWork** | Base classes: Entity, ValueObject, Enumeration, IAggregateRoot | +| **AggregatesModel** | Aggregate roots with their entities and value objects | +| **Events** | Domain events for cross-aggregate communication | +| **Exceptions** | Domain-specific exceptions for business rule violations | + +### 2. Infrastructure Layer (MyService.Infrastructure) + +Technical implementations and external concerns: +- Database access (EF Core) +- Repository implementations +- External service integrations + +### 3. API Layer (MyService.API) + +Application entry point and CQRS implementation: +- Controllers for HTTP handling +- Commands for write operations +- Queries for read operations +- MediatR behaviors for cross-cutting concerns + +## CQRS Flow + +```mermaid +sequenceDiagram + participant Client + participant Controller + participant MediatR + participant LoggingBehavior + participant ValidatorBehavior + participant TransactionBehavior + participant CommandHandler + participant Repository + participant DbContext + + Client->>Controller: HTTP Request + Controller->>MediatR: Send(Command) + MediatR->>LoggingBehavior: Handle + LoggingBehavior->>ValidatorBehavior: Next() + ValidatorBehavior->>TransactionBehavior: Next() + TransactionBehavior->>CommandHandler: Next() + CommandHandler->>Repository: Add/Update/Delete + Repository->>DbContext: SaveEntitiesAsync() + DbContext-->>Repository: Success + Repository-->>CommandHandler: Result + CommandHandler-->>Controller: Response + Controller-->>Client: HTTP Response +``` + +## Domain Events + +```mermaid +graph LR + AR[Aggregate Root] -->|Raises| DE[Domain Event] + DE -->|Dispatched by| CTX[DbContext] + CTX -->|Publishes to| M[MediatR] + M -->|Handled by| H1[Handler 1] + M -->|Handled by| H2[Handler 2] + + style AR fill:#50c878,stroke:#2d8659,color:#fff + style DE fill:#f39c12,stroke:#d68910,color:#fff + style M fill:#9b59b6,stroke:#7d3c98,color:#fff +``` + +## Database Schema + +### Sample Aggregate + +```mermaid +erDiagram + samples { + uuid id PK + varchar(200) name + varchar(1000) description + int status_id FK + timestamp created_at + timestamp updated_at + } + + sample_statuses { + int id PK + varchar(50) name + } + + samples ||--o{ sample_statuses : has +``` + +## MediatR Pipeline + +``` +Request → LoggingBehavior → ValidatorBehavior → TransactionBehavior → Handler → Response + │ │ │ + ▼ ▼ ▼ + Log start/end Validate Begin/Commit + + timing with Transaction + FluentValidation +``` + +### Behavior Order + +1. **LoggingBehavior** - Logs request handling with timing +2. **ValidatorBehavior** - Validates request using FluentValidation +3. **TransactionBehavior** - Wraps command handlers in database transactions + +## Error Handling + +### Exception Hierarchy + +``` +Exception +└── DomainException + └── SampleDomainException +``` + +### Problem Details (RFC 7807) + +All errors are returned in Problem Details format: + +```json +{ + "type": "https://tools.ietf.org/html/rfc7807", + "title": "Validation Error", + "status": 400, + "detail": "One or more validation errors occurred.", + "errors": { + "Name": ["Name is required"] + } +} +``` + +## Health Checks + +```mermaid +graph TD + HC[Health Check Endpoint] + HC --> |/health/live| L[Liveness] + HC --> |/health/ready| R[Readiness] + HC --> |/health| F[Full Status] + + R --> PG[(PostgreSQL)] + R --> RD[(Redis)] + + style HC fill:#3498db,stroke:#2980b9,color:#fff + style L fill:#2ecc71,stroke:#27ae60,color:#fff + style R fill:#f39c12,stroke:#d68910,color:#fff +``` + +## Deployment Architecture + +### Docker Compose (Local) + +```yaml +services: + myservice-api: + build: . + ports: ["5000:8080"] + depends_on: + - postgres + - redis + + postgres: + image: postgres:16-alpine + + redis: + image: redis:7-alpine +``` + +### Kubernetes (Production) + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: myservice-api +spec: + replicas: 3 + template: + spec: + containers: + - name: api + image: myservice:latest + ports: + - containerPort: 8080 + livenessProbe: + httpGet: + path: /health/live + port: 8080 + readinessProbe: + httpGet: + path: /health/ready + port: 8080 +``` + +## Security Considerations + +1. **Authentication**: JWT Bearer token (configure in production) +2. **Authorization**: Role-based access control +3. **Input Validation**: FluentValidation on all requests +4. **SQL Injection**: EF Core parameterized queries +5. **Secrets**: Environment variables, never in code + +## Performance Optimization + +1. **Connection Pooling**: EF Core with Npgsql connection resilience +2. **Async/Await**: All I/O operations are async +3. **Response Caching**: Add caching headers for queries +4. **Database Indexes**: Configure in EntityConfigurations + +## References + +- [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers) +- [.NET Microservices Architecture Guide](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/) +- [Domain-Driven Design](https://martinfowler.com/bliki/DomainDrivenDesign.html) +- [CQRS Pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/cqrs) diff --git a/services/ads-manager-service-net/docs/en/README.md b/services/ads-manager-service-net/docs/en/README.md new file mode 100644 index 00000000..4cb53d44 --- /dev/null +++ b/services/ads-manager-service-net/docs/en/README.md @@ -0,0 +1,265 @@ +# .NET 10 Microservice Template + +> Enterprise-grade .NET 10 microservice template following DDD, CQRS, and Clean Architecture patterns. + +## Overview + +This template provides a production-ready structure for .NET microservices based on the eShopOnContainers reference architecture with: + +- **Domain-Driven Design (DDD)** - Aggregates, Entities, Value Objects, Domain Events +- **CQRS Pattern** - Separate Commands (write) and Queries (read) with MediatR +- **Clean Architecture** - Domain, Infrastructure, API layered separation +- **EF Core 10** - PostgreSQL with connection resilience +- **FluentValidation** - Request validation +- **API Versioning** - URL segment versioning +- **Health Checks** - Kubernetes-ready probes +- **Structured Logging** - Serilog with console and Seq + +## Prerequisites + +| Requirement | Version | +|-------------|---------| +| .NET SDK | 10.0.101+ | +| Docker | 24.0+ | +| PostgreSQL | 15+ (or use Docker) | + +```bash +# Check .NET version +dotnet --version +# Should output: 10.0.xxx +``` + +## Quick Start + +### 1. Create New Service + +```bash +# Copy template to new service +cp -r services/_template_dot_net services/your-service-name + +# Navigate to service directory +cd services/your-service-name + +# Rename all occurrences of "MyService" to "YourService" +find . -type f -name "*.cs" -exec sed -i '' 's/MyService/YourService/g' {} + +find . -type f -name "*.csproj" -exec sed -i '' 's/MyService/YourService/g' {} + +``` + +### 2. Configure Environment + +```bash +# Copy environment template +cp .env.example .env + +# Edit with your configuration +nano .env +``` + +### 3. Run with Docker + +```bash +# Start all services (API + PostgreSQL + Redis) +docker-compose up -d + +# View logs +docker-compose logs -f myservice-api +``` + +### 4. Run Locally + +```bash +# Restore dependencies +dotnet restore + +# Build all projects +dotnet build + +# Run the API +dotnet run --project src/MyService.API +``` + +## Project Structure + +``` +_template_dot_net/ +├── src/ +│ ├── MyService.API/ # Presentation Layer (Controllers, CQRS) +│ │ ├── Controllers/ # API endpoints +│ │ ├── Application/ # CQRS Implementation +│ │ │ ├── Commands/ # Write operations (MediatR) +│ │ │ ├── Queries/ # Read operations +│ │ │ ├── Behaviors/ # MediatR pipeline behaviors +│ │ │ └── Validations/ # FluentValidation validators +│ │ ├── Middleware/ # Custom middleware +│ │ └── Program.cs # Application entry point +│ │ +│ ├── MyService.Domain/ # Domain Layer (Pure business logic) +│ │ ├── AggregatesModel/ # Aggregate roots and entities +│ │ ├── Events/ # Domain events +│ │ ├── Exceptions/ # Domain exceptions +│ │ └── SeedWork/ # Base classes (Entity, ValueObject, etc.) +│ │ +│ └── MyService.Infrastructure/ # Infrastructure Layer (Data access) +│ ├── EntityConfigurations/ # EF Core Fluent API configurations +│ ├── Repositories/ # Repository implementations +│ ├── Idempotency/ # Request idempotency handling +│ └── MyServiceContext.cs # DbContext with Unit of Work +│ +├── tests/ +│ ├── MyService.UnitTests/ # Unit tests (Domain, Application) +│ └── MyService.FunctionalTests/ # Integration tests (API endpoints) +│ +├── Dockerfile # Multi-stage Docker build +├── docker-compose.yml # Local development setup +├── global.json # .NET SDK version pinning +└── Directory.Build.props # Common MSBuild properties +``` + +## API Endpoints + +| Method | Endpoint | Description | +|--------|----------|-------------| +| `GET` | `/api/v1/samples` | Get all samples | +| `GET` | `/api/v1/samples/{id}` | Get sample by ID | +| `POST` | `/api/v1/samples` | Create new sample | +| `PUT` | `/api/v1/samples/{id}` | Update sample | +| `DELETE` | `/api/v1/samples/{id}` | Delete sample | +| `PATCH` | `/api/v1/samples/{id}/status` | Change status | + +### Health Endpoints + +| Endpoint | Purpose | +|----------|---------| +| `/health` | Full health status | +| `/health/live` | Liveness probe | +| `/health/ready` | Readiness probe | + +## CQRS Pattern + +### Commands (Write Operations) + +```csharp +// Define command +public record CreateSampleCommand(string Name, string? Description) + : IRequest; + +// Handle command +public class CreateSampleCommandHandler : IRequestHandler +{ + public async Task Handle(CreateSampleCommand request, CancellationToken ct) + { + var sample = new Sample(request.Name, request.Description); + _repository.Add(sample); + await _repository.UnitOfWork.SaveEntitiesAsync(ct); + return new CreateSampleCommandResult(sample.Id); + } +} +``` + +### Queries (Read Operations) + +```csharp +// Define query +public record GetSampleQuery(Guid SampleId) : IRequest; +``` + +## Domain Model + +### Aggregate Root + +```csharp +public class Sample : Entity, IAggregateRoot +{ + public string Name => _name; + public SampleStatus Status => _status; + + public Sample(string name, string? description) { + // Business logic validation + if (string.IsNullOrWhiteSpace(name)) + throw new SampleDomainException("Sample name cannot be empty"); + + // Domain event + AddDomainEvent(new SampleCreatedDomainEvent(this)); + } + + public void Activate() { + if (_status != SampleStatus.Draft) + throw new SampleDomainException("Only draft samples can be activated"); + // State transition + } +} +``` + +## Testing + +```bash +# Run all tests +dotnet test + +# Run with coverage +dotnet test /p:CollectCoverage=true /p:CoverageReportFormat=cobertura + +# Run specific test project +dotnet test tests/MyService.UnitTests +``` + +## Configuration + +### Environment Variables + +| Variable | Description | Default | +|----------|-------------|---------| +| `ASPNETCORE_ENVIRONMENT` | Environment name | `Development` | +| `DATABASE_URL` | PostgreSQL connection string | - | +| `REDIS_URL` | Redis connection string | - | +| `JWT_SECRET` | JWT signing secret (min 32 chars) | - | + +### appsettings.json + +```json +{ + "ConnectionStrings": { + "DefaultConnection": "Host=localhost;Database=myservice;Username=postgres;Password=postgres" + }, + "Serilog": { + "MinimumLevel": "Information" + } +} +``` + +## Deployment + +### Docker Build + +```bash +# Build Docker image +docker build -t myservice:latest . + +# Run container +docker run -p 5000:8080 --env-file .env myservice:latest +``` + +### Kubernetes + +See [ARCHITECTURE.md](./ARCHITECTURE.md) for Kubernetes deployment manifests. + +## What's New in .NET 10 + +- **C# 14** language features +- Improved **Native AOT** support +- Better **async/await** performance +- Enhanced **JSON serialization** +- Performance improvements across the board +- 3-year **LTS** support (until November 2028) + +## Resources + +- [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers) - Reference architecture +- [.NET 10 Documentation](https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-10) +- [DDD with .NET](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/) +- [MediatR](https://github.com/jbogard/MediatR) - CQRS library +- [FluentValidation](https://docs.fluentvalidation.net/) - Validation library + +## License + +Proprietary - GoodGo Platform diff --git a/services/ads-manager-service-net/docs/vi/ARCHITECTURE.md b/services/ads-manager-service-net/docs/vi/ARCHITECTURE.md new file mode 100644 index 00000000..55a5d13b --- /dev/null +++ b/services/ads-manager-service-net/docs/vi/ARCHITECTURE.md @@ -0,0 +1,271 @@ +# Tài Liệu Kiến Trúc + +> Tài liệu kiến trúc chi tiết cho Template Microservice .NET 10. + +## Tổng Quan Kiến Trúc + +```mermaid +graph TB + subgraph "Lớp API" + C[Controllers] + CMD[Commands] + Q[Queries] + B[Behaviors] + V[Validations] + end + + subgraph "Lớp Domain" + AR[Aggregate Roots] + E[Entities] + VO[Value Objects] + DE[Domain Events] + DX[Domain Exceptions] + end + + subgraph "Lớp Infrastructure" + DB[(PostgreSQL)] + R[Repositories] + CTX[DbContext] + ID[Idempotency] + end + + C --> CMD + C --> Q + CMD --> B --> V + CMD --> AR + Q --> R + R --> CTX --> DB + AR --> DE + R --> AR + + style C fill:#4a90d9,stroke:#2d5986,color:#fff + style AR fill:#50c878,stroke:#2d8659,color:#fff + style DB fill:#ff6b6b,stroke:#c0392b,color:#fff +``` + +## Trách Nhiệm Các Lớp + +### 1. Lớp Domain (MyService.Domain) + +Trái tim của ứng dụng chứa business logic thuần túy. Lớp này: +- Có **ZERO** phụ thuộc bên ngoài (ngoại trừ MediatR.Contracts cho events) +- Chỉ chứa các class POCO +- Triển khai các tactical patterns của DDD + +#### Thành Phần + +| Thành phần | Mục Đích | +|------------|----------| +| **SeedWork** | Base classes: Entity, ValueObject, Enumeration, IAggregateRoot | +| **AggregatesModel** | Aggregate roots với entities và value objects | +| **Events** | Domain events cho giao tiếp cross-aggregate | +| **Exceptions** | Domain exceptions cho vi phạm business rules | + +### 2. Lớp Infrastructure (MyService.Infrastructure) + +Triển khai kỹ thuật và các mối quan tâm bên ngoài: +- Truy cập database (EF Core) +- Triển khai repositories +- Tích hợp external services + +### 3. Lớp API (MyService.API) + +Điểm vào ứng dụng và triển khai CQRS: +- Controllers để xử lý HTTP +- Commands cho các thao tác ghi +- Queries cho các thao tác đọc +- MediatR behaviors cho cross-cutting concerns + +## Luồng CQRS + +```mermaid +sequenceDiagram + participant Client + participant Controller + participant MediatR + participant LoggingBehavior + participant ValidatorBehavior + participant TransactionBehavior + participant CommandHandler + participant Repository + participant DbContext + + Client->>Controller: HTTP Request + Controller->>MediatR: Send(Command) + MediatR->>LoggingBehavior: Handle + LoggingBehavior->>ValidatorBehavior: Next() + ValidatorBehavior->>TransactionBehavior: Next() + TransactionBehavior->>CommandHandler: Next() + CommandHandler->>Repository: Add/Update/Delete + Repository->>DbContext: SaveEntitiesAsync() + DbContext-->>Repository: Success + Repository-->>CommandHandler: Result + CommandHandler-->>Controller: Response + Controller-->>Client: HTTP Response +``` + +## Domain Events + +```mermaid +graph LR + AR[Aggregate Root] -->|Phát sinh| DE[Domain Event] + DE -->|Dispatch bởi| CTX[DbContext] + CTX -->|Publish tới| M[MediatR] + M -->|Xử lý bởi| H1[Handler 1] + M -->|Xử lý bởi| H2[Handler 2] + + style AR fill:#50c878,stroke:#2d8659,color:#fff + style DE fill:#f39c12,stroke:#d68910,color:#fff + style M fill:#9b59b6,stroke:#7d3c98,color:#fff +``` + +## Schema Database + +### Sample Aggregate + +```mermaid +erDiagram + samples { + uuid id PK + varchar(200) name + varchar(1000) description + int status_id FK + timestamp created_at + timestamp updated_at + } + + sample_statuses { + int id PK + varchar(50) name + } + + samples ||--o{ sample_statuses : has +``` + +## Pipeline MediatR + +``` +Request → LoggingBehavior → ValidatorBehavior → TransactionBehavior → Handler → Response + │ │ │ + ▼ ▼ ▼ + Log start/end Validate Begin/Commit + + timing với Transaction + FluentValidation +``` + +### Thứ Tự Behaviors + +1. **LoggingBehavior** - Ghi log xử lý request với timing +2. **ValidatorBehavior** - Validate request sử dụng FluentValidation +3. **TransactionBehavior** - Bao bọc command handlers trong database transactions + +## Xử Lý Lỗi + +### Phân Cấp Exceptions + +``` +Exception +└── DomainException + └── SampleDomainException +``` + +### Problem Details (RFC 7807) + +Tất cả lỗi được trả về theo định dạng Problem Details: + +```json +{ + "type": "https://tools.ietf.org/html/rfc7807", + "title": "Lỗi Validation", + "status": 400, + "detail": "Một hoặc nhiều lỗi validation đã xảy ra.", + "errors": { + "Name": ["Tên là bắt buộc"] + } +} +``` + +## Health Checks + +```mermaid +graph TD + HC[Health Check Endpoint] + HC --> |/health/live| L[Liveness] + HC --> |/health/ready| R[Readiness] + HC --> |/health| F[Full Status] + + R --> PG[(PostgreSQL)] + R --> RD[(Redis)] + + style HC fill:#3498db,stroke:#2980b9,color:#fff + style L fill:#2ecc71,stroke:#27ae60,color:#fff + style R fill:#f39c12,stroke:#d68910,color:#fff +``` + +## Kiến Trúc Deployment + +### Docker Compose (Local) + +```yaml +services: + myservice-api: + build: . + ports: ["5000:8080"] + depends_on: + - postgres + - redis + + postgres: + image: postgres:16-alpine + + redis: + image: redis:7-alpine +``` + +### Kubernetes (Production) + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: myservice-api +spec: + replicas: 3 + template: + spec: + containers: + - name: api + image: myservice:latest + ports: + - containerPort: 8080 + livenessProbe: + httpGet: + path: /health/live + port: 8080 + readinessProbe: + httpGet: + path: /health/ready + port: 8080 +``` + +## Cân Nhắc Bảo Mật + +1. **Authentication**: JWT Bearer token (cấu hình trong production) +2. **Authorization**: Role-based access control +3. **Input Validation**: FluentValidation trên tất cả requests +4. **SQL Injection**: EF Core parameterized queries +5. **Secrets**: Biến môi trường, không bao giờ trong code + +## Tối Ưu Hiệu Năng + +1. **Connection Pooling**: EF Core với Npgsql connection resilience +2. **Async/Await**: Tất cả I/O operations đều async +3. **Response Caching**: Thêm caching headers cho queries +4. **Database Indexes**: Cấu hình trong EntityConfigurations + +## Tài Liệu Tham Khảo + +- [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers) +- [Hướng dẫn Kiến trúc .NET Microservices](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/) +- [Domain-Driven Design](https://martinfowler.com/bliki/DomainDrivenDesign.html) +- [CQRS Pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/cqrs) diff --git a/services/ads-manager-service-net/docs/vi/README.md b/services/ads-manager-service-net/docs/vi/README.md new file mode 100644 index 00000000..7d7e48b6 --- /dev/null +++ b/services/ads-manager-service-net/docs/vi/README.md @@ -0,0 +1,265 @@ +# Template Microservice .NET 10 + +> Template microservice .NET 10 cấp doanh nghiệp theo các pattern DDD, CQRS và Clean Architecture. + +## Tổng Quan + +Template này cung cấp cấu trúc sẵn sàng production cho microservices .NET dựa trên kiến trúc tham chiếu eShopOnContainers với: + +- **Domain-Driven Design (DDD)** - Aggregates, Entities, Value Objects, Domain Events +- **CQRS Pattern** - Tách biệt Commands (ghi) và Queries (đọc) với MediatR +- **Clean Architecture** - Phân tầng Domain, Infrastructure, API +- **EF Core 10** - PostgreSQL với connection resilience +- **FluentValidation** - Validation request +- **API Versioning** - Versioning theo URL segment +- **Health Checks** - Probes sẵn sàng cho Kubernetes +- **Structured Logging** - Serilog với console và Seq + +## Yêu Cầu + +| Yêu cầu | Phiên bản | +|---------|-----------| +| .NET SDK | 10.0.101+ | +| Docker | 24.0+ | +| PostgreSQL | 15+ (hoặc dùng Docker) | + +```bash +# Kiểm tra phiên bản .NET +dotnet --version +# Kết quả nên là: 10.0.xxx +``` + +## Bắt Đầu Nhanh + +### 1. Tạo Service Mới + +```bash +# Sao chép template sang service mới +cp -r services/_template_dot_net services/your-service-name + +# Di chuyển đến thư mục service +cd services/your-service-name + +# Đổi tên tất cả "MyService" thành "YourService" +find . -type f -name "*.cs" -exec sed -i '' 's/MyService/YourService/g' {} + +find . -type f -name "*.csproj" -exec sed -i '' 's/MyService/YourService/g' {} + +``` + +### 2. Cấu Hình Môi Trường + +```bash +# Sao chép template môi trường +cp .env.example .env + +# Chỉnh sửa với cấu hình của bạn +nano .env +``` + +### 3. Chạy với Docker + +```bash +# Khởi động tất cả services (API + PostgreSQL + Redis) +docker-compose up -d + +# Xem logs +docker-compose logs -f myservice-api +``` + +### 4. Chạy Local + +```bash +# Khôi phục dependencies +dotnet restore + +# Build tất cả projects +dotnet build + +# Chạy API +dotnet run --project src/MyService.API +``` + +## Cấu Trúc Dự Án + +``` +_template_dot_net/ +├── src/ +│ ├── MyService.API/ # Lớp Presentation (Controllers, CQRS) +│ │ ├── Controllers/ # Các API endpoints +│ │ ├── Application/ # Triển khai CQRS +│ │ │ ├── Commands/ # Thao tác ghi (MediatR) +│ │ │ ├── Queries/ # Thao tác đọc +│ │ │ ├── Behaviors/ # MediatR pipeline behaviors +│ │ │ └── Validations/ # FluentValidation validators +│ │ ├── Middleware/ # Custom middleware +│ │ └── Program.cs # Điểm vào ứng dụng +│ │ +│ ├── MyService.Domain/ # Lớp Domain (Business logic thuần túy) +│ │ ├── AggregatesModel/ # Aggregate roots và entities +│ │ ├── Events/ # Domain events +│ │ ├── Exceptions/ # Domain exceptions +│ │ └── SeedWork/ # Base classes (Entity, ValueObject, etc.) +│ │ +│ └── MyService.Infrastructure/ # Lớp Infrastructure (Truy cập dữ liệu) +│ ├── EntityConfigurations/ # Cấu hình EF Core Fluent API +│ ├── Repositories/ # Triển khai repositories +│ ├── Idempotency/ # Xử lý idempotency request +│ └── MyServiceContext.cs # DbContext với Unit of Work +│ +├── tests/ +│ ├── MyService.UnitTests/ # Unit tests (Domain, Application) +│ └── MyService.FunctionalTests/ # Integration tests (API endpoints) +│ +├── Dockerfile # Multi-stage Docker build +├── docker-compose.yml # Thiết lập phát triển local +├── global.json # Pin phiên bản .NET SDK +└── Directory.Build.props # Thuộc tính MSBuild chung +``` + +## Các Endpoint API + +| Method | Endpoint | Mô Tả | +|--------|----------|-------| +| `GET` | `/api/v1/samples` | Lấy tất cả samples | +| `GET` | `/api/v1/samples/{id}` | Lấy sample theo ID | +| `POST` | `/api/v1/samples` | Tạo sample mới | +| `PUT` | `/api/v1/samples/{id}` | Cập nhật sample | +| `DELETE` | `/api/v1/samples/{id}` | Xóa sample | +| `PATCH` | `/api/v1/samples/{id}/status` | Thay đổi trạng thái | + +### Health Endpoints + +| Endpoint | Mục Đích | +|----------|----------| +| `/health` | Trạng thái health đầy đủ | +| `/health/live` | Kiểm tra sống | +| `/health/ready` | Kiểm tra sẵn sàng | + +## Pattern CQRS + +### Commands (Thao Tác Ghi) + +```csharp +// Định nghĩa command +public record CreateSampleCommand(string Name, string? Description) + : IRequest; + +// Xử lý command +public class CreateSampleCommandHandler : IRequestHandler +{ + public async Task Handle(CreateSampleCommand request, CancellationToken ct) + { + var sample = new Sample(request.Name, request.Description); + _repository.Add(sample); + await _repository.UnitOfWork.SaveEntitiesAsync(ct); + return new CreateSampleCommandResult(sample.Id); + } +} +``` + +### Queries (Thao Tác Đọc) + +```csharp +// Định nghĩa query +public record GetSampleQuery(Guid SampleId) : IRequest; +``` + +## Domain Model + +### Aggregate Root + +```csharp +public class Sample : Entity, IAggregateRoot +{ + public string Name => _name; + public SampleStatus Status => _status; + + public Sample(string name, string? description) { + // Validation business logic + if (string.IsNullOrWhiteSpace(name)) + throw new SampleDomainException("Tên sample không được để trống"); + + // Domain event + AddDomainEvent(new SampleCreatedDomainEvent(this)); + } + + public void Activate() { + if (_status != SampleStatus.Draft) + throw new SampleDomainException("Chỉ sample draft mới có thể kích hoạt"); + // Chuyển đổi trạng thái + } +} +``` + +## Kiểm Thử + +```bash +# Chạy tất cả tests +dotnet test + +# Chạy với coverage +dotnet test /p:CollectCoverage=true /p:CoverageReportFormat=cobertura + +# Chạy project test cụ thể +dotnet test tests/MyService.UnitTests +``` + +## Cấu Hình + +### Biến Môi Trường + +| Biến | Mô Tả | Mặc định | +|------|-------|----------| +| `ASPNETCORE_ENVIRONMENT` | Tên môi trường | `Development` | +| `DATABASE_URL` | Connection string PostgreSQL | - | +| `REDIS_URL` | Connection string Redis | - | +| `JWT_SECRET` | Secret ký JWT (tối thiểu 32 ký tự) | - | + +### appsettings.json + +```json +{ + "ConnectionStrings": { + "DefaultConnection": "Host=localhost;Database=myservice;Username=postgres;Password=postgres" + }, + "Serilog": { + "MinimumLevel": "Information" + } +} +``` + +## Triển Khai + +### Docker Build + +```bash +# Build Docker image +docker build -t myservice:latest . + +# Chạy container +docker run -p 5000:8080 --env-file .env myservice:latest +``` + +### Kubernetes + +Xem [ARCHITECTURE.md](./ARCHITECTURE.md) để biết manifests triển khai Kubernetes. + +## Có Gì Mới Trong .NET 10 + +- Tính năng ngôn ngữ **C# 14** +- Hỗ trợ **Native AOT** được cải thiện +- Hiệu suất **async/await** tốt hơn +- **JSON serialization** được nâng cao +- Cải thiện hiệu suất toàn diện +- Hỗ trợ **LTS** 3 năm (đến tháng 11/2028) + +## Tài Nguyên + +- [eShopOnContainers](https://github.com/dotnet-architecture/eShopOnContainers) - Kiến trúc tham chiếu +- [Tài liệu .NET 10](https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-10) +- [DDD với .NET](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/) +- [MediatR](https://github.com/jbogard/MediatR) - Thư viện CQRS +- [FluentValidation](https://docs.fluentvalidation.net/) - Thư viện validation + +## Giấy Phép + +Độc quyền - GoodGo Platform diff --git a/services/ads-manager-service-net/global.json b/services/ads-manager-service-net/global.json new file mode 100644 index 00000000..f78eeaf4 --- /dev/null +++ b/services/ads-manager-service-net/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "10.0.101", + "rollForward": "latestMinor", + "allowPrerelease": false + } +} \ No newline at end of file diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Behaviors/LoggingBehavior.cs b/services/ads-manager-service-net/src/MyService.API/Application/Behaviors/LoggingBehavior.cs new file mode 100644 index 00000000..a724424d --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Behaviors/LoggingBehavior.cs @@ -0,0 +1,58 @@ +using System.Diagnostics; +using MediatR; + +namespace MyService.API.Application.Behaviors; + +/// +/// EN: MediatR behavior for logging request handling. +/// VI: MediatR behavior để logging việc xử lý request. +/// +/// EN: Request type / VI: Loại request +/// EN: Response type / VI: Loại response +public class LoggingBehavior : IPipelineBehavior + where TRequest : IRequest +{ + private readonly ILogger> _logger; + + public LoggingBehavior(ILogger> logger) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task Handle( + TRequest request, + RequestHandlerDelegate 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; + } + } +} diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Behaviors/TransactionBehavior.cs b/services/ads-manager-service-net/src/MyService.API/Application/Behaviors/TransactionBehavior.cs new file mode 100644 index 00000000..8675b649 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Behaviors/TransactionBehavior.cs @@ -0,0 +1,84 @@ +using MediatR; +using Microsoft.EntityFrameworkCore; +using MyService.Infrastructure; + +namespace MyService.API.Application.Behaviors; + +/// +/// EN: MediatR behavior for handling database transactions. +/// VI: MediatR behavior để xử lý database transactions. +/// +/// EN: Request type / VI: Loại request +/// EN: Response type / VI: Loại response +public class TransactionBehavior : IPipelineBehavior + where TRequest : IRequest +{ + private readonly MyServiceContext _dbContext; + private readonly ILogger> _logger; + + public TransactionBehavior( + MyServiceContext dbContext, + ILogger> logger) + { + _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task Handle( + TRequest request, + RequestHandlerDelegate 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; + } + }); + } +} diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Behaviors/ValidatorBehavior.cs b/services/ads-manager-service-net/src/MyService.API/Application/Behaviors/ValidatorBehavior.cs new file mode 100644 index 00000000..0062cd60 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Behaviors/ValidatorBehavior.cs @@ -0,0 +1,63 @@ +using FluentValidation; +using MediatR; + +namespace MyService.API.Application.Behaviors; + +/// +/// EN: MediatR behavior for FluentValidation integration. +/// VI: MediatR behavior để tích hợp FluentValidation. +/// +/// EN: Request type / VI: Loại request +/// EN: Response type / VI: Loại response +public class ValidatorBehavior : IPipelineBehavior + where TRequest : IRequest +{ + private readonly IEnumerable> _validators; + private readonly ILogger> _logger; + + public ValidatorBehavior( + IEnumerable> validators, + ILogger> logger) + { + _validators = validators ?? throw new ArgumentNullException(nameof(validators)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task Handle( + TRequest request, + RequestHandlerDelegate 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(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(); + } +} diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Commands/ChangeSampleStatusCommand.cs b/services/ads-manager-service-net/src/MyService.API/Application/Commands/ChangeSampleStatusCommand.cs new file mode 100644 index 00000000..49825490 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Commands/ChangeSampleStatusCommand.cs @@ -0,0 +1,14 @@ +using MediatR; + +namespace MyService.API.Application.Commands; + +/// +/// EN: Command to change status of a Sample. +/// VI: Command để thay đổi trạng thái của Sample. +/// +/// EN: Sample ID / VI: ID sample +/// EN: New status (activate, complete, cancel) / VI: Trạng thái mới (activate, complete, cancel) +public record ChangeSampleStatusCommand( + Guid SampleId, + string NewStatus +) : IRequest; diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Commands/ChangeSampleStatusCommandHandler.cs b/services/ads-manager-service-net/src/MyService.API/Application/Commands/ChangeSampleStatusCommandHandler.cs new file mode 100644 index 00000000..76e31030 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Commands/ChangeSampleStatusCommandHandler.cs @@ -0,0 +1,70 @@ +using MediatR; +using MyService.Domain.AggregatesModel.SampleAggregate; + +namespace MyService.API.Application.Commands; + +/// +/// EN: Handler for ChangeSampleStatusCommand. +/// VI: Handler cho ChangeSampleStatusCommand. +/// +public class ChangeSampleStatusCommandHandler : IRequestHandler +{ + private readonly ISampleRepository _sampleRepository; + private readonly ILogger _logger; + + public ChangeSampleStatusCommandHandler( + ISampleRepository sampleRepository, + ILogger logger) + { + _sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task 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; + } +} diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Commands/CreateSampleCommand.cs b/services/ads-manager-service-net/src/MyService.API/Application/Commands/CreateSampleCommand.cs new file mode 100644 index 00000000..138cc794 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Commands/CreateSampleCommand.cs @@ -0,0 +1,21 @@ +using MediatR; + +namespace MyService.API.Application.Commands; + +/// +/// EN: Command to create a new Sample. +/// VI: Command để tạo một Sample mới. +/// +/// EN: Sample name / VI: Tên sample +/// EN: Optional description / VI: Mô tả tùy chọn +public record CreateSampleCommand( + string Name, + string? Description +) : IRequest; + +/// +/// EN: Result of CreateSampleCommand. +/// VI: Kết quả của CreateSampleCommand. +/// +/// EN: Created sample ID / VI: ID sample đã tạo +public record CreateSampleCommandResult(Guid Id); diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Commands/CreateSampleCommandHandler.cs b/services/ads-manager-service-net/src/MyService.API/Application/Commands/CreateSampleCommandHandler.cs new file mode 100644 index 00000000..d7d0fd7c --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Commands/CreateSampleCommandHandler.cs @@ -0,0 +1,46 @@ +using MediatR; +using MyService.Domain.AggregatesModel.SampleAggregate; + +namespace MyService.API.Application.Commands; + +/// +/// EN: Handler for CreateSampleCommand. +/// VI: Handler cho CreateSampleCommand. +/// +public class CreateSampleCommandHandler : IRequestHandler +{ + private readonly ISampleRepository _sampleRepository; + private readonly ILogger _logger; + + public CreateSampleCommandHandler( + ISampleRepository sampleRepository, + ILogger logger) + { + _sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task 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); + } +} diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Commands/DeleteSampleCommand.cs b/services/ads-manager-service-net/src/MyService.API/Application/Commands/DeleteSampleCommand.cs new file mode 100644 index 00000000..0de392db --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Commands/DeleteSampleCommand.cs @@ -0,0 +1,10 @@ +using MediatR; + +namespace MyService.API.Application.Commands; + +/// +/// EN: Command to delete a Sample. +/// VI: Command để xóa một Sample. +/// +/// EN: Sample ID to delete / VI: ID sample cần xóa +public record DeleteSampleCommand(Guid SampleId) : IRequest; diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Commands/DeleteSampleCommandHandler.cs b/services/ads-manager-service-net/src/MyService.API/Application/Commands/DeleteSampleCommandHandler.cs new file mode 100644 index 00000000..c7632189 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Commands/DeleteSampleCommandHandler.cs @@ -0,0 +1,54 @@ +using MediatR; +using MyService.Domain.AggregatesModel.SampleAggregate; + +namespace MyService.API.Application.Commands; + +/// +/// EN: Handler for DeleteSampleCommand. +/// VI: Handler cho DeleteSampleCommand. +/// +public class DeleteSampleCommandHandler : IRequestHandler +{ + private readonly ISampleRepository _sampleRepository; + private readonly ILogger _logger; + + public DeleteSampleCommandHandler( + ISampleRepository sampleRepository, + ILogger logger) + { + _sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task 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; + } +} diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Commands/UpdateSampleCommand.cs b/services/ads-manager-service-net/src/MyService.API/Application/Commands/UpdateSampleCommand.cs new file mode 100644 index 00000000..6fad8514 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Commands/UpdateSampleCommand.cs @@ -0,0 +1,16 @@ +using MediatR; + +namespace MyService.API.Application.Commands; + +/// +/// EN: Command to update an existing Sample. +/// VI: Command để cập nhật một Sample đã tồn tại. +/// +/// EN: Sample ID to update / VI: ID sample cần cập nhật +/// EN: New name / VI: Tên mới +/// EN: New description / VI: Mô tả mới +public record UpdateSampleCommand( + Guid SampleId, + string Name, + string? Description +) : IRequest; diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Commands/UpdateSampleCommandHandler.cs b/services/ads-manager-service-net/src/MyService.API/Application/Commands/UpdateSampleCommandHandler.cs new file mode 100644 index 00000000..e904cf0a --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Commands/UpdateSampleCommandHandler.cs @@ -0,0 +1,54 @@ +using MediatR; +using MyService.Domain.AggregatesModel.SampleAggregate; + +namespace MyService.API.Application.Commands; + +/// +/// EN: Handler for UpdateSampleCommand. +/// VI: Handler cho UpdateSampleCommand. +/// +public class UpdateSampleCommandHandler : IRequestHandler +{ + private readonly ISampleRepository _sampleRepository; + private readonly ILogger _logger; + + public UpdateSampleCommandHandler( + ISampleRepository sampleRepository, + ILogger logger) + { + _sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public async Task 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; + } +} diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSampleQuery.cs b/services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSampleQuery.cs new file mode 100644 index 00000000..8b90789c --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSampleQuery.cs @@ -0,0 +1,23 @@ +using MediatR; + +namespace MyService.API.Application.Queries; + +/// +/// EN: Query to get a Sample by ID. +/// VI: Query để lấy một Sample theo ID. +/// +/// EN: Sample ID / VI: ID sample +public record GetSampleQuery(Guid SampleId) : IRequest; + +/// +/// EN: Sample view model for API responses. +/// VI: Sample view model cho API responses. +/// +public record SampleViewModel( + Guid Id, + string Name, + string? Description, + string Status, + DateTime CreatedAt, + DateTime? UpdatedAt +); diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSampleQueryHandler.cs b/services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSampleQueryHandler.cs new file mode 100644 index 00000000..2da10b6d --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSampleQueryHandler.cs @@ -0,0 +1,39 @@ +using MediatR; +using MyService.Domain.AggregatesModel.SampleAggregate; + +namespace MyService.API.Application.Queries; + +/// +/// EN: Handler for GetSampleQuery. +/// VI: Handler cho GetSampleQuery. +/// +public class GetSampleQueryHandler : IRequestHandler +{ + private readonly ISampleRepository _sampleRepository; + + public GetSampleQueryHandler(ISampleRepository sampleRepository) + { + _sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository)); + } + + public async Task 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 + ); + } +} diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSamplesQuery.cs b/services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSamplesQuery.cs new file mode 100644 index 00000000..d6a98e34 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSamplesQuery.cs @@ -0,0 +1,9 @@ +using MediatR; + +namespace MyService.API.Application.Queries; + +/// +/// EN: Query to get all Samples. +/// VI: Query để lấy tất cả Samples. +/// +public record GetSamplesQuery : IRequest>; diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSamplesQueryHandler.cs b/services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSamplesQueryHandler.cs new file mode 100644 index 00000000..2185302d --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Queries/GetSamplesQueryHandler.cs @@ -0,0 +1,34 @@ +using MediatR; +using MyService.Domain.AggregatesModel.SampleAggregate; + +namespace MyService.API.Application.Queries; + +/// +/// EN: Handler for GetSamplesQuery. +/// VI: Handler cho GetSamplesQuery. +/// +public class GetSamplesQueryHandler : IRequestHandler> +{ + private readonly ISampleRepository _sampleRepository; + + public GetSamplesQueryHandler(ISampleRepository sampleRepository) + { + _sampleRepository = sampleRepository ?? throw new ArgumentNullException(nameof(sampleRepository)); + } + + public async Task> 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 + )); + } +} diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Validations/CreateSampleCommandValidator.cs b/services/ads-manager-service-net/src/MyService.API/Application/Validations/CreateSampleCommandValidator.cs new file mode 100644 index 00000000..2f339fb3 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Validations/CreateSampleCommandValidator.cs @@ -0,0 +1,25 @@ +using FluentValidation; +using MyService.API.Application.Commands; + +namespace MyService.API.Application.Validations; + +/// +/// EN: Validator for CreateSampleCommand. +/// VI: Validator cho CreateSampleCommand. +/// +public class CreateSampleCommandValidator : AbstractValidator +{ + 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); + } +} diff --git a/services/ads-manager-service-net/src/MyService.API/Application/Validations/UpdateSampleCommandValidator.cs b/services/ads-manager-service-net/src/MyService.API/Application/Validations/UpdateSampleCommandValidator.cs new file mode 100644 index 00000000..7030d5c8 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Application/Validations/UpdateSampleCommandValidator.cs @@ -0,0 +1,29 @@ +using FluentValidation; +using MyService.API.Application.Commands; + +namespace MyService.API.Application.Validations; + +/// +/// EN: Validator for UpdateSampleCommand. +/// VI: Validator cho UpdateSampleCommand. +/// +public class UpdateSampleCommandValidator : AbstractValidator +{ + 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); + } +} diff --git a/services/ads-manager-service-net/src/MyService.API/Controllers/SamplesController.cs b/services/ads-manager-service-net/src/MyService.API/Controllers/SamplesController.cs new file mode 100644 index 00000000..c87e0ffa --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Controllers/SamplesController.cs @@ -0,0 +1,200 @@ +using Asp.Versioning; +using MediatR; +using Microsoft.AspNetCore.Mvc; +using MyService.API.Application.Commands; +using MyService.API.Application.Queries; + +namespace MyService.API.Controllers; + +/// +/// EN: Controller for Sample CRUD operations using CQRS pattern. +/// VI: Controller cho các thao tác CRUD Sample sử dụng pattern CQRS. +/// +[ApiController] +[ApiVersion("1.0")] +[Route("api/v{version:apiVersion}/[controller]")] +[Produces("application/json")] +public class SamplesController : ControllerBase +{ + private readonly IMediator _mediator; + private readonly ILogger _logger; + + public SamplesController(IMediator mediator, ILogger logger) + { + _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// + /// EN: Get all samples. + /// VI: Lấy tất cả samples. + /// + /// EN: List of samples / VI: Danh sách samples + [HttpGet] + [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] + public async Task GetSamples() + { + var samples = await _mediator.Send(new GetSamplesQuery()); + return Ok(new { success = true, data = samples }); + } + + /// + /// EN: Get a sample by ID. + /// VI: Lấy một sample theo ID. + /// + /// EN: Sample ID / VI: ID sample + /// EN: Sample details / VI: Chi tiết sample + [HttpGet("{id:guid}")] + [ProducesResponseType(typeof(SampleViewModel), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task 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 }); + } + + /// + /// EN: Create a new sample. + /// VI: Tạo một sample mới. + /// + /// EN: Create request / VI: Request tạo + /// EN: Created sample ID / VI: ID sample đã tạo + [HttpPost] + [ProducesResponseType(typeof(CreateSampleCommandResult), StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task 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 }); + } + + /// + /// EN: Update an existing sample. + /// VI: Cập nhật một sample đã tồn tại. + /// + /// EN: Sample ID / VI: ID sample + /// EN: Update request / VI: Request cập nhật + /// EN: Success status / VI: Trạng thái thành công + [HttpPut("{id:guid}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task 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" }); + } + + /// + /// EN: Delete a sample. + /// VI: Xóa một sample. + /// + /// EN: Sample ID / VI: ID sample + /// EN: Success status / VI: Trạng thái thành công + [HttpDelete("{id:guid}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task 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(); + } + + /// + /// EN: Change sample status. + /// VI: Thay đổi trạng thái sample. + /// + /// EN: Sample ID / VI: ID sample + /// EN: Status change request / VI: Request thay đổi trạng thái + /// EN: Success status / VI: Trạng thái thành công + [HttpPatch("{id:guid}/status")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task 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" }); + } +} + +/// +/// EN: Request model for creating a sample. +/// VI: Model request để tạo sample. +/// +public record CreateSampleRequest(string Name, string? Description); + +/// +/// EN: Request model for updating a sample. +/// VI: Model request để cập nhật sample. +/// +public record UpdateSampleRequest(string Name, string? Description); + +/// +/// EN: Request model for changing sample status. +/// VI: Model request để thay đổi trạng thái sample. +/// +public record ChangeStatusRequest(string Status); diff --git a/services/ads-manager-service-net/src/MyService.API/MyService.API.csproj b/services/ads-manager-service-net/src/MyService.API/MyService.API.csproj new file mode 100644 index 00000000..1b5bb222 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/MyService.API.csproj @@ -0,0 +1,43 @@ + + + + MyService.API + MyService.API + Web API layer with CQRS pattern + myservice-api + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/ads-manager-service-net/src/MyService.API/Program.cs b/services/ads-manager-service-net/src/MyService.API/Program.cs new file mode 100644 index 00000000..bd9b3df4 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Program.cs @@ -0,0 +1,144 @@ +using Asp.Versioning; +using FluentValidation; +using Hellang.Middleware.ProblemDetails; +using MyService.API.Application.Behaviors; +using MyService.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 MyService API / Khởi động MyService 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(); + cfg.AddOpenBehavior(typeof(LoggingBehavior<,>)); + cfg.AddOpenBehavior(typeof(ValidatorBehavior<,>)); + cfg.AddOpenBehavior(typeof(TransactionBehavior<,>)); + }); + + // EN: Add FluentValidation / VI: Thêm FluentValidation + builder.Services.AddValidatorsFromAssemblyContaining(); + + // 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 = "MyService API", + Version = "v1", + Description = "MyService microservice API / API microservice MyService" + }); + }); + + // 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", "MyService 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 { } diff --git a/services/ads-manager-service-net/src/MyService.API/Properties/launchSettings.json b/services/ads-manager-service-net/src/MyService.API/Properties/launchSettings.json new file mode 100644 index 00000000..6355d40b --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/Properties/launchSettings.json @@ -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" + } + } + } +} \ No newline at end of file diff --git a/services/ads-manager-service-net/src/MyService.API/appsettings.Development.json b/services/ads-manager-service-net/src/MyService.API/appsettings.Development.json new file mode 100644 index 00000000..e407ac85 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/appsettings.Development.json @@ -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" + } + } + } +} \ No newline at end of file diff --git a/services/ads-manager-service-net/src/MyService.API/appsettings.json b/services/ads-manager-service-net/src/MyService.API/appsettings.json new file mode 100644 index 00000000..523dc0fc --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.API/appsettings.json @@ -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": "*" +} \ No newline at end of file diff --git a/services/ads-manager-service-net/src/MyService.Domain/AggregatesModel/SampleAggregate/ISampleRepository.cs b/services/ads-manager-service-net/src/MyService.Domain/AggregatesModel/SampleAggregate/ISampleRepository.cs new file mode 100644 index 00000000..40bc8c3a --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Domain/AggregatesModel/SampleAggregate/ISampleRepository.cs @@ -0,0 +1,61 @@ +using MyService.Domain.SeedWork; + +namespace MyService.Domain.AggregatesModel.SampleAggregate; + +/// +/// EN: Repository interface for Sample aggregate. +/// VI: Interface repository cho Sample aggregate. +/// +/// +/// 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. +/// +public interface ISampleRepository : IRepository +{ + /// + /// EN: Get a sample by its ID. + /// VI: Lấy một sample theo ID. + /// + /// EN: The sample ID / VI: ID của sample + /// EN: The sample or null if not found / VI: Sample hoặc null nếu không tìm thấy + Task GetAsync(Guid sampleId); + + /// + /// EN: Get all samples. + /// VI: Lấy tất cả samples. + /// + /// EN: List of samples / VI: Danh sách samples + Task> GetAllAsync(); + + /// + /// EN: Add a new sample. + /// VI: Thêm một sample mới. + /// + /// EN: The sample to add / VI: Sample cần thêm + /// EN: The added sample / VI: Sample đã thêm + Sample Add(Sample sample); + + /// + /// EN: Update an existing sample. + /// VI: Cập nhật một sample đã tồn tại. + /// + /// EN: The sample to update / VI: Sample cần cập nhật + void Update(Sample sample); + + /// + /// EN: Delete a sample. + /// VI: Xóa một sample. + /// + /// EN: The sample to delete / VI: Sample cần xóa + void Delete(Sample sample); + + /// + /// EN: Get samples by status. + /// VI: Lấy samples theo trạng thái. + /// + /// EN: The status ID / VI: ID trạng thái + /// EN: List of samples with given status / VI: Danh sách samples với trạng thái cho trước + Task> GetByStatusAsync(int statusId); +} diff --git a/services/ads-manager-service-net/src/MyService.Domain/AggregatesModel/SampleAggregate/Sample.cs b/services/ads-manager-service-net/src/MyService.Domain/AggregatesModel/SampleAggregate/Sample.cs new file mode 100644 index 00000000..641bb385 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Domain/AggregatesModel/SampleAggregate/Sample.cs @@ -0,0 +1,158 @@ +using MyService.Domain.Events; +using MyService.Domain.Exceptions; +using MyService.Domain.SeedWork; + +namespace MyService.Domain.AggregatesModel.SampleAggregate; + +/// +/// EN: Sample aggregate root demonstrating DDD patterns. +/// VI: Sample aggregate root minh họa các pattern DDD. +/// +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; + + /// + /// EN: Sample name (required). + /// VI: Tên sample (bắt buộc). + /// + public string Name => _name; + + /// + /// EN: Optional description. + /// VI: Mô tả tùy chọn. + /// + public string? Description => _description; + + /// + /// EN: Current status. + /// VI: Trạng thái hiện tại. + /// + public SampleStatus Status => _status; + + /// + /// EN: Status ID for EF Core mapping. + /// VI: ID trạng thái cho EF Core mapping. + /// + public int StatusId { get; private set; } + + /// + /// EN: Creation timestamp. + /// VI: Thời gian tạo. + /// + public DateTime CreatedAt => _createdAt; + + /// + /// EN: Last update timestamp. + /// VI: Thời gian cập nhật cuối. + /// + public DateTime? UpdatedAt => _updatedAt; + + /// + /// EN: Private constructor for EF Core. + /// VI: Constructor private cho EF Core. + /// + protected Sample() + { + } + + /// + /// 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. + /// + /// EN: Sample name / VI: Tên sample + /// EN: Optional description / VI: Mô tả tùy chọn + 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)); + } + + /// + /// EN: Update sample information. + /// VI: Cập nhật thông tin sample. + /// + 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; + } + + /// + /// EN: Activate the sample. + /// VI: Kích hoạt sample. + /// + 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)); + } + + /// + /// EN: Complete the sample. + /// VI: Hoàn thành sample. + /// + 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)); + } + + /// + /// EN: Cancel the sample. + /// VI: Hủy sample. + /// + 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)); + } +} diff --git a/services/ads-manager-service-net/src/MyService.Domain/AggregatesModel/SampleAggregate/SampleStatus.cs b/services/ads-manager-service-net/src/MyService.Domain/AggregatesModel/SampleAggregate/SampleStatus.cs new file mode 100644 index 00000000..54ce63ba --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Domain/AggregatesModel/SampleAggregate/SampleStatus.cs @@ -0,0 +1,77 @@ +using MyService.Domain.SeedWork; + +namespace MyService.Domain.AggregatesModel.SampleAggregate; + +/// +/// EN: Sample status enumeration following type-safe enum pattern. +/// VI: Enumeration trạng thái Sample theo pattern enum an toàn kiểu. +/// +public class SampleStatus : Enumeration +{ + /// + /// EN: Draft status - initial state + /// VI: Trạng thái nháp - trạng thái ban đầu + /// + public static SampleStatus Draft = new(1, nameof(Draft)); + + /// + /// EN: Active status - ready for use + /// VI: Trạng thái hoạt động - sẵn sàng sử dụng + /// + public static SampleStatus Active = new(2, nameof(Active)); + + /// + /// EN: Completed status - finished processing + /// VI: Trạng thái hoàn thành - đã xử lý xong + /// + public static SampleStatus Completed = new(3, nameof(Completed)); + + /// + /// EN: Cancelled status - cancelled by user + /// VI: Trạng thái đã hủy - bị hủy bởi người dùng + /// + public static SampleStatus Cancelled = new(4, nameof(Cancelled)); + + public SampleStatus(int id, string name) : base(id, name) + { + } + + /// + /// EN: Get all available statuses. + /// VI: Lấy tất cả các trạng thái có sẵn. + /// + public static IEnumerable List() => GetAll(); + + /// + /// EN: Parse status from name. + /// VI: Parse trạng thái từ tên. + /// + 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; + } + + /// + /// EN: Parse status from ID. + /// VI: Parse trạng thái từ ID. + /// + 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; + } +} diff --git a/services/ads-manager-service-net/src/MyService.Domain/Events/SampleCreatedDomainEvent.cs b/services/ads-manager-service-net/src/MyService.Domain/Events/SampleCreatedDomainEvent.cs new file mode 100644 index 00000000..7e838214 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Domain/Events/SampleCreatedDomainEvent.cs @@ -0,0 +1,22 @@ +using MediatR; +using MyService.Domain.AggregatesModel.SampleAggregate; + +namespace MyService.Domain.Events; + +/// +/// 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. +/// +public class SampleCreatedDomainEvent : INotification +{ + /// + /// EN: The newly created sample. + /// VI: Sample mới được tạo. + /// + public Sample Sample { get; } + + public SampleCreatedDomainEvent(Sample sample) + { + Sample = sample; + } +} diff --git a/services/ads-manager-service-net/src/MyService.Domain/Events/SampleStatusChangedDomainEvent.cs b/services/ads-manager-service-net/src/MyService.Domain/Events/SampleStatusChangedDomainEvent.cs new file mode 100644 index 00000000..f6d9b422 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Domain/Events/SampleStatusChangedDomainEvent.cs @@ -0,0 +1,39 @@ +using MediatR; +using MyService.Domain.AggregatesModel.SampleAggregate; + +namespace MyService.Domain.Events; + +/// +/// EN: Domain event raised when Sample status changes. +/// VI: Domain event được phát ra khi trạng thái Sample thay đổi. +/// +public class SampleStatusChangedDomainEvent : INotification +{ + /// + /// EN: The sample ID. + /// VI: ID của sample. + /// + public Guid SampleId { get; } + + /// + /// EN: Previous status before the change. + /// VI: Trạng thái trước khi thay đổi. + /// + public SampleStatus PreviousStatus { get; } + + /// + /// EN: New status after the change. + /// VI: Trạng thái mới sau khi thay đổi. + /// + public SampleStatus NewStatus { get; } + + public SampleStatusChangedDomainEvent( + Guid sampleId, + SampleStatus previousStatus, + SampleStatus newStatus) + { + SampleId = sampleId; + PreviousStatus = previousStatus; + NewStatus = newStatus; + } +} diff --git a/services/ads-manager-service-net/src/MyService.Domain/Exceptions/DomainException.cs b/services/ads-manager-service-net/src/MyService.Domain/Exceptions/DomainException.cs new file mode 100644 index 00000000..7e737f64 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Domain/Exceptions/DomainException.cs @@ -0,0 +1,21 @@ +namespace MyService.Domain.Exceptions; + +/// +/// EN: Base exception for domain errors. +/// VI: Exception cơ sở cho các lỗi domain. +/// +public class DomainException : Exception +{ + public DomainException() + { + } + + public DomainException(string message) : base(message) + { + } + + public DomainException(string message, Exception innerException) + : base(message, innerException) + { + } +} diff --git a/services/ads-manager-service-net/src/MyService.Domain/Exceptions/SampleDomainException.cs b/services/ads-manager-service-net/src/MyService.Domain/Exceptions/SampleDomainException.cs new file mode 100644 index 00000000..c850944c --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Domain/Exceptions/SampleDomainException.cs @@ -0,0 +1,21 @@ +namespace MyService.Domain.Exceptions; + +/// +/// EN: Exception for Sample aggregate domain errors. +/// VI: Exception cho các lỗi domain của Sample aggregate. +/// +public class SampleDomainException : DomainException +{ + public SampleDomainException() + { + } + + public SampleDomainException(string message) : base(message) + { + } + + public SampleDomainException(string message, Exception innerException) + : base(message, innerException) + { + } +} diff --git a/services/ads-manager-service-net/src/MyService.Domain/MyService.Domain.csproj b/services/ads-manager-service-net/src/MyService.Domain/MyService.Domain.csproj new file mode 100644 index 00000000..3208317a --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Domain/MyService.Domain.csproj @@ -0,0 +1,14 @@ + + + + MyService.Domain + MyService.Domain + Domain layer containing core business logic and entities + + + + + + + + diff --git a/services/ads-manager-service-net/src/MyService.Domain/SeedWork/Entity.cs b/services/ads-manager-service-net/src/MyService.Domain/SeedWork/Entity.cs new file mode 100644 index 00000000..b07fdd3b --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Domain/SeedWork/Entity.cs @@ -0,0 +1,102 @@ +using MediatR; + +namespace MyService.Domain.SeedWork; + +/// +/// EN: Base class for all domain entities. +/// VI: Lớp cơ sở cho tất cả các entity trong domain. +/// +public abstract class Entity +{ + private int? _requestedHashCode; + private Guid _id; + private List _domainEvents = new(); + + /// + /// EN: Unique identifier for the entity. + /// VI: Định danh duy nhất cho entity. + /// + public virtual Guid Id + { + get => _id; + protected set => _id = value; + } + + /// + /// EN: Domain events raised by this entity. + /// VI: Các domain event được phát ra bởi entity này. + /// + public IReadOnlyCollection DomainEvents => _domainEvents.AsReadOnly(); + + /// + /// EN: Add a domain event to be dispatched. + /// VI: Thêm một domain event để dispatch. + /// + public void AddDomainEvent(INotification eventItem) + { + _domainEvents.Add(eventItem); + } + + /// + /// EN: Remove a domain event. + /// VI: Xóa một domain event. + /// + public void RemoveDomainEvent(INotification eventItem) + { + _domainEvents.Remove(eventItem); + } + + /// + /// EN: Clear all domain events. + /// VI: Xóa tất cả domain events. + /// + public void ClearDomainEvents() + { + _domainEvents.Clear(); + } + + /// + /// 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. + /// + 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); + } +} diff --git a/services/ads-manager-service-net/src/MyService.Domain/SeedWork/Enumeration.cs b/services/ads-manager-service-net/src/MyService.Domain/SeedWork/Enumeration.cs new file mode 100644 index 00000000..6641979c --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Domain/SeedWork/Enumeration.cs @@ -0,0 +1,95 @@ +using System.Reflection; + +namespace MyService.Domain.SeedWork; + +/// +/// 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). +/// +/// +/// 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ú. +/// +public abstract class Enumeration : IComparable +{ + /// + /// EN: The name of the enumeration value. + /// VI: Tên của giá trị enumeration. + /// + public string Name { get; private set; } + + /// + /// EN: The unique identifier of the enumeration value. + /// VI: Định danh duy nhất của giá trị enumeration. + /// + public int Id { get; private set; } + + protected Enumeration(int id, string name) => (Id, Name) = (id, name); + + public override string ToString() => Name; + + /// + /// 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. + /// + public static IEnumerable GetAll() where T : Enumeration => + typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) + .Select(f => f.GetValue(null)) + .Cast(); + + 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(); + + /// + /// 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. + /// + public static int AbsoluteDifference(Enumeration firstValue, Enumeration secondValue) + { + return Math.Abs(firstValue.Id - secondValue.Id); + } + + /// + /// EN: Parse an integer ID to the corresponding enumeration value. + /// VI: Parse một ID integer thành giá trị enumeration tương ứng. + /// + public static T FromValue(int value) where T : Enumeration + { + var matchingItem = Parse(value, "value", item => item.Id == value); + return matchingItem; + } + + /// + /// 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. + /// + public static T FromDisplayName(string displayName) where T : Enumeration + { + var matchingItem = Parse(displayName, "display name", item => item.Name == displayName); + return matchingItem; + } + + private static T Parse(TValue value, string description, Func predicate) where T : Enumeration + { + var matchingItem = GetAll().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); +} diff --git a/services/ads-manager-service-net/src/MyService.Domain/SeedWork/IAggregateRoot.cs b/services/ads-manager-service-net/src/MyService.Domain/SeedWork/IAggregateRoot.cs new file mode 100644 index 00000000..d361394f --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Domain/SeedWork/IAggregateRoot.cs @@ -0,0 +1,15 @@ +namespace MyService.Domain.SeedWork; + +/// +/// EN: Marker interface for aggregate roots. +/// VI: Interface đánh dấu cho aggregate roots. +/// +/// +/// 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. +/// +public interface IAggregateRoot +{ +} diff --git a/services/ads-manager-service-net/src/MyService.Domain/SeedWork/IRepository.cs b/services/ads-manager-service-net/src/MyService.Domain/SeedWork/IRepository.cs new file mode 100644 index 00000000..2d539e44 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Domain/SeedWork/IRepository.cs @@ -0,0 +1,15 @@ +namespace MyService.Domain.SeedWork; + +/// +/// EN: Generic repository interface for aggregate roots. +/// VI: Interface repository generic cho aggregate roots. +/// +/// EN: The aggregate root type / VI: Kiểu aggregate root +public interface IRepository where T : IAggregateRoot +{ + /// + /// EN: The unit of work for this repository. + /// VI: Unit of work cho repository này. + /// + IUnitOfWork UnitOfWork { get; } +} diff --git a/services/ads-manager-service-net/src/MyService.Domain/SeedWork/IUnitOfWork.cs b/services/ads-manager-service-net/src/MyService.Domain/SeedWork/IUnitOfWork.cs new file mode 100644 index 00000000..d37d8fa4 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Domain/SeedWork/IUnitOfWork.cs @@ -0,0 +1,30 @@ +namespace MyService.Domain.SeedWork; + +/// +/// EN: Unit of Work pattern interface. +/// VI: Interface cho Unit of Work pattern. +/// +/// +/// 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. +/// +public interface IUnitOfWork : IDisposable +{ + /// + /// 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. + /// + /// EN: Cancellation token / VI: Token hủy + /// EN: Number of entities written / VI: Số entity đã ghi + Task SaveChangesAsync(CancellationToken cancellationToken = default); + + /// + /// EN: Save all changes and dispatch domain events. + /// VI: Lưu tất cả thay đổi và dispatch domain events. + /// + /// EN: Cancellation token / VI: Token hủy + /// EN: True if successful / VI: True nếu thành công + Task SaveEntitiesAsync(CancellationToken cancellationToken = default); +} diff --git a/services/ads-manager-service-net/src/MyService.Domain/SeedWork/ValueObject.cs b/services/ads-manager-service-net/src/MyService.Domain/SeedWork/ValueObject.cs new file mode 100644 index 00000000..5cf4188f --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Domain/SeedWork/ValueObject.cs @@ -0,0 +1,53 @@ +namespace MyService.Domain.SeedWork; + +/// +/// EN: Base class for Value Objects following DDD patterns. +/// VI: Lớp cơ sở cho Value Objects theo mẫu DDD. +/// +/// +/// 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. +/// +public abstract class ValueObject +{ + /// + /// 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. + /// + protected abstract IEnumerable 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); + } + + /// + /// 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. + /// + protected ValueObject GetCopy() + { + return (ValueObject)MemberwiseClone(); + } +} diff --git a/services/ads-manager-service-net/src/MyService.Infrastructure/DependencyInjection.cs b/services/ads-manager-service-net/src/MyService.Infrastructure/DependencyInjection.cs new file mode 100644 index 00000000..a8dfba0d --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Infrastructure/DependencyInjection.cs @@ -0,0 +1,57 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using MyService.Domain.AggregatesModel.SampleAggregate; +using MyService.Infrastructure.Idempotency; +using MyService.Infrastructure.Repositories; + +namespace MyService.Infrastructure; + +/// +/// EN: Dependency injection extensions for Infrastructure layer. +/// VI: Extensions dependency injection cho lớp Infrastructure. +/// +public static class DependencyInjection +{ + /// + /// EN: Add infrastructure services to the DI container. + /// VI: Thêm các services infrastructure vào DI container. + /// + public static IServiceCollection AddInfrastructure( + this IServiceCollection services, + IConfiguration configuration) + { + // EN: Add DbContext with PostgreSQL / VI: Thêm DbContext với PostgreSQL + services.AddDbContext(options => + { + var connectionString = configuration.GetConnectionString("DefaultConnection") + ?? configuration["DATABASE_URL"] + ?? throw new InvalidOperationException("Connection string not configured"); + + options.UseNpgsql(connectionString, npgsqlOptions => + { + npgsqlOptions.MigrationsAssembly(typeof(MyServiceContext).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(); + + // EN: Register idempotency services / VI: Đăng ký idempotency services + services.AddScoped(); + + return services; + } +} diff --git a/services/ads-manager-service-net/src/MyService.Infrastructure/EntityConfigurations/SampleEntityTypeConfiguration.cs b/services/ads-manager-service-net/src/MyService.Infrastructure/EntityConfigurations/SampleEntityTypeConfiguration.cs new file mode 100644 index 00000000..5c2fbd42 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Infrastructure/EntityConfigurations/SampleEntityTypeConfiguration.cs @@ -0,0 +1,61 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using MyService.Domain.AggregatesModel.SampleAggregate; + +namespace MyService.Infrastructure.EntityConfigurations; + +/// +/// EN: EF Core configuration for Sample entity. +/// VI: Cấu hình EF Core cho entity Sample. +/// +public class SampleEntityTypeConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder 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("_name") + .HasColumnName("name") + .HasMaxLength(200) + .IsRequired(); + + builder.Property("_description") + .HasColumnName("description") + .HasMaxLength(1000); + + builder.Property("_createdAt") + .HasColumnName("created_at") + .IsRequired(); + + builder.Property("_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"); + } +} diff --git a/services/ads-manager-service-net/src/MyService.Infrastructure/EntityConfigurations/SampleStatusEntityTypeConfiguration.cs b/services/ads-manager-service-net/src/MyService.Infrastructure/EntityConfigurations/SampleStatusEntityTypeConfiguration.cs new file mode 100644 index 00000000..8b683f56 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Infrastructure/EntityConfigurations/SampleStatusEntityTypeConfiguration.cs @@ -0,0 +1,39 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using MyService.Domain.AggregatesModel.SampleAggregate; + +namespace MyService.Infrastructure.EntityConfigurations; + +/// +/// EN: EF Core configuration for SampleStatus enumeration. +/// VI: Cấu hình EF Core cho enumeration SampleStatus. +/// +public class SampleStatusEntityTypeConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder 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 + ); + } +} diff --git a/services/ads-manager-service-net/src/MyService.Infrastructure/Idempotency/ClientRequest.cs b/services/ads-manager-service-net/src/MyService.Infrastructure/Idempotency/ClientRequest.cs new file mode 100644 index 00000000..f65e4a56 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Infrastructure/Idempotency/ClientRequest.cs @@ -0,0 +1,26 @@ +namespace MyService.Infrastructure.Idempotency; + +/// +/// EN: Entity for tracking client requests to ensure idempotency. +/// VI: Entity để theo dõi các requests từ client đảm bảo idempotency. +/// +public class ClientRequest +{ + /// + /// EN: Unique request identifier. + /// VI: Định danh request duy nhất. + /// + public Guid Id { get; set; } + + /// + /// EN: Name of the command/request type. + /// VI: Tên của loại command/request. + /// + public string Name { get; set; } = null!; + + /// + /// EN: Timestamp when the request was received. + /// VI: Thời điểm request được nhận. + /// + public DateTime Time { get; set; } +} diff --git a/services/ads-manager-service-net/src/MyService.Infrastructure/Idempotency/IRequestManager.cs b/services/ads-manager-service-net/src/MyService.Infrastructure/Idempotency/IRequestManager.cs new file mode 100644 index 00000000..92097399 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Infrastructure/Idempotency/IRequestManager.cs @@ -0,0 +1,24 @@ +namespace MyService.Infrastructure.Idempotency; + +/// +/// EN: Interface for managing client request idempotency. +/// VI: Interface để quản lý idempotency của client requests. +/// +public interface IRequestManager +{ + /// + /// 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. + /// + /// EN: Request ID / VI: ID của request + /// EN: True if exists / VI: True nếu tồn tại + Task ExistAsync(Guid id); + + /// + /// EN: Create a new request record for tracking. + /// VI: Tạo bản ghi request mới để theo dõi. + /// + /// EN: Command type / VI: Loại command + /// EN: Request ID / VI: ID của request + Task CreateRequestForCommandAsync(Guid id); +} diff --git a/services/ads-manager-service-net/src/MyService.Infrastructure/Idempotency/RequestManager.cs b/services/ads-manager-service-net/src/MyService.Infrastructure/Idempotency/RequestManager.cs new file mode 100644 index 00000000..41a5f318 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Infrastructure/Idempotency/RequestManager.cs @@ -0,0 +1,45 @@ +using Microsoft.EntityFrameworkCore; + +namespace MyService.Infrastructure.Idempotency; + +/// +/// EN: Implementation of request manager for idempotency. +/// VI: Triển khai request manager cho idempotency. +/// +public class RequestManager : IRequestManager +{ + private readonly MyServiceContext _context; + + public RequestManager(MyServiceContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + } + + /// + public async Task ExistAsync(Guid id) + { + var request = await _context + .FindAsync(id); + + return request != null; + } + + /// + public async Task CreateRequestForCommandAsync(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(); + } +} diff --git a/services/ads-manager-service-net/src/MyService.Infrastructure/MyService.Infrastructure.csproj b/services/ads-manager-service-net/src/MyService.Infrastructure/MyService.Infrastructure.csproj new file mode 100644 index 00000000..7c81b5e9 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Infrastructure/MyService.Infrastructure.csproj @@ -0,0 +1,36 @@ + + + + MyService.Infrastructure + MyService.Infrastructure + Infrastructure layer for data access and external services + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + + + + + diff --git a/services/ads-manager-service-net/src/MyService.Infrastructure/MyServiceContext.cs b/services/ads-manager-service-net/src/MyService.Infrastructure/MyServiceContext.cs new file mode 100644 index 00000000..4486367d --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Infrastructure/MyServiceContext.cs @@ -0,0 +1,160 @@ +using MediatR; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using MyService.Domain.AggregatesModel.SampleAggregate; +using MyService.Domain.SeedWork; +using MyService.Infrastructure.EntityConfigurations; + +namespace MyService.Infrastructure; + +/// +/// EN: EF Core DbContext for MyService. +/// VI: EF Core DbContext cho MyService. +/// +public class MyServiceContext : DbContext, IUnitOfWork +{ + private readonly IMediator _mediator; + private IDbContextTransaction? _currentTransaction; + + /// + /// EN: Samples table. + /// VI: Bảng Samples. + /// + public DbSet Samples => Set(); + + /// + /// EN: Read-only access to current transaction. + /// VI: Truy cập chỉ đọc đến transaction hiện tại. + /// + public IDbContextTransaction? CurrentTransaction => _currentTransaction; + + /// + /// EN: Check if there is an active transaction. + /// VI: Kiểm tra xem có transaction đang hoạt động không. + /// + public bool HasActiveTransaction => _currentTransaction != null; + + public MyServiceContext(DbContextOptions options) : base(options) + { + _mediator = null!; + } + + public MyServiceContext(DbContextOptions options, IMediator mediator) : base(options) + { + _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator)); + + System.Diagnostics.Debug.WriteLine("MyServiceContext::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()); + } + + /// + /// EN: Save entities and dispatch domain events. + /// VI: Lưu entities và dispatch domain events. + /// + public async Task 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; + } + + /// + /// 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. + /// + public async Task BeginTransactionAsync() + { + if (_currentTransaction != null) return null; + + _currentTransaction = await Database.BeginTransactionAsync(System.Data.IsolationLevel.ReadCommitted); + + return _currentTransaction; + } + + /// + /// EN: Commit the current transaction. + /// VI: Commit transaction hiện tại. + /// + 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; + } + } + } + + /// + /// EN: Rollback the current transaction. + /// VI: Rollback transaction hiện tại. + /// + public void RollbackTransaction() + { + try + { + _currentTransaction?.Rollback(); + } + finally + { + if (_currentTransaction != null) + { + _currentTransaction.Dispose(); + _currentTransaction = null; + } + } + } + + /// + /// EN: Dispatch all domain events from tracked entities. + /// VI: Dispatch tất cả domain events từ các entities đang được track. + /// + private async Task DispatchDomainEventsAsync() + { + var domainEntities = ChangeTracker + .Entries() + .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); + } + } +} diff --git a/services/ads-manager-service-net/src/MyService.Infrastructure/Repositories/SampleRepository.cs b/services/ads-manager-service-net/src/MyService.Infrastructure/Repositories/SampleRepository.cs new file mode 100644 index 00000000..f0a4b109 --- /dev/null +++ b/services/ads-manager-service-net/src/MyService.Infrastructure/Repositories/SampleRepository.cs @@ -0,0 +1,72 @@ +using Microsoft.EntityFrameworkCore; +using MyService.Domain.AggregatesModel.SampleAggregate; +using MyService.Domain.SeedWork; + +namespace MyService.Infrastructure.Repositories; + +/// +/// EN: Repository implementation for Sample aggregate. +/// VI: Triển khai repository cho Sample aggregate. +/// +public class SampleRepository : ISampleRepository +{ + private readonly MyServiceContext _context; + + /// + /// EN: Unit of work for transaction management. + /// VI: Unit of work cho quản lý transaction. + /// + public IUnitOfWork UnitOfWork => _context; + + public SampleRepository(MyServiceContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + } + + /// + public async Task GetAsync(Guid sampleId) + { + var sample = await _context.Samples + .Include(s => s.Status) + .FirstOrDefaultAsync(s => s.Id == sampleId); + + return sample; + } + + /// + public async Task> GetAllAsync() + { + return await _context.Samples + .Include(s => s.Status) + .OrderByDescending(s => s.CreatedAt) + .ToListAsync(); + } + + /// + public Sample Add(Sample sample) + { + return _context.Samples.Add(sample).Entity; + } + + /// + public void Update(Sample sample) + { + _context.Entry(sample).State = EntityState.Modified; + } + + /// + public void Delete(Sample sample) + { + _context.Samples.Remove(sample); + } + + /// + public async Task> GetByStatusAsync(int statusId) + { + return await _context.Samples + .Include(s => s.Status) + .Where(s => s.StatusId == statusId) + .OrderByDescending(s => s.CreatedAt) + .ToListAsync(); + } +} diff --git a/services/ads-manager-service-net/tests/MyService.FunctionalTests/Controllers/SamplesControllerTests.cs b/services/ads-manager-service-net/tests/MyService.FunctionalTests/Controllers/SamplesControllerTests.cs new file mode 100644 index 00000000..e6e99ac5 --- /dev/null +++ b/services/ads-manager-service-net/tests/MyService.FunctionalTests/Controllers/SamplesControllerTests.cs @@ -0,0 +1,80 @@ +using System.Net; +using System.Net.Http.Json; +using FluentAssertions; +using Microsoft.AspNetCore.Mvc.Testing; +using Xunit; + +namespace MyService.FunctionalTests.Controllers; + +/// +/// EN: Functional tests for Samples API endpoints. +/// VI: Functional tests cho các endpoints API Samples. +/// +public class SamplesControllerTests : IClassFixture +{ + 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>>(); + 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>(); + 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(bool Success, T? Data); + private record CreateSampleResult(Guid Id); +} diff --git a/services/ads-manager-service-net/tests/MyService.FunctionalTests/CustomWebApplicationFactory.cs b/services/ads-manager-service-net/tests/MyService.FunctionalTests/CustomWebApplicationFactory.cs new file mode 100644 index 00000000..d74d8338 --- /dev/null +++ b/services/ads-manager-service-net/tests/MyService.FunctionalTests/CustomWebApplicationFactory.cs @@ -0,0 +1,56 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using MyService.Infrastructure; + +namespace MyService.FunctionalTests; + +/// +/// EN: Custom WebApplicationFactory for functional tests. +/// VI: WebApplicationFactory tùy chỉnh cho functional tests. +/// +public class CustomWebApplicationFactory : WebApplicationFactory +{ + 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)); + + if (descriptor != null) + { + services.Remove(descriptor); + } + + // EN: Remove DbContext service + // VI: Xóa DbContext service + var dbContextDescriptor = services.SingleOrDefault( + d => d.ServiceType == typeof(MyServiceContext)); + + if (dbContextDescriptor != null) + { + services.Remove(dbContextDescriptor); + } + + // EN: Add in-memory database for testing + // VI: Thêm in-memory database để test + services.AddDbContext(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(); + db.Database.EnsureCreated(); + }); + } +} diff --git a/services/ads-manager-service-net/tests/MyService.FunctionalTests/MyService.FunctionalTests.csproj b/services/ads-manager-service-net/tests/MyService.FunctionalTests/MyService.FunctionalTests.csproj new file mode 100644 index 00000000..4cc894f8 --- /dev/null +++ b/services/ads-manager-service-net/tests/MyService.FunctionalTests/MyService.FunctionalTests.csproj @@ -0,0 +1,38 @@ + + + + MyService.FunctionalTests + MyService.FunctionalTests + false + true + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + diff --git a/services/ads-manager-service-net/tests/MyService.UnitTests/Application/CreateSampleCommandHandlerTests.cs b/services/ads-manager-service-net/tests/MyService.UnitTests/Application/CreateSampleCommandHandlerTests.cs new file mode 100644 index 00000000..75cdd0e8 --- /dev/null +++ b/services/ads-manager-service-net/tests/MyService.UnitTests/Application/CreateSampleCommandHandlerTests.cs @@ -0,0 +1,65 @@ +using FluentAssertions; +using Microsoft.Extensions.Logging; +using Moq; +using MyService.API.Application.Commands; +using MyService.Domain.AggregatesModel.SampleAggregate; +using MyService.Domain.SeedWork; +using Xunit; + +namespace MyService.UnitTests.Application; + +/// +/// EN: Unit tests for CreateSampleCommandHandler. +/// VI: Unit tests cho CreateSampleCommandHandler. +/// +public class CreateSampleCommandHandlerTests +{ + private readonly Mock _mockRepository; + private readonly Mock> _mockLogger; + private readonly CreateSampleCommandHandler _handler; + + public CreateSampleCommandHandlerTests() + { + _mockRepository = new Mock(); + _mockLogger = new Mock>(); + + var mockUnitOfWork = new Mock(); + mockUnitOfWork.Setup(u => u.SaveEntitiesAsync(It.IsAny())) + .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())) + .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()), 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()), Times.Once); + } +} diff --git a/services/ads-manager-service-net/tests/MyService.UnitTests/Domain/SampleAggregateTests.cs b/services/ads-manager-service-net/tests/MyService.UnitTests/Domain/SampleAggregateTests.cs new file mode 100644 index 00000000..dcf48767 --- /dev/null +++ b/services/ads-manager-service-net/tests/MyService.UnitTests/Domain/SampleAggregateTests.cs @@ -0,0 +1,151 @@ +using FluentAssertions; +using MyService.Domain.AggregatesModel.SampleAggregate; +using MyService.Domain.Exceptions; +using Xunit; + +namespace MyService.UnitTests.Domain; + +/// +/// EN: Unit tests for Sample aggregate. +/// VI: Unit tests cho Sample aggregate. +/// +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() + .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() + .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() + .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() + .WithMessage("Cannot update a cancelled sample"); + } +} diff --git a/services/ads-manager-service-net/tests/MyService.UnitTests/MyService.UnitTests.csproj b/services/ads-manager-service-net/tests/MyService.UnitTests/MyService.UnitTests.csproj new file mode 100644 index 00000000..b40272dc --- /dev/null +++ b/services/ads-manager-service-net/tests/MyService.UnitTests/MyService.UnitTests.csproj @@ -0,0 +1,35 @@ + + + + MyService.UnitTests + MyService.UnitTests + false + true + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + diff --git a/services/promotion-service-net/src/PromotionService.API/Application/Commands/AdminCommandHandlers.cs b/services/promotion-service-net/src/PromotionService.API/Application/Commands/AdminCommandHandlers.cs new file mode 100644 index 00000000..e92be7ca --- /dev/null +++ b/services/promotion-service-net/src/PromotionService.API/Application/Commands/AdminCommandHandlers.cs @@ -0,0 +1,159 @@ +using MediatR; +using Microsoft.Extensions.Logging; +using PromotionService.Domain.AggregatesModel.CampaignAggregate; +using PromotionService.Domain.Exceptions; + +namespace PromotionService.API.Application.Commands; + +/// +/// EN: Handler for UpdateCampaignCommand. +/// VI: Handler cho UpdateCampaignCommand. +/// +public class UpdateCampaignCommandHandler : IRequestHandler +{ + private readonly ICampaignRepository _campaignRepository; + private readonly ILogger _logger; + + public UpdateCampaignCommandHandler( + ICampaignRepository campaignRepository, + ILogger logger) + { + _campaignRepository = campaignRepository; + _logger = logger; + } + + public async Task Handle(UpdateCampaignCommand request, CancellationToken cancellationToken) + { + var campaign = await _campaignRepository.GetByIdAsync(request.CampaignId) + ?? throw new PromotionDomainException($"Campaign {request.CampaignId} not found"); + + campaign.Update(request.Name, request.Description, request.StartDate, request.EndDate, request.MaxPerUser); + _campaignRepository.Update(campaign); + await _campaignRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken); + + _logger.LogInformation("Campaign {CampaignId} updated", request.CampaignId); + return true; + } +} + +/// +/// EN: Handler for CompleteCampaignCommand. +/// VI: Handler cho CompleteCampaignCommand. +/// +public class CompleteCampaignCommandHandler : IRequestHandler +{ + private readonly ICampaignRepository _campaignRepository; + private readonly ILogger _logger; + + public CompleteCampaignCommandHandler( + ICampaignRepository campaignRepository, + ILogger logger) + { + _campaignRepository = campaignRepository; + _logger = logger; + } + + public async Task Handle(CompleteCampaignCommand request, CancellationToken cancellationToken) + { + var campaign = await _campaignRepository.GetByIdAsync(request.CampaignId) + ?? throw new PromotionDomainException($"Campaign {request.CampaignId} not found"); + + campaign.Complete(); + _campaignRepository.Update(campaign); + await _campaignRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken); + + _logger.LogInformation("Campaign {CampaignId} force completed", request.CampaignId); + return true; + } +} + +/// +/// EN: Handler for DeleteCampaignCommand (soft delete). +/// VI: Handler cho DeleteCampaignCommand (xóa mềm). +/// +public class DeleteCampaignCommandHandler : IRequestHandler +{ + private readonly ICampaignRepository _campaignRepository; + private readonly ILogger _logger; + + public DeleteCampaignCommandHandler( + ICampaignRepository campaignRepository, + ILogger logger) + { + _campaignRepository = campaignRepository; + _logger = logger; + } + + public async Task Handle(DeleteCampaignCommand request, CancellationToken cancellationToken) + { + var campaign = await _campaignRepository.GetByIdAsync(request.CampaignId) + ?? throw new PromotionDomainException($"Campaign {request.CampaignId} not found"); + + campaign.Cancel(); // Soft delete = Cancel + _campaignRepository.Update(campaign); + await _campaignRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken); + + _logger.LogInformation("Campaign {CampaignId} soft deleted (cancelled)", request.CampaignId); + return true; + } +} + +/// +/// EN: Handler for RevokeVoucherCommand. +/// VI: Handler cho RevokeVoucherCommand. +/// +public class RevokeVoucherCommandHandler : IRequestHandler +{ + private readonly ICampaignRepository _campaignRepository; + private readonly ILogger _logger; + + public RevokeVoucherCommandHandler( + ICampaignRepository campaignRepository, + ILogger logger) + { + _campaignRepository = campaignRepository; + _logger = logger; + } + + public async Task Handle(RevokeVoucherCommand request, CancellationToken cancellationToken) + { + var voucher = await _campaignRepository.GetVoucherByIdAsync(request.VoucherId) + ?? throw new PromotionDomainException($"Voucher {request.VoucherId} not found"); + + voucher.Expire(); // Revoke = Mark as expired + await _campaignRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken); + + _logger.LogInformation("Voucher {VoucherId} revoked. Reason: {Reason}", request.VoucherId, request.Reason); + return true; + } +} + +/// +/// EN: Handler for ExtendVoucherExpiryCommand. +/// VI: Handler cho ExtendVoucherExpiryCommand. +/// +public class ExtendVoucherExpiryCommandHandler : IRequestHandler +{ + private readonly ICampaignRepository _campaignRepository; + private readonly ILogger _logger; + + public ExtendVoucherExpiryCommandHandler( + ICampaignRepository campaignRepository, + ILogger logger) + { + _campaignRepository = campaignRepository; + _logger = logger; + } + + public async Task Handle(ExtendVoucherExpiryCommand request, CancellationToken cancellationToken) + { + var voucher = await _campaignRepository.GetVoucherByIdAsync(request.VoucherId) + ?? throw new PromotionDomainException($"Voucher {request.VoucherId} not found"); + + voucher.ExtendExpiry(request.AdditionalDays); + await _campaignRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken); + + _logger.LogInformation("Voucher {VoucherId} expiry extended by {Days} days", request.VoucherId, request.AdditionalDays); + return true; + } +} diff --git a/services/promotion-service-net/src/PromotionService.API/Application/Commands/AdminCommands.cs b/services/promotion-service-net/src/PromotionService.API/Application/Commands/AdminCommands.cs new file mode 100644 index 00000000..b6b981bf --- /dev/null +++ b/services/promotion-service-net/src/PromotionService.API/Application/Commands/AdminCommands.cs @@ -0,0 +1,43 @@ +using MediatR; + +namespace PromotionService.API.Application.Commands; + +/// +/// EN: Command to update a campaign. +/// VI: Command để cập nhật chiến dịch. +/// +public record UpdateCampaignCommand( + Guid CampaignId, + string? Name = null, + string? Description = null, + DateTime? StartDate = null, + DateTime? EndDate = null, + int? MaxPerUser = null) : IRequest; + +/// +/// EN: Command to force complete a campaign. +/// VI: Command để bắt buộc hoàn thành chiến dịch. +/// +public record CompleteCampaignCommand(Guid CampaignId) : IRequest; + +/// +/// EN: Command to soft delete a campaign. +/// VI: Command để xóa mềm chiến dịch. +/// +public record DeleteCampaignCommand(Guid CampaignId) : IRequest; + +/// +/// EN: Command to revoke a voucher. +/// VI: Command để thu hồi voucher. +/// +public record RevokeVoucherCommand( + Guid VoucherId, + string Reason) : IRequest; + +/// +/// EN: Command to extend voucher expiry. +/// VI: Command để gia hạn voucher. +/// +public record ExtendVoucherExpiryCommand( + Guid VoucherId, + int AdditionalDays) : IRequest; diff --git a/services/promotion-service-net/src/PromotionService.API/Application/DTOs/AdminDtos.cs b/services/promotion-service-net/src/PromotionService.API/Application/DTOs/AdminDtos.cs new file mode 100644 index 00000000..de4bc725 --- /dev/null +++ b/services/promotion-service-net/src/PromotionService.API/Application/DTOs/AdminDtos.cs @@ -0,0 +1,126 @@ +using PromotionService.API.Application.DTOs; + +namespace PromotionService.API.Application.DTOs; + +/// +/// EN: Paginated response wrapper. +/// VI: Wrapper cho response phân trang. +/// +public record PaginatedResponse( + IEnumerable Items, + int TotalCount, + int PageNumber, + int PageSize, + int TotalPages); + +/// +/// EN: Campaign statistics for admin view. +/// VI: Thống kê chiến dịch cho admin. +/// +public record AdminCampaignStatisticsDto( + Guid CampaignId, + string CampaignName, + string Status, + int TotalVouchers, + int IssuedVouchers, + int AvailableVouchers, + int ClaimedVouchers, + int RedeemedVouchers, + int ExpiredVouchers, + decimal TotalFaceValue, + decimal TotalRedeemedValue, + decimal TotalRefundedValue, + decimal UtilizationRate, + int TotalRedemptions, + DateTime? FirstClaimedAt, + DateTime? LastRedeemedAt); + +/// +/// EN: Admin campaign list item with stats. +/// VI: Item danh sách chiến dịch admin với thống kê. +/// +public record AdminCampaignListDto( + Guid Id, + Guid MerchantId, + string Name, + string BackingAssetType, + string BackingAssetCode, + decimal FaceValue, + string AcquisitionType, + string Status, + int TotalVouchers, + int IssuedVouchers, + DateTime StartDate, + DateTime EndDate, + DateTime CreatedAt); + +/// +/// EN: Admin voucher list item with details. +/// VI: Item danh sách voucher admin với chi tiết. +/// +public record AdminVoucherListDto( + Guid Id, + Guid CampaignId, + string CampaignName, + string Code, + Guid? OwnerId, + string? OwnerEmail, + decimal FaceValue, + decimal RemainingValue, + string Status, + DateTime? ClaimedAt, + DateTime? ExpiresAt, + DateTime? RedeemedAt, + DateTime CreatedAt); + +/// +/// EN: Admin redemption list item. +/// VI: Item danh sách redemption admin. +/// +public record AdminRedemptionListDto( + Guid Id, + Guid VoucherId, + string VoucherCode, + Guid CampaignId, + string CampaignName, + Guid UserId, + Guid? OrderId, + decimal AmountUsed, + decimal AmountRefunded, + DateTime RedeemedAt); + +/// +/// EN: Redemption statistics for admin. +/// VI: Thống kê redemption cho admin. +/// +public record AdminRedemptionStatisticsDto( + int TotalRedemptions, + decimal TotalAmountUsed, + decimal TotalAmountRefunded, + decimal AverageRedemptionAmount, + int RedemptionsToday, + int RedemptionsThisWeek, + int RedemptionsThisMonth); + +/// +/// EN: Campaign filter for admin queries. +/// VI: Filter chiến dịch cho admin queries. +/// +public record AdminCampaignFilter( + Guid? MerchantId = null, + string? Status = null, + DateTime? StartDateFrom = null, + DateTime? StartDateTo = null, + string? SearchTerm = null); + +/// +/// EN: Voucher filter for admin queries. +/// VI: Filter voucher cho admin queries. +/// +public record AdminVoucherFilter( + Guid? CampaignId = null, + Guid? UserId = null, + string? Status = null, + string? CodeSearch = null, + DateTime? ExpiresAfter = null, + DateTime? ExpiresBefore = null); diff --git a/services/promotion-service-net/src/PromotionService.API/Application/Queries/AdminQueries.cs b/services/promotion-service-net/src/PromotionService.API/Application/Queries/AdminQueries.cs new file mode 100644 index 00000000..fdf8a9e3 --- /dev/null +++ b/services/promotion-service-net/src/PromotionService.API/Application/Queries/AdminQueries.cs @@ -0,0 +1,68 @@ +using MediatR; +using PromotionService.API.Application.DTOs; + +namespace PromotionService.API.Application.Queries; + +/// +/// EN: Query to get all campaigns with pagination and filters. +/// VI: Query để lấy tất cả chiến dịch với phân trang và bộ lọc. +/// +public record GetAllCampaignsQuery( + int PageNumber = 1, + int PageSize = 20, + Guid? MerchantId = null, + string? Status = null, + string? SearchTerm = null) : IRequest>; + +/// +/// EN: Query to get campaign statistics for admin. +/// VI: Query để lấy thống kê chiến dịch cho admin. +/// +public record GetAdminCampaignStatisticsQuery(Guid CampaignId) : IRequest; + +/// +/// EN: Query to get vouchers for a campaign. +/// VI: Query để lấy vouchers của chiến dịch. +/// +public record GetCampaignVouchersQuery( + Guid CampaignId, + int PageNumber = 1, + int PageSize = 20, + string? Status = null) : IRequest>; + +/// +/// EN: Query to get all vouchers with filters. +/// VI: Query để lấy tất cả vouchers với bộ lọc. +/// +public record GetAllVouchersQuery( + int PageNumber = 1, + int PageSize = 20, + Guid? CampaignId = null, + Guid? UserId = null, + string? Status = null, + string? CodeSearch = null) : IRequest>; + +/// +/// EN: Query to search vouchers by code. +/// VI: Query để tìm kiếm vouchers theo mã. +/// +public record SearchVouchersQuery(string SearchTerm) : IRequest>; + +/// +/// EN: Query to get all redemptions with filters. +/// VI: Query để lấy tất cả redemptions với bộ lọc. +/// +public record GetAllRedemptionsQuery( + int PageNumber = 1, + int PageSize = 20, + Guid? CampaignId = null, + Guid? VoucherId = null, + Guid? UserId = null, + DateTime? DateFrom = null, + DateTime? DateTo = null) : IRequest>; + +/// +/// EN: Query to get redemption statistics. +/// VI: Query để lấy thống kê redemption. +/// +public record GetRedemptionStatisticsQuery(Guid? CampaignId = null) : IRequest; diff --git a/services/promotion-service-net/src/PromotionService.API/Application/Queries/AdminQueryHandlers.cs b/services/promotion-service-net/src/PromotionService.API/Application/Queries/AdminQueryHandlers.cs new file mode 100644 index 00000000..81225d52 --- /dev/null +++ b/services/promotion-service-net/src/PromotionService.API/Application/Queries/AdminQueryHandlers.cs @@ -0,0 +1,309 @@ +using MediatR; +using Microsoft.EntityFrameworkCore; +using PromotionService.API.Application.DTOs; +using PromotionService.Domain.AggregatesModel.CampaignAggregate; +using PromotionService.Domain.AggregatesModel.RedemptionAggregate; +using PromotionService.Infrastructure; + +namespace PromotionService.API.Application.Queries; + +/// +/// EN: Handler for GetAllCampaignsQuery. +/// VI: Handler cho GetAllCampaignsQuery. +/// +public class GetAllCampaignsQueryHandler : IRequestHandler> +{ + private readonly PromotionServiceContext _context; + + public GetAllCampaignsQueryHandler(PromotionServiceContext context) + { + _context = context; + } + + public async Task> Handle(GetAllCampaignsQuery request, CancellationToken cancellationToken) + { + var query = _context.Campaigns.AsQueryable(); + + if (request.MerchantId.HasValue) + query = query.Where(c => c.MerchantId == request.MerchantId.Value); + + if (!string.IsNullOrEmpty(request.Status)) + { + var statusId = request.Status.ToLower() switch + { + "draft" => 1, + "active" => 2, + "paused" => 3, + "completed" => 4, + "cancelled" => 5, + _ => 0 + }; + if (statusId > 0) + query = query.Where(c => c.StatusId == statusId); + } + + if (!string.IsNullOrEmpty(request.SearchTerm)) + query = query.Where(c => c.Name.Contains(request.SearchTerm)); + + var totalCount = await query.CountAsync(cancellationToken); + var totalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize); + + var items = await query + .OrderByDescending(c => c.CreatedAt) + .Skip((request.PageNumber - 1) * request.PageSize) + .Take(request.PageSize) + .Select(c => new AdminCampaignListDto( + c.Id, + c.MerchantId, + c.Name, + c.BackingAssetTypeId == 1 ? "Currency" : "Point", + c.BackingAssetCode, + c.FaceValue, + c.AcquisitionTypeId == 1 ? "Free" : c.AcquisitionTypeId == 2 ? "ExchangePoints" : "Purchase", + c.StatusId == 1 ? "Draft" : c.StatusId == 2 ? "Active" : c.StatusId == 3 ? "Paused" : c.StatusId == 4 ? "Completed" : "Cancelled", + c.TotalVouchers, + c.IssuedVouchers, + c.StartDate, + c.EndDate, + c.CreatedAt)) + .ToListAsync(cancellationToken); + + return new PaginatedResponse(items, totalCount, request.PageNumber, request.PageSize, totalPages); + } +} + +/// +/// EN: Handler for GetAdminCampaignStatisticsQuery. +/// VI: Handler cho GetAdminCampaignStatisticsQuery. +/// +public class GetAdminCampaignStatisticsQueryHandler : IRequestHandler +{ + private readonly PromotionServiceContext _context; + + public GetAdminCampaignStatisticsQueryHandler(PromotionServiceContext context) + { + _context = context; + } + + public async Task Handle(GetAdminCampaignStatisticsQuery request, CancellationToken cancellationToken) + { + var campaign = await _context.Campaigns + .Include(c => c.Vouchers) + .FirstOrDefaultAsync(c => c.Id == request.CampaignId, cancellationToken); + + if (campaign == null) return null; + + var redemptions = await _context.Redemptions + .Where(r => r.CampaignId == request.CampaignId) + .ToListAsync(cancellationToken); + + var vouchers = campaign.Vouchers.ToList(); + var claimed = vouchers.Count(v => v.OwnerId.HasValue); + var redeemed = vouchers.Count(v => v.StatusId == VoucherStatus.FullyRedeemed.Id || v.StatusId == VoucherStatus.PartiallyRedeemed.Id); + var expired = vouchers.Count(v => v.StatusId == VoucherStatus.Expired.Id); + var totalRedeemed = redemptions.Sum(r => r.AmountUsed); + var totalRefunded = redemptions.Sum(r => r.AmountRefunded); + + return new AdminCampaignStatisticsDto( + campaign.Id, + campaign.Name, + campaign.StatusId == 1 ? "Draft" : campaign.StatusId == 2 ? "Active" : campaign.StatusId == 3 ? "Paused" : campaign.StatusId == 4 ? "Completed" : "Cancelled", + campaign.TotalVouchers, + campaign.IssuedVouchers, + campaign.AvailableVoucherCount, + claimed, + redeemed, + expired, + campaign.FaceValue * campaign.TotalVouchers, + totalRedeemed, + totalRefunded, + campaign.TotalVouchers > 0 ? (decimal)redeemed / campaign.TotalVouchers * 100 : 0, + redemptions.Count, + vouchers.Where(v => v.ClaimedAt.HasValue).MinBy(v => v.ClaimedAt)?.ClaimedAt, + redemptions.OrderByDescending(r => r.RedeemedAt).FirstOrDefault()?.RedeemedAt); + } +} + +/// +/// EN: Handler for GetAllVouchersQuery. +/// VI: Handler cho GetAllVouchersQuery. +/// +public class GetAllVouchersQueryHandler : IRequestHandler> +{ + private readonly PromotionServiceContext _context; + + public GetAllVouchersQueryHandler(PromotionServiceContext context) + { + _context = context; + } + + public async Task> Handle(GetAllVouchersQuery request, CancellationToken cancellationToken) + { + var query = _context.Vouchers.AsQueryable(); + + if (request.CampaignId.HasValue) + query = query.Where(v => v.CampaignId == request.CampaignId.Value); + + if (request.UserId.HasValue) + query = query.Where(v => v.OwnerId == request.UserId.Value); + + if (!string.IsNullOrEmpty(request.CodeSearch)) + query = query.Where(v => v.Code.Contains(request.CodeSearch)); + + if (!string.IsNullOrEmpty(request.Status)) + { + var statusId = request.Status.ToLower() switch + { + "available" => 1, + "claimed" => 2, + "partiallyredeemed" => 3, + "fullyredeemed" => 4, + "expired" => 5, + _ => 0 + }; + if (statusId > 0) + query = query.Where(v => v.StatusId == statusId); + } + + var totalCount = await query.CountAsync(cancellationToken); + var totalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize); + + var items = await query + .OrderByDescending(v => v.CreatedAt) + .Skip((request.PageNumber - 1) * request.PageSize) + .Take(request.PageSize) + .Join(_context.Campaigns, + v => v.CampaignId, + c => c.Id, + (v, c) => new AdminVoucherListDto( + v.Id, + v.CampaignId, + c.Name, + v.Code, + v.OwnerId, + null, + v.FaceValue, + v.RemainingValue, + v.StatusId == 1 ? "Available" : v.StatusId == 2 ? "Claimed" : v.StatusId == 3 ? "PartiallyRedeemed" : v.StatusId == 4 ? "FullyRedeemed" : "Expired", + v.ClaimedAt, + v.ExpiresAt, + v.RedeemedAt, + v.CreatedAt)) + .ToListAsync(cancellationToken); + + return new PaginatedResponse(items, totalCount, request.PageNumber, request.PageSize, totalPages); + } +} + +/// +/// EN: Handler for GetAllRedemptionsQuery. +/// VI: Handler cho GetAllRedemptionsQuery. +/// +public class GetAllRedemptionsQueryHandler : IRequestHandler> +{ + private readonly PromotionServiceContext _context; + + public GetAllRedemptionsQueryHandler(PromotionServiceContext context) + { + _context = context; + } + + public async Task> Handle(GetAllRedemptionsQuery request, CancellationToken cancellationToken) + { + var query = _context.Redemptions.AsQueryable(); + + if (request.CampaignId.HasValue) + query = query.Where(r => r.CampaignId == request.CampaignId.Value); + + if (request.VoucherId.HasValue) + query = query.Where(r => r.VoucherId == request.VoucherId.Value); + + if (request.UserId.HasValue) + query = query.Where(r => r.UserId == request.UserId.Value); + + if (request.DateFrom.HasValue) + query = query.Where(r => r.RedeemedAt >= request.DateFrom.Value); + + if (request.DateTo.HasValue) + query = query.Where(r => r.RedeemedAt <= request.DateTo.Value); + + var totalCount = await query.CountAsync(cancellationToken); + var totalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize); + + var items = await query + .OrderByDescending(r => r.RedeemedAt) + .Skip((request.PageNumber - 1) * request.PageSize) + .Take(request.PageSize) + .Join(_context.Vouchers, + r => r.VoucherId, + v => v.Id, + (r, v) => new { Redemption = r, Voucher = v }) + .Join(_context.Campaigns, + rv => rv.Voucher.CampaignId, + c => c.Id, + (rv, c) => new AdminRedemptionListDto( + rv.Redemption.Id, + rv.Redemption.VoucherId, + rv.Voucher.Code, + rv.Redemption.CampaignId, + c.Name, + rv.Redemption.UserId, + rv.Redemption.OrderId, + rv.Redemption.AmountUsed, + rv.Redemption.AmountRefunded, + rv.Redemption.RedeemedAt)) + .ToListAsync(cancellationToken); + + return new PaginatedResponse(items, totalCount, request.PageNumber, request.PageSize, totalPages); + } +} + +/// +/// EN: Handler for GetRedemptionStatisticsQuery. +/// VI: Handler cho GetRedemptionStatisticsQuery. +/// +public class GetRedemptionStatisticsQueryHandler : IRequestHandler +{ + private readonly PromotionServiceContext _context; + + public GetRedemptionStatisticsQueryHandler(PromotionServiceContext context) + { + _context = context; + } + + public async Task Handle(GetRedemptionStatisticsQuery request, CancellationToken cancellationToken) + { + var query = _context.Redemptions.AsQueryable(); + + if (request.CampaignId.HasValue) + query = query.Where(r => r.CampaignId == request.CampaignId.Value); + + var today = DateTime.UtcNow.Date; + var weekStart = today.AddDays(-(int)today.DayOfWeek); + var monthStart = new DateTime(today.Year, today.Month, 1); + + var stats = await query + .GroupBy(_ => 1) + .Select(g => new + { + Total = g.Count(), + TotalAmountUsed = g.Sum(r => r.AmountUsed), + TotalAmountRefunded = g.Sum(r => r.AmountRefunded), + AvgAmount = g.Average(r => r.AmountUsed) + }) + .FirstOrDefaultAsync(cancellationToken); + + var todayCount = await query.CountAsync(r => r.RedeemedAt >= today, cancellationToken); + var weekCount = await query.CountAsync(r => r.RedeemedAt >= weekStart, cancellationToken); + var monthCount = await query.CountAsync(r => r.RedeemedAt >= monthStart, cancellationToken); + + return new AdminRedemptionStatisticsDto( + stats?.Total ?? 0, + stats?.TotalAmountUsed ?? 0, + stats?.TotalAmountRefunded ?? 0, + stats?.AvgAmount ?? 0, + todayCount, + weekCount, + monthCount); + } +} diff --git a/services/promotion-service-net/src/PromotionService.API/Controllers/Admin/AdminCampaignsController.cs b/services/promotion-service-net/src/PromotionService.API/Controllers/Admin/AdminCampaignsController.cs new file mode 100644 index 00000000..c2bd60da --- /dev/null +++ b/services/promotion-service-net/src/PromotionService.API/Controllers/Admin/AdminCampaignsController.cs @@ -0,0 +1,125 @@ +using MediatR; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using PromotionService.API.Application.Commands; +using PromotionService.API.Application.DTOs; +using PromotionService.API.Application.Queries; + +namespace PromotionService.API.Controllers.Admin; + +/// +/// EN: Admin controller for Campaign management. +/// VI: Admin controller để quản lý Campaign. +/// +[ApiController] +[Route("api/v1/admin/campaigns")] +[Authorize(Roles = "Admin")] +[Produces("application/json")] +public class AdminCampaignsController : ControllerBase +{ + private readonly IMediator _mediator; + private readonly ILogger _logger; + + public AdminCampaignsController(IMediator mediator, ILogger logger) + { + _mediator = mediator; + _logger = logger; + } + + /// + /// EN: Get all campaigns with pagination and filters. + /// VI: Lấy tất cả chiến dịch với phân trang và bộ lọc. + /// + [HttpGet] + [ProducesResponseType(typeof(PaginatedResponse), StatusCodes.Status200OK)] + public async Task>> GetAllCampaigns( + [FromQuery] int pageNumber = 1, + [FromQuery] int pageSize = 20, + [FromQuery] Guid? merchantId = null, + [FromQuery] string? status = null, + [FromQuery] string? searchTerm = null) + { + var result = await _mediator.Send(new GetAllCampaignsQuery(pageNumber, pageSize, merchantId, status, searchTerm)); + return Ok(result); + } + + /// + /// EN: Get campaign statistics. + /// VI: Lấy thống kê chiến dịch. + /// + [HttpGet("{id:guid}/statistics")] + [ProducesResponseType(typeof(AdminCampaignStatisticsDto), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task> GetCampaignStatistics(Guid id) + { + var result = await _mediator.Send(new GetAdminCampaignStatisticsQuery(id)); + return result == null ? NotFound() : Ok(result); + } + + /// + /// EN: Get vouchers for a campaign. + /// VI: Lấy vouchers của chiến dịch. + /// + [HttpGet("{id:guid}/vouchers")] + [ProducesResponseType(typeof(PaginatedResponse), StatusCodes.Status200OK)] + public async Task>> GetCampaignVouchers( + Guid id, + [FromQuery] int pageNumber = 1, + [FromQuery] int pageSize = 20, + [FromQuery] string? status = null) + { + var result = await _mediator.Send(new GetCampaignVouchersQuery(id, pageNumber, pageSize, status)); + return Ok(result); + } + + /// + /// EN: Update campaign details. + /// VI: Cập nhật thông tin chiến dịch. + /// + [HttpPut("{id:guid}")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task UpdateCampaign(Guid id, [FromBody] UpdateCampaignRequest request) + { + var result = await _mediator.Send(new UpdateCampaignCommand( + id, request.Name, request.Description, request.StartDate, request.EndDate, request.MaxPerUser)); + return result ? Ok() : NotFound(); + } + + /// + /// EN: Force complete a campaign. + /// VI: Bắt buộc hoàn thành chiến dịch. + /// + [HttpPost("{id:guid}/complete")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task CompleteCampaign(Guid id) + { + var result = await _mediator.Send(new CompleteCampaignCommand(id)); + return result ? Ok() : NotFound(); + } + + /// + /// EN: Delete (soft delete) a campaign. + /// VI: Xóa (xóa mềm) chiến dịch. + /// + [HttpDelete("{id:guid}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task DeleteCampaign(Guid id) + { + var result = await _mediator.Send(new DeleteCampaignCommand(id)); + return result ? NoContent() : NotFound(); + } +} + +/// +/// EN: Request to update campaign. +/// VI: Request để cập nhật chiến dịch. +/// +public record UpdateCampaignRequest( + string? Name = null, + string? Description = null, + DateTime? StartDate = null, + DateTime? EndDate = null, + int? MaxPerUser = null); diff --git a/services/promotion-service-net/src/PromotionService.API/Controllers/Admin/AdminRedemptionsController.cs b/services/promotion-service-net/src/PromotionService.API/Controllers/Admin/AdminRedemptionsController.cs new file mode 100644 index 00000000..db894a99 --- /dev/null +++ b/services/promotion-service-net/src/PromotionService.API/Controllers/Admin/AdminRedemptionsController.cs @@ -0,0 +1,89 @@ +using MediatR; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using PromotionService.API.Application.DTOs; +using PromotionService.API.Application.Queries; + +namespace PromotionService.API.Controllers.Admin; + +/// +/// EN: Admin controller for Redemption management. +/// VI: Admin controller để quản lý Redemption. +/// +[ApiController] +[Route("api/v1/admin/redemptions")] +[Authorize(Roles = "Admin")] +[Produces("application/json")] +public class AdminRedemptionsController : ControllerBase +{ + private readonly IMediator _mediator; + private readonly ILogger _logger; + + public AdminRedemptionsController(IMediator mediator, ILogger logger) + { + _mediator = mediator; + _logger = logger; + } + + /// + /// EN: Get all redemptions with pagination and filters. + /// VI: Lấy tất cả redemptions với phân trang và bộ lọc. + /// + [HttpGet] + [ProducesResponseType(typeof(PaginatedResponse), StatusCodes.Status200OK)] + public async Task>> GetAllRedemptions( + [FromQuery] int pageNumber = 1, + [FromQuery] int pageSize = 20, + [FromQuery] Guid? campaignId = null, + [FromQuery] Guid? voucherId = null, + [FromQuery] Guid? userId = null, + [FromQuery] DateTime? dateFrom = null, + [FromQuery] DateTime? dateTo = null) + { + var result = await _mediator.Send(new GetAllRedemptionsQuery(pageNumber, pageSize, campaignId, voucherId, userId, dateFrom, dateTo)); + return Ok(result); + } + + /// + /// EN: Get redemptions by campaign. + /// VI: Lấy redemptions theo chiến dịch. + /// + [HttpGet("by-campaign/{campaignId:guid}")] + [ProducesResponseType(typeof(PaginatedResponse), StatusCodes.Status200OK)] + public async Task>> GetRedemptionsByCampaign( + Guid campaignId, + [FromQuery] int pageNumber = 1, + [FromQuery] int pageSize = 20) + { + var result = await _mediator.Send(new GetAllRedemptionsQuery(pageNumber, pageSize, campaignId, null, null, null, null)); + return Ok(result); + } + + /// + /// EN: Get redemptions by voucher. + /// VI: Lấy redemptions theo voucher. + /// + [HttpGet("by-voucher/{voucherId:guid}")] + [ProducesResponseType(typeof(PaginatedResponse), StatusCodes.Status200OK)] + public async Task>> GetRedemptionsByVoucher( + Guid voucherId, + [FromQuery] int pageNumber = 1, + [FromQuery] int pageSize = 20) + { + var result = await _mediator.Send(new GetAllRedemptionsQuery(pageNumber, pageSize, null, voucherId, null, null, null)); + return Ok(result); + } + + /// + /// EN: Get redemption statistics. + /// VI: Lấy thống kê redemption. + /// + [HttpGet("statistics")] + [ProducesResponseType(typeof(AdminRedemptionStatisticsDto), StatusCodes.Status200OK)] + public async Task> GetRedemptionStatistics( + [FromQuery] Guid? campaignId = null) + { + var result = await _mediator.Send(new GetRedemptionStatisticsQuery(campaignId)); + return Ok(result); + } +} diff --git a/services/promotion-service-net/src/PromotionService.API/Controllers/Admin/AdminVouchersController.cs b/services/promotion-service-net/src/PromotionService.API/Controllers/Admin/AdminVouchersController.cs new file mode 100644 index 00000000..27c80b1d --- /dev/null +++ b/services/promotion-service-net/src/PromotionService.API/Controllers/Admin/AdminVouchersController.cs @@ -0,0 +1,103 @@ +using MediatR; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using PromotionService.API.Application.Commands; +using PromotionService.API.Application.DTOs; +using PromotionService.API.Application.Queries; + +namespace PromotionService.API.Controllers.Admin; + +/// +/// EN: Admin controller for Voucher management. +/// VI: Admin controller để quản lý Voucher. +/// +[ApiController] +[Route("api/v1/admin/vouchers")] +[Authorize(Roles = "Admin")] +[Produces("application/json")] +public class AdminVouchersController : ControllerBase +{ + private readonly IMediator _mediator; + private readonly ILogger _logger; + + public AdminVouchersController(IMediator mediator, ILogger logger) + { + _mediator = mediator; + _logger = logger; + } + + /// + /// EN: Get all vouchers with pagination and filters. + /// VI: Lấy tất cả vouchers với phân trang và bộ lọc. + /// + [HttpGet] + [ProducesResponseType(typeof(PaginatedResponse), StatusCodes.Status200OK)] + public async Task>> GetAllVouchers( + [FromQuery] int pageNumber = 1, + [FromQuery] int pageSize = 20, + [FromQuery] Guid? campaignId = null, + [FromQuery] Guid? userId = null, + [FromQuery] string? status = null, + [FromQuery] string? codeSearch = null) + { + var result = await _mediator.Send(new GetAllVouchersQuery(pageNumber, pageSize, campaignId, userId, status, codeSearch)); + return Ok(result); + } + + /// + /// EN: Search vouchers by code. + /// VI: Tìm kiếm vouchers theo mã. + /// + [HttpGet("search")] + [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] + public async Task>> SearchVouchers( + [FromQuery] string q) + { + var result = await _mediator.Send(new SearchVouchersQuery(q)); + return Ok(result); + } + + /// + /// EN: Get vouchers by user. + /// VI: Lấy vouchers theo user. + /// + [HttpGet("by-user/{userId:guid}")] + [ProducesResponseType(typeof(PaginatedResponse), StatusCodes.Status200OK)] + public async Task>> GetVouchersByUser( + Guid userId, + [FromQuery] int pageNumber = 1, + [FromQuery] int pageSize = 20) + { + var result = await _mediator.Send(new GetAllVouchersQuery(pageNumber, pageSize, null, userId, null, null)); + return Ok(result); + } + + /// + /// EN: Revoke a voucher. + /// VI: Thu hồi voucher. + /// + [HttpPost("{id:guid}/revoke")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task RevokeVoucher(Guid id, [FromBody] RevokeVoucherRequest request) + { + var result = await _mediator.Send(new RevokeVoucherCommand(id, request.Reason)); + return result ? Ok() : NotFound(); + } + + /// + /// EN: Extend voucher expiry. + /// VI: Gia hạn voucher. + /// + [HttpPost("{id:guid}/extend")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task ExtendVoucherExpiry(Guid id, [FromBody] ExtendExpiryRequest request) + { + var result = await _mediator.Send(new ExtendVoucherExpiryCommand(id, request.AdditionalDays)); + return result ? Ok() : NotFound(); + } +} + +public record RevokeVoucherRequest(string Reason); +public record ExtendExpiryRequest(int AdditionalDays); diff --git a/services/promotion-service-net/src/PromotionService.Domain/AggregatesModel/CampaignAggregate/Campaign.cs b/services/promotion-service-net/src/PromotionService.Domain/AggregatesModel/CampaignAggregate/Campaign.cs index f71538fe..34c0d41e 100644 --- a/services/promotion-service-net/src/PromotionService.Domain/AggregatesModel/CampaignAggregate/Campaign.cs +++ b/services/promotion-service-net/src/PromotionService.Domain/AggregatesModel/CampaignAggregate/Campaign.cs @@ -305,6 +305,38 @@ public class Campaign : Entity, IAggregateRoot UpdatedAt = DateTime.UtcNow; } + /// + /// EN: Update campaign details (admin only). + /// VI: Cập nhật thông tin chiến dịch (chỉ admin). + /// + public void Update(string? name, string? description, DateTime? startDate, DateTime? endDate, int? maxPerUser) + { + if (!string.IsNullOrWhiteSpace(name)) + Name = name; + + if (description != null) + Description = description; + + if (startDate.HasValue) + { + if (endDate.HasValue && endDate.Value <= startDate.Value) + throw new PromotionDomainException("End date must be after start date"); + StartDate = startDate.Value; + } + + if (endDate.HasValue) + { + if (endDate.Value <= StartDate) + throw new PromotionDomainException("End date must be after start date"); + EndDate = endDate.Value; + } + + if (maxPerUser.HasValue && maxPerUser.Value >= 0) + MaxPerUser = maxPerUser.Value; + + UpdatedAt = DateTime.UtcNow; + } + #endregion #region Voucher Management diff --git a/services/promotion-service-net/src/PromotionService.Domain/AggregatesModel/CampaignAggregate/ICampaignRepository.cs b/services/promotion-service-net/src/PromotionService.Domain/AggregatesModel/CampaignAggregate/ICampaignRepository.cs index 6d17bae6..b0a89d1a 100644 --- a/services/promotion-service-net/src/PromotionService.Domain/AggregatesModel/CampaignAggregate/ICampaignRepository.cs +++ b/services/promotion-service-net/src/PromotionService.Domain/AggregatesModel/CampaignAggregate/ICampaignRepository.cs @@ -38,6 +38,12 @@ public interface ICampaignRepository : IRepository /// Task> GetUserVouchersAsync(Guid userId); + /// + /// EN: Get voucher by ID. + /// VI: Lấy voucher theo ID. + /// + Task GetVoucherByIdAsync(Guid voucherId); + /// /// EN: Add a new campaign. /// VI: Thêm chiến dịch mới. diff --git a/services/promotion-service-net/src/PromotionService.Domain/AggregatesModel/CampaignAggregate/Voucher.cs b/services/promotion-service-net/src/PromotionService.Domain/AggregatesModel/CampaignAggregate/Voucher.cs index e3dc5846..7ea255bf 100644 --- a/services/promotion-service-net/src/PromotionService.Domain/AggregatesModel/CampaignAggregate/Voucher.cs +++ b/services/promotion-service-net/src/PromotionService.Domain/AggregatesModel/CampaignAggregate/Voucher.cs @@ -159,6 +159,26 @@ public class Voucher : Entity UpdatedAt = DateTime.UtcNow; } + /// + /// EN: Extend voucher expiry by additional days. + /// VI: Gia hạn voucher thêm số ngày. + /// + public void ExtendExpiry(int additionalDays) + { + if (additionalDays <= 0) + throw new PromotionDomainException("Additional days must be positive"); + + if (Status == VoucherStatus.FullyRedeemed || Status == VoucherStatus.Expired) + throw new PromotionDomainException("Cannot extend expired or fully redeemed voucher"); + + if (!ExpiresAt.HasValue) + ExpiresAt = DateTime.UtcNow.AddDays(additionalDays); + else + ExpiresAt = ExpiresAt.Value.AddDays(additionalDays); + + UpdatedAt = DateTime.UtcNow; + } + /// /// EN: Check if voucher is valid for redemption. /// VI: Kiểm tra voucher có hợp lệ để sử dụng. diff --git a/services/promotion-service-net/src/PromotionService.Infrastructure/Repositories/CampaignRepository.cs b/services/promotion-service-net/src/PromotionService.Infrastructure/Repositories/CampaignRepository.cs index 98b7ab2f..2936d069 100644 --- a/services/promotion-service-net/src/PromotionService.Infrastructure/Repositories/CampaignRepository.cs +++ b/services/promotion-service-net/src/PromotionService.Infrastructure/Repositories/CampaignRepository.cs @@ -59,6 +59,12 @@ public class CampaignRepository : ICampaignRepository .ToListAsync(); } + public async Task GetVoucherByIdAsync(Guid voucherId) + { + return await _context.Vouchers + .FirstOrDefaultAsync(v => v.Id == voucherId); + } + public Campaign Add(Campaign campaign) { return _context.Campaigns.Add(campaign).Entity; diff --git a/services/promotion-service-net/tests/PromotionService.UnitTests/Application/ClaimVoucherCommandHandlerTests.cs b/services/promotion-service-net/tests/PromotionService.UnitTests/Application/ClaimVoucherCommandHandlerTests.cs new file mode 100644 index 00000000..0b4cb5b6 --- /dev/null +++ b/services/promotion-service-net/tests/PromotionService.UnitTests/Application/ClaimVoucherCommandHandlerTests.cs @@ -0,0 +1,128 @@ +using FluentAssertions; +using Microsoft.Extensions.Logging; +using NSubstitute; +using PromotionService.API.Application.Commands; +using PromotionService.Domain.AggregatesModel.CampaignAggregate; +using PromotionService.Domain.Exceptions; +using PromotionService.Domain.SeedWork; +using Xunit; + +namespace PromotionService.UnitTests.Application; + +/// +/// EN: Unit tests for ClaimVoucherCommandHandler. +/// VI: Unit tests cho ClaimVoucherCommandHandler. +/// +public class ClaimVoucherCommandHandlerTests +{ + private readonly ICampaignRepository _campaignRepository; + private readonly ILogger _logger; + private readonly ClaimVoucherCommandHandler _handler; + + public ClaimVoucherCommandHandlerTests() + { + _campaignRepository = Substitute.For(); + _logger = Substitute.For>(); + + var unitOfWork = Substitute.For(); + unitOfWork.SaveEntitiesAsync(Arg.Any()).Returns(true); + _campaignRepository.UnitOfWork.Returns(unitOfWork); + + _handler = new ClaimVoucherCommandHandler(_campaignRepository, _logger); + } + + private static Campaign CreateActiveCampaign() + { + var campaign = new Campaign( + merchantId: Guid.NewGuid(), + name: "Free Voucher Campaign", + description: null, + backingAssetType: AssetType.Currency, + backingAssetCode: "VND", + faceValue: 50_000m, + acquisitionType: AcquisitionType.Free, + acquisitionPrice: 0m, + totalVouchers: 100, + startDate: DateTime.UtcNow.AddDays(-1), + endDate: DateTime.UtcNow.AddDays(30), + voucherValidityDays: 30, + maxPerUser: 1); + + campaign.SetEscrowHold(Guid.NewGuid(), Guid.NewGuid()); + campaign.GenerateVouchers(100); + campaign.Activate(); + return campaign; + } + + [Fact] + public async Task Handle_FreeCampaign_ClaimsVoucherSuccessfully() + { + // Arrange + var campaign = CreateActiveCampaign(); + var userId = Guid.NewGuid(); + var command = new ClaimVoucherCommand(campaign.Id, userId); + + _campaignRepository.GetByIdAsync(campaign.Id) + .Returns(campaign); + + // Act + var result = await _handler.Handle(command, CancellationToken.None); + + // Assert + result.Should().NotBeNull(); + result.OwnerId.Should().Be(userId); + result.Status.Should().Be("Claimed"); + result.RemainingValue.Should().Be(50_000m); + + _campaignRepository.Received(1).Update(campaign); + await _campaignRepository.UnitOfWork.Received(1).SaveEntitiesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_NonFreeCampaign_ThrowsDomainException() + { + // Arrange + var campaign = new Campaign( + merchantId: Guid.NewGuid(), + name: "Paid Voucher Campaign", + description: null, + backingAssetType: AssetType.Currency, + backingAssetCode: "VND", + faceValue: 100_000m, + acquisitionType: AcquisitionType.Purchase, // Not free! + acquisitionPrice: 50_000m, + totalVouchers: 100, + startDate: DateTime.UtcNow.AddDays(-1), + endDate: DateTime.UtcNow.AddDays(30), + voucherValidityDays: 30, + maxPerUser: 1); + + campaign.SetEscrowHold(Guid.NewGuid(), Guid.NewGuid()); + campaign.GenerateVouchers(100); + campaign.Activate(); + + _campaignRepository.GetByIdAsync(campaign.Id).Returns(campaign); + + var command = new ClaimVoucherCommand(campaign.Id, Guid.NewGuid()); + + // Act & Assert + var act = async () => await _handler.Handle(command, CancellationToken.None); + await act.Should().ThrowAsync() + .WithMessage("*requires payment*"); + } + + [Fact] + public async Task Handle_CampaignNotFound_ThrowsDomainException() + { + // Arrange + var nonExistentId = Guid.NewGuid(); + _campaignRepository.GetByIdAsync(nonExistentId).Returns((Campaign?)null); + + var command = new ClaimVoucherCommand(nonExistentId, Guid.NewGuid()); + + // Act & Assert + var act = async () => await _handler.Handle(command, CancellationToken.None); + await act.Should().ThrowAsync() + .WithMessage("*not found*"); + } +} diff --git a/services/promotion-service-net/tests/PromotionService.UnitTests/Application/CreateCampaignCommandHandlerTests.cs b/services/promotion-service-net/tests/PromotionService.UnitTests/Application/CreateCampaignCommandHandlerTests.cs new file mode 100644 index 00000000..e11923b6 --- /dev/null +++ b/services/promotion-service-net/tests/PromotionService.UnitTests/Application/CreateCampaignCommandHandlerTests.cs @@ -0,0 +1,172 @@ +using FluentAssertions; +using Microsoft.Extensions.Logging; +using NSubstitute; +using PromotionService.API.Application.Commands; +using PromotionService.API.Application.Services; +using PromotionService.Domain.AggregatesModel.CampaignAggregate; +using PromotionService.Domain.Exceptions; +using PromotionService.Domain.SeedWork; +using Xunit; + +namespace PromotionService.UnitTests.Application; + +/// +/// EN: Unit tests for CreateCampaignCommandHandler. +/// VI: Unit tests cho CreateCampaignCommandHandler. +/// +public class CreateCampaignCommandHandlerTests +{ + private readonly ICampaignRepository _campaignRepository; + private readonly IWalletServiceClient _walletService; + private readonly ILogger _logger; + private readonly CreateCampaignCommandHandler _handler; + + public CreateCampaignCommandHandlerTests() + { + _campaignRepository = Substitute.For(); + _walletService = Substitute.For(); + _logger = Substitute.For>(); + + // Setup UnitOfWork + var unitOfWork = Substitute.For(); + unitOfWork.SaveEntitiesAsync(Arg.Any()).Returns(true); + _campaignRepository.UnitOfWork.Returns(unitOfWork); + + _handler = new CreateCampaignCommandHandler( + _campaignRepository, + _walletService, + _logger); + } + + private static CreateCampaignCommand CreateValidCommand() => new CreateCampaignCommand( + MerchantId: Guid.NewGuid(), + MerchantWalletId: Guid.NewGuid(), + Name: "Test Campaign", + Description: "Test Description", + BackingAssetType: "Currency", + BackingAssetCode: "VND", + FaceValue: 100_000m, + AcquisitionType: "Free", + AcquisitionPrice: 0m, + TotalVouchers: 100, + StartDate: DateTime.UtcNow.AddDays(1), + EndDate: DateTime.UtcNow.AddDays(30), + VoucherValidityDays: 30, + MaxPerUser: 1); + + [Fact] + public async Task Handle_ValidCommand_CreatesCampaignAndReturnsDto() + { + // Arrange + var command = CreateValidCommand(); + var holdResult = new HoldResult( + HoldId: Guid.NewGuid(), + WalletId: command.MerchantWalletId, + Amount: command.FaceValue * command.TotalVouchers, + CurrencyType: command.BackingAssetCode, + ReferenceType: "CAMPAIGN", + ReferenceId: Guid.NewGuid(), + Status: "Active"); + + _walletService.CreateHoldAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(holdResult); + + _campaignRepository.Add(Arg.Any()) + .Returns(callInfo => callInfo.Arg()); + + // Act + var result = await _handler.Handle(command, CancellationToken.None); + + // Assert + result.Should().NotBeNull(); + result.Name.Should().Be(command.Name); + result.TotalVouchers.Should().Be(command.TotalVouchers); + result.Status.Should().Be("Draft"); + + // Verify repository called + _campaignRepository.Received(1).Add(Arg.Is(c => c.Name == command.Name)); + await _campaignRepository.UnitOfWork.Received(1).SaveEntitiesAsync(Arg.Any()); + } + + [Fact] + public async Task Handle_ValidCommand_CallsWalletServiceToCreateEscrow() + { + // Arrange + var command = CreateValidCommand(); + var expectedEscrowAmount = command.FaceValue * command.TotalVouchers; + + _walletService.CreateHoldAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()) + .Returns(new HoldResult( + Guid.NewGuid(), + command.MerchantWalletId, + expectedEscrowAmount, + "VND", + "CAMPAIGN", + Guid.NewGuid(), + "Active")); + + _campaignRepository.Add(Arg.Any()) + .Returns(callInfo => callInfo.Arg()); + + // Act + await _handler.Handle(command, CancellationToken.None); + + // Assert - Verify wallet service was called with correct escrow amount + await _walletService.Received(1).CreateHoldAsync( + command.MerchantWalletId, + expectedEscrowAmount, + command.BackingAssetCode, + "CAMPAIGN", + Arg.Any(), + Arg.Is(s => s.Contains(command.Name)), + Arg.Any()); + } + + [Fact] + public async Task Handle_InvalidAcquisitionType_ThrowsDomainException() + { + // Arrange + var command = new CreateCampaignCommand( + MerchantId: Guid.NewGuid(), + MerchantWalletId: Guid.NewGuid(), + Name: "Test Campaign", + Description: null, + BackingAssetType: "Currency", + BackingAssetCode: "VND", + FaceValue: 100_000m, + AcquisitionType: "InvalidType", // Invalid! + AcquisitionPrice: 0m, + TotalVouchers: 100, + StartDate: DateTime.UtcNow.AddDays(1), + EndDate: DateTime.UtcNow.AddDays(30)); + + // Act & Assert + var act = async () => await _handler.Handle(command, CancellationToken.None); + await act.Should().ThrowAsync() + .WithMessage("*Invalid acquisition type*"); + + // Verify wallet service was NOT called + await _walletService.DidNotReceive().CreateHoldAsync( + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any()); + } +} diff --git a/services/promotion-service-net/tests/PromotionService.UnitTests/Domain/CampaignAggregateTests.cs b/services/promotion-service-net/tests/PromotionService.UnitTests/Domain/CampaignAggregateTests.cs new file mode 100644 index 00000000..6ec31ef6 --- /dev/null +++ b/services/promotion-service-net/tests/PromotionService.UnitTests/Domain/CampaignAggregateTests.cs @@ -0,0 +1,326 @@ +using FluentAssertions; +using PromotionService.Domain.AggregatesModel.CampaignAggregate; +using PromotionService.Domain.Events; +using PromotionService.Domain.Exceptions; +using Xunit; + +namespace PromotionService.UnitTests.Domain; + +/// +/// EN: Unit tests for Campaign aggregate root. +/// VI: Unit tests cho Campaign aggregate root. +/// +public class CampaignAggregateTests +{ + #region Helper Methods + + /// + /// EN: Creates a campaign with future start date (for constructor/lifecycle tests). + /// VI: Tạo campaign với ngày bắt đầu trong tương lai (cho constructor/lifecycle tests). + /// + private static Campaign CreateValidCampaign() => new Campaign( + merchantId: Guid.NewGuid(), + name: "Test Campaign", + description: "Test Description", + backingAssetType: AssetType.Currency, + backingAssetCode: "VND", + faceValue: 100_000m, + acquisitionType: AcquisitionType.Free, + acquisitionPrice: 0m, + totalVouchers: 100, + startDate: DateTime.UtcNow.AddDays(1), + endDate: DateTime.UtcNow.AddDays(30), + voucherValidityDays: 30, + maxPerUser: 1); + + /// + /// EN: Creates a campaign with past start date (for issuing vouchers tests). + /// VI: Tạo campaign với ngày bắt đầu trong quá khứ (cho tests phát hành voucher). + /// + private static Campaign CreateActiveCampaign() => new Campaign( + merchantId: Guid.NewGuid(), + name: "Active Campaign", + description: "Active Description", + backingAssetType: AssetType.Currency, + backingAssetCode: "VND", + faceValue: 100_000m, + acquisitionType: AcquisitionType.Free, + acquisitionPrice: 0m, + totalVouchers: 100, + startDate: DateTime.UtcNow.AddDays(-1), // Started yesterday + endDate: DateTime.UtcNow.AddDays(30), + voucherValidityDays: 30, + maxPerUser: 1); + + #endregion + + #region Constructor Tests + + [Fact] + public void Constructor_ValidParameters_CreatesCampaignInDraftStatus() + { + // Arrange & Act + var campaign = CreateValidCampaign(); + + // Assert + campaign.Id.Should().NotBeEmpty(); + campaign.StatusId.Should().Be(CampaignStatus.Draft.Id); + campaign.TotalVouchers.Should().Be(100); + campaign.IssuedVouchers.Should().Be(0); + campaign.Vouchers.Should().BeEmpty(); + } + + [Fact] + public void Constructor_ZeroTotalVouchers_ThrowsException() + { + // Arrange & Act + var act = () => new Campaign( + merchantId: Guid.NewGuid(), + name: "Test Campaign", + description: null, + backingAssetType: AssetType.Currency, + backingAssetCode: "VND", + faceValue: 100_000m, + acquisitionType: AcquisitionType.Free, + acquisitionPrice: 0m, + totalVouchers: 0, // Invalid! + startDate: DateTime.UtcNow.AddDays(1), + endDate: DateTime.UtcNow.AddDays(30), + voucherValidityDays: 30, + maxPerUser: 1); + + // Assert + act.Should().Throw() + .WithMessage("*Total vouchers*"); + } + + [Fact] + public void Constructor_EndDateBeforeStartDate_ThrowsException() + { + // Arrange & Act + var act = () => new Campaign( + merchantId: Guid.NewGuid(), + name: "Test Campaign", + description: null, + backingAssetType: AssetType.Currency, + backingAssetCode: "VND", + faceValue: 100_000m, + acquisitionType: AcquisitionType.Free, + acquisitionPrice: 0m, + totalVouchers: 100, + startDate: DateTime.UtcNow.AddDays(30), + endDate: DateTime.UtcNow.AddDays(1), // Before start! + voucherValidityDays: 30, + maxPerUser: 1); + + // Assert + act.Should().Throw() + .WithMessage("*End date*"); + } + + #endregion + + #region Lifecycle Tests + + [Fact] + public void Activate_DraftCampaign_ChangesStatusToActive() + { + // Arrange + var campaign = CreateValidCampaign(); + campaign.SetEscrowHold(Guid.NewGuid(), Guid.NewGuid()); + + // Act + campaign.Activate(); + + // Assert + campaign.StatusId.Should().Be(CampaignStatus.Active.Id); + } + + [Fact] + public void Activate_WithoutEscrow_ThrowsException() + { + // Arrange + var campaign = CreateValidCampaign(); + + // Act & Assert + var act = () => campaign.Activate(); + act.Should().Throw() + .WithMessage("*escrow*"); + } + + [Fact] + public void Pause_ActiveCampaign_ChangesStatusToPaused() + { + // Arrange + var campaign = CreateValidCampaign(); + campaign.SetEscrowHold(Guid.NewGuid(), Guid.NewGuid()); + campaign.Activate(); + + // Act + campaign.Pause(); + + // Assert + campaign.StatusId.Should().Be(CampaignStatus.Paused.Id); + } + + [Fact] + public void Cancel_DraftCampaign_ChangesStatusToCancelled() + { + // Arrange + var campaign = CreateValidCampaign(); + + // Act + campaign.Cancel(); + + // Assert + campaign.StatusId.Should().Be(CampaignStatus.Cancelled.Id); + } + + [Fact] + public void Cancel_ActiveCampaign_ChangesStatusToCancelled() + { + // Arrange + var campaign = CreateValidCampaign(); + campaign.SetEscrowHold(Guid.NewGuid(), Guid.NewGuid()); + campaign.Activate(); + + // Act + campaign.Cancel(); + + // Assert + campaign.StatusId.Should().Be(CampaignStatus.Cancelled.Id); + campaign.DomainEvents.Should().ContainSingle(e => e is CampaignCancelledDomainEvent); + } + + #endregion + + #region Voucher Generation Tests + + [Fact] + public void GenerateVouchers_ValidCount_CreatesVouchersWithUniqueCodes() + { + // Arrange + var campaign = CreateValidCampaign(); + + // Act + campaign.GenerateVouchers(10); + + // Assert + campaign.Vouchers.Should().HaveCount(10); + campaign.Vouchers.Select(v => v.Code).Should().OnlyHaveUniqueItems(); + campaign.Vouchers.All(v => v.FaceValue == campaign.FaceValue).Should().BeTrue(); + } + + [Fact] + public void GenerateVouchers_ExceedsTotalLimit_ThrowsException() + { + // Arrange + var campaign = CreateValidCampaign(); // totalVouchers = 100 + + // Act & Assert + var act = () => campaign.GenerateVouchers(150); + act.Should().Throw() + .WithMessage("*Maximum*"); + } + + #endregion + + #region Issue Voucher Tests + + [Fact] + public void IssueVoucher_ActiveCampaign_ReturnsClaimedVoucher() + { + // Arrange + var campaign = CreateActiveCampaign(); + campaign.SetEscrowHold(Guid.NewGuid(), Guid.NewGuid()); + campaign.GenerateVouchers(10); + campaign.Activate(); + var userId = Guid.NewGuid(); + + // Act + var voucher = campaign.IssueVoucher(userId); + + // Assert + voucher.Should().NotBeNull(); + voucher.OwnerId.Should().Be(userId); + voucher.StatusId.Should().Be(VoucherStatus.Claimed.Id); + campaign.IssuedVouchers.Should().Be(1); + } + + [Fact] + public void IssueVoucher_DraftCampaign_ThrowsException() + { + // Arrange + var campaign = CreateValidCampaign(); + campaign.GenerateVouchers(10); + + // Act & Assert + var act = () => campaign.IssueVoucher(Guid.NewGuid()); + act.Should().Throw(); + } + + [Fact] + public void IssueVoucher_NoAvailableVouchers_ThrowsException() + { + // Arrange + var campaign = new Campaign( + merchantId: Guid.NewGuid(), + name: "Small Campaign", + description: null, + backingAssetType: AssetType.Currency, + backingAssetCode: "VND", + faceValue: 50_000m, + acquisitionType: AcquisitionType.Free, + acquisitionPrice: 0m, + totalVouchers: 1, + startDate: DateTime.UtcNow.AddDays(-1), + endDate: DateTime.UtcNow.AddDays(30), + voucherValidityDays: 30, + maxPerUser: 1); + campaign.SetEscrowHold(Guid.NewGuid(), Guid.NewGuid()); + campaign.GenerateVouchers(1); + campaign.Activate(); + campaign.IssueVoucher(Guid.NewGuid()); // Take the only one + + // Act & Assert + var act = () => campaign.IssueVoucher(Guid.NewGuid()); + act.Should().Throw() + .WithMessage("*voucher*"); + } + + #endregion + + #region Domain Events Tests + + [Fact] + public void Activate_AddsCampaignActivatedDomainEvent() + { + // Arrange + var campaign = CreateValidCampaign(); + campaign.SetEscrowHold(Guid.NewGuid(), Guid.NewGuid()); + + // Act + campaign.Activate(); + + // Assert + campaign.DomainEvents.Should().ContainSingle(e => e is CampaignActivatedDomainEvent); + } + + [Fact] + public void IssueVoucher_AddsVoucherClaimedDomainEvent() + { + // Arrange + var campaign = CreateActiveCampaign(); + campaign.SetEscrowHold(Guid.NewGuid(), Guid.NewGuid()); + campaign.GenerateVouchers(10); + campaign.Activate(); + + // Act + campaign.IssueVoucher(Guid.NewGuid()); + + // Assert + campaign.DomainEvents.Should().Contain(e => e is VoucherClaimedDomainEvent); + } + + #endregion +} diff --git a/services/promotion-service-net/tests/PromotionService.UnitTests/Domain/VoucherEntityTests.cs b/services/promotion-service-net/tests/PromotionService.UnitTests/Domain/VoucherEntityTests.cs new file mode 100644 index 00000000..47cd5395 --- /dev/null +++ b/services/promotion-service-net/tests/PromotionService.UnitTests/Domain/VoucherEntityTests.cs @@ -0,0 +1,199 @@ +using FluentAssertions; +using PromotionService.Domain.AggregatesModel.CampaignAggregate; +using PromotionService.Domain.Exceptions; +using Xunit; + +namespace PromotionService.UnitTests.Domain; + +/// +/// EN: Unit tests for Voucher entity. +/// VI: Unit tests cho Voucher entity. +/// +public class VoucherEntityTests +{ + private const int DefaultValidityDays = 30; + + #region Helper Methods + + private static Voucher CreateAvailableVoucher() => new Voucher( + campaignId: Guid.NewGuid(), + code: "TEST-VOUCHER-001", + faceValue: 100_000m, + validityDays: DefaultValidityDays); + + private static Voucher CreateClaimedVoucher() + { + var voucher = CreateAvailableVoucher(); + voucher.Claim(Guid.NewGuid(), DefaultValidityDays); + return voucher; + } + + #endregion + + #region Constructor Tests + + [Fact] + public void Constructor_ValidParameters_CreatesVoucherInAvailableStatus() + { + // Arrange & Act + var voucher = CreateAvailableVoucher(); + + // Assert + voucher.Id.Should().NotBeEmpty(); + voucher.Code.Should().Be("TEST-VOUCHER-001"); + voucher.FaceValue.Should().Be(100_000m); + voucher.RemainingValue.Should().Be(100_000m); + voucher.StatusId.Should().Be(VoucherStatus.Available.Id); + voucher.OwnerId.Should().BeNull(); + } + + #endregion + + #region Claim Tests + + [Fact] + public void Claim_AvailableVoucher_SetsOwnerAndClaimedStatus() + { + // Arrange + var voucher = CreateAvailableVoucher(); + var userId = Guid.NewGuid(); + + // Act + voucher.Claim(userId, DefaultValidityDays); + + // Assert + voucher.OwnerId.Should().Be(userId); + voucher.StatusId.Should().Be(VoucherStatus.Claimed.Id); + voucher.ClaimedAt.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromSeconds(5)); + voucher.ExpiresAt.Should().BeCloseTo(DateTime.UtcNow.AddDays(DefaultValidityDays), TimeSpan.FromSeconds(5)); + } + + [Fact] + public void Claim_AlreadyClaimedVoucher_ThrowsException() + { + // Arrange + var voucher = CreateClaimedVoucher(); + + // Act & Assert + var act = () => voucher.Claim(Guid.NewGuid(), DefaultValidityDays); + act.Should().Throw(); + } + + #endregion + + #region Redeem Tests + + [Fact] + public void Redeem_FullValue_SetsStatusToFullyRedeemed() + { + // Arrange + var voucher = CreateClaimedVoucher(); + + // Act + voucher.Redeem(100_000m); // Full face value + + // Assert + voucher.RemainingValue.Should().Be(0); + voucher.StatusId.Should().Be(VoucherStatus.FullyRedeemed.Id); + voucher.RedeemedAt.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromSeconds(5)); + } + + [Fact] + public void Redeem_PartialValue_SetsStatusToPartiallyRedeemed() + { + // Arrange + var voucher = CreateClaimedVoucher(); + + // Act + voucher.Redeem(50_000m); // Half + + // Assert + voucher.RemainingValue.Should().Be(50_000m); + voucher.StatusId.Should().Be(VoucherStatus.PartiallyRedeemed.Id); + } + + [Fact] + public void Redeem_MoreThanRemainingValue_CapsAtRemainingValue() + { + // Arrange + var voucher = CreateClaimedVoucher(); + + // Act - Request more than available + var actualRedeemed = voucher.Redeem(150_000m); + + // Assert - Only redeems what's available + actualRedeemed.Should().Be(100_000m); + voucher.RemainingValue.Should().Be(0); + voucher.StatusId.Should().Be(VoucherStatus.FullyRedeemed.Id); + } + + [Fact] + public void Redeem_AvailableVoucher_ThrowsException() + { + // Arrange + var voucher = CreateAvailableVoucher(); // Not claimed + + // Act & Assert + var act = () => voucher.Redeem(50_000m); + act.Should().Throw() + .WithMessage("*not been claimed*"); + } + + #endregion + + #region Expire Tests + + [Fact] + public void Expire_ClaimedVoucher_SetsStatusToExpired() + { + // Arrange + var voucher = CreateClaimedVoucher(); + + // Act + voucher.Expire(); + + // Assert + voucher.StatusId.Should().Be(VoucherStatus.Expired.Id); + } + + [Fact] + public void Expire_FullyRedeemedVoucher_DoesNotChangeStatus() + { + // Arrange + var voucher = CreateClaimedVoucher(); + voucher.Redeem(100_000m); + + // Act + voucher.Expire(); + + // Assert - Status remains FullyRedeemed + voucher.StatusId.Should().Be(VoucherStatus.FullyRedeemed.Id); + } + + #endregion + + #region Validation Tests + + [Fact] + public void IsValidForRedemption_ClaimedNotExpired_ReturnsTrue() + { + // Arrange + var voucher = CreateClaimedVoucher(); + + // Act & Assert + voucher.IsValidForRedemption().Should().BeTrue(); + } + + [Fact] + public void IsValidForRedemption_FullyRedeemed_ReturnsFalse() + { + // Arrange + var voucher = CreateClaimedVoucher(); + voucher.Redeem(100_000m); + + // Act & Assert + voucher.IsValidForRedemption().Should().BeFalse(); + } + + #endregion +} diff --git a/services/promotion-service-net/tests/PromotionService.UnitTests/PromotionService.UnitTests.csproj b/services/promotion-service-net/tests/PromotionService.UnitTests/PromotionService.UnitTests.csproj index f53c5ba1..250f8c06 100644 --- a/services/promotion-service-net/tests/PromotionService.UnitTests/PromotionService.UnitTests.csproj +++ b/services/promotion-service-net/tests/PromotionService.UnitTests/PromotionService.UnitTests.csproj @@ -10,6 +10,7 @@ + runtime; build; native; contentfiles; analyzers; buildtransitive