feat: Implement Zalo and MktX services with API controllers, add web client pages for Auth and Products, and update client navigation and styling.
This commit is contained in:
66
apps/web-client-base-net/Dockerfile
Normal file
66
apps/web-client-base-net/Dockerfile
Normal file
@@ -0,0 +1,66 @@
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# WebClientBase Dockerfile
|
||||
# EN: Multi-stage build for Blazor WebAssembly Hosted
|
||||
# VI: Multi-stage build cho Blazor WebAssembly Hosted
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# Stage 1: Build
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-alpine AS build
|
||||
WORKDIR /src
|
||||
|
||||
# EN: Copy solution and project files for layer caching
|
||||
# VI: Copy solution và project files để cache layers
|
||||
COPY WebClientBase.slnx ./
|
||||
COPY src/WebClientBase.Shared/WebClientBase.Shared.csproj ./src/WebClientBase.Shared/
|
||||
COPY src/WebClientBase.Client/WebClientBase.Client.csproj ./src/WebClientBase.Client/
|
||||
COPY src/WebClientBase.Server/WebClientBase.Server.csproj ./src/WebClientBase.Server/
|
||||
|
||||
# EN: Restore dependencies
|
||||
# VI: Restore dependencies
|
||||
RUN dotnet restore
|
||||
|
||||
# EN: Copy source code
|
||||
# VI: Copy source code
|
||||
COPY . .
|
||||
|
||||
# EN: Build and publish
|
||||
# VI: Build và publish
|
||||
RUN dotnet publish src/WebClientBase.Server/WebClientBase.Server.csproj \
|
||||
-c Release \
|
||||
-o /app/publish \
|
||||
--no-restore
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# Stage 2: Runtime
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine AS runtime
|
||||
WORKDIR /app
|
||||
|
||||
# EN: Create non-root user for security
|
||||
# VI: Tạo user không phải root để bảo mật
|
||||
RUN adduser -D -u 1000 appuser && chown -R appuser /app
|
||||
USER appuser
|
||||
|
||||
# EN: Copy published output
|
||||
# VI: Copy output đã publish
|
||||
COPY --from=build /app/publish .
|
||||
|
||||
# EN: Expose port
|
||||
# VI: Expose port
|
||||
EXPOSE 8080
|
||||
|
||||
# EN: Health check
|
||||
# VI: Health check
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1
|
||||
|
||||
# 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: Run the application
|
||||
# VI: Chạy ứng dụng
|
||||
ENTRYPOINT ["dotnet", "WebClientBase.Server.dll"]
|
||||
116
apps/web-client-base-net/README.md
Normal file
116
apps/web-client-base-net/README.md
Normal file
@@ -0,0 +1,116 @@
|
||||
# WebClientBase - Blazor Web App .NET 10
|
||||
|
||||
Base frontend web application cho GoodGo Platform được xây dựng với Blazor WebAssembly Hosted.
|
||||
|
||||
## Features / Tính năng
|
||||
|
||||
- **Blazor WebAssembly Hosted** - Client chạy trong browser, Server host API
|
||||
- **Shared Library Pattern** - DTOs và Validation được chia sẻ giữa Client và Server
|
||||
- **Data Annotations Validation** - Viết 1 lần, dùng chung cả 2 đầu
|
||||
- **[ApiController] Auto-Validation** - Server tự động validate, không cần `if (!ModelState.IsValid)`
|
||||
- **Dark/Light Mode** - CSS variables với theme toggle
|
||||
- **Glassmorphism UI** - Modern design với backdrop blur và shadows
|
||||
|
||||
## Tech Stack
|
||||
|
||||
| Layer | Technology |
|
||||
|-------|------------|
|
||||
| Client | Blazor WebAssembly (.NET 10) |
|
||||
| Server | ASP.NET Core Web API (.NET 10) |
|
||||
| Shared | Class Library với Data Annotations |
|
||||
| Styling | CSS Variables, Dark Mode |
|
||||
|
||||
## Project Structure / Cấu trúc dự án
|
||||
|
||||
```
|
||||
web-client-base-net/
|
||||
├── WebClientBase.slnx # Solution file
|
||||
├── src/
|
||||
│ ├── WebClientBase.Client/ # Blazor WebAssembly
|
||||
│ │ ├── Layout/ # MainLayout, NavMenu
|
||||
│ │ ├── Pages/ # Razor pages (Products, Auth)
|
||||
│ │ └── wwwroot/css/ # Design System CSS
|
||||
│ ├── WebClientBase.Server/ # ASP.NET Core Host
|
||||
│ │ └── Controllers/ # API Controllers
|
||||
│ └── WebClientBase.Shared/ # Shared Library
|
||||
│ └── DTOs/ # Data Transfer Objects
|
||||
└── Dockerfile
|
||||
```
|
||||
|
||||
## Getting Started / Bắt đầu
|
||||
|
||||
```bash
|
||||
# Navigate to project
|
||||
cd apps/web-client-base-net
|
||||
|
||||
# Restore packages
|
||||
dotnet restore
|
||||
|
||||
# Run Server (hosts both API and Blazor client)
|
||||
dotnet run --project src/WebClientBase.Server
|
||||
|
||||
# Open browser
|
||||
# https://localhost:5001 hoặc http://localhost:5000
|
||||
```
|
||||
|
||||
## Shared Validation Pattern / Mẫu Validation Chia Sẻ
|
||||
|
||||
### 1. Define DTO with Validation (một lần)
|
||||
```csharp
|
||||
// WebClientBase.Shared/DTOs/ProductDto.cs
|
||||
public class ProductDto
|
||||
{
|
||||
[Required(ErrorMessage = "Tên là bắt buộc / Name is required")]
|
||||
[StringLength(100, MinimumLength = 3)]
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
[Range(0.01, 1_000_000)]
|
||||
public decimal Price { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Server (Auto-validation với [ApiController])
|
||||
```csharp
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class ProductsController : ControllerBase
|
||||
{
|
||||
[HttpPost]
|
||||
public IActionResult Create(ProductDto request)
|
||||
{
|
||||
// Không cần if (!ModelState.IsValid) - [ApiController] đã làm hộ
|
||||
return Ok(ApiResponse<ProductDto>.Ok(request));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Client (DataAnnotationsValidator)
|
||||
```razor
|
||||
<EditForm Model="@product" OnValidSubmit="HandleSubmit">
|
||||
<DataAnnotationsValidator />
|
||||
<ValidationSummary />
|
||||
|
||||
<InputText @bind-Value="product.Name" />
|
||||
<ValidationMessage For="() => product.Name" />
|
||||
|
||||
<button type="submit">Submit</button>
|
||||
</EditForm>
|
||||
```
|
||||
|
||||
## API Endpoints
|
||||
|
||||
| Method | Endpoint | Description |
|
||||
|--------|----------|-------------|
|
||||
| GET | `/api/products` | Get all products |
|
||||
| POST | `/api/products` | Create product |
|
||||
| PUT | `/api/products` | Update product |
|
||||
| POST | `/api/auth/register` | Register user |
|
||||
| POST | `/api/auth/login` | Login |
|
||||
| GET | `/api/auth/profile/{id}` | Get profile |
|
||||
| GET | `/health` | Health check |
|
||||
|
||||
## Related Skills
|
||||
|
||||
- [React Enterprise Architect](../../.agent/skills/react-enterprise-architect/SKILL.md)
|
||||
- [Tailwind Design System](../../.agent/skills/tailwind-design-system/SKILL.md)
|
||||
- [Project Rules](../../.agent/skills/project-rules/SKILL.md)
|
||||
@@ -1,16 +1,60 @@
|
||||
@inherits LayoutComponentBase
|
||||
<div class="page">
|
||||
<div class="sidebar">
|
||||
@inject IJSRuntime JS
|
||||
|
||||
@*
|
||||
EN: Main layout with sidebar navigation and theme toggle.
|
||||
VI: Layout chính với sidebar navigation và theme toggle.
|
||||
*@
|
||||
|
||||
<div class="page" data-theme="@currentTheme">
|
||||
<aside class="sidebar">
|
||||
<NavMenu />
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main>
|
||||
<div class="top-row px-4">
|
||||
<a href="https://learn.microsoft.com/aspnet/core/" target="_blank">About</a>
|
||||
</div>
|
||||
<header class="top-row">
|
||||
<button class="theme-toggle" @onclick="ToggleTheme" title="Toggle theme / Đổi theme">
|
||||
@if (currentTheme == "dark")
|
||||
{
|
||||
<span>☀️ Light</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span>🌙 Dark</span>
|
||||
}
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<article class="content px-4">
|
||||
<article class="content">
|
||||
@Body
|
||||
</article>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private string currentTheme = "light";
|
||||
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
if (firstRender)
|
||||
{
|
||||
// EN: Load saved theme from localStorage
|
||||
// VI: Tải theme đã lưu từ localStorage
|
||||
var savedTheme = await JS.InvokeAsync<string>("localStorage.getItem", "theme");
|
||||
if (!string.IsNullOrEmpty(savedTheme))
|
||||
{
|
||||
currentTheme = savedTheme;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ToggleTheme()
|
||||
{
|
||||
currentTheme = currentTheme == "dark" ? "light" : "dark";
|
||||
|
||||
// EN: Save theme to localStorage
|
||||
// VI: Lưu theme vào localStorage
|
||||
await JS.InvokeVoidAsync("localStorage.setItem", "theme", currentTheme);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,39 +1,30 @@
|
||||
<div class="top-row ps-3 navbar navbar-dark">
|
||||
<div class="container-fluid">
|
||||
<a class="navbar-brand" href="">WebClientBase.Client</a>
|
||||
<button title="Navigation menu" class="navbar-toggler" @onclick="ToggleNavMenu">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
</div>
|
||||
@*
|
||||
EN: Navigation menu with Products and Auth links.
|
||||
VI: Menu navigation với các link Products và Auth.
|
||||
*@
|
||||
|
||||
<div class="nav-brand">
|
||||
GoodGo
|
||||
</div>
|
||||
|
||||
<div class="@NavMenuCssClass nav-scrollable" @onclick="ToggleNavMenu">
|
||||
<nav class="nav flex-column">
|
||||
<div class="nav-item px-3">
|
||||
<NavLink class="nav-link" href="" Match="NavLinkMatch.All">
|
||||
<span class="bi bi-house-door-fill-nav-menu" aria-hidden="true"></span> Home
|
||||
</NavLink>
|
||||
</div>
|
||||
<div class="nav-item px-3">
|
||||
<NavLink class="nav-link" href="counter">
|
||||
<span class="bi bi-plus-square-fill-nav-menu" aria-hidden="true"></span> Counter
|
||||
</NavLink>
|
||||
</div>
|
||||
<div class="nav-item px-3">
|
||||
<NavLink class="nav-link" href="weather">
|
||||
<span class="bi bi-list-nested-nav-menu" aria-hidden="true"></span> Weather
|
||||
</NavLink>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private bool collapseNavMenu = true;
|
||||
|
||||
private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null;
|
||||
|
||||
private void ToggleNavMenu()
|
||||
{
|
||||
collapseNavMenu = !collapseNavMenu;
|
||||
}
|
||||
}
|
||||
<nav class="nav-menu">
|
||||
<NavLink class="nav-link" href="" Match="NavLinkMatch.All">
|
||||
<span>🏠</span> Home
|
||||
</NavLink>
|
||||
|
||||
<NavLink class="nav-link" href="products">
|
||||
<span>📦</span> Products / Sản phẩm
|
||||
</NavLink>
|
||||
|
||||
<NavLink class="nav-link" href="auth">
|
||||
<span>🔐</span> Auth / Xác thực
|
||||
</NavLink>
|
||||
|
||||
<NavLink class="nav-link" href="counter">
|
||||
<span>➕</span> Counter
|
||||
</NavLink>
|
||||
|
||||
<NavLink class="nav-link" href="weather">
|
||||
<span>🌤️</span> Weather
|
||||
</NavLink>
|
||||
</nav>
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
@page "/auth"
|
||||
@inject HttpClient Http
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
@*
|
||||
EN: Authentication page with Register and Login forms.
|
||||
VI: Trang xác thực với form Đăng ký và Đăng nhập.
|
||||
*@
|
||||
|
||||
<PageTitle>Authentication / Xác thực</PageTitle>
|
||||
|
||||
<div class="auth-container">
|
||||
<div class="auth-tabs">
|
||||
<button class="tab-btn @(activeTab == "login" ? "active" : "")" @onclick="@(() => activeTab = "login")">
|
||||
Login / Đăng nhập
|
||||
</button>
|
||||
<button class="tab-btn @(activeTab == "register" ? "active" : "")" @onclick="@(() => activeTab = "register")">
|
||||
Register / Đăng ký
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@* ═══════════════════════════════════════════════════════════════════════════════
|
||||
EN: Login Form
|
||||
VI: Form đăng nhập
|
||||
═══════════════════════════════════════════════════════════════════════════════ *@
|
||||
@if (activeTab == "login")
|
||||
{
|
||||
<section class="glass-card auth-card">
|
||||
<h2>Welcome Back / Chào mừng trở lại</h2>
|
||||
<p class="subtitle">Sign in to your account / Đăng nhập vào tài khoản</p>
|
||||
|
||||
<EditForm Model="@loginModel" OnValidSubmit="HandleLogin" FormName="Login">
|
||||
<DataAnnotationsValidator />
|
||||
|
||||
<div class="form-group">
|
||||
<label for="login-email">Email *</label>
|
||||
<InputText id="login-email" @bind-Value="loginModel.Email" class="form-input" placeholder="email@example.com" />
|
||||
<ValidationMessage For="() => loginModel.Email" class="validation-message" />
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="login-password">Password / Mật khẩu *</label>
|
||||
<InputText id="login-password" @bind-Value="loginModel.Password" type="password" class="form-input" placeholder="••••••••" />
|
||||
<ValidationMessage For="() => loginModel.Password" class="validation-message" />
|
||||
</div>
|
||||
|
||||
<div class="form-group checkbox-group">
|
||||
<InputCheckbox id="remember-me" @bind-Value="loginModel.RememberMe" class="form-checkbox" />
|
||||
<label for="remember-me">Remember me / Ghi nhớ đăng nhập</label>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary btn-full" disabled="@isSubmitting">
|
||||
@if (isSubmitting)
|
||||
{
|
||||
<span class="spinner"></span>
|
||||
}
|
||||
Sign In / Đăng nhập
|
||||
</button>
|
||||
</EditForm>
|
||||
</section>
|
||||
}
|
||||
|
||||
@* ═══════════════════════════════════════════════════════════════════════════════
|
||||
EN: Register Form
|
||||
VI: Form đăng ký
|
||||
═══════════════════════════════════════════════════════════════════════════════ *@
|
||||
@if (activeTab == "register")
|
||||
{
|
||||
<section class="glass-card auth-card">
|
||||
<h2>Create Account / Tạo tài khoản</h2>
|
||||
<p class="subtitle">Join us today / Tham gia với chúng tôi</p>
|
||||
|
||||
<EditForm Model="@registerModel" OnValidSubmit="HandleRegister" FormName="Register">
|
||||
<DataAnnotationsValidator />
|
||||
<ValidationSummary class="validation-summary" />
|
||||
|
||||
<div class="form-group">
|
||||
<label for="reg-name">Display Name / Tên hiển thị *</label>
|
||||
<InputText id="reg-name" @bind-Value="registerModel.DisplayName" class="form-input" placeholder="John Doe" />
|
||||
<ValidationMessage For="() => registerModel.DisplayName" class="validation-message" />
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="reg-email">Email *</label>
|
||||
<InputText id="reg-email" @bind-Value="registerModel.Email" class="form-input" placeholder="email@example.com" />
|
||||
<ValidationMessage For="() => registerModel.Email" class="validation-message" />
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="reg-password">Password / Mật khẩu *</label>
|
||||
<InputText id="reg-password" @bind-Value="registerModel.Password" type="password" class="form-input" placeholder="••••••••" />
|
||||
<ValidationMessage For="() => registerModel.Password" class="validation-message" />
|
||||
<small class="form-hint">Min 8 chars, uppercase, lowercase, digit / Tối thiểu 8 ký tự, chữ hoa, chữ thường, số</small>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="reg-confirm">Confirm Password / Xác nhận mật khẩu *</label>
|
||||
<InputText id="reg-confirm" @bind-Value="registerModel.ConfirmPassword" type="password" class="form-input" placeholder="••••••••" />
|
||||
<ValidationMessage For="() => registerModel.ConfirmPassword" class="validation-message" />
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary btn-full" disabled="@isSubmitting">
|
||||
@if (isSubmitting)
|
||||
{
|
||||
<span class="spinner"></span>
|
||||
}
|
||||
Create Account / Tạo tài khoản
|
||||
</button>
|
||||
</EditForm>
|
||||
</section>
|
||||
}
|
||||
|
||||
@if (!string.IsNullOrEmpty(message))
|
||||
{
|
||||
<div class="alert @(success ? "alert-success" : "alert-error")">
|
||||
@message
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private string activeTab = "login";
|
||||
private LoginDto loginModel = new();
|
||||
private RegisterDto registerModel = new();
|
||||
private bool isSubmitting = false;
|
||||
private string message = "";
|
||||
private bool success = false;
|
||||
|
||||
private async Task HandleLogin()
|
||||
{
|
||||
isSubmitting = true;
|
||||
message = "";
|
||||
|
||||
try
|
||||
{
|
||||
var response = await Http.PostAsJsonAsync("api/Auth/login", loginModel);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var result = await response.Content.ReadFromJsonAsync<ApiResponse<UserProfileDto>>();
|
||||
if (result?.Success == true)
|
||||
{
|
||||
success = true;
|
||||
message = $"Welcome back, {result.Data?.DisplayName}! / Chào mừng trở lại, {result.Data?.DisplayName}!";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
success = false;
|
||||
message = "Login failed. Please check your credentials. / Đăng nhập thất bại.";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
success = false;
|
||||
message = $"Error: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
isSubmitting = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleRegister()
|
||||
{
|
||||
isSubmitting = true;
|
||||
message = "";
|
||||
|
||||
try
|
||||
{
|
||||
var response = await Http.PostAsJsonAsync("api/Auth/register", registerModel);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var result = await response.Content.ReadFromJsonAsync<ApiResponse<UserProfileDto>>();
|
||||
if (result?.Success == true)
|
||||
{
|
||||
success = true;
|
||||
message = "Account created successfully! / Tạo tài khoản thành công!";
|
||||
activeTab = "login";
|
||||
registerModel = new();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
success = false;
|
||||
var content = await response.Content.ReadAsStringAsync();
|
||||
message = $"Registration failed: {content}";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
success = false;
|
||||
message = $"Error: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
isSubmitting = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
@page "/products"
|
||||
@inject HttpClient Http
|
||||
|
||||
@*
|
||||
EN: Products page demonstrating shared validation between Client and Server.
|
||||
VI: Trang sản phẩm demo validation được chia sẻ giữa Client và Server.
|
||||
*@
|
||||
|
||||
<PageTitle>Products / Sản phẩm</PageTitle>
|
||||
|
||||
<div class="container">
|
||||
<h1 class="page-title">Products Management / Quản lý sản phẩm</h1>
|
||||
|
||||
@* ═══════════════════════════════════════════════════════════════════════════════
|
||||
EN: Create Product Form with shared validation
|
||||
VI: Form tạo sản phẩm với validation được chia sẻ
|
||||
═══════════════════════════════════════════════════════════════════════════════ *@
|
||||
<section class="glass-card">
|
||||
<h2>Create Product / Tạo sản phẩm</h2>
|
||||
|
||||
<EditForm Model="@newProduct" OnValidSubmit="HandleSubmit" OnInvalidSubmit="HandleInvalid" FormName="CreateProduct">
|
||||
@* EN: DataAnnotationsValidator uses the same validation rules as the Server
|
||||
VI: DataAnnotationsValidator sử dụng cùng validation rules với Server *@
|
||||
<DataAnnotationsValidator />
|
||||
|
||||
@* EN: Display all validation errors
|
||||
VI: Hiển thị tất cả lỗi validation *@
|
||||
<ValidationSummary class="validation-summary" />
|
||||
|
||||
<div class="form-group">
|
||||
<label for="name">Product Name / Tên sản phẩm *</label>
|
||||
<InputText id="name" @bind-Value="newProduct.Name" class="form-input" placeholder="Enter product name..." />
|
||||
<ValidationMessage For="() => newProduct.Name" class="validation-message" />
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="description">Description / Mô tả</label>
|
||||
<InputTextArea id="description" @bind-Value="newProduct.Description" class="form-input" rows="3" placeholder="Enter description..." />
|
||||
<ValidationMessage For="() => newProduct.Description" class="validation-message" />
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<div class="form-group">
|
||||
<label for="price">Price / Giá *</label>
|
||||
<InputNumber id="price" @bind-Value="newProduct.Price" class="form-input" placeholder="0.00" />
|
||||
<ValidationMessage For="() => newProduct.Price" class="validation-message" />
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="quantity">Quantity / Số lượng</label>
|
||||
<InputNumber id="quantity" @bind-Value="newProduct.Quantity" class="form-input" placeholder="0" />
|
||||
<ValidationMessage For="() => newProduct.Quantity" class="validation-message" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="category">Category ID / ID Danh mục *</label>
|
||||
<InputText id="category" @bind-Value="categoryIdString" class="form-input" placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" />
|
||||
<ValidationMessage For="() => newProduct.CategoryId" class="validation-message" />
|
||||
</div>
|
||||
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn btn-primary" disabled="@isSubmitting">
|
||||
@if (isSubmitting)
|
||||
{
|
||||
<span class="spinner"></span>
|
||||
<span>Submitting...</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span>Create Product / Tạo sản phẩm</span>
|
||||
}
|
||||
</button>
|
||||
<button type="button" class="btn btn-secondary" @onclick="ResetForm">Reset</button>
|
||||
</div>
|
||||
</EditForm>
|
||||
|
||||
@if (!string.IsNullOrEmpty(submitMessage))
|
||||
{
|
||||
<div class="alert @(submitSuccess ? "alert-success" : "alert-error")">
|
||||
@submitMessage
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
@* ═══════════════════════════════════════════════════════════════════════════════
|
||||
EN: Product List
|
||||
VI: Danh sách sản phẩm
|
||||
═══════════════════════════════════════════════════════════════════════════════ *@
|
||||
<section class="glass-card">
|
||||
<h2>Product List / Danh sách sản phẩm</h2>
|
||||
|
||||
@if (products == null)
|
||||
{
|
||||
<p class="loading">Loading products... / Đang tải sản phẩm...</p>
|
||||
}
|
||||
else if (!products.Any())
|
||||
{
|
||||
<p class="empty-state">No products found. / Không tìm thấy sản phẩm.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="product-grid">
|
||||
@foreach (var product in products)
|
||||
{
|
||||
<div class="product-card">
|
||||
<h3>@product.Name</h3>
|
||||
<p class="description">@(product.Description ?? "No description")</p>
|
||||
<div class="product-details">
|
||||
<span class="price">@product.Price.ToString("C")</span>
|
||||
<span class="quantity">Stock: @product.Quantity</span>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private CreateProductDto newProduct = new();
|
||||
private List<ProductDto>? products;
|
||||
private bool isSubmitting = false;
|
||||
private string submitMessage = "";
|
||||
private bool submitSuccess = false;
|
||||
private string categoryIdString = "";
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await LoadProducts();
|
||||
}
|
||||
|
||||
private async Task LoadProducts()
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await Http.GetFromJsonAsync<ApiResponse<List<ProductDto>>>("api/Products");
|
||||
if (response?.Success == true)
|
||||
{
|
||||
products = response.Data ?? new List<ProductDto>();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"Error loading products: {ex.Message}");
|
||||
products = new List<ProductDto>();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleSubmit()
|
||||
{
|
||||
isSubmitting = true;
|
||||
submitMessage = "";
|
||||
|
||||
// Parse category ID
|
||||
if (Guid.TryParse(categoryIdString, out var categoryId))
|
||||
{
|
||||
newProduct.CategoryId = categoryId;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var response = await Http.PostAsJsonAsync("api/Products", newProduct);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
submitSuccess = true;
|
||||
submitMessage = "Product created successfully! / Tạo sản phẩm thành công!";
|
||||
ResetForm();
|
||||
await LoadProducts();
|
||||
}
|
||||
else
|
||||
{
|
||||
submitSuccess = false;
|
||||
var content = await response.Content.ReadAsStringAsync();
|
||||
submitMessage = $"Error: {response.StatusCode} - {content}";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
submitSuccess = false;
|
||||
submitMessage = $"Error: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
isSubmitting = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleInvalid()
|
||||
{
|
||||
submitMessage = "Please fix the validation errors. / Vui lòng sửa các lỗi validation.";
|
||||
submitSuccess = false;
|
||||
}
|
||||
|
||||
private void ResetForm()
|
||||
{
|
||||
newProduct = new CreateProductDto();
|
||||
categoryIdString = "";
|
||||
}
|
||||
}
|
||||
@@ -8,3 +8,6 @@
|
||||
@using Microsoft.JSInterop
|
||||
@using WebClientBase.Client
|
||||
@using WebClientBase.Client.Layout
|
||||
@using WebClientBase.Shared
|
||||
@using WebClientBase.Shared.DTOs
|
||||
|
||||
|
||||
@@ -1,115 +1,553 @@
|
||||
html, body {
|
||||
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
WebClientBase Design System
|
||||
EN: GoodGo branding with Dark/Light mode support
|
||||
VI: GoodGo branding với hỗ trợ Dark/Light mode
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
CSS Variables / Biến CSS
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
:root {
|
||||
/* Light Mode Colors */
|
||||
--bg-primary: #ffffff;
|
||||
--bg-secondary: #f5f5f7;
|
||||
--bg-tertiary: #e5e5ea;
|
||||
--bg-elevated: #ffffff;
|
||||
|
||||
--text-primary: #1d1d1f;
|
||||
--text-secondary: #6e6e73;
|
||||
--text-tertiary: #8e8e93;
|
||||
|
||||
--accent-primary: #3b82f6;
|
||||
--accent-primary-hover: #2563eb;
|
||||
--accent-success: #22c55e;
|
||||
--accent-warning: #f59e0b;
|
||||
--accent-error: #ef4444;
|
||||
|
||||
--border-default: rgba(0, 0, 0, 0.1);
|
||||
--border-strong: rgba(0, 0, 0, 0.2);
|
||||
|
||||
/* Glass Effects */
|
||||
--glass-bg: rgba(255, 255, 255, 0.7);
|
||||
--glass-border: rgba(255, 255, 255, 0.3);
|
||||
--glass-blur: 20px;
|
||||
--glass-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
|
||||
|
||||
/* Brand */
|
||||
--brand-gradient: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
|
||||
|
||||
/* Typography */
|
||||
--font-sans: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
--font-mono: 'JetBrains Mono', 'SF Mono', monospace;
|
||||
|
||||
--text-xs: 0.75rem;
|
||||
--text-sm: 0.875rem;
|
||||
--text-base: 1rem;
|
||||
--text-lg: 1.125rem;
|
||||
--text-xl: 1.25rem;
|
||||
--text-2xl: 1.5rem;
|
||||
--text-3xl: 1.875rem;
|
||||
|
||||
/* Spacing */
|
||||
--space-1: 0.25rem;
|
||||
--space-2: 0.5rem;
|
||||
--space-3: 0.75rem;
|
||||
--space-4: 1rem;
|
||||
--space-6: 1.5rem;
|
||||
--space-8: 2rem;
|
||||
--space-12: 3rem;
|
||||
|
||||
/* Border Radius */
|
||||
--radius-sm: 0.25rem;
|
||||
--radius-md: 0.5rem;
|
||||
--radius-lg: 0.75rem;
|
||||
--radius-xl: 1rem;
|
||||
--radius-full: 9999px;
|
||||
|
||||
/* Transitions */
|
||||
--transition-fast: 150ms ease;
|
||||
--transition-normal: 250ms ease;
|
||||
|
||||
/* Sidebar */
|
||||
--sidebar-width: 280px;
|
||||
}
|
||||
|
||||
h1:focus {
|
||||
outline: none;
|
||||
/* Dark Mode */
|
||||
[data-theme="dark"] {
|
||||
--bg-primary: #000000;
|
||||
--bg-secondary: #1c1c1e;
|
||||
--bg-tertiary: #2c2c2e;
|
||||
--bg-elevated: #1c1c1e;
|
||||
|
||||
--text-primary: #f5f5f7;
|
||||
--text-secondary: #a1a1a6;
|
||||
--text-tertiary: #6e6e73;
|
||||
|
||||
--border-default: rgba(255, 255, 255, 0.1);
|
||||
--border-strong: rgba(255, 255, 255, 0.2);
|
||||
|
||||
--glass-bg: rgba(28, 28, 30, 0.8);
|
||||
--glass-border: rgba(255, 255, 255, 0.1);
|
||||
--glass-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
|
||||
a, .btn-link {
|
||||
color: #0071c1;
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
Base Styles
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
color: #fff;
|
||||
background-color: #1b6ec2;
|
||||
border-color: #1861ac;
|
||||
html {
|
||||
font-size: 16px;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
.btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus {
|
||||
box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb;
|
||||
body {
|
||||
font-family: var(--font-sans);
|
||||
background: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
line-height: 1.5;
|
||||
transition: background-color var(--transition-normal), color var(--transition-normal);
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
Layout
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
.page {
|
||||
display: flex;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
width: var(--sidebar-width);
|
||||
background: var(--bg-secondary);
|
||||
border-right: 1px solid var(--border-default);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
main {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.top-row {
|
||||
background: var(--bg-elevated);
|
||||
border-bottom: 1px solid var(--border-default);
|
||||
padding: var(--space-4);
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.content {
|
||||
padding-top: 1.1rem;
|
||||
flex: 1;
|
||||
padding: var(--space-6);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.valid.modified:not([type=checkbox]) {
|
||||
outline: 1px solid #26b050;
|
||||
.container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.invalid {
|
||||
outline: 1px solid red;
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
Navigation
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
.nav-brand {
|
||||
padding: var(--space-6) var(--space-4);
|
||||
font-size: var(--text-xl);
|
||||
font-weight: 700;
|
||||
background: var(--brand-gradient);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
.validation-message {
|
||||
color: red;
|
||||
.nav-menu {
|
||||
padding: var(--space-4);
|
||||
}
|
||||
|
||||
#blazor-error-ui {
|
||||
color-scheme: light only;
|
||||
background: lightyellow;
|
||||
bottom: 0;
|
||||
box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2);
|
||||
box-sizing: border-box;
|
||||
display: none;
|
||||
left: 0;
|
||||
padding: 0.6rem 1.25rem 0.7rem 1.25rem;
|
||||
position: fixed;
|
||||
width: 100%;
|
||||
z-index: 1000;
|
||||
.nav-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
color: var(--text-secondary);
|
||||
text-decoration: none;
|
||||
border-radius: var(--radius-lg);
|
||||
transition: all var(--transition-fast);
|
||||
}
|
||||
|
||||
#blazor-error-ui .dismiss {
|
||||
cursor: pointer;
|
||||
position: absolute;
|
||||
right: 0.75rem;
|
||||
top: 0.5rem;
|
||||
}
|
||||
.nav-link:hover {
|
||||
background: var(--bg-tertiary);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.blazor-error-boundary {
|
||||
background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121;
|
||||
padding: 1rem 1rem 1rem 3.7rem;
|
||||
.nav-link.active {
|
||||
background: var(--accent-primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.blazor-error-boundary::after {
|
||||
content: "An error has occurred."
|
||||
}
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
Glass Card
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
.glass-card {
|
||||
background: var(--glass-bg);
|
||||
backdrop-filter: blur(var(--glass-blur));
|
||||
-webkit-backdrop-filter: blur(var(--glass-blur));
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: var(--radius-xl);
|
||||
padding: var(--space-6);
|
||||
box-shadow: var(--glass-shadow);
|
||||
margin-bottom: var(--space-6);
|
||||
}
|
||||
|
||||
.loading-progress {
|
||||
position: absolute;
|
||||
.glass-card h2 {
|
||||
margin: 0 0 var(--space-4);
|
||||
font-size: var(--text-xl);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
Forms
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
.form-group {
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
width: 8rem;
|
||||
height: 8rem;
|
||||
inset: 20vh 0 auto 0;
|
||||
margin: 0 auto 0 auto;
|
||||
margin-bottom: var(--space-2);
|
||||
font-size: var(--text-sm);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.loading-progress circle {
|
||||
fill: none;
|
||||
stroke: #e0e0e0;
|
||||
stroke-width: 0.6rem;
|
||||
transform-origin: 50% 50%;
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
.form-input {
|
||||
width: 100%;
|
||||
padding: var(--space-3) var(--space-4);
|
||||
font-size: var(--text-base);
|
||||
font-family: var(--font-sans);
|
||||
background: var(--bg-primary);
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: var(--radius-md);
|
||||
color: var(--text-primary);
|
||||
transition: border-color var(--transition-fast), box-shadow var(--transition-fast);
|
||||
}
|
||||
|
||||
.loading-progress circle:last-child {
|
||||
stroke: #1b6ec2;
|
||||
stroke-dasharray: calc(3.141 * var(--blazor-load-percentage, 0%) * 0.8), 500%;
|
||||
transition: stroke-dasharray 0.05s ease-in-out;
|
||||
}
|
||||
.form-input:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent-primary);
|
||||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
|
||||
}
|
||||
|
||||
.loading-progress-text {
|
||||
position: absolute;
|
||||
.form-input::placeholder {
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.form-input.invalid,
|
||||
.form-input:invalid {
|
||||
border-color: var(--accent-error);
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.form-hint {
|
||||
display: block;
|
||||
margin-top: var(--space-1);
|
||||
font-size: var(--text-xs);
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
display: flex;
|
||||
gap: var(--space-3);
|
||||
margin-top: var(--space-6);
|
||||
}
|
||||
|
||||
.checkbox-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.checkbox-group label {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
Buttons
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-3) var(--space-6);
|
||||
font-size: var(--text-base);
|
||||
font-weight: 500;
|
||||
font-family: var(--font-sans);
|
||||
border: none;
|
||||
border-radius: var(--radius-md);
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
}
|
||||
|
||||
.btn:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--brand-gradient);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover:not(:disabled) {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: var(--bg-tertiary);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.btn-secondary:hover:not(:disabled) {
|
||||
background: var(--bg-secondary);
|
||||
}
|
||||
|
||||
.btn-full {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
Validation
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
.validation-summary {
|
||||
background: rgba(239, 68, 68, 0.1);
|
||||
border: 1px solid var(--accent-error);
|
||||
border-radius: var(--radius-md);
|
||||
padding: var(--space-4);
|
||||
margin-bottom: var(--space-4);
|
||||
color: var(--accent-error);
|
||||
}
|
||||
|
||||
.validation-summary ul {
|
||||
margin: 0;
|
||||
padding-left: var(--space-4);
|
||||
}
|
||||
|
||||
.validation-message {
|
||||
display: block;
|
||||
margin-top: var(--space-1);
|
||||
font-size: var(--text-xs);
|
||||
color: var(--accent-error);
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
Alerts
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
.alert {
|
||||
padding: var(--space-4);
|
||||
border-radius: var(--radius-md);
|
||||
margin-top: var(--space-4);
|
||||
}
|
||||
|
||||
.alert-success {
|
||||
background: rgba(34, 197, 94, 0.1);
|
||||
border: 1px solid var(--accent-success);
|
||||
color: var(--accent-success);
|
||||
}
|
||||
|
||||
.alert-error {
|
||||
background: rgba(239, 68, 68, 0.1);
|
||||
border: 1px solid var(--accent-error);
|
||||
color: var(--accent-error);
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
Product Grid
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
.product-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.product-card {
|
||||
background: var(--bg-elevated);
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: var(--radius-lg);
|
||||
padding: var(--space-4);
|
||||
transition: all var(--transition-fast);
|
||||
}
|
||||
|
||||
.product-card:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: var(--glass-shadow);
|
||||
}
|
||||
|
||||
.product-card h3 {
|
||||
margin: 0 0 var(--space-2);
|
||||
font-size: var(--text-lg);
|
||||
}
|
||||
|
||||
.product-card .description {
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--text-sm);
|
||||
margin-bottom: var(--space-3);
|
||||
}
|
||||
|
||||
.product-details {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.product-details .price {
|
||||
font-weight: 600;
|
||||
color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.product-details .quantity {
|
||||
font-size: var(--text-sm);
|
||||
color: var(--text-tertiary);
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
Auth
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
.auth-container {
|
||||
max-width: 400px;
|
||||
margin: var(--space-12) auto;
|
||||
}
|
||||
|
||||
.auth-tabs {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
|
||||
.tab-btn {
|
||||
flex: 1;
|
||||
padding: var(--space-3);
|
||||
font-size: var(--text-base);
|
||||
font-weight: 500;
|
||||
background: var(--bg-tertiary);
|
||||
border: none;
|
||||
border-radius: var(--radius-md);
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
}
|
||||
|
||||
.tab-btn.active {
|
||||
background: var(--accent-primary);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.auth-card .subtitle {
|
||||
color: var(--text-secondary);
|
||||
margin-bottom: var(--space-6);
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
Page Title
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
.page-title {
|
||||
font-size: var(--text-2xl);
|
||||
font-weight: 700;
|
||||
margin-bottom: var(--space-6);
|
||||
background: var(--brand-gradient);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
Theme Toggle
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
.theme-toggle {
|
||||
padding: var(--space-2) var(--space-3);
|
||||
background: var(--bg-tertiary);
|
||||
border: 1px solid var(--border-default);
|
||||
border-radius: var(--radius-full);
|
||||
color: var(--text-primary);
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-fast);
|
||||
}
|
||||
|
||||
.theme-toggle:hover {
|
||||
background: var(--bg-secondary);
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
Loading & States
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
.loading {
|
||||
text-align: center;
|
||||
font-weight: bold;
|
||||
inset: calc(20vh + 3.25rem) 0 auto 0.2rem;
|
||||
color: var(--text-secondary);
|
||||
padding: var(--space-8);
|
||||
}
|
||||
|
||||
.loading-progress-text:after {
|
||||
content: var(--blazor-load-percentage-text, "Loading");
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
color: var(--text-tertiary);
|
||||
padding: var(--space-8);
|
||||
}
|
||||
|
||||
.spinner {
|
||||
display: inline-block;
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
border: 2px solid currentColor;
|
||||
border-right-color: transparent;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.75s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════════
|
||||
Responsive
|
||||
═══════════════════════════════════════════════════════════════════════════════ */
|
||||
@media (max-width: 768px) {
|
||||
.sidebar {
|
||||
position: fixed;
|
||||
left: -100%;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
z-index: 100;
|
||||
transition: left var(--transition-normal);
|
||||
}
|
||||
|
||||
code {
|
||||
color: #c02d76;
|
||||
}
|
||||
.sidebar.open {
|
||||
left: 0;
|
||||
}
|
||||
|
||||
.form-floating > .form-control-plaintext::placeholder, .form-floating > .form-control::placeholder {
|
||||
color: var(--bs-secondary-color);
|
||||
text-align: end;
|
||||
}
|
||||
.form-row {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.form-floating > .form-control-plaintext:focus::placeholder, .form-floating > .form-control:focus::placeholder {
|
||||
text-align: start;
|
||||
.content {
|
||||
padding: var(--space-4);
|
||||
}
|
||||
}
|
||||
@@ -4,31 +4,51 @@
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>WebClientBase.Client</title>
|
||||
<title>GoodGo Web Client Base</title>
|
||||
<base href="/" />
|
||||
<link rel="preload" id="webassembly" />
|
||||
<link rel="stylesheet" href="lib/bootstrap/dist/css/bootstrap.min.css" />
|
||||
|
||||
<!-- EN: Google Fonts - Inter for modern typography -->
|
||||
<!-- VI: Google Fonts - Inter cho typography hiện đại -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||
|
||||
<!-- EN: Design System CSS -->
|
||||
<!-- VI: CSS Design System -->
|
||||
<link rel="stylesheet" href="css/app.css" />
|
||||
<link rel="icon" type="image/png" href="favicon.png" />
|
||||
<link href="WebClientBase.Client.styles.css" rel="stylesheet" />
|
||||
<script type="importmap"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="app">
|
||||
<svg class="loading-progress">
|
||||
<circle r="40%" cx="50%" cy="50%" />
|
||||
<circle r="40%" cx="50%" cy="50%" />
|
||||
</svg>
|
||||
<div class="loading-progress-text"></div>
|
||||
<!-- EN: Loading indicator -->
|
||||
<!-- VI: Chỉ báo đang tải -->
|
||||
<div style="display: flex; justify-content: center; align-items: center; height: 100vh; flex-direction: column; gap: 1rem;">
|
||||
<svg class="loading-progress" width="80" height="80" viewBox="0 0 80 80">
|
||||
<circle cx="40" cy="40" r="32" fill="none" stroke="#e5e5ea" stroke-width="4" />
|
||||
<circle cx="40" cy="40" r="32" fill="none" stroke="#3b82f6" stroke-width="4"
|
||||
stroke-dasharray="200" stroke-dashoffset="60"
|
||||
style="animation: spin 1s linear infinite; transform-origin: center;">
|
||||
</circle>
|
||||
</svg>
|
||||
<p style="color: #6e6e73; font-family: Inter, sans-serif;">Loading GoodGo... / Đang tải...</p>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
</style>
|
||||
</div>
|
||||
|
||||
<div id="blazor-error-ui">
|
||||
An unhandled error has occurred.
|
||||
<a href="." class="reload">Reload</a>
|
||||
<span class="dismiss">🗙</span>
|
||||
<div id="blazor-error-ui" style="display: none; position: fixed; bottom: 0; left: 0; right: 0; padding: 1rem; background: #ef4444; color: white; text-align: center;">
|
||||
An unhandled error has occurred. / Đã xảy ra lỗi.
|
||||
<a href="." class="reload" style="color: white; text-decoration: underline; margin-left: 1rem;">Reload / Tải lại</a>
|
||||
<span class="dismiss" style="cursor: pointer; margin-left: 1rem;">✕</span>
|
||||
</div>
|
||||
<script src="_framework/blazor.webassembly#[.{fingerprint}].js"></script>
|
||||
|
||||
<script src="_framework/blazor.webassembly.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
using MediatR;
|
||||
using MktXService.Domain.AggregatesModel.CampaignAggregate;
|
||||
|
||||
namespace MktXService.API.Application.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for CreateCampaignCommand.
|
||||
/// VI: Handler cho CreateCampaignCommand.
|
||||
/// </summary>
|
||||
public class CreateCampaignCommandHandler : IRequestHandler<CreateCampaignCommand, CreateCampaignResult>
|
||||
{
|
||||
private readonly ICampaignRepository _campaignRepository;
|
||||
private readonly ILogger<CreateCampaignCommandHandler> _logger;
|
||||
|
||||
public CreateCampaignCommandHandler(
|
||||
ICampaignRepository campaignRepository,
|
||||
ILogger<CreateCampaignCommandHandler> logger)
|
||||
{
|
||||
_campaignRepository = campaignRepository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<CreateCampaignResult> Handle(
|
||||
CreateCampaignCommand request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("Creating campaign {Name} for merchant {MerchantId}",
|
||||
request.Name, request.MerchantId);
|
||||
|
||||
try
|
||||
{
|
||||
var campaign = new Campaign(
|
||||
request.MerchantId,
|
||||
request.Name,
|
||||
request.Type,
|
||||
request.TemplateId);
|
||||
|
||||
// EN: Add segments to campaign
|
||||
// VI: Thêm segments vào chiến dịch
|
||||
foreach (var segmentId in request.SegmentIds)
|
||||
{
|
||||
campaign.AddSegment(segmentId);
|
||||
}
|
||||
|
||||
// EN: Set schedule if provided
|
||||
// VI: Thiết lập lịch trình nếu có
|
||||
if (request.Schedule != null)
|
||||
{
|
||||
campaign.SetSchedule(request.Schedule);
|
||||
}
|
||||
|
||||
_campaignRepository.Add(campaign);
|
||||
await _campaignRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation("Campaign {CampaignId} created successfully", campaign.Id);
|
||||
return new CreateCampaignResult(true, campaign.Id, null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to create campaign {Name}", request.Name);
|
||||
return new CreateCampaignResult(false, null, ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for StartCampaignCommand.
|
||||
/// VI: Handler cho StartCampaignCommand.
|
||||
/// </summary>
|
||||
public class StartCampaignCommandHandler : IRequestHandler<StartCampaignCommand, bool>
|
||||
{
|
||||
private readonly ICampaignRepository _campaignRepository;
|
||||
private readonly ILogger<StartCampaignCommandHandler> _logger;
|
||||
|
||||
public StartCampaignCommandHandler(
|
||||
ICampaignRepository campaignRepository,
|
||||
ILogger<StartCampaignCommandHandler> logger)
|
||||
{
|
||||
_campaignRepository = campaignRepository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<bool> Handle(StartCampaignCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var campaign = await _campaignRepository.GetByIdAsync(request.CampaignId);
|
||||
if (campaign == null) return false;
|
||||
|
||||
campaign.Start();
|
||||
await _campaignRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation("Campaign {CampaignId} started", request.CampaignId);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for PauseCampaignCommand.
|
||||
/// VI: Handler cho PauseCampaignCommand.
|
||||
/// </summary>
|
||||
public class PauseCampaignCommandHandler : IRequestHandler<PauseCampaignCommand, bool>
|
||||
{
|
||||
private readonly ICampaignRepository _campaignRepository;
|
||||
private readonly ILogger<PauseCampaignCommandHandler> _logger;
|
||||
|
||||
public PauseCampaignCommandHandler(
|
||||
ICampaignRepository campaignRepository,
|
||||
ILogger<PauseCampaignCommandHandler> logger)
|
||||
{
|
||||
_campaignRepository = campaignRepository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<bool> Handle(PauseCampaignCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var campaign = await _campaignRepository.GetByIdAsync(request.CampaignId);
|
||||
if (campaign == null) return false;
|
||||
|
||||
campaign.Pause();
|
||||
await _campaignRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation("Campaign {CampaignId} paused", request.CampaignId);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for ResumeCampaignCommand.
|
||||
/// VI: Handler cho ResumeCampaignCommand.
|
||||
/// </summary>
|
||||
public class ResumeCampaignCommandHandler : IRequestHandler<ResumeCampaignCommand, bool>
|
||||
{
|
||||
private readonly ICampaignRepository _campaignRepository;
|
||||
private readonly ILogger<ResumeCampaignCommandHandler> _logger;
|
||||
|
||||
public ResumeCampaignCommandHandler(
|
||||
ICampaignRepository campaignRepository,
|
||||
ILogger<ResumeCampaignCommandHandler> logger)
|
||||
{
|
||||
_campaignRepository = campaignRepository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<bool> Handle(ResumeCampaignCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var campaign = await _campaignRepository.GetByIdAsync(request.CampaignId);
|
||||
if (campaign == null) return false;
|
||||
|
||||
campaign.Resume();
|
||||
await _campaignRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation("Campaign {CampaignId} resumed", request.CampaignId);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for CancelCampaignCommand.
|
||||
/// VI: Handler cho CancelCampaignCommand.
|
||||
/// </summary>
|
||||
public class CancelCampaignCommandHandler : IRequestHandler<CancelCampaignCommand, bool>
|
||||
{
|
||||
private readonly ICampaignRepository _campaignRepository;
|
||||
private readonly ILogger<CancelCampaignCommandHandler> _logger;
|
||||
|
||||
public CancelCampaignCommandHandler(
|
||||
ICampaignRepository campaignRepository,
|
||||
ILogger<CancelCampaignCommandHandler> logger)
|
||||
{
|
||||
_campaignRepository = campaignRepository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<bool> Handle(CancelCampaignCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var campaign = await _campaignRepository.GetByIdAsync(request.CampaignId);
|
||||
if (campaign == null) return false;
|
||||
|
||||
campaign.Cancel();
|
||||
await _campaignRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation("Campaign {CampaignId} cancelled: {Reason}",
|
||||
request.CampaignId, request.Reason);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for UpdateCampaignMetricsCommand.
|
||||
/// VI: Handler cho UpdateCampaignMetricsCommand.
|
||||
/// </summary>
|
||||
public class UpdateCampaignMetricsCommandHandler : IRequestHandler<UpdateCampaignMetricsCommand, bool>
|
||||
{
|
||||
private readonly ICampaignRepository _campaignRepository;
|
||||
|
||||
public UpdateCampaignMetricsCommandHandler(ICampaignRepository campaignRepository)
|
||||
{
|
||||
_campaignRepository = campaignRepository;
|
||||
}
|
||||
|
||||
public async Task<bool> Handle(UpdateCampaignMetricsCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var campaign = await _campaignRepository.GetByIdAsync(request.CampaignId);
|
||||
if (campaign == null) return false;
|
||||
|
||||
var metrics = new CampaignMetrics(
|
||||
request.Sent, request.Delivered, request.Opened,
|
||||
request.Clicked, request.Replied, request.Failed);
|
||||
|
||||
campaign.UpdateMetrics(metrics);
|
||||
await _campaignRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using MediatR;
|
||||
using MktXService.Domain.AggregatesModel.CampaignAggregate;
|
||||
|
||||
namespace MktXService.API.Application.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to create a new campaign.
|
||||
/// VI: Command để tạo chiến dịch mới.
|
||||
/// </summary>
|
||||
public record CreateCampaignCommand(
|
||||
Guid MerchantId,
|
||||
string Name,
|
||||
string Type,
|
||||
Guid? TemplateId,
|
||||
List<Guid> SegmentIds,
|
||||
CampaignSchedule? Schedule = null
|
||||
) : IRequest<CreateCampaignResult>;
|
||||
|
||||
public record CreateCampaignResult(bool Success, Guid? CampaignId, string? Error);
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to start a campaign.
|
||||
/// VI: Command để bắt đầu chiến dịch.
|
||||
/// </summary>
|
||||
public record StartCampaignCommand(Guid CampaignId) : IRequest<bool>;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to pause a running campaign.
|
||||
/// VI: Command để tạm dừng chiến dịch đang chạy.
|
||||
/// </summary>
|
||||
public record PauseCampaignCommand(Guid CampaignId) : IRequest<bool>;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to resume a paused campaign.
|
||||
/// VI: Command để tiếp tục chiến dịch đã tạm dừng.
|
||||
/// </summary>
|
||||
public record ResumeCampaignCommand(Guid CampaignId) : IRequest<bool>;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to cancel a campaign.
|
||||
/// VI: Command để hủy chiến dịch.
|
||||
/// </summary>
|
||||
public record CancelCampaignCommand(Guid CampaignId, string? Reason = null) : IRequest<bool>;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to update campaign metrics.
|
||||
/// VI: Command để cập nhật metrics chiến dịch.
|
||||
/// </summary>
|
||||
public record UpdateCampaignMetricsCommand(
|
||||
Guid CampaignId,
|
||||
int Sent,
|
||||
int Delivered,
|
||||
int Opened,
|
||||
int Clicked,
|
||||
int Replied,
|
||||
int Failed
|
||||
) : IRequest<bool>;
|
||||
@@ -0,0 +1,188 @@
|
||||
using MediatR;
|
||||
using MktXService.Domain.AggregatesModel.ConversationAggregate;
|
||||
using MktXService.Domain.AggregatesModel.ContactAggregate;
|
||||
using MktXService.Infrastructure.ExternalServices.Twitter;
|
||||
|
||||
namespace MktXService.API.Application.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for SendMessageCommand.
|
||||
/// VI: Handler cho SendMessageCommand.
|
||||
/// </summary>
|
||||
public class SendMessageCommandHandler : IRequestHandler<SendMessageCommand, SendMessageResult>
|
||||
{
|
||||
private readonly IConversationRepository _conversationRepository;
|
||||
private readonly IContactRepository _contactRepository;
|
||||
private readonly ITwitterApiClient _twitterClient;
|
||||
private readonly ILogger<SendMessageCommandHandler> _logger;
|
||||
|
||||
public SendMessageCommandHandler(
|
||||
IConversationRepository conversationRepository,
|
||||
IContactRepository contactRepository,
|
||||
ITwitterApiClient twitterClient,
|
||||
ILogger<SendMessageCommandHandler> logger)
|
||||
{
|
||||
_conversationRepository = conversationRepository;
|
||||
_contactRepository = contactRepository;
|
||||
_twitterClient = twitterClient;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<SendMessageResult> Handle(
|
||||
SendMessageCommand request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var conversation = await _conversationRepository.GetByIdAsync(request.ConversationId);
|
||||
if (conversation == null)
|
||||
return new SendMessageResult(false, null, null, "Conversation not found");
|
||||
|
||||
try
|
||||
{
|
||||
// EN: Get contact to find Twitter ID
|
||||
// VI: Lấy contact để tìm Twitter ID
|
||||
var contact = await _contactRepository.GetByIdAsync(conversation.ContactId);
|
||||
if (contact == null)
|
||||
return new SendMessageResult(false, null, null, "Contact not found");
|
||||
|
||||
// EN: Send message via Twitter API
|
||||
// VI: Gửi tin nhắn qua Twitter API
|
||||
var twitterResult = await _twitterClient.SendDirectMessageAsync(
|
||||
contact.TwitterUserId,
|
||||
request.Content,
|
||||
cancellationToken);
|
||||
|
||||
if (!twitterResult.Success)
|
||||
return new SendMessageResult(false, null, null, twitterResult.Error);
|
||||
|
||||
// EN: Add message to conversation
|
||||
// VI: Thêm tin nhắn vào hội thoại
|
||||
var message = conversation.AddMessage(
|
||||
"outbound",
|
||||
"text",
|
||||
request.Content,
|
||||
request.IsFromBot,
|
||||
twitterResult.MessageId);
|
||||
|
||||
await _conversationRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation("Message {MessageId} sent in conversation {ConversationId}",
|
||||
message.Id, request.ConversationId);
|
||||
|
||||
return new SendMessageResult(true, message.Id, twitterResult.MessageId, null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to send message in conversation {ConversationId}", request.ConversationId);
|
||||
return new SendMessageResult(false, null, null, ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for CloseConversationCommand.
|
||||
/// VI: Handler cho CloseConversationCommand.
|
||||
/// </summary>
|
||||
public class CloseConversationCommandHandler : IRequestHandler<CloseConversationCommand, bool>
|
||||
{
|
||||
private readonly IConversationRepository _conversationRepository;
|
||||
private readonly ILogger<CloseConversationCommandHandler> _logger;
|
||||
|
||||
public CloseConversationCommandHandler(
|
||||
IConversationRepository conversationRepository,
|
||||
ILogger<CloseConversationCommandHandler> logger)
|
||||
{
|
||||
_conversationRepository = conversationRepository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<bool> Handle(CloseConversationCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var conversation = await _conversationRepository.GetByIdAsync(request.ConversationId);
|
||||
if (conversation == null) return false;
|
||||
|
||||
conversation.Close(request.Reason);
|
||||
await _conversationRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation("Conversation {ConversationId} closed", request.ConversationId);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for AssignConversationCommand.
|
||||
/// VI: Handler cho AssignConversationCommand.
|
||||
/// </summary>
|
||||
public class AssignConversationCommandHandler : IRequestHandler<AssignConversationCommand, bool>
|
||||
{
|
||||
private readonly IConversationRepository _conversationRepository;
|
||||
private readonly ILogger<AssignConversationCommandHandler> _logger;
|
||||
|
||||
public AssignConversationCommandHandler(
|
||||
IConversationRepository conversationRepository,
|
||||
ILogger<AssignConversationCommandHandler> logger)
|
||||
{
|
||||
_conversationRepository = conversationRepository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<bool> Handle(AssignConversationCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var conversation = await _conversationRepository.GetByIdAsync(request.ConversationId);
|
||||
if (conversation == null) return false;
|
||||
|
||||
conversation.AssignTo(request.UserId);
|
||||
await _conversationRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation("Conversation {ConversationId} assigned to {UserId}",
|
||||
request.ConversationId, request.UserId);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for ReopenConversationCommand.
|
||||
/// VI: Handler cho ReopenConversationCommand.
|
||||
/// </summary>
|
||||
public class ReopenConversationCommandHandler : IRequestHandler<ReopenConversationCommand, bool>
|
||||
{
|
||||
private readonly IConversationRepository _conversationRepository;
|
||||
|
||||
public ReopenConversationCommandHandler(IConversationRepository conversationRepository)
|
||||
{
|
||||
_conversationRepository = conversationRepository;
|
||||
}
|
||||
|
||||
public async Task<bool> Handle(ReopenConversationCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var conversation = await _conversationRepository.GetByIdAsync(request.ConversationId);
|
||||
if (conversation == null) return false;
|
||||
|
||||
conversation.Reopen();
|
||||
await _conversationRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for MarkConversationPendingCommand.
|
||||
/// VI: Handler cho MarkConversationPendingCommand.
|
||||
/// </summary>
|
||||
public class MarkConversationPendingCommandHandler : IRequestHandler<MarkConversationPendingCommand, bool>
|
||||
{
|
||||
private readonly IConversationRepository _conversationRepository;
|
||||
|
||||
public MarkConversationPendingCommandHandler(IConversationRepository conversationRepository)
|
||||
{
|
||||
_conversationRepository = conversationRepository;
|
||||
}
|
||||
|
||||
public async Task<bool> Handle(MarkConversationPendingCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var conversation = await _conversationRepository.GetByIdAsync(request.ConversationId);
|
||||
if (conversation == null) return false;
|
||||
|
||||
conversation.MarkAsPending();
|
||||
await _conversationRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using MediatR;
|
||||
|
||||
namespace MktXService.API.Application.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to send a message in a conversation.
|
||||
/// VI: Command để gửi tin nhắn trong hội thoại.
|
||||
/// </summary>
|
||||
public record SendMessageCommand(
|
||||
Guid ConversationId,
|
||||
string Content,
|
||||
bool IsFromBot = false,
|
||||
List<string>? MediaUrls = null
|
||||
) : IRequest<SendMessageResult>;
|
||||
|
||||
public record SendMessageResult(bool Success, Guid? MessageId, string? TwitterMessageId, string? Error);
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to close a conversation.
|
||||
/// VI: Command để đóng hội thoại.
|
||||
/// </summary>
|
||||
public record CloseConversationCommand(
|
||||
Guid ConversationId,
|
||||
string? Reason = null
|
||||
) : IRequest<bool>;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to assign a conversation to an agent.
|
||||
/// VI: Command để gán hội thoại cho agent.
|
||||
/// </summary>
|
||||
public record AssignConversationCommand(
|
||||
Guid ConversationId,
|
||||
Guid UserId
|
||||
) : IRequest<bool>;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to reopen a closed conversation.
|
||||
/// VI: Command để mở lại hội thoại đã đóng.
|
||||
/// </summary>
|
||||
public record ReopenConversationCommand(Guid ConversationId) : IRequest<bool>;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to mark conversation as pending.
|
||||
/// VI: Command để đánh dấu hội thoại đang chờ.
|
||||
/// </summary>
|
||||
public record MarkConversationPendingCommand(Guid ConversationId) : IRequest<bool>;
|
||||
@@ -0,0 +1,136 @@
|
||||
using MediatR;
|
||||
using MktXService.Domain.AggregatesModel.TwitterAccountAggregate;
|
||||
using MktXService.Infrastructure.ExternalServices.Twitter;
|
||||
|
||||
namespace MktXService.API.Application.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for ConnectTwitterAccountCommand.
|
||||
/// VI: Handler cho ConnectTwitterAccountCommand.
|
||||
/// </summary>
|
||||
public class ConnectTwitterAccountCommandHandler : IRequestHandler<ConnectTwitterAccountCommand, ConnectTwitterAccountResult>
|
||||
{
|
||||
private readonly ITwitterAccountRepository _accountRepository;
|
||||
private readonly ITwitterApiClient _twitterClient;
|
||||
private readonly ILogger<ConnectTwitterAccountCommandHandler> _logger;
|
||||
|
||||
public ConnectTwitterAccountCommandHandler(
|
||||
ITwitterAccountRepository accountRepository,
|
||||
ITwitterApiClient twitterClient,
|
||||
ILogger<ConnectTwitterAccountCommandHandler> logger)
|
||||
{
|
||||
_accountRepository = accountRepository;
|
||||
_twitterClient = twitterClient;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ConnectTwitterAccountResult> Handle(
|
||||
ConnectTwitterAccountCommand request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("Connecting Twitter account {Username} for merchant {MerchantId}",
|
||||
request.Username, request.MerchantId);
|
||||
|
||||
try
|
||||
{
|
||||
// EN: Check if account already exists
|
||||
// VI: Kiểm tra xem tài khoản đã tồn tại chưa
|
||||
var existingAccount = await _accountRepository.GetByTwitterUserIdAsync(request.TwitterUserId);
|
||||
if (existingAccount != null)
|
||||
{
|
||||
return new ConnectTwitterAccountResult(false, null, "Twitter account already connected");
|
||||
}
|
||||
|
||||
// EN: Create new account
|
||||
// VI: Tạo tài khoản mới
|
||||
var account = new TwitterAccount(
|
||||
request.MerchantId,
|
||||
request.TwitterUserId,
|
||||
request.Username,
|
||||
request.OAuthToken,
|
||||
request.OAuthTokenSecret,
|
||||
request.DisplayName,
|
||||
request.ProfileImageUrl);
|
||||
|
||||
_accountRepository.Add(account);
|
||||
await _accountRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation("Twitter account {AccountId} connected successfully", account.Id);
|
||||
return new ConnectTwitterAccountResult(true, account.Id, null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to connect Twitter account {Username}", request.Username);
|
||||
return new ConnectTwitterAccountResult(false, null, ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for DisconnectTwitterAccountCommand.
|
||||
/// VI: Handler cho DisconnectTwitterAccountCommand.
|
||||
/// </summary>
|
||||
public class DisconnectTwitterAccountCommandHandler : IRequestHandler<DisconnectTwitterAccountCommand, bool>
|
||||
{
|
||||
private readonly ITwitterAccountRepository _accountRepository;
|
||||
private readonly ILogger<DisconnectTwitterAccountCommandHandler> _logger;
|
||||
|
||||
public DisconnectTwitterAccountCommandHandler(
|
||||
ITwitterAccountRepository accountRepository,
|
||||
ILogger<DisconnectTwitterAccountCommandHandler> logger)
|
||||
{
|
||||
_accountRepository = accountRepository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<bool> Handle(
|
||||
DisconnectTwitterAccountCommand request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("Disconnecting Twitter account {AccountId}", request.AccountId);
|
||||
|
||||
var account = await _accountRepository.GetByIdAsync(request.AccountId);
|
||||
if (account == null)
|
||||
{
|
||||
_logger.LogWarning("Account {AccountId} not found", request.AccountId);
|
||||
return false;
|
||||
}
|
||||
|
||||
account.Disconnect();
|
||||
await _accountRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation("Twitter account {AccountId} disconnected", request.AccountId);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for RefreshTwitterAccountTokensCommand.
|
||||
/// VI: Handler cho RefreshTwitterAccountTokensCommand.
|
||||
/// </summary>
|
||||
public class RefreshTwitterAccountTokensCommandHandler : IRequestHandler<RefreshTwitterAccountTokensCommand, bool>
|
||||
{
|
||||
private readonly ITwitterAccountRepository _accountRepository;
|
||||
private readonly ILogger<RefreshTwitterAccountTokensCommandHandler> _logger;
|
||||
|
||||
public RefreshTwitterAccountTokensCommandHandler(
|
||||
ITwitterAccountRepository accountRepository,
|
||||
ILogger<RefreshTwitterAccountTokensCommandHandler> logger)
|
||||
{
|
||||
_accountRepository = accountRepository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<bool> Handle(
|
||||
RefreshTwitterAccountTokensCommand request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var account = await _accountRepository.GetByIdAsync(request.AccountId);
|
||||
if (account == null) return false;
|
||||
|
||||
account.UpdateCredentials(request.NewOAuthToken, request.NewOAuthTokenSecret);
|
||||
await _accountRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using MediatR;
|
||||
|
||||
namespace MktXService.API.Application.Commands;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to connect a Twitter account via OAuth.
|
||||
/// VI: Command để kết nối tài khoản Twitter qua OAuth.
|
||||
/// </summary>
|
||||
public record ConnectTwitterAccountCommand(
|
||||
Guid MerchantId,
|
||||
string TwitterUserId,
|
||||
string Username,
|
||||
string OAuthToken,
|
||||
string OAuthTokenSecret,
|
||||
string? DisplayName = null,
|
||||
string? ProfileImageUrl = null
|
||||
) : IRequest<ConnectTwitterAccountResult>;
|
||||
|
||||
public record ConnectTwitterAccountResult(
|
||||
bool Success,
|
||||
Guid? AccountId,
|
||||
string? Error);
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to disconnect a Twitter account.
|
||||
/// VI: Command để ngắt kết nối tài khoản Twitter.
|
||||
/// </summary>
|
||||
public record DisconnectTwitterAccountCommand(
|
||||
Guid AccountId,
|
||||
string? Reason = null
|
||||
) : IRequest<bool>;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to refresh OAuth tokens for a Twitter account.
|
||||
/// VI: Command để làm mới OAuth tokens cho tài khoản Twitter.
|
||||
/// </summary>
|
||||
public record RefreshTwitterAccountTokensCommand(
|
||||
Guid AccountId,
|
||||
string NewOAuthToken,
|
||||
string NewOAuthTokenSecret
|
||||
) : IRequest<bool>;
|
||||
@@ -0,0 +1,166 @@
|
||||
using MediatR;
|
||||
|
||||
namespace MktXService.API.Application.Queries;
|
||||
|
||||
#region Twitter Account Queries
|
||||
|
||||
public record GetTwitterAccountsQuery(Guid MerchantId) : IRequest<IEnumerable<TwitterAccountDto>>;
|
||||
|
||||
public record GetTwitterAccountQuery(Guid AccountId) : IRequest<TwitterAccountDto?>;
|
||||
|
||||
public record TwitterAccountDto(
|
||||
Guid Id,
|
||||
Guid MerchantId,
|
||||
string TwitterUserId,
|
||||
string Username,
|
||||
string? DisplayName,
|
||||
string? ProfileImageUrl,
|
||||
string Status,
|
||||
DateTime ConnectedAt);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Campaign Queries
|
||||
|
||||
public record GetCampaignsQuery(
|
||||
Guid MerchantId,
|
||||
string? Status = null,
|
||||
int Skip = 0,
|
||||
int Take = 20
|
||||
) : IRequest<IEnumerable<CampaignDto>>;
|
||||
|
||||
public record GetCampaignQuery(Guid CampaignId) : IRequest<CampaignDetailDto?>;
|
||||
|
||||
public record CampaignDto(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string Type,
|
||||
string Status,
|
||||
int TotalSent,
|
||||
int TotalDelivered,
|
||||
DateTime CreatedAt);
|
||||
|
||||
public record CampaignDetailDto(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string Type,
|
||||
string Status,
|
||||
Guid? TemplateId,
|
||||
List<Guid> SegmentIds,
|
||||
CampaignMetricsDto Metrics,
|
||||
CampaignScheduleDto? Schedule,
|
||||
DateTime CreatedAt);
|
||||
|
||||
public record CampaignMetricsDto(int Sent, int Delivered, int Opened, int Clicked, int Replied, int Failed);
|
||||
|
||||
public record CampaignScheduleDto(DateTime? StartAt, DateTime? EndAt, string? Recurrence);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Conversation Queries
|
||||
|
||||
public record GetConversationsQuery(
|
||||
Guid AccountId,
|
||||
string? Status = null,
|
||||
Guid? AssignedToUserId = null,
|
||||
int Skip = 0,
|
||||
int Take = 20
|
||||
) : IRequest<IEnumerable<ConversationDto>>;
|
||||
|
||||
public record GetConversationQuery(Guid ConversationId, bool IncludeMessages = true)
|
||||
: IRequest<ConversationDetailDto?>;
|
||||
|
||||
public record ConversationDto(
|
||||
Guid Id,
|
||||
Guid ContactId,
|
||||
string ContactUsername,
|
||||
string Status,
|
||||
int MessageCount,
|
||||
DateTime StartedAt,
|
||||
DateTime? LastMessageAt);
|
||||
|
||||
public record ConversationDetailDto(
|
||||
Guid Id,
|
||||
Guid ContactId,
|
||||
ContactSummaryDto Contact,
|
||||
string Status,
|
||||
Guid? AssignedToUserId,
|
||||
List<MessageDto> Messages,
|
||||
DateTime StartedAt,
|
||||
DateTime? ClosedAt);
|
||||
|
||||
public record ContactSummaryDto(
|
||||
Guid Id,
|
||||
string TwitterUserId,
|
||||
string Username,
|
||||
string? DisplayName,
|
||||
string? ProfileImageUrl);
|
||||
|
||||
public record MessageDto(
|
||||
Guid Id,
|
||||
string Direction,
|
||||
string Type,
|
||||
string Content,
|
||||
bool IsFromBot,
|
||||
DateTime SentAt);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Contact Queries
|
||||
|
||||
public record GetContactsQuery(
|
||||
Guid AccountId,
|
||||
string? SearchTerm = null,
|
||||
List<string>? Tags = null,
|
||||
int Skip = 0,
|
||||
int Take = 20
|
||||
) : IRequest<IEnumerable<ContactDto>>;
|
||||
|
||||
public record GetContactQuery(Guid ContactId) : IRequest<ContactDetailDto?>;
|
||||
|
||||
public record ContactDto(
|
||||
Guid Id,
|
||||
string TwitterUserId,
|
||||
string Username,
|
||||
string? DisplayName,
|
||||
List<string> Tags,
|
||||
DateTime? LastInteractionAt);
|
||||
|
||||
public record ContactDetailDto(
|
||||
Guid Id,
|
||||
string TwitterUserId,
|
||||
string Username,
|
||||
string? DisplayName,
|
||||
string? ProfileImageUrl,
|
||||
string Source,
|
||||
Dictionary<string, object> Attributes,
|
||||
List<string> Tags,
|
||||
DateTime FirstInteractionAt,
|
||||
DateTime? LastInteractionAt);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Template Queries
|
||||
|
||||
public record GetTemplatesQuery(
|
||||
Guid MerchantId,
|
||||
string? Type = null
|
||||
) : IRequest<IEnumerable<TemplateDto>>;
|
||||
|
||||
public record GetTemplateQuery(Guid TemplateId) : IRequest<TemplateDetailDto?>;
|
||||
|
||||
public record TemplateDto(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string Type,
|
||||
DateTime CreatedAt);
|
||||
|
||||
public record TemplateDetailDto(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string Type,
|
||||
string Content,
|
||||
List<string> Variables,
|
||||
DateTime CreatedAt);
|
||||
|
||||
#endregion
|
||||
@@ -0,0 +1,263 @@
|
||||
using MediatR;
|
||||
using MktXService.Domain.AggregatesModel.TwitterAccountAggregate;
|
||||
using MktXService.Domain.AggregatesModel.CampaignAggregate;
|
||||
using MktXService.Domain.AggregatesModel.ConversationAggregate;
|
||||
using MktXService.Domain.AggregatesModel.ContactAggregate;
|
||||
using MktXService.Domain.AggregatesModel.TemplateAggregate;
|
||||
|
||||
namespace MktXService.API.Application.Queries;
|
||||
|
||||
#region Twitter Account Query Handlers
|
||||
|
||||
public class GetTwitterAccountsQueryHandler : IRequestHandler<GetTwitterAccountsQuery, IEnumerable<TwitterAccountDto>>
|
||||
{
|
||||
private readonly ITwitterAccountRepository _repository;
|
||||
|
||||
public GetTwitterAccountsQueryHandler(ITwitterAccountRepository repository) => _repository = repository;
|
||||
|
||||
public async Task<IEnumerable<TwitterAccountDto>> Handle(GetTwitterAccountsQuery request, CancellationToken ct)
|
||||
{
|
||||
var accounts = await _repository.GetByMerchantIdAsync(request.MerchantId);
|
||||
return accounts.Select(a => new TwitterAccountDto(
|
||||
a.Id, a.MerchantId, a.TwitterUserId, a.Username,
|
||||
a.DisplayName, a.ProfileImageUrl, a.Status.Name, a.ConnectedAt));
|
||||
}
|
||||
}
|
||||
|
||||
public class GetTwitterAccountQueryHandler : IRequestHandler<GetTwitterAccountQuery, TwitterAccountDto?>
|
||||
{
|
||||
private readonly ITwitterAccountRepository _repository;
|
||||
|
||||
public GetTwitterAccountQueryHandler(ITwitterAccountRepository repository) => _repository = repository;
|
||||
|
||||
public async Task<TwitterAccountDto?> Handle(GetTwitterAccountQuery request, CancellationToken ct)
|
||||
{
|
||||
var a = await _repository.GetByIdAsync(request.AccountId);
|
||||
if (a == null) return null;
|
||||
return new TwitterAccountDto(
|
||||
a.Id, a.MerchantId, a.TwitterUserId, a.Username,
|
||||
a.DisplayName, a.ProfileImageUrl, a.Status.Name, a.ConnectedAt);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Campaign Query Handlers
|
||||
|
||||
public class GetCampaignsQueryHandler : IRequestHandler<GetCampaignsQuery, IEnumerable<CampaignDto>>
|
||||
{
|
||||
private readonly ICampaignRepository _repository;
|
||||
|
||||
public GetCampaignsQueryHandler(ICampaignRepository repository) => _repository = repository;
|
||||
|
||||
public async Task<IEnumerable<CampaignDto>> Handle(GetCampaignsQuery request, CancellationToken ct)
|
||||
{
|
||||
IEnumerable<Campaign> campaigns;
|
||||
if (!string.IsNullOrEmpty(request.Status))
|
||||
{
|
||||
var status = CampaignStatus.FromName(request.Status);
|
||||
campaigns = await _repository.GetByStatusAsync(request.MerchantId, status);
|
||||
}
|
||||
else
|
||||
{
|
||||
campaigns = await _repository.GetByMerchantIdAsync(request.MerchantId, request.Skip, request.Take);
|
||||
}
|
||||
|
||||
return campaigns.Select(c => new CampaignDto(
|
||||
c.Id, c.Name, c.Type, c.Status.Name,
|
||||
c.Metrics.TotalSent, c.Metrics.Delivered, c.CreatedAt));
|
||||
}
|
||||
}
|
||||
|
||||
public class GetCampaignQueryHandler : IRequestHandler<GetCampaignQuery, CampaignDetailDto?>
|
||||
{
|
||||
private readonly ICampaignRepository _repository;
|
||||
|
||||
public GetCampaignQueryHandler(ICampaignRepository repository) => _repository = repository;
|
||||
|
||||
public async Task<CampaignDetailDto?> Handle(GetCampaignQuery request, CancellationToken ct)
|
||||
{
|
||||
var c = await _repository.GetByIdAsync(request.CampaignId);
|
||||
if (c == null) return null;
|
||||
|
||||
return new CampaignDetailDto(
|
||||
c.Id, c.Name, c.Type, c.Status.Name, c.TemplateId, c.SegmentIds.ToList(),
|
||||
new CampaignMetricsDto(c.Metrics.TotalSent, c.Metrics.Delivered, c.Metrics.Opened,
|
||||
c.Metrics.Clicked, c.Metrics.Replied, c.Metrics.Failed),
|
||||
c.Schedule != null ? new CampaignScheduleDto(c.Schedule.StartAt, c.Schedule.EndAt, c.Schedule.Recurrence) : null,
|
||||
c.CreatedAt);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Conversation Query Handlers
|
||||
|
||||
public class GetConversationsQueryHandler : IRequestHandler<GetConversationsQuery, IEnumerable<ConversationDto>>
|
||||
{
|
||||
private readonly IConversationRepository _repository;
|
||||
private readonly IContactRepository _contactRepository;
|
||||
|
||||
public GetConversationsQueryHandler(IConversationRepository repository, IContactRepository contactRepository)
|
||||
{
|
||||
_repository = repository;
|
||||
_contactRepository = contactRepository;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<ConversationDto>> Handle(GetConversationsQuery request, CancellationToken ct)
|
||||
{
|
||||
IEnumerable<Conversation> conversations;
|
||||
|
||||
if (request.AssignedToUserId.HasValue)
|
||||
{
|
||||
conversations = await _repository.GetByAssignedUserAsync(request.AssignedToUserId.Value, request.Skip, request.Take);
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(request.Status))
|
||||
{
|
||||
var status = ConversationStatus.FromName(request.Status);
|
||||
conversations = await _repository.GetByStatusAsync(request.AccountId, status, request.Skip, request.Take);
|
||||
}
|
||||
else
|
||||
{
|
||||
conversations = await _repository.GetByAccountIdAsync(request.AccountId, request.Skip, request.Take);
|
||||
}
|
||||
|
||||
var results = new List<ConversationDto>();
|
||||
foreach (var c in conversations)
|
||||
{
|
||||
var contact = await _contactRepository.GetByIdAsync(c.ContactId);
|
||||
results.Add(new ConversationDto(
|
||||
c.Id, c.ContactId, contact?.Username ?? "unknown", c.Status.Name,
|
||||
c.Messages.Count, c.StartedAt, c.Messages.Any() ? c.Messages.Max(m => m.SentAt) : null));
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
public class GetConversationQueryHandler : IRequestHandler<GetConversationQuery, ConversationDetailDto?>
|
||||
{
|
||||
private readonly IConversationRepository _repository;
|
||||
private readonly IContactRepository _contactRepository;
|
||||
|
||||
public GetConversationQueryHandler(IConversationRepository repository, IContactRepository contactRepository)
|
||||
{
|
||||
_repository = repository;
|
||||
_contactRepository = contactRepository;
|
||||
}
|
||||
|
||||
public async Task<ConversationDetailDto?> Handle(GetConversationQuery request, CancellationToken ct)
|
||||
{
|
||||
var c = request.IncludeMessages
|
||||
? await _repository.GetByIdWithMessagesAsync(request.ConversationId)
|
||||
: await _repository.GetByIdAsync(request.ConversationId);
|
||||
|
||||
if (c == null) return null;
|
||||
|
||||
var contact = await _contactRepository.GetByIdAsync(c.ContactId);
|
||||
var contactDto = contact != null
|
||||
? new ContactSummaryDto(contact.Id, contact.TwitterUserId, contact.Username,
|
||||
contact.DisplayName, contact.ProfileImageUrl)
|
||||
: new ContactSummaryDto(Guid.Empty, "", "unknown", null, null);
|
||||
|
||||
return new ConversationDetailDto(
|
||||
c.Id, c.ContactId, contactDto, c.Status.Name, c.AssignedToUserId,
|
||||
c.Messages.Select(m => new MessageDto(m.Id, m.Direction, m.Type, m.Content, m.IsFromBot, m.SentAt)).ToList(),
|
||||
c.StartedAt, c.ClosedAt);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Contact Query Handlers
|
||||
|
||||
public class GetContactsQueryHandler : IRequestHandler<GetContactsQuery, IEnumerable<ContactDto>>
|
||||
{
|
||||
private readonly IContactRepository _repository;
|
||||
|
||||
public GetContactsQueryHandler(IContactRepository repository) => _repository = repository;
|
||||
|
||||
public async Task<IEnumerable<ContactDto>> Handle(GetContactsQuery request, CancellationToken ct)
|
||||
{
|
||||
IEnumerable<Contact> contacts;
|
||||
|
||||
if (request.Tags?.Any() == true)
|
||||
{
|
||||
contacts = await _repository.GetByTagsAsync(request.AccountId, request.Tags, request.Skip, request.Take);
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(request.SearchTerm))
|
||||
{
|
||||
contacts = await _repository.SearchAsync(request.AccountId, request.SearchTerm, request.Skip, request.Take);
|
||||
}
|
||||
else
|
||||
{
|
||||
contacts = await _repository.GetByAccountIdAsync(request.AccountId, request.Skip, request.Take);
|
||||
}
|
||||
|
||||
return contacts.Select(c => new ContactDto(
|
||||
c.Id, c.TwitterUserId, c.Username, c.DisplayName,
|
||||
c.Tags.Select(t => t.Name).ToList(), c.LastInteractionAt));
|
||||
}
|
||||
}
|
||||
|
||||
public class GetContactQueryHandler : IRequestHandler<GetContactQuery, ContactDetailDto?>
|
||||
{
|
||||
private readonly IContactRepository _repository;
|
||||
|
||||
public GetContactQueryHandler(IContactRepository repository) => _repository = repository;
|
||||
|
||||
public async Task<ContactDetailDto?> Handle(GetContactQuery request, CancellationToken ct)
|
||||
{
|
||||
var c = await _repository.GetByIdAsync(request.ContactId);
|
||||
if (c == null) return null;
|
||||
|
||||
return new ContactDetailDto(
|
||||
c.Id, c.TwitterUserId, c.Username, c.DisplayName, c.ProfileImageUrl, c.Source,
|
||||
c.Attributes.ToDictionary(k => k.Key, v => v.Value),
|
||||
c.Tags.Select(t => t.Name).ToList(), c.FirstInteractionAt, c.LastInteractionAt);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Template Query Handlers
|
||||
|
||||
public class GetTemplatesQueryHandler : IRequestHandler<GetTemplatesQuery, IEnumerable<TemplateDto>>
|
||||
{
|
||||
private readonly ITemplateRepository _repository;
|
||||
|
||||
public GetTemplatesQueryHandler(ITemplateRepository repository) => _repository = repository;
|
||||
|
||||
public async Task<IEnumerable<TemplateDto>> Handle(GetTemplatesQuery request, CancellationToken ct)
|
||||
{
|
||||
IEnumerable<Template> templates;
|
||||
|
||||
if (!string.IsNullOrEmpty(request.Type))
|
||||
{
|
||||
templates = await _repository.GetByTypeAsync(request.MerchantId, request.Type);
|
||||
}
|
||||
else
|
||||
{
|
||||
templates = await _repository.GetByMerchantIdAsync(request.MerchantId);
|
||||
}
|
||||
|
||||
return templates.Select(t => new TemplateDto(t.Id, t.Name, t.Type, t.CreatedAt));
|
||||
}
|
||||
}
|
||||
|
||||
public class GetTemplateQueryHandler : IRequestHandler<GetTemplateQuery, TemplateDetailDto?>
|
||||
{
|
||||
private readonly ITemplateRepository _repository;
|
||||
|
||||
public GetTemplateQueryHandler(ITemplateRepository repository) => _repository = repository;
|
||||
|
||||
public async Task<TemplateDetailDto?> Handle(GetTemplateQuery request, CancellationToken ct)
|
||||
{
|
||||
var t = await _repository.GetByIdAsync(request.TemplateId);
|
||||
if (t == null) return null;
|
||||
|
||||
return new TemplateDetailDto(t.Id, t.Name, t.Type, t.Content, t.Variables.ToList(), t.CreatedAt);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -0,0 +1,129 @@
|
||||
using Asp.Versioning;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using MktXService.API.Application.Commands;
|
||||
using MktXService.API.Application.Queries;
|
||||
|
||||
namespace MktXService.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Controller for Twitter Account management.
|
||||
/// VI: Controller quản lý tài khoản Twitter.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[ApiVersion("1.0")]
|
||||
[Route("api/v{version:apiVersion}/[controller]")]
|
||||
[Produces("application/json")]
|
||||
public class AccountsController : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
private readonly ILogger<AccountsController> _logger;
|
||||
|
||||
public AccountsController(IMediator mediator, ILogger<AccountsController> logger)
|
||||
{
|
||||
_mediator = mediator;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Get all Twitter accounts for a merchant.
|
||||
/// VI: Lấy tất cả tài khoản Twitter của merchant.
|
||||
/// </summary>
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IEnumerable<TwitterAccountDto>), StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> GetAccounts([FromQuery] Guid merchantId)
|
||||
{
|
||||
var accounts = await _mediator.Send(new GetTwitterAccountsQuery(merchantId));
|
||||
return Ok(new { success = true, data = accounts });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Get a Twitter account by ID.
|
||||
/// VI: Lấy tài khoản Twitter theo ID.
|
||||
/// </summary>
|
||||
[HttpGet("{id:guid}")]
|
||||
[ProducesResponseType(typeof(TwitterAccountDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetAccount(Guid id)
|
||||
{
|
||||
var account = await _mediator.Send(new GetTwitterAccountQuery(id));
|
||||
if (account == null)
|
||||
return NotFound(new { success = false, error = new { code = "ACCOUNT_NOT_FOUND", message = $"Account {id} not found" } });
|
||||
|
||||
return Ok(new { success = true, data = account });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Connect a new Twitter account via OAuth.
|
||||
/// VI: Kết nối tài khoản Twitter mới qua OAuth.
|
||||
/// </summary>
|
||||
[HttpPost("connect")]
|
||||
[ProducesResponseType(typeof(ConnectTwitterAccountResult), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> ConnectAccount([FromBody] ConnectAccountRequest request)
|
||||
{
|
||||
var command = new ConnectTwitterAccountCommand(
|
||||
request.MerchantId,
|
||||
request.TwitterUserId,
|
||||
request.Username,
|
||||
request.OAuthToken,
|
||||
request.OAuthTokenSecret,
|
||||
request.DisplayName,
|
||||
request.ProfileImageUrl);
|
||||
|
||||
var result = await _mediator.Send(command);
|
||||
|
||||
if (!result.Success)
|
||||
return BadRequest(new { success = false, error = new { code = "CONNECTION_FAILED", message = result.Error } });
|
||||
|
||||
return CreatedAtAction(nameof(GetAccount), new { id = result.AccountId },
|
||||
new { success = true, data = result });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Disconnect a Twitter account.
|
||||
/// VI: Ngắt kết nối tài khoản Twitter.
|
||||
/// </summary>
|
||||
[HttpPost("{id:guid}/disconnect")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> DisconnectAccount(Guid id)
|
||||
{
|
||||
var result = await _mediator.Send(new DisconnectTwitterAccountCommand(id));
|
||||
if (!result)
|
||||
return NotFound(new { success = false, error = new { code = "ACCOUNT_NOT_FOUND", message = $"Account {id} not found" } });
|
||||
|
||||
return Ok(new { success = true, message = "Account disconnected successfully" });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Refresh OAuth tokens.
|
||||
/// VI: Làm mới OAuth tokens.
|
||||
/// </summary>
|
||||
[HttpPost("{id:guid}/refresh-tokens")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> RefreshTokens(Guid id, [FromBody] RefreshTokensRequest request)
|
||||
{
|
||||
var result = await _mediator.Send(new RefreshTwitterAccountTokensCommand(id, request.OAuthToken, request.OAuthTokenSecret));
|
||||
if (!result)
|
||||
return NotFound(new { success = false, error = new { code = "ACCOUNT_NOT_FOUND", message = $"Account {id} not found" } });
|
||||
|
||||
return Ok(new { success = true, message = "Tokens refreshed successfully" });
|
||||
}
|
||||
}
|
||||
|
||||
#region Request Models
|
||||
|
||||
public record ConnectAccountRequest(
|
||||
Guid MerchantId,
|
||||
string TwitterUserId,
|
||||
string Username,
|
||||
string OAuthToken,
|
||||
string OAuthTokenSecret,
|
||||
string? DisplayName = null,
|
||||
string? ProfileImageUrl = null);
|
||||
|
||||
public record RefreshTokensRequest(string OAuthToken, string OAuthTokenSecret);
|
||||
|
||||
#endregion
|
||||
@@ -0,0 +1,22 @@
|
||||
using MediatR;
|
||||
|
||||
namespace MktZaloService.API.Application.Commands.Customers;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to update customer profile and tags.
|
||||
/// VI: Command để cập nhật profile và tags khách hàng.
|
||||
/// </summary>
|
||||
public record UpdateCustomerCommand(
|
||||
Guid CustomerId,
|
||||
string? DisplayName,
|
||||
string? AvatarUrl,
|
||||
string? PhoneNumber,
|
||||
string? Email,
|
||||
List<string>? TagsToAdd,
|
||||
List<string>? TagsToRemove
|
||||
) : IRequest<UpdateCustomerResult>;
|
||||
|
||||
public record UpdateCustomerResult(
|
||||
bool Success,
|
||||
string? Error = null
|
||||
);
|
||||
@@ -0,0 +1,86 @@
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using MktZaloService.Domain.AggregatesModel.CustomerAggregate;
|
||||
|
||||
namespace MktZaloService.API.Application.Commands.Customers;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for UpdateCustomerCommand.
|
||||
/// VI: Handler cho UpdateCustomerCommand.
|
||||
/// </summary>
|
||||
public class UpdateCustomerCommandHandler : IRequestHandler<UpdateCustomerCommand, UpdateCustomerResult>
|
||||
{
|
||||
private readonly ICustomerRepository _customerRepository;
|
||||
private readonly ILogger<UpdateCustomerCommandHandler> _logger;
|
||||
|
||||
public UpdateCustomerCommandHandler(
|
||||
ICustomerRepository customerRepository,
|
||||
ILogger<UpdateCustomerCommandHandler> logger)
|
||||
{
|
||||
_customerRepository = customerRepository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<UpdateCustomerResult> Handle(
|
||||
UpdateCustomerCommand request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var customer = await _customerRepository.GetByIdAsync(request.CustomerId, cancellationToken);
|
||||
|
||||
if (customer == null)
|
||||
{
|
||||
return new UpdateCustomerResult(false, Error: "Customer not found");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// EN: Update profile if any field provided / VI: Cập nhật profile nếu có field nào được cung cấp
|
||||
if (!string.IsNullOrEmpty(request.DisplayName) ||
|
||||
!string.IsNullOrEmpty(request.AvatarUrl) ||
|
||||
!string.IsNullOrEmpty(request.PhoneNumber) ||
|
||||
!string.IsNullOrEmpty(request.Email))
|
||||
{
|
||||
var newProfile = new CustomerProfile(
|
||||
request.DisplayName ?? customer.Profile.DisplayName,
|
||||
request.AvatarUrl ?? customer.Profile.AvatarUrl,
|
||||
request.PhoneNumber ?? customer.Profile.PhoneNumber,
|
||||
request.Email ?? customer.Profile.Email);
|
||||
|
||||
customer.UpdateProfile(newProfile);
|
||||
}
|
||||
|
||||
// EN: Add tags / VI: Thêm tags
|
||||
if (request.TagsToAdd?.Any() == true)
|
||||
{
|
||||
foreach (var tagName in request.TagsToAdd)
|
||||
{
|
||||
customer.AddTag(tagName);
|
||||
}
|
||||
}
|
||||
|
||||
// EN: Remove tags / VI: Xóa tags
|
||||
if (request.TagsToRemove?.Any() == true)
|
||||
{
|
||||
foreach (var tagName in request.TagsToRemove)
|
||||
{
|
||||
customer.RemoveTag(tagName);
|
||||
}
|
||||
}
|
||||
|
||||
_customerRepository.Update(customer);
|
||||
await _customerRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation(
|
||||
"EN: Updated customer {CustomerId}. VI: Đã cập nhật khách hàng {CustomerId}",
|
||||
customer.Id);
|
||||
|
||||
return new UpdateCustomerResult(true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"EN: Error updating customer. VI: Lỗi cập nhật khách hàng");
|
||||
return new UpdateCustomerResult(false, Error: ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using MediatR;
|
||||
using MktZaloService.Domain.Enums;
|
||||
|
||||
namespace MktZaloService.API.Application.Commands.Rules;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to create a new chatbot rule.
|
||||
/// VI: Command để tạo quy tắc chatbot mới.
|
||||
/// </summary>
|
||||
public record CreateChatbotRuleCommand(
|
||||
string Name,
|
||||
string? Description,
|
||||
RuleType Type,
|
||||
int Priority,
|
||||
ActionType ActionType,
|
||||
string? ResponseText,
|
||||
Guid? TemplateId,
|
||||
List<RuleConditionDto> Conditions
|
||||
) : IRequest<CreateChatbotRuleResult>;
|
||||
|
||||
public record RuleConditionDto(string Field, string Operator, string Value);
|
||||
|
||||
public record CreateChatbotRuleResult(
|
||||
bool Success,
|
||||
Guid? RuleId = null,
|
||||
string? Error = null
|
||||
);
|
||||
@@ -0,0 +1,78 @@
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using MktZaloService.Domain.AggregatesModel.ChatbotRuleAggregate;
|
||||
using MktZaloService.Domain.Enums;
|
||||
using MktZaloService.Infrastructure.Caching;
|
||||
|
||||
namespace MktZaloService.API.Application.Commands.Rules;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for CreateChatbotRuleCommand.
|
||||
/// VI: Handler cho CreateChatbotRuleCommand.
|
||||
/// </summary>
|
||||
public class CreateChatbotRuleCommandHandler
|
||||
: IRequestHandler<CreateChatbotRuleCommand, CreateChatbotRuleResult>
|
||||
{
|
||||
private readonly IChatbotRuleRepository _ruleRepository;
|
||||
private readonly IChatbotRuleCacheService _cacheService;
|
||||
private readonly ILogger<CreateChatbotRuleCommandHandler> _logger;
|
||||
|
||||
public CreateChatbotRuleCommandHandler(
|
||||
IChatbotRuleRepository ruleRepository,
|
||||
IChatbotRuleCacheService cacheService,
|
||||
ILogger<CreateChatbotRuleCommandHandler> logger)
|
||||
{
|
||||
_ruleRepository = ruleRepository;
|
||||
_cacheService = cacheService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<CreateChatbotRuleResult> Handle(
|
||||
CreateChatbotRuleCommand request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// EN: Create action based on type / VI: Tạo action theo loại
|
||||
var action = request.ActionType switch
|
||||
{
|
||||
ActionType.SendText => RuleAction.SendText(request.ResponseText ?? string.Empty),
|
||||
ActionType.SendTemplate => RuleAction.SendTemplate(request.TemplateId ?? Guid.Empty),
|
||||
ActionType.ForwardToHuman => RuleAction.ForwardToHuman(),
|
||||
_ => RuleAction.SendText(request.ResponseText ?? string.Empty)
|
||||
};
|
||||
|
||||
// EN: Create rule / VI: Tạo quy tắc
|
||||
var rule = new ChatbotRule(
|
||||
request.Name,
|
||||
request.Type,
|
||||
action,
|
||||
request.Priority,
|
||||
request.Description);
|
||||
|
||||
// EN: Add conditions / VI: Thêm điều kiện
|
||||
foreach (var condition in request.Conditions)
|
||||
{
|
||||
rule.AddCondition(condition.Field, condition.Operator, condition.Value);
|
||||
}
|
||||
|
||||
_ruleRepository.Add(rule);
|
||||
await _ruleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
|
||||
// EN: Invalidate cache / VI: Xóa cache
|
||||
await _cacheService.InvalidateRulesCacheAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation(
|
||||
"EN: Created chatbot rule '{Name}' with ID {Id}. VI: Đã tạo quy tắc chatbot '{Name}' với ID {Id}",
|
||||
rule.Name, rule.Id);
|
||||
|
||||
return new CreateChatbotRuleResult(true, RuleId: rule.Id);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"EN: Error creating chatbot rule. VI: Lỗi tạo quy tắc chatbot");
|
||||
return new CreateChatbotRuleResult(false, Error: ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using MediatR;
|
||||
|
||||
namespace MktZaloService.API.Application.Commands.Rules;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to delete a chatbot rule.
|
||||
/// VI: Command để xóa quy tắc chatbot.
|
||||
/// </summary>
|
||||
public record DeleteChatbotRuleCommand(Guid RuleId) : IRequest<DeleteChatbotRuleResult>;
|
||||
|
||||
public record DeleteChatbotRuleResult(
|
||||
bool Success,
|
||||
string? Error = null
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// EN: Command to toggle a chatbot rule active status.
|
||||
/// VI: Command để bật/tắt trạng thái hoạt động của quy tắc chatbot.
|
||||
/// </summary>
|
||||
public record ToggleChatbotRuleCommand(Guid RuleId, bool Activate) : IRequest<ToggleChatbotRuleResult>;
|
||||
|
||||
public record ToggleChatbotRuleResult(
|
||||
bool Success,
|
||||
string? Error = null
|
||||
);
|
||||
@@ -0,0 +1,100 @@
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using MktZaloService.Domain.AggregatesModel.ChatbotRuleAggregate;
|
||||
using MktZaloService.Infrastructure.Caching;
|
||||
|
||||
namespace MktZaloService.API.Application.Commands.Rules;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for DeleteChatbotRuleCommand.
|
||||
/// VI: Handler cho DeleteChatbotRuleCommand.
|
||||
/// </summary>
|
||||
public class DeleteChatbotRuleCommandHandler :
|
||||
IRequestHandler<DeleteChatbotRuleCommand, DeleteChatbotRuleResult>,
|
||||
IRequestHandler<ToggleChatbotRuleCommand, ToggleChatbotRuleResult>
|
||||
{
|
||||
private readonly IChatbotRuleRepository _ruleRepository;
|
||||
private readonly IChatbotRuleCacheService _cacheService;
|
||||
private readonly ILogger<DeleteChatbotRuleCommandHandler> _logger;
|
||||
|
||||
public DeleteChatbotRuleCommandHandler(
|
||||
IChatbotRuleRepository ruleRepository,
|
||||
IChatbotRuleCacheService cacheService,
|
||||
ILogger<DeleteChatbotRuleCommandHandler> logger)
|
||||
{
|
||||
_ruleRepository = ruleRepository;
|
||||
_cacheService = cacheService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<DeleteChatbotRuleResult> Handle(
|
||||
DeleteChatbotRuleCommand request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var rule = await _ruleRepository.GetByIdAsync(request.RuleId, cancellationToken);
|
||||
|
||||
if (rule == null)
|
||||
{
|
||||
return new DeleteChatbotRuleResult(false, Error: "Rule not found");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_ruleRepository.Delete(rule);
|
||||
await _ruleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
await _cacheService.InvalidateRulesCacheAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation(
|
||||
"EN: Deleted chatbot rule {RuleId}. VI: Đã xóa quy tắc chatbot {RuleId}",
|
||||
request.RuleId);
|
||||
|
||||
return new DeleteChatbotRuleResult(true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"EN: Error deleting chatbot rule. VI: Lỗi xóa quy tắc chatbot");
|
||||
return new DeleteChatbotRuleResult(false, Error: ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ToggleChatbotRuleResult> Handle(
|
||||
ToggleChatbotRuleCommand request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var rule = await _ruleRepository.GetByIdAsync(request.RuleId, cancellationToken);
|
||||
|
||||
if (rule == null)
|
||||
{
|
||||
return new ToggleChatbotRuleResult(false, Error: "Rule not found");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (request.Activate)
|
||||
{
|
||||
rule.Activate();
|
||||
}
|
||||
else
|
||||
{
|
||||
rule.Deactivate();
|
||||
}
|
||||
|
||||
_ruleRepository.Update(rule);
|
||||
await _ruleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
|
||||
await _cacheService.InvalidateRulesCacheAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation(
|
||||
"EN: Toggled rule {RuleId} to {Status}. VI: Đã chuyển trạng thái rule {RuleId} sang {Status}",
|
||||
request.RuleId, request.Activate ? "active" : "inactive");
|
||||
|
||||
return new ToggleChatbotRuleResult(true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"EN: Error toggling chatbot rule. VI: Lỗi chuyển trạng thái quy tắc chatbot");
|
||||
return new ToggleChatbotRuleResult(false, Error: ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using MediatR;
|
||||
using MktZaloService.Domain.Enums;
|
||||
|
||||
namespace MktZaloService.API.Application.Queries.Customers;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Query to get customer details.
|
||||
/// VI: Query để lấy thông tin khách hàng.
|
||||
/// </summary>
|
||||
public record GetCustomerQuery(Guid CustomerId) : IRequest<CustomerDto?>;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Query to get customer by Zalo user ID.
|
||||
/// VI: Query để lấy khách hàng theo Zalo user ID.
|
||||
/// </summary>
|
||||
public record GetCustomerByZaloIdQuery(string ZaloUserId) : IRequest<CustomerDto?>;
|
||||
|
||||
/// <summary>
|
||||
/// EN: DTO for customer details.
|
||||
/// VI: DTO cho thông tin khách hàng.
|
||||
/// </summary>
|
||||
public record CustomerDto(
|
||||
Guid Id,
|
||||
string ZaloUserId,
|
||||
string DisplayName,
|
||||
string? AvatarUrl,
|
||||
string? PhoneNumber,
|
||||
string? Email,
|
||||
string Segment,
|
||||
int ConversationCount,
|
||||
int TotalMessageCount,
|
||||
bool IsActive,
|
||||
DateTime FirstInteractionAt,
|
||||
DateTime LastInteractionAt,
|
||||
List<string> Tags
|
||||
);
|
||||
@@ -0,0 +1,55 @@
|
||||
using MediatR;
|
||||
using MktZaloService.Domain.AggregatesModel.CustomerAggregate;
|
||||
|
||||
namespace MktZaloService.API.Application.Queries.Customers;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for GetCustomerQuery.
|
||||
/// VI: Handler cho GetCustomerQuery.
|
||||
/// </summary>
|
||||
public class GetCustomerQueryHandler :
|
||||
IRequestHandler<GetCustomerQuery, CustomerDto?>,
|
||||
IRequestHandler<GetCustomerByZaloIdQuery, CustomerDto?>
|
||||
{
|
||||
private readonly ICustomerRepository _customerRepository;
|
||||
|
||||
public GetCustomerQueryHandler(ICustomerRepository customerRepository)
|
||||
{
|
||||
_customerRepository = customerRepository;
|
||||
}
|
||||
|
||||
public async Task<CustomerDto?> Handle(
|
||||
GetCustomerQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var customer = await _customerRepository.GetByIdAsync(request.CustomerId, cancellationToken);
|
||||
return customer != null ? MapToDto(customer) : null;
|
||||
}
|
||||
|
||||
public async Task<CustomerDto?> Handle(
|
||||
GetCustomerByZaloIdQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var customer = await _customerRepository.FindByZaloUserIdAsync(request.ZaloUserId, cancellationToken);
|
||||
return customer != null ? MapToDto(customer) : null;
|
||||
}
|
||||
|
||||
private static CustomerDto MapToDto(ZaloCustomer customer)
|
||||
{
|
||||
return new CustomerDto(
|
||||
customer.Id,
|
||||
customer.ZaloUserId,
|
||||
customer.Profile.DisplayName,
|
||||
customer.Profile.AvatarUrl,
|
||||
customer.Profile.PhoneNumber,
|
||||
customer.Profile.Email,
|
||||
customer.Segment.ToString(),
|
||||
customer.ConversationCount,
|
||||
customer.TotalMessageCount,
|
||||
customer.IsActive,
|
||||
customer.FirstInteractionAt,
|
||||
customer.LastInteractionAt,
|
||||
customer.Tags.Select(t => t.Name).ToList()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using MediatR;
|
||||
using MktZaloService.Domain.AggregatesModel.ChatbotRuleAggregate;
|
||||
using MktZaloService.API.Application.Commands.Rules;
|
||||
|
||||
namespace MktZaloService.API.Application.Queries.Rules;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Query to get all chatbot rules.
|
||||
/// VI: Query để lấy tất cả quy tắc chatbot.
|
||||
/// </summary>
|
||||
public record GetChatbotRulesQuery(bool IncludeInactive = false) : IRequest<List<ChatbotRuleDto>>;
|
||||
|
||||
/// <summary>
|
||||
/// EN: DTO for chatbot rule.
|
||||
/// VI: DTO cho quy tắc chatbot.
|
||||
/// </summary>
|
||||
public record ChatbotRuleDto(
|
||||
Guid Id,
|
||||
string Name,
|
||||
string? Description,
|
||||
string Type,
|
||||
int Priority,
|
||||
bool IsActive,
|
||||
string ActionType,
|
||||
string? ResponseText,
|
||||
Guid? TemplateId,
|
||||
List<RuleConditionDto> Conditions,
|
||||
int MatchCount,
|
||||
DateTime? LastMatchedAt,
|
||||
DateTime CreatedAt
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// EN: Handler for GetChatbotRulesQuery.
|
||||
/// VI: Handler cho GetChatbotRulesQuery.
|
||||
/// </summary>
|
||||
public class GetChatbotRulesQueryHandler : IRequestHandler<GetChatbotRulesQuery, List<ChatbotRuleDto>>
|
||||
{
|
||||
private readonly IChatbotRuleRepository _ruleRepository;
|
||||
|
||||
public GetChatbotRulesQueryHandler(IChatbotRuleRepository ruleRepository)
|
||||
{
|
||||
_ruleRepository = ruleRepository;
|
||||
}
|
||||
|
||||
public async Task<List<ChatbotRuleDto>> Handle(
|
||||
GetChatbotRulesQuery request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var rules = request.IncludeInactive
|
||||
? await _ruleRepository.GetAllAsync(cancellationToken)
|
||||
: await _ruleRepository.GetActiveRulesOrderedByPriorityAsync(cancellationToken);
|
||||
|
||||
return rules.Select(r => new ChatbotRuleDto(
|
||||
r.Id,
|
||||
r.Name,
|
||||
r.Description,
|
||||
r.Type.ToString(),
|
||||
r.Priority,
|
||||
r.IsActive,
|
||||
r.Action.ActionType.ToString(),
|
||||
r.Action.ResponseText,
|
||||
r.Action.TemplateId,
|
||||
r.Conditions.Select(c => new RuleConditionDto(c.Field, c.Operator, c.Value)).ToList(),
|
||||
r.MatchCount,
|
||||
r.LastMatchedAt,
|
||||
r.CreatedAt
|
||||
)).ToList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using MktZaloService.Domain.AggregatesModel.ConversationAggregate;
|
||||
using MktZaloService.Infrastructure.Caching;
|
||||
|
||||
namespace MktZaloService.API.Application.Services;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Interface for chatbot engines.
|
||||
/// VI: Interface cho các engine chatbot.
|
||||
/// </summary>
|
||||
public interface IChatbotEngine
|
||||
{
|
||||
/// <summary>
|
||||
/// EN: Get the name of the engine.
|
||||
/// VI: Lấy tên của engine.
|
||||
/// </summary>
|
||||
string Name { get; }
|
||||
|
||||
/// <summary>
|
||||
/// EN: Check if this engine can handle the message.
|
||||
/// VI: Kiểm tra xem engine này có thể xử lý tin nhắn không.
|
||||
/// </summary>
|
||||
Task<bool> CanHandleAsync(string userMessage, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// EN: Generate a response for the user message.
|
||||
/// VI: Tạo phản hồi cho tin nhắn người dùng.
|
||||
/// </summary>
|
||||
Task<ChatbotResponse> GenerateResponseAsync(
|
||||
Guid conversationId,
|
||||
string userMessage,
|
||||
CancellationToken ct = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Response from a chatbot engine.
|
||||
/// VI: Phản hồi từ engine chatbot.
|
||||
/// </summary>
|
||||
public record ChatbotResponse(
|
||||
bool Success,
|
||||
string? ResponseText = null,
|
||||
bool RequiresHumanHandoff = false,
|
||||
string? Error = null
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// EN: AI chatbot engine using Azure OpenAI.
|
||||
/// VI: Engine chatbot AI sử dụng Azure OpenAI.
|
||||
/// </summary>
|
||||
public class AiChatbotEngine : IChatbotEngine
|
||||
{
|
||||
public string Name => "AI";
|
||||
|
||||
private readonly IConversationCacheService _cacheService;
|
||||
private readonly IConversationRepository _conversationRepository;
|
||||
private readonly ILogger<AiChatbotEngine> _logger;
|
||||
|
||||
// EN: System prompt for the AI / VI: Prompt hệ thống cho AI
|
||||
private const string SystemPrompt = """
|
||||
Bạn là trợ lý ảo thân thiện của cửa hàng. Hãy trả lời ngắn gọn, lịch sự bằng tiếng Việt.
|
||||
Nếu không biết câu trả lời, hãy đề nghị chuyển đến nhân viên hỗ trợ.
|
||||
Không bao giờ tiết lộ rằng bạn là AI.
|
||||
""";
|
||||
|
||||
public AiChatbotEngine(
|
||||
IConversationCacheService cacheService,
|
||||
IConversationRepository conversationRepository,
|
||||
ILogger<AiChatbotEngine> logger)
|
||||
{
|
||||
_cacheService = cacheService;
|
||||
_conversationRepository = conversationRepository;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public Task<bool> CanHandleAsync(string userMessage, CancellationToken ct = default)
|
||||
{
|
||||
// EN: AI engine is the fallback, so it can handle anything
|
||||
// VI: AI engine là fallback, nên có thể xử lý mọi thứ
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
public async Task<ChatbotResponse> GenerateResponseAsync(
|
||||
Guid conversationId,
|
||||
string userMessage,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
// EN: Get conversation context from cache / VI: Lấy context cuộc hội thoại từ cache
|
||||
var context = await _cacheService.GetContextAsync(conversationId, ct);
|
||||
|
||||
// EN: Build conversation history for context
|
||||
// VI: Xây dựng lịch sử hội thoại cho context
|
||||
var chatHistory = new List<(string Role, string Content)>
|
||||
{
|
||||
("system", SystemPrompt)
|
||||
};
|
||||
|
||||
// EN: Add recent messages from context if available
|
||||
// VI: Thêm các tin nhắn gần đây từ context nếu có
|
||||
if (context?.RecentMessages != null)
|
||||
{
|
||||
foreach (var msg in context.RecentMessages.TakeLast(10))
|
||||
{
|
||||
chatHistory.Add((msg.IsFromBot ? "assistant" : "user", msg.Content));
|
||||
}
|
||||
}
|
||||
|
||||
chatHistory.Add(("user", userMessage));
|
||||
|
||||
// EN: NOTE: This is a placeholder. In production, integrate with Azure OpenAI:
|
||||
// VI: LƯU Ý: Đây là placeholder. Trong production, tích hợp với Azure OpenAI:
|
||||
//
|
||||
// var client = new OpenAIClient(endpoint, credential);
|
||||
// var response = await client.GetChatCompletionsAsync(deploymentId, chatOptions, ct);
|
||||
// var responseText = response.Value.Choices[0].Message.Content;
|
||||
|
||||
// EN: For now, return a placeholder response / VI: Tạm thời trả về phản hồi placeholder
|
||||
var responseText = GeneratePlaceholderResponse(userMessage);
|
||||
|
||||
_logger.LogInformation(
|
||||
"EN: AI generated response for conversation {ConversationId}. VI: AI đã tạo phản hồi cho cuộc hội thoại {ConversationId}",
|
||||
conversationId);
|
||||
|
||||
// EN: Update context cache / VI: Cập nhật cache context
|
||||
if (context != null)
|
||||
{
|
||||
context.RecentMessages.Add(new CachedMessage
|
||||
{
|
||||
Content = userMessage,
|
||||
IsFromBot = false,
|
||||
SentAt = DateTime.UtcNow
|
||||
});
|
||||
context.RecentMessages.Add(new CachedMessage
|
||||
{
|
||||
Content = responseText,
|
||||
IsFromBot = true,
|
||||
SentAt = DateTime.UtcNow
|
||||
});
|
||||
await _cacheService.SetContextAsync(conversationId, context, ct);
|
||||
}
|
||||
|
||||
return new ChatbotResponse(true, ResponseText: responseText);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"EN: AI engine error. VI: Lỗi engine AI");
|
||||
return new ChatbotResponse(false, Error: ex.Message, RequiresHumanHandoff: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Generate a placeholder response (to be replaced with real AI).
|
||||
/// VI: Tạo phản hồi placeholder (sẽ thay bằng AI thật).
|
||||
/// </summary>
|
||||
private static string GeneratePlaceholderResponse(string userMessage)
|
||||
{
|
||||
var lowerMsg = userMessage.ToLowerInvariant();
|
||||
|
||||
if (lowerMsg.Contains("cảm ơn") || lowerMsg.Contains("thank"))
|
||||
{
|
||||
return "Rất vui được hỗ trợ bạn! Nếu cần thêm thông tin, hãy liên hệ lại nhé.";
|
||||
}
|
||||
|
||||
if (lowerMsg.Contains("?") || lowerMsg.Contains("gì") || lowerMsg.Contains("nào"))
|
||||
{
|
||||
return "Cảm ơn câu hỏi của bạn. Để được hỗ trợ chi tiết hơn, vui lòng liên hệ số hotline hoặc nhắn 'gặp nhân viên'.";
|
||||
}
|
||||
|
||||
return "Cảm ơn bạn đã liên hệ. Chúng tôi sẽ phản hồi sớm nhất có thể!";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using MktZaloService.API.Application.Commands.Rules;
|
||||
using MktZaloService.API.Application.Queries.Rules;
|
||||
using MktZaloService.Domain.Enums;
|
||||
|
||||
namespace MktZaloService.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Controller for managing chatbot rules.
|
||||
/// VI: Controller để quản lý quy tắc chatbot.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/v1/chatbot-rules")]
|
||||
[Authorize]
|
||||
public class ChatbotRulesController : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
private readonly ILogger<ChatbotRulesController> _logger;
|
||||
|
||||
public ChatbotRulesController(IMediator mediator, ILogger<ChatbotRulesController> logger)
|
||||
{
|
||||
_mediator = mediator;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Get all chatbot rules.
|
||||
/// VI: Lấy tất cả quy tắc chatbot.
|
||||
/// </summary>
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<List<ChatbotRuleDto>>> GetRules(
|
||||
[FromQuery] bool includeInactive = false,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var query = new GetChatbotRulesQuery(includeInactive);
|
||||
var result = await _mediator.Send(query, ct);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Create a new chatbot rule.
|
||||
/// VI: Tạo quy tắc chatbot mới.
|
||||
/// </summary>
|
||||
[HttpPost]
|
||||
public async Task<ActionResult<CreateChatbotRuleResult>> CreateRule(
|
||||
[FromBody] CreateRuleRequest request,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var command = new CreateChatbotRuleCommand(
|
||||
request.Name,
|
||||
request.Description,
|
||||
Enum.Parse<RuleType>(request.Type),
|
||||
request.Priority,
|
||||
Enum.Parse<ActionType>(request.ActionType),
|
||||
request.ResponseText,
|
||||
request.TemplateId,
|
||||
request.Conditions.Select(c => new RuleConditionDto(c.Field, c.Operator, c.Value)).ToList()
|
||||
);
|
||||
|
||||
var result = await _mediator.Send(command, ct);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
return BadRequest(new { error = result.Error });
|
||||
}
|
||||
|
||||
_logger.LogInformation(
|
||||
"EN: Created rule {RuleId}. VI: Đã tạo quy tắc {RuleId}",
|
||||
result.RuleId);
|
||||
|
||||
return CreatedAtAction(nameof(GetRules), new { id = result.RuleId }, result);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Request to create a chatbot rule.
|
||||
/// VI: Request để tạo quy tắc chatbot.
|
||||
/// </summary>
|
||||
public record CreateRuleRequest(
|
||||
string Name,
|
||||
string? Description,
|
||||
string Type,
|
||||
int Priority,
|
||||
string ActionType,
|
||||
string? ResponseText,
|
||||
Guid? TemplateId,
|
||||
List<ConditionRequest> Conditions
|
||||
);
|
||||
|
||||
public record ConditionRequest(string Field, string Operator, string Value);
|
||||
@@ -0,0 +1,106 @@
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using MktZaloService.API.Application.Commands.Customers;
|
||||
using MktZaloService.API.Application.Queries.Customers;
|
||||
|
||||
namespace MktZaloService.API.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// EN: Controller for managing customers.
|
||||
/// VI: Controller để quản lý khách hàng.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("api/v1/customers")]
|
||||
[Authorize]
|
||||
public class CustomersController : ControllerBase
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public CustomersController(IMediator mediator)
|
||||
{
|
||||
_mediator = mediator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Get customer by ID.
|
||||
/// VI: Lấy khách hàng theo ID.
|
||||
/// </summary>
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<ActionResult<CustomerDto>> GetCustomer(
|
||||
Guid id,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var query = new GetCustomerQuery(id);
|
||||
var result = await _mediator.Send(query, ct);
|
||||
|
||||
if (result == null)
|
||||
{
|
||||
return NotFound(new { error = "Customer not found" });
|
||||
}
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Get customer by Zalo user ID.
|
||||
/// VI: Lấy khách hàng theo Zalo user ID.
|
||||
/// </summary>
|
||||
[HttpGet("by-zalo/{zaloUserId}")]
|
||||
public async Task<ActionResult<CustomerDto>> GetCustomerByZaloId(
|
||||
string zaloUserId,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var query = new GetCustomerByZaloIdQuery(zaloUserId);
|
||||
var result = await _mediator.Send(query, ct);
|
||||
|
||||
if (result == null)
|
||||
{
|
||||
return NotFound(new { error = "Customer not found" });
|
||||
}
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Update customer profile and tags.
|
||||
/// VI: Cập nhật profile và tags khách hàng.
|
||||
/// </summary>
|
||||
[HttpPatch("{id:guid}")]
|
||||
public async Task<IActionResult> UpdateCustomer(
|
||||
Guid id,
|
||||
[FromBody] UpdateCustomerRequest request,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var command = new UpdateCustomerCommand(
|
||||
id,
|
||||
request.DisplayName,
|
||||
request.AvatarUrl,
|
||||
request.PhoneNumber,
|
||||
request.Email,
|
||||
request.TagsToAdd,
|
||||
request.TagsToRemove);
|
||||
|
||||
var result = await _mediator.Send(command, ct);
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
return BadRequest(new { error = result.Error });
|
||||
}
|
||||
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// EN: Request to update customer.
|
||||
/// VI: Request để cập nhật khách hàng.
|
||||
/// </summary>
|
||||
public record UpdateCustomerRequest(
|
||||
string? DisplayName,
|
||||
string? AvatarUrl,
|
||||
string? PhoneNumber,
|
||||
string? Email,
|
||||
List<string>? TagsToAdd,
|
||||
List<string>? TagsToRemove
|
||||
);
|
||||
@@ -2,6 +2,7 @@ using Asp.Versioning;
|
||||
using FluentValidation;
|
||||
using Hellang.Middleware.ProblemDetails;
|
||||
using MktZaloService.API.Application.Behaviors;
|
||||
using MktZaloService.API.Application.Services;
|
||||
using MktZaloService.Infrastructure;
|
||||
using Serilog;
|
||||
|
||||
@@ -26,6 +27,9 @@ try
|
||||
// EN: Add Infrastructure services / VI: Thêm Infrastructure services
|
||||
builder.Services.AddInfrastructure(builder.Configuration);
|
||||
|
||||
// EN: Add application services / VI: Thêm application services
|
||||
builder.Services.AddScoped<IChatbotRulesService, ChatbotRulesService>();
|
||||
|
||||
// EN: Add MediatR with behaviors / VI: Thêm MediatR với behaviors
|
||||
builder.Services.AddMediatR(cfg =>
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user