diff --git a/AGENTS.md b/AGENTS.md
index e3088a6..88d598f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -64,7 +64,7 @@ cd SafeSpace-Customer-UI/SafeSpace-Customer-UI && npm run dev # UI: http://
```
Cần: .NET SDK 10 (project đặt `net10.0`), Node ≥ 22.12, SQL Server (mặc định `.\SQLEXPRESS`).
-Tài khoản seed: `customer01`/`Customer@123`, `staff01`/`Staff@123`, `admin`/`Admin@123`.
+Tài khoản seed: `customer01`/`Customer@123`, `staff01`/`Staff@123`, `ops01`/`Ops@123` (Vận hành KD), `admin`/`Admin@123`.
Không có backend: tạo `.env.local` với `VITE_USE_API=false`, hoặc `MOCK_OPS=1 npm run dev:mock` (máy chủ giả có cả `/api/ops/*`,
thêm `manager01`/`Manager@123`).
diff --git a/DECISIONS.md b/DECISIONS.md
index c423cbd..6ba929d 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -75,3 +75,14 @@
- Backend trả 404 cho `/api/ops/board` → giao diện chuyển sang lưu trên trình duyệt (`safespace.ops.v1`) và hiện dòng
"Khu vận hành chưa kết nối được máy chủ. Thao tác đang được lưu trên trình duyệt này." (không dùng chữ "dữ liệu mẫu", theo D07).
- Mock `npm run dev:mock` với `MOCK_OPS=1` có đủ endpoint này để thử; backend làm xong thì không cần sửa giao diện.
+
+## D16 — Vai trò Vận hành KD và quy ước báo cáo — Đã chốt (14/10/2026)
+- Tên role backend là `OPERATIONS` (khớp `src/lib/roles.js`). API riêng `/api/operations/*`, chỉ role này gọi được;
+ hợp đồng chi tiết ở `docs/operations-api.md`. Tài khoản seed `ops01` / `Ops@123`.
+- Chính sách `DEPOSIT`: `PERCENTAGE` = % tiền thuê cả kỳ; `FIXED ≥ 1.000` = số tiền VND; `FIXED < 1.000` = số tháng tiền thuê
+ (giữ nghĩa của chính sách seed `Value = 1` = 1 tháng, khớp D09). Chỉ chính sách `ACTIVE` còn hiệu lực mới được áp dụng.
+- Tra cứu giá thuê chỉ lấy `rental_rates.Status = ACTIVE`, để giá bị thay thế (`INACTIVE`) không còn được dùng.
+- Báo cáo: `payments` chưa có `original_payment_id`, và hoàn tiền hiện chỉ có hoàn cọc, nên mọi REFUND trừ vào
+ "Cọc còn giữ"; "Doanh thu thuê và phí" không trừ REFUND. Khi thêm hoàn tiền thuê/phí thì phải thêm liên kết khoản gốc.
+- Cơ sở `TEMPORARILY_CLOSED` chặn đặt chỗ mới; `INACTIVE` chỉ khi không còn hợp đồng / đơn đang xử lý. Không xoá cơ sở.
+
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md
index 23b8bdc..b3375fa 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md
@@ -75,8 +75,8 @@ Luật nghiệp vụ chi tiết (điều kiện chặn, chuyển trạng thái)
## C. Ưu tiên 3 — chỉnh nhỏ
- [ ] JSON `DateTime` trả kèm `Z` (UTC); hiện đọc từ DB không có múi giờ, giao diện phải tự coi là UTC.
- [ ] Giữ chỗ đơn chờ chuyển khoản: backend 24 giờ, Figma 1 phút → thống nhất một con số (giao diện đọc `VITE_PAYMENT_TIMEOUT_SECONDS`).
-- [ ] Khu quản trị: role `OPERATIONS` (Vận hành KD), ghi lịch sử đăng nhập thất bại, lọc nhật ký nhiều `action`.
-- [ ] Khu Vận hành KD (Figma B01–B05) chưa có giao diện lẫn API — để sau.
+- [ ] Khu quản trị: ~~role `OPERATIONS` (Vận hành KD)~~ (đã có), ghi lịch sử đăng nhập thất bại, lọc nhật ký nhiều `action`.
+- [x] API khu Vận hành KD (Figma B01–B05): `/api/operations/*`, role `OPERATIONS`, tài khoản `ops01` / `Ops@123` — hợp đồng ở `docs/operations-api.md`. Giao diện B01–B05 chưa có.
---
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md
index 7aa3662..98c15f0 100644
--- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md
+++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md
@@ -38,7 +38,7 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend:
Đã gọi toàn bộ `/api/admin/*` hiện có (xem `ADMIN-FLOW-COVERAGE.md`). Đề xuất bổ sung phía backend:
- Gửi email mời / đặt mật khẩu lần đầu khi tạo tài khoản (Figma A02 "Gửi lời mời").
-- Vai trò `OPERATIONS` (Vận hành KD) như Figma.
+- ~~Vai trò `OPERATIONS` (Vận hành KD) như Figma.~~ Đã có (14/10/2026): role `OPERATIONS`, tài khoản `ops01`, API `/api/operations/*` — xem `docs/operations-api.md`.
- Ghi lịch sử đăng nhập **thất bại** (hiện chỉ ghi khi thành công) và lưu IP vào nhật ký hoạt động.
- Cho lọc nhật ký theo nhiều `action` một lúc (để tab "Thay đổi dữ liệu" / "Phân quyền" phân trang ở máy chủ).
- Trả kèm cơ sở phụ trách trong `GET /api/admin/users` để khỏi gọi thêm từng người.
diff --git a/StorageProject.Api/Endpoints/OperationsEndpoints.cs b/StorageProject.Api/Endpoints/OperationsEndpoints.cs
new file mode 100644
index 0000000..d8d20f6
--- /dev/null
+++ b/StorageProject.Api/Endpoints/OperationsEndpoints.cs
@@ -0,0 +1,168 @@
+using System.Security.Claims;
+using StorageProject.Api.Extensions;
+using StorageProject.Core.DTOs.Operations;
+using StorageProject.Core.Exceptions;
+using StorageProject.Core.Interfaces;
+
+namespace StorageProject.Api.Endpoints;
+
+///
+/// Khu Quản lý vận hành kinh doanh (Business Operations Manager) — UC19–UC23.
+/// Chỉ role OPERATIONS; sai vai trò trả 403.
+///
+public static class OperationsEndpoints
+{
+ public static void MapOperationsEndpoints(this IEndpointRouteBuilder routes)
+ {
+ var group = routes.MapGroup("/api/operations")
+ .WithTags("Business Operations")
+ .RequireAuthorization(policy => policy.RequireRole("OPERATIONS"));
+
+ // ==========================================
+ // UC19 — Cơ sở toàn hệ thống
+ // ==========================================
+ group.MapGet("/facilities", (string? status, string? search, IOperationsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.GetFacilitiesAsync(status, search, ct))))
+ .WithSummary("Danh sách cơ sở toàn hệ thống kèm số kho, tỷ lệ sử dụng, số loại kho có giá, số nhân sự");
+
+ group.MapGet("/facilities/{id:long}", (long id, IOperationsService ops, CancellationToken ct) =>
+ Run(async () =>
+ {
+ var facility = await ops.GetFacilityAsync(id, ct);
+ return facility != null ? Results.Ok(facility) : NotFound($"Không tìm thấy cơ sở với ID: {id}");
+ }))
+ .WithSummary("Chi tiết một cơ sở");
+
+ group.MapPost("/facilities", (UpsertFacilityRequest request, ClaimsPrincipal user, IOperationsService ops, CancellationToken ct) =>
+ Run(async () =>
+ {
+ var result = await ops.CreateFacilityAsync(request, user.GetUserId(), ct);
+ return Results.Created($"/api/operations/facilities/{result.Facility.FacilityId}", result);
+ }))
+ .WithSummary("Thêm cơ sở mới; trả kèm cảnh báo (tên gần giống, thiếu giá/ô kho/nhân sự)");
+
+ group.MapPut("/facilities/{id:long}", (long id, UpsertFacilityRequest request, ClaimsPrincipal user, IOperationsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.UpdateFacilityAsync(id, request, user.GetUserId(), ct))))
+ .WithSummary("Cập nhật tên, địa chỉ, liên hệ, giờ hoạt động");
+
+ group.MapPut("/facilities/{id:long}/status", (long id, ChangeFacilityStatusRequest request, ClaimsPrincipal user, IOperationsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.ChangeFacilityStatusAsync(id, request, user.GetUserId(), ct))))
+ .WithSummary("Đổi trạng thái: ACTIVE / TEMPORARILY_CLOSED (chặn đặt mới) / INACTIVE (chỉ khi không còn hợp đồng, đơn đang xử lý)");
+
+ // ==========================================
+ // UC20 / UC21 — Chính sách, khung giá, phí, giảm giá, miễn phí
+ // ==========================================
+ group.MapGet("/policies", (string? type, string? status, long? facilityId, long? unitTypeId, IOperationsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.GetPoliciesAsync(new PolicyQuery(type, status, facilityId, unitTypeId), ct))))
+ .WithSummary("Danh sách chính sách, lọc theo loại / trạng thái / cơ sở / loại kho");
+
+ group.MapGet("/policies/{id:long}", (long id, IOperationsService ops, CancellationToken ct) =>
+ Run(async () =>
+ {
+ var policy = await ops.GetPolicyAsync(id, ct);
+ return policy != null ? Results.Ok(policy) : NotFound($"Không tìm thấy chính sách với ID: {id}");
+ }))
+ .WithSummary("Chi tiết chính sách");
+
+ group.MapPost("/policies", (UpsertPolicyRequest request, ClaimsPrincipal user, IOperationsService ops, CancellationToken ct) =>
+ Run(async () =>
+ {
+ var policy = await ops.CreatePolicyAsync(request, user.GetUserId(), ct);
+ return Results.Created($"/api/operations/policies/{policy.PolicyId}", policy);
+ }))
+ .WithSummary("Tạo chính sách ở trạng thái Nháp (DRAFT)");
+
+ group.MapPut("/policies/{id:long}", (long id, UpsertPolicyRequest request, ClaimsPrincipal user, IOperationsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.UpdatePolicyAsync(id, request, user.GetUserId(), ct))))
+ .WithSummary("Sửa chính sách Nháp");
+
+ group.MapPost("/policies/{id:long}/activate", (long id, bool? replaceExisting, ClaimsPrincipal user, IOperationsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.ActivatePolicyAsync(id, replaceExisting ?? false, user.GetUserId(), ct))))
+ .WithSummary("Áp dụng chính sách; trùng phạm vi trả 409, gửi replaceExisting=true để kết thúc hiệu lực bản cũ");
+
+ group.MapPost("/policies/{id:long}/deactivate", (long id, ClaimsPrincipal user, IOperationsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.DeactivatePolicyAsync(id, user.GetUserId(), ct))))
+ .WithSummary("Ngừng áp dụng chính sách (giữ lại để truy vết)");
+
+ group.MapDelete("/policies/{id:long}", (long id, ClaimsPrincipal user, IOperationsService ops, CancellationToken ct) =>
+ Run(async () =>
+ {
+ await ops.DeleteDraftPolicyAsync(id, user.GetUserId(), ct);
+ return Results.Ok(new { message = "Đã xoá chính sách nháp." });
+ }))
+ .WithSummary("Xoá chính sách Nháp chưa từng áp dụng");
+
+ // ==========================================
+ // UC21 — Bảng giá thuê
+ // ==========================================
+ group.MapGet("/rates", (long? facilityId, long? unitTypeId, bool? includeHistory, IOperationsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.GetRatesAsync(facilityId, unitTypeId, includeHistory ?? false, ct))))
+ .WithSummary("Giá đang áp dụng và đã lên lịch; includeHistory=true để xem cả giá cũ");
+
+ group.MapPost("/rates", (SetRateRequest request, ClaimsPrincipal user, IOperationsService ops, CancellationToken ct) =>
+ Run(async () => Results.Ok(await ops.SetRateAsync(request, user.GetUserId(), ct))))
+ .WithSummary("Đặt giá mới cho cơ sở + loại kho; kiểm tra khung giá, tự kết thúc giá cũ, không sửa giá đã chốt");
+
+ // ==========================================
+ // UC22 / UC23 — Báo cáo toàn hệ thống
+ // ==========================================
+ group.MapGet("/reports/facilities", (DateOnly? from, DateOnly? to, long? facilityId, long? unitTypeId, IOperationsReportService reports, CancellationToken ct) =>
+ Run(async () => Results.Ok(await reports.GetSystemReportAsync(Filter(from, to, facilityId, unitTypeId), ct))))
+ .WithSummary("Doanh thu, tiền thu/hoàn, cọc, công nợ, tỷ lệ sử dụng, quá hạn theo từng cơ sở + tổng hệ thống");
+
+ group.MapGet("/reports/unit-types", (DateOnly? from, DateOnly? to, long? facilityId, long? unitTypeId, IOperationsReportService reports, CancellationToken ct) =>
+ Run(async () => Results.Ok(await reports.GetUnitTypeReportAsync(Filter(from, to, facilityId, unitTypeId), ct))))
+ .WithSummary("Các chỉ tiêu trên theo loại kho");
+
+ group.MapGet("/reports/revenue-trend", (int? months, long? facilityId, long? unitTypeId, IOperationsReportService reports, CancellationToken ct) =>
+ Run(async () => Results.Ok(await reports.GetRevenueTrendAsync(months ?? 6, facilityId, unitTypeId, ct))))
+ .WithSummary("Tiền thu theo tháng (mặc định 6 tháng gần nhất)");
+
+ group.MapGet("/reports/rental-status", (long? facilityId, long? unitTypeId, IOperationsReportService reports, CancellationToken ct) =>
+ Run(async () => Results.Ok(await reports.GetRentalStatusAsync(facilityId, unitTypeId, ct))))
+ .WithSummary("Số hợp đồng, đơn đặt chỗ, ô kho theo trạng thái");
+
+ group.MapGet("/reports/facilities/{id:long}/contracts", (long id, string? status, long? unitTypeId, IOperationsReportService reports, CancellationToken ct) =>
+ Run(async () => Results.Ok(await reports.GetFacilityContractsAsync(id, status, unitTypeId, ct))))
+ .WithSummary("Chi tiết một cơ sở: hợp đồng, công nợ, case quá hạn");
+
+ group.MapGet("/reports/export", (string? view, DateOnly? from, DateOnly? to, long? facilityId, long? unitTypeId, int? months,
+ ClaimsPrincipal user, IOperationsReportService reports, CancellationToken ct) =>
+ Run(async () =>
+ {
+ var file = await reports.ExportCsvAsync(view ?? "facilities", Filter(from, to, facilityId, unitTypeId), months ?? 6, user.GetUserId(), ct);
+ return Results.File(file.Content, "text/csv; charset=utf-8", file.FileName);
+ }))
+ .WithSummary("Xuất CSV UTF-8: view = facilities | unit-types | revenue-trend, cùng bộ lọc với màn xem");
+ }
+
+ /// Kỳ mặc định: từ đầu tháng hiện tại đến hôm nay (giờ Việt Nam).
+ private static ReportFilter Filter(DateOnly? from, DateOnly? to, long? facilityId, long? unitTypeId)
+ {
+ var today = DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7));
+ return new ReportFilter(from ?? new DateOnly(today.Year, today.Month, 1), to ?? today, facilityId, unitTypeId);
+ }
+
+ private static IResult NotFound(string message) => Results.NotFound(new { error = message });
+
+ /// Quy ước lỗi chung (docs/conventions.md): 400 { error }, 404 { error }, 409 { error, details }.
+ private static async Task Run(Func> action)
+ {
+ try
+ {
+ return await action();
+ }
+ catch (OperationConflictException ex)
+ {
+ return Results.Conflict(new { error = ex.Message, details = ex.Details });
+ }
+ catch (KeyNotFoundException ex)
+ {
+ return NotFound(ex.Message);
+ }
+ catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
+ {
+ return Results.BadRequest(new { error = ex.Message });
+ }
+ }
+}
diff --git a/StorageProject.Api/Program.cs b/StorageProject.Api/Program.cs
index 6e9384b..eaa3f52 100644
--- a/StorageProject.Api/Program.cs
+++ b/StorageProject.Api/Program.cs
@@ -45,7 +45,7 @@
{
Title = "SSFRMS Customer API",
Version = "v1",
- Description = "Self-Storage Facility Rental Management System - Customer Scope API"
+ Description = "Self-Storage Facility Rental Management System - Customer, Admin & Business Operations API"
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
@@ -88,6 +88,8 @@
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();
+builder.Services.AddScoped();
+builder.Services.AddScoped();
var app = builder.Build();
@@ -117,6 +119,7 @@
app.MapRenewalEndpoints();
app.MapSupportTicketEndpoints();
app.MapAdminEndpoints();
+app.MapOperationsEndpoints();
// Root status check
app.MapGet("/health", () => Results.Ok(new
diff --git a/StorageProject.Api/StorageProject.Api.http b/StorageProject.Api/StorageProject.Api.http
index c0fc767..45c3143 100644
--- a/StorageProject.Api/StorageProject.Api.http
+++ b/StorageProject.Api/StorageProject.Api.http
@@ -1,6 +1,67 @@
@StorageProject.Api_HostAddress = http://localhost:5151
-GET {{StorageProject.Api_HostAddress}}/weatherforecast/
-Accept: application/json
+### ==== Quản lý vận hành KD (/api/operations) — đăng nhập ops01 / Ops@123 rồi dán token ====
+@opsToken =
+
+POST {{StorageProject.Api_HostAddress}}/api/auth/login
+Content-Type: application/json
+
+{ "username": "ops01", "password": "Ops@123" }
+
+###
+GET {{StorageProject.Api_HostAddress}}/api/operations/facilities
+Authorization: Bearer {{opsToken}}
+
+###
+POST {{StorageProject.Api_HostAddress}}/api/operations/facilities
+Authorization: Bearer {{opsToken}}
+Content-Type: application/json
+
+{ "name": "SafeSpace Tân Phú", "address": "Đường Lũy Bán Bích, Quận Tân Phú, TP. Hồ Chí Minh", "contactPhone": "028 3700 1022", "openingTime": "06:00", "closingTime": "22:00", "status": "TEMPORARILY_CLOSED" }
+
+###
+PUT {{StorageProject.Api_HostAddress}}/api/operations/facilities/1/status
+Authorization: Bearer {{opsToken}}
+Content-Type: application/json
+
+{ "status": "TEMPORARILY_CLOSED", "reason": "Bảo trì hệ thống PCCC" }
+
+###
+GET {{StorageProject.Api_HostAddress}}/api/operations/policies?status=ACTIVE
+Authorization: Bearer {{opsToken}}
+
+###
+POST {{StorageProject.Api_HostAddress}}/api/operations/policies
+Authorization: Bearer {{opsToken}}
+Content-Type: application/json
+
+{ "policyName": "Khung giá kho Mini S", "policyType": "PRICE_RANGE", "calculationType": "RANGE", "minValue": 300000, "maxValue": 800000, "ruleDescription": "Giá thuê tháng kho Mini S tại mọi cơ sở", "facilityId": null, "unitTypeId": 1, "effectiveFrom": "2026-10-15", "effectiveTo": null }
+
+###
+POST {{StorageProject.Api_HostAddress}}/api/operations/policies/3/activate?replaceExisting=false
+Authorization: Bearer {{opsToken}}
+
+###
+GET {{StorageProject.Api_HostAddress}}/api/operations/rates?facilityId=1
+Authorization: Bearer {{opsToken}}
+
+###
+POST {{StorageProject.Api_HostAddress}}/api/operations/rates
+Authorization: Bearer {{opsToken}}
+Content-Type: application/json
+
+{ "facilityId": 1, "unitTypeId": 1, "monthlyRate": 520000, "effectiveFrom": "2026-11-01" }
+
+###
+GET {{StorageProject.Api_HostAddress}}/api/operations/reports/facilities?from=2026-09-01&to=2026-10-31
+Authorization: Bearer {{opsToken}}
+
+###
+GET {{StorageProject.Api_HostAddress}}/api/operations/reports/revenue-trend?months=6
+Authorization: Bearer {{opsToken}}
+
+###
+GET {{StorageProject.Api_HostAddress}}/api/operations/reports/export?view=facilities&from=2026-09-01&to=2026-10-31
+Authorization: Bearer {{opsToken}}
###
diff --git a/StorageProject.Core/DTOs/Operations/OperationsDtos.cs b/StorageProject.Core/DTOs/Operations/OperationsDtos.cs
new file mode 100644
index 0000000..f5a7fa1
--- /dev/null
+++ b/StorageProject.Core/DTOs/Operations/OperationsDtos.cs
@@ -0,0 +1,181 @@
+namespace StorageProject.Core.DTOs.Operations;
+
+// =====================================================================
+// UC19 — Quản lý danh sách cơ sở toàn hệ thống
+// =====================================================================
+
+public record OpsFacilityDto(
+ long FacilityId,
+ string Name,
+ string Address,
+ string? ContactPhone,
+ string? OpeningTime,
+ string? ClosingTime,
+ string Status,
+ int TotalUnits,
+ int UnitsInUse,
+ int OperableUnits,
+ decimal? OccupancyRate, // null = "Không áp dụng" (không có kho khai thác)
+ int PricedUnitTypes, // số loại kho đang có giá áp dụng hôm nay
+ int AssignedStaff, // số nhân sự (STAFF/MANAGER) đang được phân công
+ DateTime CreatedAt,
+ DateTime UpdatedAt
+);
+
+public record UpsertFacilityRequest(
+ string Name,
+ string Address,
+ string? ContactPhone,
+ string? OpeningTime, // "HH:mm"
+ string? ClosingTime, // "HH:mm"
+ string? Status // chỉ dùng khi tạo mới; đổi trạng thái dùng endpoint /status
+);
+
+public record ChangeFacilityStatusRequest(string Status, string? Reason);
+
+public record FacilitySaveResult(OpsFacilityDto Facility, IReadOnlyList Warnings);
+
+// =====================================================================
+// UC20 / UC21 — Chính sách thuê, khung giá, phí, giảm giá, miễn phí
+// =====================================================================
+
+public record PolicyDto(
+ long PolicyId,
+ string PolicyName,
+ string PolicyType,
+ string? CalculationType,
+ decimal? Value,
+ decimal? MinValue,
+ decimal? MaxValue,
+ string RuleDescription,
+ string Scope, // GLOBAL, FACILITY, UNIT_TYPE, FACILITY_UNIT_TYPE
+ long? FacilityId,
+ string? FacilityName,
+ long? UnitTypeId,
+ string? UnitTypeName,
+ DateOnly EffectiveFrom,
+ DateOnly? EffectiveTo,
+ string Status,
+ long CreatedBy,
+ string CreatedByName,
+ DateTime CreatedAt,
+ DateTime UpdatedAt
+);
+
+public record UpsertPolicyRequest(
+ string PolicyName,
+ string PolicyType,
+ string CalculationType,
+ decimal? Value,
+ decimal? MinValue,
+ decimal? MaxValue,
+ string RuleDescription,
+ long? FacilityId, // null = toàn hệ thống
+ long? UnitTypeId, // null = mọi loại kho
+ DateOnly EffectiveFrom,
+ DateOnly? EffectiveTo
+);
+
+public record PolicyQuery(string? PolicyType, string? Status, long? FacilityId, long? UnitTypeId);
+
+public record ActivatePolicyResult(PolicyDto Policy, IReadOnlyList Superseded);
+
+// =====================================================================
+// UC21 — Bảng giá thuê theo cơ sở và loại kho
+// =====================================================================
+
+public record OpsRateDto(
+ long RateId,
+ long FacilityId,
+ string FacilityName,
+ long UnitTypeId,
+ string UnitTypeName,
+ decimal MonthlyRate,
+ DateOnly EffectiveFrom,
+ DateOnly? EffectiveTo,
+ string Status,
+ bool IsCurrent
+);
+
+public record SetRateRequest(long FacilityId, long UnitTypeId, decimal MonthlyRate, DateOnly? EffectiveFrom);
+
+// =====================================================================
+// UC22 / UC23 — Báo cáo toàn hệ thống (định nghĩa chỉ tiêu theo SRS mục 10.2)
+// =====================================================================
+
+public record ReportFilter(DateOnly From, DateOnly To, long? FacilityId, long? UnitTypeId);
+
+public record ReportMetrics(
+ decimal Collected, // Tiền thu trong kỳ (mọi loại trừ REFUND, kể cả cọc)
+ decimal Refunded, // Tiền hoàn trong kỳ
+ decimal NetCollected, // Thu tiền ròng = thu − hoàn
+ decimal RentalAndFeeRevenue, // Doanh thu thuê và phí theo tiền thu (không gồm cọc)
+ decimal DepositCollected, // Cọc thu trong kỳ
+ decimal DepositHeld, // Cọc còn giữ đến thời điểm báo cáo
+ decimal Outstanding, // Công nợ hiện tại (PENDING/FAILED, amount > 0)
+ int TotalUnits,
+ int UnitsInUse, // OCCUPIED + RETURN_PENDING
+ int UnitsAvailable, // AVAILABLE
+ int UnitsReserved, // RESERVED + ASSIGNED
+ int UnitsUnavailable, // MAINTENANCE + OUT_OF_SERVICE + INSPECTION
+ int OperableUnits, // TotalUnits − UnitsUnavailable
+ decimal? OccupancyRate, // UnitsInUse / OperableUnits × 100; null = Không áp dụng
+ int ActiveContracts,
+ int OverdueCases, // overdue_cases chưa RESOLVED
+ int OverdueContracts // DISTINCT contract_id của các case trên
+);
+
+public record FacilityReportRow(long FacilityId, string FacilityName, string FacilityStatus, ReportMetrics Metrics);
+
+public record UnitTypeReportRow(long UnitTypeId, string UnitTypeName, ReportMetrics Metrics);
+
+public record SystemReportDto(
+ ReportFilter Filter,
+ DateTime SnapshotAt,
+ ReportMetrics Totals,
+ IReadOnlyList Facilities
+);
+
+public record UnitTypeReportDto(
+ ReportFilter Filter,
+ DateTime SnapshotAt,
+ ReportMetrics Totals,
+ IReadOnlyList UnitTypes
+);
+
+public record RevenueMonthRow(
+ int Year,
+ int Month,
+ string Label,
+ decimal Collected,
+ decimal Refunded,
+ decimal RentalAndFeeRevenue,
+ decimal DepositCollected
+);
+
+public record RevenueTrendDto(long? FacilityId, long? UnitTypeId, DateTime SnapshotAt, IReadOnlyList Months);
+
+public record StatusCount(string Status, int Count);
+
+public record RentalStatusDto(
+ long? FacilityId,
+ long? UnitTypeId,
+ DateTime SnapshotAt,
+ IReadOnlyList Contracts,
+ IReadOnlyList Reservations,
+ IReadOnlyList Units
+);
+
+public record FacilityContractRow(
+ long ContractId,
+ string CustomerName,
+ string UnitNumber,
+ string UnitTypeName,
+ DateOnly StartDate,
+ DateOnly EndDate,
+ string Status,
+ decimal Outstanding,
+ int OpenOverdueCases
+);
+
+public record CsvExport(string FileName, byte[] Content);
diff --git a/StorageProject.Core/Exceptions/OperationConflictException.cs b/StorageProject.Core/Exceptions/OperationConflictException.cs
new file mode 100644
index 0000000..495e894
--- /dev/null
+++ b/StorageProject.Core/Exceptions/OperationConflictException.cs
@@ -0,0 +1,10 @@
+namespace StorageProject.Core.Exceptions;
+
+///
+/// Thao tác hợp lệ về dữ liệu nhưng xung đột với trạng thái hiện tại của hệ thống
+/// (ví dụ: chính sách trùng mức ưu tiên, ngừng cơ sở còn hợp đồng). Endpoint trả 409.
+///
+public class OperationConflictException(string message, object? details = null) : Exception(message)
+{
+ public object? Details { get; } = details;
+}
diff --git a/StorageProject.Core/Interfaces/IOperationsServices.cs b/StorageProject.Core/Interfaces/IOperationsServices.cs
new file mode 100644
index 0000000..4abd559
--- /dev/null
+++ b/StorageProject.Core/Interfaces/IOperationsServices.cs
@@ -0,0 +1,38 @@
+using StorageProject.Core.DTOs.Operations;
+
+namespace StorageProject.Core.Interfaces;
+
+/// Quản lý vận hành kinh doanh (Business Operations Manager) — UC19, UC20, UC21.
+public interface IOperationsService
+{
+ // UC19 — Cơ sở
+ Task> GetFacilitiesAsync(string? status, string? search, CancellationToken ct = default);
+ Task GetFacilityAsync(long facilityId, CancellationToken ct = default);
+ Task CreateFacilityAsync(UpsertFacilityRequest request, long userId, CancellationToken ct = default);
+ Task UpdateFacilityAsync(long facilityId, UpsertFacilityRequest request, long userId, CancellationToken ct = default);
+ Task ChangeFacilityStatusAsync(long facilityId, ChangeFacilityStatusRequest request, long userId, CancellationToken ct = default);
+
+ // UC20 / UC21 — Chính sách
+ Task> GetPoliciesAsync(PolicyQuery query, CancellationToken ct = default);
+ Task GetPolicyAsync(long policyId, CancellationToken ct = default);
+ Task CreatePolicyAsync(UpsertPolicyRequest request, long userId, CancellationToken ct = default);
+ Task UpdatePolicyAsync(long policyId, UpsertPolicyRequest request, long userId, CancellationToken ct = default);
+ Task ActivatePolicyAsync(long policyId, bool replaceExisting, long userId, CancellationToken ct = default);
+ Task DeactivatePolicyAsync(long policyId, long userId, CancellationToken ct = default);
+ Task DeleteDraftPolicyAsync(long policyId, long userId, CancellationToken ct = default);
+
+ // UC21 — Bảng giá
+ Task> GetRatesAsync(long? facilityId, long? unitTypeId, bool includeHistory, CancellationToken ct = default);
+ Task SetRateAsync(SetRateRequest request, long userId, CancellationToken ct = default);
+}
+
+/// Báo cáo toàn hệ thống — UC22, UC23. Định nghĩa chỉ tiêu theo SRS mục 10.2.
+public interface IOperationsReportService
+{
+ Task GetSystemReportAsync(ReportFilter filter, CancellationToken ct = default);
+ Task GetUnitTypeReportAsync(ReportFilter filter, CancellationToken ct = default);
+ Task GetRevenueTrendAsync(int months, long? facilityId, long? unitTypeId, CancellationToken ct = default);
+ Task GetRentalStatusAsync(long? facilityId, long? unitTypeId, CancellationToken ct = default);
+ Task> GetFacilityContractsAsync(long facilityId, string? status, long? unitTypeId, CancellationToken ct = default);
+ Task ExportCsvAsync(string view, ReportFilter filter, int months, long userId, CancellationToken ct = default);
+}
diff --git a/StorageProject.Infrastructure/Data/DbSeeder.cs b/StorageProject.Infrastructure/Data/DbSeeder.cs
index 8995836..3e54a99 100644
--- a/StorageProject.Infrastructure/Data/DbSeeder.cs
+++ b/StorageProject.Infrastructure/Data/DbSeeder.cs
@@ -125,6 +125,9 @@ public static async Task SeedAsync(AppDbContext context)
await context.SaveChangesAsync();
}
+ // 2b. Vai trò Quản lý vận hành KD (OPERATIONS) + tài khoản ops01 — chạy lại được với DB đã có
+ await EnsureOperationsRoleAsync(context);
+
var admin = await context.Users.FirstAsync(u => u.Username == "admin");
var staff = await context.Users.FirstAsync(u => u.Username == "staff01");
var cust1 = await context.Users.FirstAsync(u => u.Username == "customer01");
@@ -448,6 +451,79 @@ public static async Task SeedAsync(AppDbContext context)
}
}
+ // ------------------------------------------------------------------------------------------
+ // Quản lý vận hành kinh doanh (SRS: Business Operations Manager — UC19–UC23)
+ // Chỉ thêm phần còn thiếu nên DB tạo từ trước cũng được bổ sung khi khởi động lại API.
+ // ------------------------------------------------------------------------------------------
+ private static async Task EnsureOperationsRoleAsync(AppDbContext context)
+ {
+ var opsRole = await context.Roles.FirstOrDefaultAsync(r => r.RoleName == "OPERATIONS");
+ if (opsRole == null)
+ {
+ opsRole = new Role { RoleName = "OPERATIONS", Description = "Quản lý vận hành kinh doanh toàn hệ thống" };
+ context.Roles.Add(opsRole);
+ await context.SaveChangesAsync();
+ }
+
+ var newPermissions = new List
+ {
+ new() { PermissionCode = "POLICY_MANAGE", PermissionName = "Quản lý chính sách", Description = "Thiết lập chính sách thuê, khung giá, phí, giảm giá và miễn phí" },
+ new() { PermissionCode = "REPORT_SYSTEM", PermissionName = "Xem báo cáo toàn hệ thống", Description = "Xem doanh thu và hiệu suất của mọi cơ sở" },
+ new() { PermissionCode = "REPORT_EXPORT", PermissionName = "Xuất báo cáo", Description = "Xuất báo cáo toàn hệ thống ra tệp CSV" }
+ };
+ foreach (var perm in newPermissions)
+ {
+ if (!await context.Permissions.AnyAsync(p => p.PermissionCode == perm.PermissionCode))
+ {
+ context.Permissions.Add(perm);
+ }
+ }
+ await context.SaveChangesAsync();
+
+ // ADMIN giữ toàn bộ quyền như thiết lập ban đầu
+ var adminRole = await context.Roles.FirstOrDefaultAsync(r => r.RoleName == "ADMIN");
+ var opsCodes = new[] { "FACILITY_MANAGE", "POLICY_MANAGE", "REPORT_VIEW", "REPORT_SYSTEM", "REPORT_EXPORT" };
+ var allPermissions = await context.Permissions.ToListAsync();
+ var existingPairs = await context.RolePermissions.Select(rp => new { rp.RoleId, rp.PermissionId }).ToListAsync();
+
+ foreach (var perm in allPermissions)
+ {
+ if (adminRole != null && !existingPairs.Any(x => x.RoleId == adminRole.RoleId && x.PermissionId == perm.PermissionId))
+ {
+ context.RolePermissions.Add(new RolePermission { RoleId = adminRole.RoleId, PermissionId = perm.PermissionId });
+ }
+ if (opsCodes.Contains(perm.PermissionCode) && !existingPairs.Any(x => x.RoleId == opsRole.RoleId && x.PermissionId == perm.PermissionId))
+ {
+ context.RolePermissions.Add(new RolePermission { RoleId = opsRole.RoleId, PermissionId = perm.PermissionId });
+ }
+ }
+ await context.SaveChangesAsync();
+
+ var opsUser = await context.Users.FirstOrDefaultAsync(u => u.Username == "ops01");
+ if (opsUser == null)
+ {
+ opsUser = new User
+ {
+ Username = "ops01",
+ Email = "ops01@storage.vn",
+ PasswordHash = BCrypt.Net.BCrypt.HashPassword("Ops@123"),
+ FullName = "Lê Vận Hành",
+ Phone = "0900000004",
+ Status = "ACTIVE",
+ CreatedAt = DateTime.UtcNow,
+ UpdatedAt = DateTime.UtcNow
+ };
+ context.Users.Add(opsUser);
+ await context.SaveChangesAsync();
+ }
+
+ if (!await context.UserRoles.AnyAsync(ur => ur.UserId == opsUser.UserId && ur.RoleId == opsRole.RoleId))
+ {
+ context.UserRoles.Add(new UserRole { UserId = opsUser.UserId, RoleId = opsRole.RoleId, AssignedAt = DateTime.UtcNow });
+ await context.SaveChangesAsync();
+ }
+ }
+
// ------------------------------------------------------------------------------------------
// Mạng lưới cơ sở SafeSpace (Figma C02 / Trang chủ)
// RateM = giá kho Tiêu Chuẩn M; các loại khác tính theo tỉ lệ (S ≈ 40%, L = 2×, XL = 3,5×).
diff --git a/StorageProject.Infrastructure/Services/FacilityService.cs b/StorageProject.Infrastructure/Services/FacilityService.cs
index 6129aad..8ea92c3 100644
--- a/StorageProject.Infrastructure/Services/FacilityService.cs
+++ b/StorageProject.Infrastructure/Services/FacilityService.cs
@@ -94,7 +94,7 @@ public async Task> GetActiveRatesAsync(long? facili
.AsNoTracking()
.Include(r => r.Facility)
.Include(r => r.UnitType)
- .Where(r => r.EffectiveFrom <= today && (r.EffectiveTo == null || r.EffectiveTo >= today));
+ .Where(r => r.Status == "ACTIVE" && r.EffectiveFrom <= today && (r.EffectiveTo == null || r.EffectiveTo >= today));
if (facilityId.HasValue)
{
@@ -134,6 +134,7 @@ public async Task> GetActiveRatesAsync(long? facili
var activeRate = await dbContext.RentalRates
.Where(r => r.FacilityId == request.FacilityId
&& r.UnitTypeId == request.UnitTypeId
+ && r.Status == "ACTIVE"
&& r.EffectiveFrom <= today
&& (r.EffectiveTo == null || r.EffectiveTo >= today))
.OrderByDescending(r => r.EffectiveFrom)
@@ -158,20 +159,12 @@ public async Task> GetActiveRatesAsync(long? facili
var availableCount = Math.Max(0, totalMatchingUnits - reservedUnitsCount);
- // Fetch deposit policy (default: 1 month of rent)
- decimal depositMultiplier = 1;
- var depositPolicy = await dbContext.Policies
- .Where(p => p.PolicyType == "DEPOSIT" &&
- (p.FacilityId == request.FacilityId || p.FacilityId == null))
- .FirstOrDefaultAsync(ct);
-
- if (depositPolicy?.Value.HasValue == true)
- {
- depositMultiplier = depositPolicy.Value.Value;
- }
+ // Cọc theo chính sách DEPOSIT đang áp dụng (BR20, BR21) — cùng cách tính với lúc tạo đơn đặt chỗ
+ var depositPolicy = await OpsRules.FindApplicablePolicyAsync(
+ dbContext, "DEPOSIT", request.FacilityId, request.UnitTypeId, today, ct);
- var requiredDeposit = monthlyRate * depositMultiplier;
var estimatedTotalRent = monthlyRate * request.RentalPeriodMonths;
+ var requiredDeposit = OpsRules.CalculateDeposit(depositPolicy, monthlyRate, estimatedTotalRent);
return new AvailabilityResultDto(
facility.FacilityId,
diff --git a/StorageProject.Infrastructure/Services/OperationsReportService.cs b/StorageProject.Infrastructure/Services/OperationsReportService.cs
new file mode 100644
index 0000000..592f1a6
--- /dev/null
+++ b/StorageProject.Infrastructure/Services/OperationsReportService.cs
@@ -0,0 +1,431 @@
+using System.Globalization;
+using System.Text;
+using System.Text.Json;
+using Microsoft.EntityFrameworkCore;
+using StorageProject.Core.DTOs.Operations;
+using StorageProject.Core.Entities;
+using StorageProject.Core.Interfaces;
+using StorageProject.Infrastructure.Data;
+
+namespace StorageProject.Infrastructure.Services;
+
+///
+/// Báo cáo toàn hệ thống cho Quản lý vận hành KD (UC22, UC23).
+/// Chỉ tiêu theo SRS mục 10.2; tiền truy qua payment → contract → unit → facility / unit_type.
+/// Kỳ báo cáo tính theo ngày giờ Việt Nam (UTC+7); trạng thái kho là ảnh chụp tại SnapshotAt, không phải số liệu lịch sử.
+///
+///
+/// Giả định của bản cơ bản: bảng payments chưa có original_payment_id, và quy trình hoàn tiền hiện có là hoàn cọc
+/// sau trả kho. Vì vậy mọi khoản REFUND được trừ vào "Cọc còn giữ"; "Doanh thu thuê và phí" không trừ REFUND.
+///
+public class OperationsReportService(AppDbContext dbContext) : IOperationsReportService
+{
+ private static readonly CultureInfo Vi = CultureInfo.InvariantCulture; // chỉ dùng định dạng số/ngày cố định, không phụ thuộc ngôn ngữ máy chủ
+
+ // ---------------------------------------------------------------------
+ // Dữ liệu nguồn (đọc một lần, tổng hợp trong bộ nhớ — dữ liệu dự án nhỏ)
+ // ---------------------------------------------------------------------
+
+ private sealed record PayRow(string Type, decimal Amount, string Status, DateTime? PaidAt, long FacilityId, long UnitTypeId, string ContractStatus);
+ private sealed record UnitRow(long FacilityId, long UnitTypeId, string Status);
+ private sealed record ContractRow(long ContractId, long FacilityId, long UnitTypeId, string Status);
+ private sealed record OverdueRow(long ContractId, long FacilityId, long UnitTypeId);
+
+ private sealed record Source(List Payments, List Units, List Contracts, List Overdues)
+ {
+ public Source Where(Func keep) => new(
+ Payments.Where(p => keep(p.FacilityId, p.UnitTypeId)).ToList(),
+ Units.Where(u => keep(u.FacilityId, u.UnitTypeId)).ToList(),
+ Contracts.Where(c => keep(c.FacilityId, c.UnitTypeId)).ToList(),
+ Overdues.Where(o => keep(o.FacilityId, o.UnitTypeId)).ToList());
+ }
+
+ private async Task LoadAsync(long? facilityId, long? unitTypeId, CancellationToken ct)
+ {
+ var payments = dbContext.Payments.AsNoTracking().AsQueryable();
+ var units = dbContext.StorageUnits.AsNoTracking().AsQueryable();
+ var contracts = dbContext.RentalContracts.AsNoTracking().AsQueryable();
+ var overdues = dbContext.OverdueCases.AsNoTracking().Where(o => o.Status != "RESOLVED");
+
+ if (facilityId.HasValue)
+ {
+ payments = payments.Where(p => p.Contract.Unit.FacilityId == facilityId);
+ units = units.Where(u => u.FacilityId == facilityId);
+ contracts = contracts.Where(c => c.Unit.FacilityId == facilityId);
+ overdues = overdues.Where(o => o.Contract.Unit.FacilityId == facilityId);
+ }
+ if (unitTypeId.HasValue)
+ {
+ payments = payments.Where(p => p.Contract.Unit.UnitTypeId == unitTypeId);
+ units = units.Where(u => u.UnitTypeId == unitTypeId);
+ contracts = contracts.Where(c => c.Unit.UnitTypeId == unitTypeId);
+ overdues = overdues.Where(o => o.Contract.Unit.UnitTypeId == unitTypeId);
+ }
+
+ return new Source(
+ await payments.Select(p => new PayRow(p.PaymentType, p.Amount, p.Status, p.PaidAt,
+ p.Contract.Unit.FacilityId, p.Contract.Unit.UnitTypeId, p.Contract.Status)).ToListAsync(ct),
+ await units.Select(u => new UnitRow(u.FacilityId, u.UnitTypeId, u.Status)).ToListAsync(ct),
+ await contracts.Select(c => new ContractRow(c.ContractId, c.Unit.FacilityId, c.Unit.UnitTypeId, c.Status)).ToListAsync(ct),
+ await overdues.Select(o => new OverdueRow(o.ContractId, o.Contract.Unit.FacilityId, o.Contract.Unit.UnitTypeId)).ToListAsync(ct));
+ }
+
+ // ---------------------------------------------------------------------
+ // Chỉ tiêu (SRS 10.2)
+ // ---------------------------------------------------------------------
+
+ private static ReportMetrics Compute(Source s, DateTime fromUtc, DateTime toUtcExclusive)
+ {
+ bool InPeriod(DateTime? t) => t.HasValue && t.Value >= fromUtc && t.Value < toUtcExclusive;
+
+ var collectedRows = s.Payments.Where(p => p.Type != "REFUND" && OpsRules.CollectedPaymentStatuses.Contains(p.Status)).ToList();
+ var refundRows = s.Payments.Where(p => p.Type == "REFUND" && p.Status == "PAID").ToList();
+
+ var collected = collectedRows.Where(p => InPeriod(p.PaidAt)).Sum(p => p.Amount);
+ var refunded = refundRows.Where(p => InPeriod(p.PaidAt)).Sum(p => p.Amount);
+ var rentalAndFees = collectedRows.Where(p => p.Type != "DEPOSIT" && InPeriod(p.PaidAt)).Sum(p => p.Amount);
+ var depositCollected = collectedRows.Where(p => p.Type == "DEPOSIT" && InPeriod(p.PaidAt)).Sum(p => p.Amount);
+ var depositHeld = Math.Max(0, collectedRows.Where(p => p.Type == "DEPOSIT").Sum(p => p.Amount) - refundRows.Sum(p => p.Amount));
+ var outstanding = s.Payments
+ .Where(p => p.Amount > 0 && OpsRules.UnpaidPaymentStatuses.Contains(p.Status) && p.ContractStatus != "CANCELLED")
+ .Sum(p => p.Amount);
+
+ var total = s.Units.Count;
+ var inUse = s.Units.Count(u => OpsRules.UnitInUseStatuses.Contains(u.Status));
+ var available = s.Units.Count(u => u.Status == "AVAILABLE");
+ var reserved = s.Units.Count(u => OpsRules.UnitReservedStatuses.Contains(u.Status));
+ var unavailable = s.Units.Count(u => OpsRules.UnitUnavailableStatuses.Contains(u.Status));
+ var operable = total - unavailable;
+
+ return new ReportMetrics(
+ collected,
+ refunded,
+ collected - refunded,
+ rentalAndFees,
+ depositCollected,
+ depositHeld,
+ outstanding,
+ total,
+ inUse,
+ available,
+ reserved,
+ unavailable,
+ operable,
+ OpsRules.OccupancyRate(inUse, operable),
+ s.Contracts.Count(c => OpsRules.OpenContractStatuses.Contains(c.Status)),
+ s.Overdues.Count,
+ s.Overdues.Select(o => o.ContractId).Distinct().Count());
+ }
+
+ /// Tổng hệ thống = tổng các dòng trong cùng bộ lọc (điểm nghiệm thu UC22).
+ private static ReportMetrics Sum(IReadOnlyCollection rows)
+ {
+ var inUse = rows.Sum(r => r.UnitsInUse);
+ var operable = rows.Sum(r => r.OperableUnits);
+ return new ReportMetrics(
+ rows.Sum(r => r.Collected),
+ rows.Sum(r => r.Refunded),
+ rows.Sum(r => r.NetCollected),
+ rows.Sum(r => r.RentalAndFeeRevenue),
+ rows.Sum(r => r.DepositCollected),
+ rows.Sum(r => r.DepositHeld),
+ rows.Sum(r => r.Outstanding),
+ rows.Sum(r => r.TotalUnits),
+ inUse,
+ rows.Sum(r => r.UnitsAvailable),
+ rows.Sum(r => r.UnitsReserved),
+ rows.Sum(r => r.UnitsUnavailable),
+ operable,
+ OpsRules.OccupancyRate(inUse, operable),
+ rows.Sum(r => r.ActiveContracts),
+ rows.Sum(r => r.OverdueCases),
+ rows.Sum(r => r.OverdueContracts));
+ }
+
+ private static (DateTime FromUtc, DateTime ToUtcExclusive) Period(ReportFilter filter)
+ {
+ if (filter.From > filter.To) throw new ArgumentException("Ngày bắt đầu phải trước hoặc bằng ngày kết thúc.");
+ if (filter.To.DayNumber - filter.From.DayNumber > 366 * 3) throw new ArgumentException("Kỳ báo cáo tối đa 3 năm.");
+ return (OpsRules.LocalDayStartUtc(filter.From), OpsRules.LocalDayStartUtc(filter.To.AddDays(1)));
+ }
+
+ // ---------------------------------------------------------------------
+ // UC22 — Báo cáo theo cơ sở / loại kho
+ // ---------------------------------------------------------------------
+
+ public async Task GetSystemReportAsync(ReportFilter filter, CancellationToken ct = default)
+ {
+ var (fromUtc, toUtc) = Period(filter);
+ var snapshotAt = DateTime.UtcNow;
+
+ var facilitiesQuery = dbContext.Facilities.AsNoTracking().AsQueryable();
+ if (filter.FacilityId.HasValue) facilitiesQuery = facilitiesQuery.Where(f => f.FacilityId == filter.FacilityId);
+ var facilities = await facilitiesQuery.OrderBy(f => f.Name)
+ .Select(f => new { f.FacilityId, f.Name, f.Status })
+ .ToListAsync(ct);
+ if (filter.FacilityId.HasValue && facilities.Count == 0) throw new KeyNotFoundException("Không tìm thấy cơ sở.");
+
+ var source = await LoadAsync(filter.FacilityId, filter.UnitTypeId, ct);
+
+ var rows = facilities
+ .Select(f => new FacilityReportRow(f.FacilityId, f.Name, f.Status,
+ Compute(source.Where((fid, _) => fid == f.FacilityId), fromUtc, toUtc)))
+ .ToList();
+
+ return new SystemReportDto(filter, snapshotAt, Sum(rows.Select(r => r.Metrics).ToList()), rows);
+ }
+
+ public async Task GetUnitTypeReportAsync(ReportFilter filter, CancellationToken ct = default)
+ {
+ var (fromUtc, toUtc) = Period(filter);
+ var snapshotAt = DateTime.UtcNow;
+
+ var typesQuery = dbContext.UnitTypes.AsNoTracking().AsQueryable();
+ if (filter.UnitTypeId.HasValue) typesQuery = typesQuery.Where(t => t.UnitTypeId == filter.UnitTypeId);
+ var types = await typesQuery.OrderBy(t => t.Area)
+ .Select(t => new { t.UnitTypeId, t.TypeName })
+ .ToListAsync(ct);
+ if (filter.UnitTypeId.HasValue && types.Count == 0) throw new KeyNotFoundException("Không tìm thấy loại kho.");
+
+ var source = await LoadAsync(filter.FacilityId, filter.UnitTypeId, ct);
+
+ var rows = types
+ .Select(t => new UnitTypeReportRow(t.UnitTypeId, t.TypeName,
+ Compute(source.Where((_, tid) => tid == t.UnitTypeId), fromUtc, toUtc)))
+ .ToList();
+
+ return new UnitTypeReportDto(filter, snapshotAt, Sum(rows.Select(r => r.Metrics).ToList()), rows);
+ }
+
+ public async Task GetRevenueTrendAsync(int months, long? facilityId, long? unitTypeId, CancellationToken ct = default)
+ {
+ if (months is < 1 or > 24) throw new ArgumentException("Số tháng phải từ 1 đến 24.");
+
+ var source = await LoadAsync(facilityId, unitTypeId, ct);
+ var today = OpsRules.TodayLocal;
+ var firstOfThisMonth = new DateOnly(today.Year, today.Month, 1);
+
+ var rows = new List();
+ for (var i = months - 1; i >= 0; i--)
+ {
+ var start = firstOfThisMonth.AddMonths(-i);
+ var m = Compute(source, OpsRules.LocalDayStartUtc(start), OpsRules.LocalDayStartUtc(start.AddMonths(1)));
+ rows.Add(new RevenueMonthRow(start.Year, start.Month, $"Tháng {start.Month}/{start.Year}",
+ m.Collected, m.Refunded, m.RentalAndFeeRevenue, m.DepositCollected));
+ }
+
+ return new RevenueTrendDto(facilityId, unitTypeId, DateTime.UtcNow, rows);
+ }
+
+ public async Task GetRentalStatusAsync(long? facilityId, long? unitTypeId, CancellationToken ct = default)
+ {
+ var source = await LoadAsync(facilityId, unitTypeId, ct);
+
+ var reservations = dbContext.Reservations.AsNoTracking().AsQueryable();
+ if (facilityId.HasValue) reservations = reservations.Where(r => r.FacilityId == facilityId);
+ if (unitTypeId.HasValue) reservations = reservations.Where(r => r.UnitTypeId == unitTypeId);
+ var reservationCounts = await reservations
+ .GroupBy(r => r.Status)
+ .Select(g => new StatusCount(g.Key, g.Count()))
+ .ToListAsync(ct);
+
+ return new RentalStatusDto(
+ facilityId,
+ unitTypeId,
+ DateTime.UtcNow,
+ source.Contracts.GroupBy(c => c.Status).Select(g => new StatusCount(g.Key, g.Count())).OrderByDescending(s => s.Count).ToList(),
+ reservationCounts.OrderByDescending(s => s.Count).ToList(),
+ source.Units.GroupBy(u => u.Status).Select(g => new StatusCount(g.Key, g.Count())).OrderByDescending(s => s.Count).ToList());
+ }
+
+ /// Drill-down một cơ sở: hợp đồng và quá hạn liên quan (UC22 bước 5).
+ public async Task> GetFacilityContractsAsync(long facilityId, string? status, long? unitTypeId, CancellationToken ct = default)
+ {
+ if (!await dbContext.Facilities.AnyAsync(f => f.FacilityId == facilityId, ct))
+ {
+ throw new KeyNotFoundException("Không tìm thấy cơ sở.");
+ }
+
+ var query = dbContext.RentalContracts.AsNoTracking().Where(c => c.Unit.FacilityId == facilityId);
+ if (!string.IsNullOrWhiteSpace(status))
+ {
+ var s = status.Trim().ToUpperInvariant();
+ query = query.Where(c => c.Status == s);
+ }
+ if (unitTypeId.HasValue) query = query.Where(c => c.Unit.UnitTypeId == unitTypeId);
+
+ return await query
+ .OrderByDescending(c => c.Status == "OVERDUE")
+ .ThenBy(c => c.EndDate)
+ .Take(500)
+ .Select(c => new FacilityContractRow(
+ c.ContractId,
+ c.Customer.FullName,
+ c.Unit.UnitNumber,
+ c.Unit.UnitType.TypeName,
+ c.StartDate,
+ c.EndDate,
+ c.Status,
+ c.Payments.Where(p => p.Amount > 0 && (p.Status == "PENDING" || p.Status == "FAILED")).Sum(p => (decimal?)p.Amount) ?? 0,
+ c.OverdueCases.Count(o => o.Status != "RESOLVED")))
+ .ToListAsync(ct);
+ }
+
+ // ---------------------------------------------------------------------
+ // UC23 — Xuất CSV (UTF-8, có tiêu đề, đơn vị, bộ lọc và thời điểm xuất)
+ // ---------------------------------------------------------------------
+
+ public async Task ExportCsvAsync(string view, ReportFilter filter, int months, long userId, CancellationToken ct = default)
+ {
+ var normalizedView = (view ?? "").Trim().ToLowerInvariant();
+ var facilityName = filter.FacilityId.HasValue
+ ? await dbContext.Facilities.Where(f => f.FacilityId == filter.FacilityId).Select(f => f.Name).FirstOrDefaultAsync(ct)
+ ?? throw new KeyNotFoundException("Không tìm thấy cơ sở.")
+ : "Tất cả cơ sở";
+ var unitTypeName = filter.UnitTypeId.HasValue
+ ? await dbContext.UnitTypes.Where(t => t.UnitTypeId == filter.UnitTypeId).Select(t => t.TypeName).FirstOrDefaultAsync(ct)
+ ?? throw new KeyNotFoundException("Không tìm thấy loại kho.")
+ : "Tất cả loại kho";
+
+ var csv = new StringBuilder();
+ DateTime snapshotAt;
+ string title;
+ string fileKey;
+
+ switch (normalizedView)
+ {
+ case "facilities":
+ {
+ var report = await GetSystemReportAsync(filter, ct);
+ snapshotAt = report.SnapshotAt;
+ title = "Báo cáo doanh thu và hiệu suất theo cơ sở";
+ fileKey = "theo-co-so";
+ WriteHeader(csv, title, filter, facilityName, unitTypeName, snapshotAt, withPeriod: true);
+ Line(csv, ["Mã cơ sở", "Tên cơ sở", "Trạng thái", .. MetricHeaders]);
+ foreach (var r in report.Facilities)
+ {
+ Line(csv, [r.FacilityId.ToString(CultureInfo.InvariantCulture), r.FacilityName, r.FacilityStatus, .. MetricCells(r.Metrics)]);
+ }
+ Line(csv, ["", "Tổng cộng", "", .. MetricCells(report.Totals)]);
+ break;
+ }
+ case "unit-types":
+ {
+ var report = await GetUnitTypeReportAsync(filter, ct);
+ snapshotAt = report.SnapshotAt;
+ title = "Báo cáo doanh thu và hiệu suất theo loại kho";
+ fileKey = "theo-loai-kho";
+ WriteHeader(csv, title, filter, facilityName, unitTypeName, snapshotAt, withPeriod: true);
+ Line(csv, ["Mã loại kho", "Loại kho", .. MetricHeaders]);
+ foreach (var r in report.UnitTypes)
+ {
+ Line(csv, [r.UnitTypeId.ToString(CultureInfo.InvariantCulture), r.UnitTypeName, .. MetricCells(r.Metrics)]);
+ }
+ Line(csv, ["", "Tổng cộng", .. MetricCells(report.Totals)]);
+ break;
+ }
+ case "revenue-trend":
+ {
+ var report = await GetRevenueTrendAsync(months, filter.FacilityId, filter.UnitTypeId, ct);
+ snapshotAt = report.SnapshotAt;
+ title = $"Báo cáo tiền thu {months} tháng gần nhất";
+ fileKey = "theo-thang";
+ WriteHeader(csv, title, filter, facilityName, unitTypeName, snapshotAt, withPeriod: false);
+ Line(csv, ["Tháng", "Tiền thu (VND)", "Tiền hoàn (VND)", "Doanh thu thuê và phí (VND)", "Cọc thu trong kỳ (VND)"]);
+ foreach (var r in report.Months)
+ {
+ Line(csv, [$"{r.Month:00}/{r.Year}", Num(r.Collected), Num(r.Refunded), Num(r.RentalAndFeeRevenue), Num(r.DepositCollected)]);
+ }
+ Line(csv, ["Tổng cộng",
+ Num(report.Months.Sum(m => m.Collected)),
+ Num(report.Months.Sum(m => m.Refunded)),
+ Num(report.Months.Sum(m => m.RentalAndFeeRevenue)),
+ Num(report.Months.Sum(m => m.DepositCollected))]);
+ break;
+ }
+ default:
+ throw new ArgumentException("Loại báo cáo xuất phải là facilities, unit-types hoặc revenue-trend.");
+ }
+
+ var preamble = Encoding.UTF8.GetPreamble();
+ var body = Encoding.UTF8.GetBytes(csv.ToString());
+ var content = new byte[preamble.Length + body.Length];
+ preamble.CopyTo(content, 0);
+ body.CopyTo(content, preamble.Length);
+
+ // Audit xuất báo cáo (UC23 bước 6) — chỉ ghi khi tạo tệp thành công
+ dbContext.ActivityLogs.Add(new ActivityLog
+ {
+ UserId = userId,
+ Action = "REPORT_EXPORT",
+ EntityType = "REPORT",
+ NewValue = JsonSerializer.Serialize(new
+ {
+ View = normalizedView,
+ From = filter.From.ToString("yyyy-MM-dd"),
+ To = filter.To.ToString("yyyy-MM-dd"),
+ filter.FacilityId,
+ filter.UnitTypeId,
+ Months = normalizedView == "revenue-trend" ? months : (int?)null,
+ SnapshotAt = snapshotAt
+ }),
+ LoggedAt = DateTime.UtcNow
+ });
+ await dbContext.SaveChangesAsync(ct);
+
+ var stamp = (snapshotAt + OpsRules.ReportOffset).ToString("yyyyMMdd-HHmm", CultureInfo.InvariantCulture);
+ return new CsvExport($"bao-cao-{fileKey}-{stamp}.csv", content);
+ }
+
+ private static readonly string[] MetricHeaders =
+ [
+ "Tiền thu (VND)", "Tiền hoàn (VND)", "Thu ròng (VND)", "Doanh thu thuê và phí (VND)",
+ "Cọc thu trong kỳ (VND)", "Cọc còn giữ (VND)", "Công nợ hiện tại (VND)",
+ "Tổng số kho", "Kho đang sử dụng", "Kho trống", "Kho đang giữ/phân bổ", "Kho bảo trì/kiểm tra",
+ "Kho khai thác được", "Tỷ lệ sử dụng (%)", "Hợp đồng hiệu lực", "Case quá hạn", "Hợp đồng quá hạn"
+ ];
+
+ private static string[] MetricCells(ReportMetrics m) =>
+ [
+ Num(m.Collected), Num(m.Refunded), Num(m.NetCollected), Num(m.RentalAndFeeRevenue),
+ Num(m.DepositCollected), Num(m.DepositHeld), Num(m.Outstanding),
+ Int(m.TotalUnits), Int(m.UnitsInUse), Int(m.UnitsAvailable), Int(m.UnitsReserved), Int(m.UnitsUnavailable),
+ Int(m.OperableUnits), m.OccupancyRate.HasValue ? Num(m.OccupancyRate.Value) : "Không áp dụng",
+ Int(m.ActiveContracts), Int(m.OverdueCases), Int(m.OverdueContracts)
+ ];
+
+ private static void WriteHeader(StringBuilder csv, string title, ReportFilter filter, string facilityName,
+ string unitTypeName, DateTime snapshotAt, bool withPeriod)
+ {
+ Line(csv, ["Báo cáo", title]);
+ if (withPeriod)
+ {
+ Line(csv, ["Kỳ tiền thu", $"{filter.From.ToString("dd/MM/yyyy", Vi)} – {filter.To.ToString("dd/MM/yyyy", Vi)} (giờ Việt Nam)"]);
+ }
+ Line(csv, ["Cơ sở", facilityName]);
+ Line(csv, ["Loại kho", unitTypeName]);
+ Line(csv, ["Thời điểm chụp dữ liệu", (snapshotAt + OpsRules.ReportOffset).ToString("dd/MM/yyyy HH:mm", Vi) + " (UTC+7)"]);
+ Line(csv, ["Ghi chú", "Trạng thái kho là ảnh chụp hiện tại, không phải số liệu lịch sử. Doanh thu thuê và phí không gồm tiền cọc."]);
+ csv.Append("\r\n");
+ }
+
+ private static void Line(StringBuilder csv, IEnumerable cells)
+ {
+ csv.Append(string.Join(",", cells.Select(Cell))).Append("\r\n");
+ }
+
+ /// Bọc ô CSV; chặn công thức khi mở bằng Excel (UC23 bước 5).
+ private static string Cell(string? value)
+ {
+ value ??= "";
+ if (value.Length > 0 && "=+-@\t\r".Contains(value[0]) && !decimal.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out _))
+ {
+ value = "'" + value;
+ }
+ return "\"" + value.Replace("\"", "\"\"") + "\"";
+ }
+
+ private static string Num(decimal value) => value.ToString("0.##", CultureInfo.InvariantCulture);
+
+ private static string Int(int value) => value.ToString(CultureInfo.InvariantCulture);
+}
diff --git a/StorageProject.Infrastructure/Services/OperationsService.cs b/StorageProject.Infrastructure/Services/OperationsService.cs
new file mode 100644
index 0000000..1dc090d
--- /dev/null
+++ b/StorageProject.Infrastructure/Services/OperationsService.cs
@@ -0,0 +1,798 @@
+using System.Globalization;
+using System.Text;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using Microsoft.EntityFrameworkCore;
+using StorageProject.Core.DTOs.Operations;
+using StorageProject.Core.Entities;
+using StorageProject.Core.Exceptions;
+using StorageProject.Core.Interfaces;
+using StorageProject.Infrastructure.Data;
+
+namespace StorageProject.Infrastructure.Services;
+
+///
+/// Quản lý vận hành kinh doanh: cơ sở (UC19), chính sách (UC20), khung giá / phí / giảm giá và bảng giá (UC21).
+/// Mọi thay đổi ghi activity_logs (BR13). Không sửa ngược giá đã chốt trong reservation/contract (BR14).
+///
+public partial class OperationsService(AppDbContext dbContext) : IOperationsService
+{
+ // =====================================================================
+ // UC19 — Cơ sở
+ // =====================================================================
+
+ public async Task> GetFacilitiesAsync(string? status, string? search, CancellationToken ct = default)
+ {
+ var query = dbContext.Facilities.AsNoTracking().AsQueryable();
+
+ if (!string.IsNullOrWhiteSpace(status))
+ {
+ var s = status.Trim().ToUpperInvariant();
+ query = query.Where(f => f.Status == s);
+ }
+
+ if (!string.IsNullOrWhiteSpace(search))
+ {
+ var term = search.Trim();
+ query = query.Where(f => f.Name.Contains(term) || f.Address.Contains(term));
+ }
+
+ var facilities = await query.OrderBy(f => f.Name).ToListAsync(ct);
+ return await ToFacilityDtosAsync(facilities, ct);
+ }
+
+ public async Task GetFacilityAsync(long facilityId, CancellationToken ct = default)
+ {
+ var facility = await dbContext.Facilities.AsNoTracking().FirstOrDefaultAsync(f => f.FacilityId == facilityId, ct);
+ if (facility == null) return null;
+ return (await ToFacilityDtosAsync([facility], ct))[0];
+ }
+
+ public async Task CreateFacilityAsync(UpsertFacilityRequest request, long userId, CancellationToken ct = default)
+ {
+ var input = ValidateFacility(request);
+ var status = NormalizeFacilityStatus(request.Status) ?? "ACTIVE";
+ var now = DateTime.UtcNow;
+
+ var facility = new Facility
+ {
+ Name = input.Name,
+ Address = input.Address,
+ ContactPhone = input.Phone,
+ OpeningTime = input.Opening,
+ ClosingTime = input.Closing,
+ Status = status,
+ CreatedAt = now,
+ UpdatedAt = now
+ };
+
+ dbContext.Facilities.Add(facility);
+ await dbContext.SaveChangesAsync(ct);
+
+ Log(userId, "FACILITY_CREATE", "FACILITY", facility.FacilityId, null, FacilitySnapshot(facility));
+ await dbContext.SaveChangesAsync(ct);
+
+ var warnings = await FacilityWarningsAsync(facility, ct);
+ return new FacilitySaveResult((await ToFacilityDtosAsync([facility], ct))[0], warnings);
+ }
+
+ public async Task UpdateFacilityAsync(long facilityId, UpsertFacilityRequest request, long userId, CancellationToken ct = default)
+ {
+ var facility = await dbContext.Facilities.FirstOrDefaultAsync(f => f.FacilityId == facilityId, ct)
+ ?? throw new KeyNotFoundException($"Không tìm thấy cơ sở với ID: {facilityId}");
+
+ var input = ValidateFacility(request);
+ var before = FacilitySnapshot(facility);
+
+ facility.Name = input.Name;
+ facility.Address = input.Address;
+ facility.ContactPhone = input.Phone;
+ facility.OpeningTime = input.Opening;
+ facility.ClosingTime = input.Closing;
+ facility.UpdatedAt = DateTime.UtcNow;
+
+ var newStatus = NormalizeFacilityStatus(request.Status);
+ if (newStatus != null && newStatus != facility.Status)
+ {
+ await EnsureStatusChangeAllowedAsync(facility, newStatus, ct);
+ facility.Status = newStatus;
+ }
+
+ Log(userId, "FACILITY_UPDATE", "FACILITY", facility.FacilityId, before, FacilitySnapshot(facility));
+ await dbContext.SaveChangesAsync(ct);
+
+ var warnings = await FacilityWarningsAsync(facility, ct);
+ return new FacilitySaveResult((await ToFacilityDtosAsync([facility], ct))[0], warnings);
+ }
+
+ public async Task ChangeFacilityStatusAsync(long facilityId, ChangeFacilityStatusRequest request, long userId, CancellationToken ct = default)
+ {
+ var status = NormalizeFacilityStatus(request.Status)
+ ?? throw new ArgumentException("Trạng thái phải là ACTIVE, INACTIVE hoặc TEMPORARILY_CLOSED.");
+
+ var facility = await dbContext.Facilities.FirstOrDefaultAsync(f => f.FacilityId == facilityId, ct)
+ ?? throw new KeyNotFoundException($"Không tìm thấy cơ sở với ID: {facilityId}");
+
+ if (facility.Status == status)
+ {
+ throw new InvalidOperationException("Cơ sở đã ở trạng thái này.");
+ }
+
+ await EnsureStatusChangeAllowedAsync(facility, status, ct);
+
+ var oldStatus = facility.Status;
+ facility.Status = status;
+ facility.UpdatedAt = DateTime.UtcNow;
+
+ Log(userId, "FACILITY_STATUS_CHANGE", "FACILITY", facility.FacilityId,
+ new { Status = oldStatus },
+ new { Status = status, Reason = request.Reason?.Trim() });
+ await dbContext.SaveChangesAsync(ct);
+
+ var warnings = await FacilityWarningsAsync(facility, ct);
+ return new FacilitySaveResult((await ToFacilityDtosAsync([facility], ct))[0], warnings);
+ }
+
+ ///
+ /// INACTIVE (ngừng hẳn) chỉ khi không còn hợp đồng / đơn đặt chỗ đang xử lý.
+ /// TEMPORARILY_CLOSED luôn được phép: chặn đặt mới nhưng vẫn xử lý khách hiện tại (UC19 A1).
+ ///
+ private async Task EnsureStatusChangeAllowedAsync(Facility facility, string newStatus, CancellationToken ct)
+ {
+ if (newStatus != "INACTIVE") return;
+
+ var contractStatuses = OpsRules.OpenContractStatuses.Append("DRAFT").ToArray();
+ var openContracts = await dbContext.RentalContracts
+ .CountAsync(c => c.Unit.FacilityId == facility.FacilityId && contractStatuses.Contains(c.Status), ct);
+ var openReservations = await dbContext.Reservations
+ .CountAsync(r => r.FacilityId == facility.FacilityId && OpsRules.OpenReservationStatuses.Contains(r.Status), ct);
+
+ if (openContracts > 0 || openReservations > 0)
+ {
+ throw new OperationConflictException(
+ $"Cơ sở còn {openContracts} hợp đồng và {openReservations} đơn đặt chỗ đang xử lý nên chưa thể ngừng hoạt động. " +
+ "Hãy chuyển sang Tạm đóng (TEMPORARILY_CLOSED) để chặn đặt mới mà vẫn phục vụ khách hiện tại.",
+ new { openContracts, openReservations });
+ }
+ }
+
+ private async Task> ToFacilityDtosAsync(List facilities, CancellationToken ct)
+ {
+ var ids = facilities.Select(f => f.FacilityId).ToList();
+ var today = OpsRules.TodayUtc;
+
+ var units = await dbContext.StorageUnits.AsNoTracking()
+ .Where(u => ids.Contains(u.FacilityId))
+ .Select(u => new { u.FacilityId, u.Status })
+ .ToListAsync(ct);
+
+ var pricedTypes = await dbContext.RentalRates.AsNoTracking()
+ .Where(r => ids.Contains(r.FacilityId)
+ && r.Status == "ACTIVE"
+ && r.EffectiveFrom <= today
+ && (r.EffectiveTo == null || r.EffectiveTo >= today))
+ .Select(r => new { r.FacilityId, r.UnitTypeId })
+ .Distinct()
+ .ToListAsync(ct);
+
+ var staff = await dbContext.UserFacilities.AsNoTracking()
+ .Where(uf => ids.Contains(uf.FacilityId) && uf.Status == "ACTIVE")
+ .Select(uf => new { uf.FacilityId, uf.UserId })
+ .Distinct()
+ .ToListAsync(ct);
+
+ return facilities.Select(f =>
+ {
+ var own = units.Where(u => u.FacilityId == f.FacilityId).ToList();
+ var inUse = own.Count(u => OpsRules.UnitInUseStatuses.Contains(u.Status));
+ var operable = own.Count - own.Count(u => OpsRules.UnitUnavailableStatuses.Contains(u.Status));
+
+ return new OpsFacilityDto(
+ f.FacilityId,
+ f.Name,
+ f.Address,
+ f.ContactPhone,
+ f.OpeningTime?.ToString("HH:mm"),
+ f.ClosingTime?.ToString("HH:mm"),
+ f.Status,
+ own.Count,
+ inUse,
+ operable,
+ OpsRules.OccupancyRate(inUse, operable),
+ pricedTypes.Count(r => r.FacilityId == f.FacilityId),
+ staff.Count(s => s.FacilityId == f.FacilityId),
+ f.CreatedAt,
+ f.UpdatedAt);
+ }).ToList();
+ }
+
+ /// Cảnh báo không chặn lưu: tên gần giống (UC19 A3), mở cơ sở thiếu cấu hình (UC19 A2).
+ private async Task> FacilityWarningsAsync(Facility facility, CancellationToken ct)
+ {
+ var warnings = new List();
+
+ var key = NameKey(facility.Name);
+ var others = await dbContext.Facilities.AsNoTracking()
+ .Where(f => f.FacilityId != facility.FacilityId)
+ .Select(f => f.Name)
+ .ToListAsync(ct);
+ var similar = others.Where(n =>
+ {
+ var k = NameKey(n);
+ return k == key || (key.Length >= 6 && k.Length >= 6 && (k.Contains(key) || key.Contains(k)));
+ }).ToList();
+ if (similar.Count > 0)
+ {
+ warnings.Add($"Tên gần giống cơ sở đã có: {string.Join(", ", similar)}. Vui lòng kiểm tra để tránh tạo trùng.");
+ }
+
+ if (facility.Status == "ACTIVE")
+ {
+ var today = OpsRules.TodayUtc;
+ var hasRate = await dbContext.RentalRates.AnyAsync(r => r.FacilityId == facility.FacilityId
+ && r.Status == "ACTIVE" && r.EffectiveFrom <= today && (r.EffectiveTo == null || r.EffectiveTo >= today), ct);
+ var hasUnit = await dbContext.StorageUnits.AnyAsync(u => u.FacilityId == facility.FacilityId, ct);
+ var hasStaff = await dbContext.UserFacilities.AnyAsync(uf => uf.FacilityId == facility.FacilityId && uf.Status == "ACTIVE", ct);
+
+ if (!hasRate) warnings.Add("Cơ sở chưa có bảng giá đang áp dụng nên khách chưa đặt chỗ được.");
+ if (!hasUnit) warnings.Add("Cơ sở chưa có ô kho nào. Quản lý cơ sở cần khai báo ô kho.");
+ if (!hasStaff) warnings.Add("Cơ sở chưa có nhân sự được phân công. Quản trị hệ thống cần phân công nhân viên/quản lý.");
+ }
+
+ return warnings;
+ }
+
+ private sealed record FacilityInput(string Name, string Address, string? Phone, TimeOnly? Opening, TimeOnly? Closing);
+
+ private static FacilityInput ValidateFacility(UpsertFacilityRequest request)
+ {
+ var name = request.Name?.Trim() ?? "";
+ var address = request.Address?.Trim() ?? "";
+
+ if (name.Length == 0) throw new ArgumentException("Tên cơ sở không được để trống.");
+ if (name.Length > 150) throw new ArgumentException("Tên cơ sở tối đa 150 ký tự.");
+ if (address.Length == 0) throw new ArgumentException("Địa chỉ không được để trống.");
+ if (address.Length > 255) throw new ArgumentException("Địa chỉ tối đa 255 ký tự.");
+
+ string? phone = null;
+ if (!string.IsNullOrWhiteSpace(request.ContactPhone))
+ {
+ phone = PhoneSeparators().Replace(request.ContactPhone.Trim(), "");
+ if (!PhonePattern().IsMatch(phone))
+ {
+ throw new ArgumentException("Số điện thoại liên hệ không hợp lệ (8–15 chữ số, có thể bắt đầu bằng +).");
+ }
+ }
+
+ var opening = ParseTime(request.OpeningTime, "Giờ mở cửa");
+ var closing = ParseTime(request.ClosingTime, "Giờ đóng cửa");
+
+ if (opening.HasValue != closing.HasValue)
+ {
+ throw new ArgumentException("Cần nhập cả giờ mở cửa và giờ đóng cửa, hoặc để trống cả hai.");
+ }
+ if (opening.HasValue && closing.HasValue && opening.Value >= closing.Value)
+ {
+ throw new ArgumentException("Giờ mở cửa phải trước giờ đóng cửa.");
+ }
+
+ return new FacilityInput(name, address, phone, opening, closing);
+ }
+
+ private static TimeOnly? ParseTime(string? value, string label)
+ {
+ if (string.IsNullOrWhiteSpace(value)) return null;
+ string[] formats = ["HH:mm", "H:mm", "HH:mm:ss"];
+ if (TimeOnly.TryParseExact(value.Trim(), formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out var t))
+ {
+ return t;
+ }
+ throw new ArgumentException($"{label} phải có dạng HH:mm (ví dụ 07:00).");
+ }
+
+ private static string? NormalizeFacilityStatus(string? status)
+ {
+ if (string.IsNullOrWhiteSpace(status)) return null;
+ var s = status.Trim().ToUpperInvariant();
+ return OpsRules.FacilityStatuses.Contains(s)
+ ? s
+ : throw new ArgumentException("Trạng thái phải là ACTIVE, INACTIVE hoặc TEMPORARILY_CLOSED.");
+ }
+
+ private static string NameKey(string name)
+ {
+ var normalized = name.Trim().ToLowerInvariant().Replace('đ', 'd').Normalize(NormalizationForm.FormD);
+ var sb = new StringBuilder();
+ foreach (var ch in normalized)
+ {
+ if (CharUnicodeInfo.GetUnicodeCategory(ch) == UnicodeCategory.NonSpacingMark) continue;
+ if (char.IsLetterOrDigit(ch)) sb.Append(ch);
+ }
+ return sb.ToString();
+ }
+
+ private static object FacilitySnapshot(Facility f) => new
+ {
+ f.Name,
+ f.Address,
+ f.ContactPhone,
+ OpeningTime = f.OpeningTime?.ToString("HH:mm"),
+ ClosingTime = f.ClosingTime?.ToString("HH:mm"),
+ f.Status
+ };
+
+ [GeneratedRegex(@"[\s.\-()]")]
+ private static partial Regex PhoneSeparators();
+
+ [GeneratedRegex(@"^\+?\d{8,15}$")]
+ private static partial Regex PhonePattern();
+
+ // =====================================================================
+ // UC20 / UC21 — Chính sách
+ // =====================================================================
+
+ public async Task> GetPoliciesAsync(PolicyQuery query, CancellationToken ct = default)
+ {
+ var q = PolicyQueryable();
+
+ if (!string.IsNullOrWhiteSpace(query.PolicyType))
+ {
+ var type = query.PolicyType.Trim().ToUpperInvariant();
+ q = q.Where(p => p.PolicyType == type);
+ }
+ if (!string.IsNullOrWhiteSpace(query.Status))
+ {
+ var status = query.Status.Trim().ToUpperInvariant();
+ q = q.Where(p => p.Status == status);
+ }
+ if (query.FacilityId.HasValue) q = q.Where(p => p.FacilityId == query.FacilityId);
+ if (query.UnitTypeId.HasValue) q = q.Where(p => p.UnitTypeId == query.UnitTypeId);
+
+ var policies = await q
+ .OrderBy(p => p.PolicyType)
+ .ThenByDescending(p => p.Status == "ACTIVE")
+ .ThenByDescending(p => p.EffectiveFrom)
+ .ToListAsync(ct);
+
+ return policies.Select(ToPolicyDto).ToList();
+ }
+
+ public async Task GetPolicyAsync(long policyId, CancellationToken ct = default)
+ {
+ var policy = await PolicyQueryable().FirstOrDefaultAsync(p => p.PolicyId == policyId, ct);
+ return policy == null ? null : ToPolicyDto(policy);
+ }
+
+ public async Task CreatePolicyAsync(UpsertPolicyRequest request, long userId, CancellationToken ct = default)
+ {
+ var input = await ValidatePolicyAsync(request, strict: false, ct);
+ var now = DateTime.UtcNow;
+
+ var policy = new Policy
+ {
+ CreatedBy = userId,
+ Status = "DRAFT",
+ CreatedAt = now,
+ UpdatedAt = now
+ };
+ ApplyPolicyInput(policy, input);
+
+ dbContext.Policies.Add(policy);
+ await dbContext.SaveChangesAsync(ct);
+
+ Log(userId, "POLICY_CREATE", "POLICY", policy.PolicyId, null, PolicySnapshot(policy));
+ await dbContext.SaveChangesAsync(ct);
+
+ return (await GetPolicyAsync(policy.PolicyId, ct))!;
+ }
+
+ public async Task UpdatePolicyAsync(long policyId, UpsertPolicyRequest request, long userId, CancellationToken ct = default)
+ {
+ var policy = await dbContext.Policies.FirstOrDefaultAsync(p => p.PolicyId == policyId, ct)
+ ?? throw new KeyNotFoundException($"Không tìm thấy chính sách với ID: {policyId}");
+
+ if (policy.Status != "DRAFT")
+ {
+ throw new InvalidOperationException(
+ "Chỉ sửa được chính sách ở trạng thái Nháp. Muốn thay chính sách đang áp dụng, hãy tạo phiên bản mới " +
+ "rồi kích hoạt với replaceExisting=true; bản cũ được giữ lại trong lịch sử (UC20 A2).");
+ }
+
+ var input = await ValidatePolicyAsync(request, strict: false, ct);
+ var before = PolicySnapshot(policy);
+
+ ApplyPolicyInput(policy, input);
+ policy.UpdatedAt = DateTime.UtcNow;
+
+ Log(userId, "POLICY_UPDATE", "POLICY", policy.PolicyId, before, PolicySnapshot(policy));
+ await dbContext.SaveChangesAsync(ct);
+
+ return (await GetPolicyAsync(policy.PolicyId, ct))!;
+ }
+
+ public async Task ActivatePolicyAsync(long policyId, bool replaceExisting, long userId, CancellationToken ct = default)
+ {
+ var policy = await dbContext.Policies.FirstOrDefaultAsync(p => p.PolicyId == policyId, ct)
+ ?? throw new KeyNotFoundException($"Không tìm thấy chính sách với ID: {policyId}");
+
+ if (policy.Status == "ACTIVE") throw new InvalidOperationException("Chính sách đang được áp dụng.");
+ if (policy.Status == "EXPIRED") throw new InvalidOperationException("Chính sách đã hết hiệu lực, không thể kích hoạt lại. Hãy tạo phiên bản mới.");
+
+ var today = OpsRules.TodayUtc;
+ if (policy.EffectiveTo.HasValue && policy.EffectiveTo.Value < today)
+ {
+ throw new InvalidOperationException("Ngày kết thúc hiệu lực đã qua, không thể kích hoạt.");
+ }
+
+ // Kiểm tra đầy đủ tham số trước khi áp dụng (UC20 A3: thiếu tham số thì giữ DRAFT)
+ await ValidatePolicyAsync(ToRequest(policy), strict: true, ct);
+
+ // Xung đột cùng mức ưu tiên = cùng loại + cùng phạm vi (BR20) + khoảng hiệu lực giao nhau
+ var sameScope = await dbContext.Policies
+ .Where(p => p.PolicyId != policy.PolicyId
+ && p.Status == "ACTIVE"
+ && p.PolicyType == policy.PolicyType
+ && p.FacilityId == policy.FacilityId
+ && p.UnitTypeId == policy.UnitTypeId)
+ .ToListAsync(ct);
+ var conflicts = sameScope
+ .Where(p => OpsRules.Overlaps(p.EffectiveFrom, p.EffectiveTo, policy.EffectiveFrom, policy.EffectiveTo))
+ .ToList();
+
+ if (conflicts.Count > 0 && !replaceExisting)
+ {
+ throw new OperationConflictException(
+ "Đã có chính sách cùng loại và cùng phạm vi đang áp dụng trong khoảng thời gian này. " +
+ "Gửi lại với replaceExisting=true để kết thúc hiệu lực bản cũ và áp dụng bản mới.",
+ new { conflictingPolicyIds = conflicts.Select(c => c.PolicyId).ToList() });
+ }
+
+ await using var tx = await dbContext.Database.BeginTransactionAsync(ct);
+
+ var now = DateTime.UtcNow;
+ foreach (var old in conflicts)
+ {
+ var before = PolicySnapshot(old);
+ if (old.EffectiveFrom >= policy.EffectiveFrom)
+ {
+ // Bản cũ chưa kịp bắt đầu trước bản mới → thay thế hoàn toàn
+ old.Status = "INACTIVE";
+ }
+ else
+ {
+ old.EffectiveTo = policy.EffectiveFrom.AddDays(-1);
+ if (old.EffectiveTo.Value < today) old.Status = "EXPIRED";
+ }
+ old.UpdatedAt = now;
+ Log(userId, "POLICY_SUPERSEDE", "POLICY", old.PolicyId, before, PolicySnapshot(old));
+ }
+
+ var activateBefore = PolicySnapshot(policy);
+ policy.Status = "ACTIVE";
+ policy.UpdatedAt = now;
+ Log(userId, "POLICY_ACTIVATE", "POLICY", policy.PolicyId, activateBefore, PolicySnapshot(policy));
+
+ await dbContext.SaveChangesAsync(ct);
+ await tx.CommitAsync(ct);
+
+ var ids = conflicts.Select(c => c.PolicyId).ToList();
+ var superseded = (await PolicyQueryable().Where(p => ids.Contains(p.PolicyId)).ToListAsync(ct))
+ .Select(ToPolicyDto).ToList();
+
+ return new ActivatePolicyResult((await GetPolicyAsync(policy.PolicyId, ct))!, superseded);
+ }
+
+ public async Task DeactivatePolicyAsync(long policyId, long userId, CancellationToken ct = default)
+ {
+ var policy = await dbContext.Policies.FirstOrDefaultAsync(p => p.PolicyId == policyId, ct)
+ ?? throw new KeyNotFoundException($"Không tìm thấy chính sách với ID: {policyId}");
+
+ if (policy.Status is "INACTIVE" or "EXPIRED")
+ {
+ throw new InvalidOperationException("Chính sách đã không còn hiệu lực.");
+ }
+
+ var before = PolicySnapshot(policy);
+ policy.Status = "INACTIVE";
+ policy.UpdatedAt = DateTime.UtcNow;
+
+ Log(userId, "POLICY_DEACTIVATE", "POLICY", policy.PolicyId, before, PolicySnapshot(policy));
+ await dbContext.SaveChangesAsync(ct);
+
+ return (await GetPolicyAsync(policy.PolicyId, ct))!;
+ }
+
+ public async Task DeleteDraftPolicyAsync(long policyId, long userId, CancellationToken ct = default)
+ {
+ var policy = await dbContext.Policies.FirstOrDefaultAsync(p => p.PolicyId == policyId, ct)
+ ?? throw new KeyNotFoundException($"Không tìm thấy chính sách với ID: {policyId}");
+
+ if (policy.Status != "DRAFT")
+ {
+ throw new InvalidOperationException("Chỉ xoá được chính sách Nháp. Chính sách đã áp dụng phải giữ lại để truy vết; hãy ngừng áp dụng thay vì xoá.");
+ }
+
+ Log(userId, "POLICY_DELETE_DRAFT", "POLICY", policy.PolicyId, PolicySnapshot(policy), null);
+ dbContext.Policies.Remove(policy);
+ await dbContext.SaveChangesAsync(ct);
+ }
+
+ private sealed record PolicyInput(
+ string Name, string Type, string CalculationType, decimal? Value, decimal? Min, decimal? Max,
+ string Rule, long? FacilityId, long? UnitTypeId, DateOnly From, DateOnly? To);
+
+ private async Task ValidatePolicyAsync(UpsertPolicyRequest request, bool strict, CancellationToken ct)
+ {
+ var name = request.PolicyName?.Trim() ?? "";
+ var rule = request.RuleDescription?.Trim() ?? "";
+ var type = request.PolicyType?.Trim().ToUpperInvariant() ?? "";
+ var calc = request.CalculationType?.Trim().ToUpperInvariant() ?? "";
+
+ if (name.Length == 0) throw new ArgumentException("Tên chính sách không được để trống.");
+ if (name.Length > 150) throw new ArgumentException("Tên chính sách tối đa 150 ký tự.");
+ if (rule.Length == 0) throw new ArgumentException("Mô tả điều kiện áp dụng không được để trống.");
+ if (!OpsRules.PolicyTypes.Contains(type))
+ {
+ throw new ArgumentException($"Loại chính sách phải là một trong: {string.Join(", ", OpsRules.PolicyTypes)}.");
+ }
+ if (!OpsRules.CalculationTypes.Contains(calc))
+ {
+ throw new ArgumentException("Cách tính phải là FIXED, PERCENTAGE, RANGE hoặc RULE.");
+ }
+ if (type == "PRICE_RANGE" && calc != "RANGE")
+ {
+ throw new ArgumentException("Khung giá (PRICE_RANGE) phải dùng cách tính RANGE với giá tối thiểu và tối đa.");
+ }
+
+ decimal? value = request.Value, min = request.MinValue, max = request.MaxValue;
+
+ if (value < 0 || min < 0 || max < 0) throw new ArgumentException("Giá trị không được âm.");
+
+ switch (calc)
+ {
+ case "FIXED":
+ if (strict && value == null) throw new ArgumentException("Cách tính FIXED cần nhập giá trị (VND).");
+ min = null; max = null;
+ break;
+ case "PERCENTAGE":
+ if (strict && value == null) throw new ArgumentException("Cách tính PERCENTAGE cần nhập phần trăm.");
+ if (value > 100) throw new ArgumentException("Phần trăm phải nằm trong khoảng 0–100.");
+ min = null; max = null;
+ break;
+ case "RANGE":
+ if (strict && (min == null || max == null)) throw new ArgumentException("Cách tính RANGE cần nhập giá trị tối thiểu và tối đa.");
+ if (min.HasValue && max.HasValue && min > max) throw new ArgumentException("Giá trị tối thiểu không được lớn hơn tối đa.");
+ value = null;
+ break;
+ case "RULE":
+ // BR23: RULE là hướng dẫn cho người có quyền đánh giá, không lưu tham số để tự thực thi
+ value = null; min = null; max = null;
+ break;
+ }
+
+ if (request.EffectiveTo.HasValue && request.EffectiveTo.Value < request.EffectiveFrom)
+ {
+ throw new ArgumentException("Ngày kết thúc hiệu lực phải sau hoặc bằng ngày bắt đầu.");
+ }
+
+ if (request.FacilityId.HasValue && !await dbContext.Facilities.AnyAsync(f => f.FacilityId == request.FacilityId, ct))
+ {
+ throw new ArgumentException("Cơ sở áp dụng không tồn tại.");
+ }
+ if (request.UnitTypeId.HasValue && !await dbContext.UnitTypes.AnyAsync(t => t.UnitTypeId == request.UnitTypeId, ct))
+ {
+ throw new ArgumentException("Loại kho áp dụng không tồn tại.");
+ }
+
+ return new PolicyInput(name, type, calc, value, min, max, rule, request.FacilityId, request.UnitTypeId,
+ request.EffectiveFrom, request.EffectiveTo);
+ }
+
+ private static void ApplyPolicyInput(Policy policy, PolicyInput input)
+ {
+ policy.PolicyName = input.Name;
+ policy.PolicyType = input.Type;
+ policy.CalculationType = input.CalculationType;
+ policy.Value = input.Value;
+ policy.MinValue = input.Min;
+ policy.MaxValue = input.Max;
+ policy.RuleDescription = input.Rule;
+ policy.FacilityId = input.FacilityId;
+ policy.UnitTypeId = input.UnitTypeId;
+ policy.EffectiveFrom = input.From;
+ policy.EffectiveTo = input.To;
+ }
+
+ private static UpsertPolicyRequest ToRequest(Policy p) => new(
+ p.PolicyName, p.PolicyType, p.CalculationType ?? "", p.Value, p.MinValue, p.MaxValue,
+ p.RuleDescription, p.FacilityId, p.UnitTypeId, p.EffectiveFrom, p.EffectiveTo);
+
+ private IQueryable PolicyQueryable() => dbContext.Policies
+ .AsNoTracking()
+ .Include(p => p.Facility)
+ .Include(p => p.UnitType)
+ .Include(p => p.CreatedByUser);
+
+ private static PolicyDto ToPolicyDto(Policy p) => new(
+ p.PolicyId,
+ p.PolicyName,
+ p.PolicyType,
+ p.CalculationType,
+ p.Value,
+ p.MinValue,
+ p.MaxValue,
+ p.RuleDescription,
+ (p.FacilityId, p.UnitTypeId) switch
+ {
+ (null, null) => "GLOBAL",
+ (not null, null) => "FACILITY",
+ (null, not null) => "UNIT_TYPE",
+ _ => "FACILITY_UNIT_TYPE"
+ },
+ p.FacilityId,
+ p.Facility?.Name,
+ p.UnitTypeId,
+ p.UnitType?.TypeName,
+ p.EffectiveFrom,
+ p.EffectiveTo,
+ p.Status,
+ p.CreatedBy,
+ p.CreatedByUser?.FullName ?? "",
+ p.CreatedAt,
+ p.UpdatedAt);
+
+ private static object PolicySnapshot(Policy p) => new
+ {
+ p.PolicyName,
+ p.PolicyType,
+ p.CalculationType,
+ p.Value,
+ p.MinValue,
+ p.MaxValue,
+ p.RuleDescription,
+ p.FacilityId,
+ p.UnitTypeId,
+ EffectiveFrom = p.EffectiveFrom.ToString("yyyy-MM-dd"),
+ EffectiveTo = p.EffectiveTo?.ToString("yyyy-MM-dd"),
+ p.Status
+ };
+
+ // =====================================================================
+ // UC21 — Bảng giá
+ // =====================================================================
+
+ public async Task> GetRatesAsync(long? facilityId, long? unitTypeId, bool includeHistory, CancellationToken ct = default)
+ {
+ var today = OpsRules.TodayUtc;
+
+ var query = dbContext.RentalRates.AsNoTracking().AsQueryable();
+ if (facilityId.HasValue) query = query.Where(r => r.FacilityId == facilityId);
+ if (unitTypeId.HasValue) query = query.Where(r => r.UnitTypeId == unitTypeId);
+ if (!includeHistory)
+ {
+ // Giá đang áp dụng và giá đã lên lịch cho tương lai
+ query = query.Where(r => r.Status == "ACTIVE" && (r.EffectiveTo == null || r.EffectiveTo >= today));
+ }
+
+ return await query
+ .OrderBy(r => r.Facility.Name)
+ .ThenBy(r => r.UnitType.Area)
+ .ThenByDescending(r => r.EffectiveFrom)
+ .Select(r => new OpsRateDto(
+ r.RateId,
+ r.FacilityId,
+ r.Facility.Name,
+ r.UnitTypeId,
+ r.UnitType.TypeName,
+ r.MonthlyRate,
+ r.EffectiveFrom,
+ r.EffectiveTo,
+ r.Status,
+ r.Status == "ACTIVE" && r.EffectiveFrom <= today && (r.EffectiveTo == null || r.EffectiveTo >= today)))
+ .ToListAsync(ct);
+ }
+
+ public async Task SetRateAsync(SetRateRequest request, long userId, CancellationToken ct = default)
+ {
+ if (request.MonthlyRate <= 0) throw new ArgumentException("Giá thuê tháng phải lớn hơn 0.");
+ if (request.MonthlyRate % 1000 != 0) throw new ArgumentException("Giá thuê tháng phải là bội số của 1.000 VND.");
+
+ var today = OpsRules.TodayUtc;
+ var from = request.EffectiveFrom ?? today;
+ if (from < today)
+ {
+ throw new ArgumentException("Không đặt giá có hiệu lực trong quá khứ; giá đã chốt cho khách không bị sửa ngược (BR14).");
+ }
+
+ var facility = await dbContext.Facilities.AsNoTracking().FirstOrDefaultAsync(f => f.FacilityId == request.FacilityId, ct)
+ ?? throw new ArgumentException("Cơ sở không tồn tại.");
+ var unitType = await dbContext.UnitTypes.AsNoTracking().FirstOrDefaultAsync(t => t.UnitTypeId == request.UnitTypeId, ct)
+ ?? throw new ArgumentException("Loại kho không tồn tại.");
+
+ // Giá phải nằm trong khung PRICE_RANGE đang áp dụng (UC21 bước 5)
+ var range = await OpsRules.FindApplicablePolicyAsync(dbContext, "PRICE_RANGE", facility.FacilityId, unitType.UnitTypeId, from, ct);
+ if (range != null
+ && ((range.MinValue.HasValue && request.MonthlyRate < range.MinValue.Value)
+ || (range.MaxValue.HasValue && request.MonthlyRate > range.MaxValue.Value)))
+ {
+ throw new ArgumentException(
+ $"Giá {request.MonthlyRate:N0} VND nằm ngoài khung giá \"{range.PolicyName}\" " +
+ $"({range.MinValue?.ToString("N0") ?? "—"} – {range.MaxValue?.ToString("N0") ?? "—"} VND).");
+ }
+
+ await using var tx = await dbContext.Database.BeginTransactionAsync(ct);
+
+ var existing = await dbContext.RentalRates
+ .Where(r => r.FacilityId == facility.FacilityId
+ && r.UnitTypeId == unitType.UnitTypeId
+ && r.Status == "ACTIVE"
+ && (r.EffectiveTo == null || r.EffectiveTo >= from))
+ .ToListAsync(ct);
+
+ foreach (var old in existing)
+ {
+ var before = RateSnapshot(old);
+ if (old.EffectiveFrom >= from)
+ {
+ // Giá đã lên lịch từ cùng ngày hoặc sau đó → thay bằng giá mới
+ old.Status = "INACTIVE";
+ }
+ else
+ {
+ // BR19: kết thúc giá cũ ngay trước ngày giá mới bắt đầu, không để hai giá chồng nhau
+ old.EffectiveTo = from.AddDays(-1);
+ if (old.EffectiveTo.Value < today) old.Status = "EXPIRED";
+ }
+ Log(userId, "RATE_SUPERSEDE", "RENTAL_RATE", old.RateId, before, RateSnapshot(old));
+ }
+
+ var rate = new RentalRate
+ {
+ FacilityId = facility.FacilityId,
+ UnitTypeId = unitType.UnitTypeId,
+ SetBy = userId,
+ MonthlyRate = request.MonthlyRate,
+ EffectiveFrom = from,
+ Status = "ACTIVE",
+ CreatedAt = DateTime.UtcNow
+ };
+ dbContext.RentalRates.Add(rate);
+ await dbContext.SaveChangesAsync(ct);
+
+ Log(userId, "RATE_SET", "RENTAL_RATE", rate.RateId, null, RateSnapshot(rate));
+ await dbContext.SaveChangesAsync(ct);
+ await tx.CommitAsync(ct);
+
+ return new OpsRateDto(
+ rate.RateId, facility.FacilityId, facility.Name, unitType.UnitTypeId, unitType.TypeName,
+ rate.MonthlyRate, rate.EffectiveFrom, rate.EffectiveTo, rate.Status, rate.EffectiveFrom <= today);
+ }
+
+ private static object RateSnapshot(RentalRate r) => new
+ {
+ r.FacilityId,
+ r.UnitTypeId,
+ r.MonthlyRate,
+ EffectiveFrom = r.EffectiveFrom.ToString("yyyy-MM-dd"),
+ EffectiveTo = r.EffectiveTo?.ToString("yyyy-MM-dd"),
+ r.Status
+ };
+
+ // =====================================================================
+ // Audit (BR13)
+ // =====================================================================
+
+ private void Log(long userId, string action, string entityType, long? entityId, object? oldValue, object? newValue)
+ {
+ dbContext.ActivityLogs.Add(new ActivityLog
+ {
+ UserId = userId,
+ Action = action,
+ EntityType = entityType,
+ EntityId = entityId,
+ OldValue = oldValue == null ? null : JsonSerializer.Serialize(oldValue),
+ NewValue = newValue == null ? null : JsonSerializer.Serialize(newValue),
+ LoggedAt = DateTime.UtcNow
+ });
+ }
+}
diff --git a/StorageProject.Infrastructure/Services/OpsRules.cs b/StorageProject.Infrastructure/Services/OpsRules.cs
new file mode 100644
index 0000000..2975efa
--- /dev/null
+++ b/StorageProject.Infrastructure/Services/OpsRules.cs
@@ -0,0 +1,91 @@
+using Microsoft.EntityFrameworkCore;
+using StorageProject.Core.Entities;
+using StorageProject.Infrastructure.Data;
+
+namespace StorageProject.Infrastructure.Services;
+
+///
+/// Hằng số và quy tắc dùng chung cho khu Vận hành KD (SRS mục 10.2, BR19–BR23).
+///
+internal static class OpsRules
+{
+ public static readonly string[] FacilityStatuses = ["ACTIVE", "INACTIVE", "TEMPORARILY_CLOSED"];
+
+ public static readonly string[] PolicyTypes =
+ ["DEPOSIT", "RENEWAL", "CANCELLATION", "RETURN", "OVERDUE", "EXTRA_FEE", "DISCOUNT", "FEE_WAIVER", "PRICE_RANGE"];
+
+ public static readonly string[] CalculationTypes = ["FIXED", "PERCENTAGE", "RANGE", "RULE"];
+
+ // Kho đang sử dụng: còn tài sản của khách (SRS 10.2)
+ public static readonly string[] UnitInUseStatuses = ["OCCUPIED", "RETURN_PENDING"];
+
+ // Không tính vào mẫu số tỷ lệ sử dụng (SRS 10.2)
+ public static readonly string[] UnitUnavailableStatuses = ["MAINTENANCE", "OUT_OF_SERVICE", "INSPECTION"];
+
+ public static readonly string[] UnitReservedStatuses = ["RESERVED", "ASSIGNED"];
+
+ public static readonly string[] OpenContractStatuses = ["ACTIVE", "EXPIRING", "OVERDUE", "RETURN_PENDING"];
+
+ public static readonly string[] OpenReservationStatuses =
+ ["PENDING_PAYMENT", "PENDING_VERIFICATION", "CONFIRMED", "UNIT_ASSIGNED"];
+
+ // Payment đã từng thu thành công (bản đã hoàn vẫn giữ lịch sử thu ban đầu)
+ public static readonly string[] CollectedPaymentStatuses = ["PAID", "REFUNDED", "PARTIALLY_REFUNDED"];
+
+ public static readonly string[] UnpaidPaymentStatuses = ["PENDING", "FAILED"];
+
+ /// Giờ Việt Nam dùng để cắt kỳ báo cáo; dữ liệu trong DB lưu UTC.
+ public static readonly TimeSpan ReportOffset = TimeSpan.FromHours(7);
+
+ public static DateOnly TodayUtc => DateOnly.FromDateTime(DateTime.UtcNow);
+
+ public static DateOnly TodayLocal => DateOnly.FromDateTime(DateTime.UtcNow + ReportOffset);
+
+ public static DateTime LocalDayStartUtc(DateOnly day) => day.ToDateTime(TimeOnly.MinValue) - ReportOffset;
+
+ public static decimal? OccupancyRate(int inUse, int operable) =>
+ operable <= 0 ? null : Math.Round(inUse * 100m / operable, 1, MidpointRounding.AwayFromZero);
+
+ public static bool Overlaps(DateOnly aFrom, DateOnly? aTo, DateOnly bFrom, DateOnly? bTo) =>
+ aFrom <= (bTo ?? DateOnly.MaxValue) && bFrom <= (aTo ?? DateOnly.MaxValue);
+
+ ///
+ /// Tìm chính sách đang áp dụng theo thứ tự ưu tiên BR20:
+ /// cơ sở + loại kho → cơ sở + mọi loại → toàn hệ thống + loại kho → toàn hệ thống + mọi loại.
+ ///
+ public static Task FindApplicablePolicyAsync(
+ AppDbContext dbContext, string policyType, long? facilityId, long? unitTypeId, DateOnly onDate, CancellationToken ct)
+ {
+ return dbContext.Policies
+ .AsNoTracking()
+ .Where(p => p.PolicyType == policyType
+ && p.Status == "ACTIVE"
+ && p.EffectiveFrom <= onDate
+ && (p.EffectiveTo == null || p.EffectiveTo >= onDate)
+ && (p.FacilityId == null || p.FacilityId == facilityId)
+ && (p.UnitTypeId == null || p.UnitTypeId == unitTypeId))
+ .OrderByDescending(p => p.FacilityId != null)
+ .ThenByDescending(p => p.UnitTypeId != null)
+ .ThenByDescending(p => p.EffectiveFrom)
+ .FirstOrDefaultAsync(ct);
+ }
+
+ ///
+ /// Tiền cọc theo chính sách DEPOSIT (BR21):
+ /// PERCENTAGE = % tiền thuê kỳ đầu trước giảm; FIXED ≥ 1.000 = số tiền VND;
+ /// FIXED < 1.000 = số tháng tiền thuê (cách ghi của chính sách seed ban đầu, Value = 1 nghĩa là 1 tháng).
+ /// Không có chính sách áp dụng hoặc RULE → mặc định 1 tháng tiền thuê.
+ ///
+ public static decimal CalculateDeposit(Policy? policy, decimal monthlyRate, decimal estimatedAmount)
+ {
+ if (policy?.Value is not decimal value) return monthlyRate;
+
+ return policy.CalculationType switch
+ {
+ "PERCENTAGE" => Math.Round(estimatedAmount * value / 100m, 0, MidpointRounding.AwayFromZero),
+ "FIXED" when value >= 1000m => value,
+ "FIXED" => monthlyRate * value,
+ _ => monthlyRate
+ };
+ }
+}
diff --git a/StorageProject.Infrastructure/Services/ReservationService.cs b/StorageProject.Infrastructure/Services/ReservationService.cs
index 45f11bd..564c456 100644
--- a/StorageProject.Infrastructure/Services/ReservationService.cs
+++ b/StorageProject.Infrastructure/Services/ReservationService.cs
@@ -86,6 +86,12 @@ public async Task CreateReservationAsync(long customerId, Create
var facility = await dbContext.Facilities.FindAsync([request.FacilityId], ct)
?? throw new InvalidOperationException("Không tìm thấy cơ sở kho.");
+ // UC19: chỉ cơ sở đang hoạt động mới nhận đặt chỗ mới (tạm đóng vẫn phục vụ khách hiện tại)
+ if (facility.Status != "ACTIVE")
+ {
+ throw new InvalidOperationException("Cơ sở này đang tạm ngừng nhận đặt chỗ mới. Vui lòng chọn cơ sở khác.");
+ }
+
var unitType = await dbContext.UnitTypes.FindAsync([request.UnitTypeId], ct)
?? throw new InvalidOperationException("Không tìm thấy loại phòng kho.");
@@ -98,6 +104,7 @@ public async Task CreateReservationAsync(long customerId, Create
var activeRate = await dbContext.RentalRates
.Where(r => r.FacilityId == request.FacilityId
&& r.UnitTypeId == request.UnitTypeId
+ && r.Status == "ACTIVE"
&& r.EffectiveFrom <= today
&& (r.EffectiveTo == null || r.EffectiveTo >= today))
.OrderByDescending(r => r.EffectiveFrom)
@@ -123,20 +130,13 @@ public async Task CreateReservationAsync(long customerId, Create
throw new InvalidOperationException("Hiện tại đã hết kho trống cho loại kho và khoảng thời gian yêu cầu.");
}
- decimal depositMonths = 1;
- var depositPolicy = await dbContext.Policies
- .Where(p => p.PolicyType == "DEPOSIT" &&
- (p.FacilityId == request.FacilityId || p.FacilityId == null))
- .FirstOrDefaultAsync(ct);
-
- if (depositPolicy?.Value.HasValue == true)
- {
- depositMonths = depositPolicy.Value.Value;
- }
+ // Chỉ chính sách đang áp dụng, chọn theo thứ tự ưu tiên BR20 (bản nháp của Vận hành KD không ảnh hưởng)
+ var depositPolicy = await OpsRules.FindApplicablePolicyAsync(
+ dbContext, "DEPOSIT", request.FacilityId, request.UnitTypeId, today, ct);
var monthlyRate = activeRate.MonthlyRate;
var estimatedAmount = monthlyRate * request.RentalPeriodMonths;
- var requiredDeposit = monthlyRate * depositMonths;
+ var requiredDeposit = OpsRules.CalculateDeposit(depositPolicy, monthlyRate, estimatedAmount);
var reservation = new Reservation
{
diff --git a/docs/operations-api.md b/docs/operations-api.md
new file mode 100644
index 0000000..3be1799
--- /dev/null
+++ b/docs/operations-api.md
@@ -0,0 +1,150 @@
+# API Quản lý vận hành kinh doanh (`/api/operations/*`)
+
+Dành cho vai trò **OPERATIONS** (Business Operations Manager trong SRS) — UC19 đến UC23, Flow 4.
+Tài khoản seed: `ops01` / `Ops@123`. Mọi endpoint cần JWT của tài khoản có role `OPERATIONS`; vai trò khác nhận **403**.
+
+Quy ước chung:
+
+- JSON dùng camelCase. Ngày `yyyy-MM-dd`, ngày giờ là UTC (D10). Tiền là số VND.
+- Lỗi: `400 { error }` dữ liệu sai · `404 { error }` không tìm thấy · `409 { error, details }` xung đột trạng thái.
+- Mọi thay đổi (cơ sở, chính sách, giá, xuất báo cáo) được ghi `activity_logs` (BR13) — xem ở màn A04 của quản trị.
+- Không cần migration: dùng các bảng `facilities`, `policies`, `rental_rates` đã có.
+
+## 1. Cơ sở (UC19) — màn B01
+
+| Phương thức | Đường dẫn | Body / query | Ghi chú |
+|---|---|---|---|
+| GET | `/api/operations/facilities` | `?status=ACTIVE&search=quận 7` | Gồm cả cơ sở INACTIVE / TEMPORARILY_CLOSED |
+| GET | `/api/operations/facilities/{id}` | — | |
+| POST | `/api/operations/facilities` | `{ name, address, contactPhone, openingTime, closingTime, status? }` | `201` + `{ facility, warnings[] }` |
+| PUT | `/api/operations/facilities/{id}` | như trên | Sửa thông tin; `status` nếu gửi thì đi qua cùng kiểm tra như endpoint dưới |
+| PUT | `/api/operations/facilities/{id}/status` | `{ status, reason? }` | `ACTIVE` · `TEMPORARILY_CLOSED` · `INACTIVE` |
+
+Một cơ sở trả về:
+
+```json
+{
+ "facilityId": 3,
+ "name": "SafeSpace Nguyễn Lương Bằng",
+ "address": "12 Nguyễn Lương Bằng, Phường Tân Phú, Quận 7, TP. Hồ Chí Minh",
+ "contactPhone": "02837001012",
+ "openingTime": "06:00",
+ "closingTime": "22:00",
+ "status": "ACTIVE",
+ "totalUnits": 6,
+ "unitsInUse": 1,
+ "operableUnits": 6,
+ "occupancyRate": 16.7,
+ "pricedUnitTypes": 4,
+ "assignedStaff": 2,
+ "createdAt": "2026-09-15T12:40:41",
+ "updatedAt": "2026-09-15T12:40:41"
+}
+```
+
+Quy tắc:
+
+- `name`, `address` bắt buộc; giờ dạng `HH:mm`, nhập cả hai hoặc bỏ trống cả hai, giờ mở < giờ đóng; điện thoại 8–15 chữ số.
+- `occupancyRate = null` nghĩa là **Không áp dụng** (không có kho khai thác được) — giao diện hiện đúng chữ đó, không hiện 0%.
+- `warnings` không chặn lưu: tên gần giống cơ sở khác; cơ sở ACTIVE nhưng chưa có giá / ô kho / nhân sự.
+- `TEMPORARILY_CLOSED`: chặn đặt chỗ mới (`POST /api/reservations` trả 400), khách hiện tại vẫn trả kho, gia hạn, gửi hỗ trợ.
+- `INACTIVE`: chỉ được khi không còn hợp đồng và đơn đặt chỗ đang xử lý; ngược lại trả **409** với
+ `details: { openContracts, openReservations }`. Không có API xoá cơ sở (SRS UC19).
+
+## 2. Chính sách, khung giá, phí, giảm giá (UC20, UC21) — màn B02, B03
+
+| Phương thức | Đường dẫn | Body / query | Ghi chú |
+|---|---|---|---|
+| GET | `/api/operations/policies` | `?type=DEPOSIT&status=ACTIVE&facilityId=&unitTypeId=` | |
+| GET | `/api/operations/policies/{id}` | — | |
+| POST | `/api/operations/policies` | xem body dưới | Luôn tạo ở trạng thái `DRAFT` |
+| PUT | `/api/operations/policies/{id}` | như POST | Chỉ sửa được `DRAFT` |
+| POST | `/api/operations/policies/{id}/activate` | `?replaceExisting=true` | `{ policy, superseded[] }` |
+| POST | `/api/operations/policies/{id}/deactivate` | — | → `INACTIVE`, giữ lại để truy vết |
+| DELETE | `/api/operations/policies/{id}` | — | Chỉ xoá `DRAFT` |
+
+Body tạo / sửa:
+
+```json
+{
+ "policyName": "Phí quá hạn trả kho",
+ "policyType": "OVERDUE",
+ "calculationType": "PERCENTAGE",
+ "value": 5,
+ "minValue": null,
+ "maxValue": null,
+ "ruleDescription": "Tính 5% tiền thuê tháng cho mỗi tuần quá hạn",
+ "facilityId": null,
+ "unitTypeId": null,
+ "effectiveFrom": "2026-10-20",
+ "effectiveTo": null
+}
+```
+
+- `policyType`: `DEPOSIT, RENEWAL, CANCELLATION, RETURN, OVERDUE, EXTRA_FEE, DISCOUNT, FEE_WAIVER, PRICE_RANGE`.
+- `calculationType`: `FIXED` (số tiền VND) · `PERCENTAGE` (0–100) · `RANGE` (`minValue ≤ maxValue`) · `RULE` (chỉ là hướng dẫn, BR23).
+- `PRICE_RANGE` bắt buộc dùng `RANGE`. Giá trị không được âm. `effectiveTo ≥ effectiveFrom`.
+- `facilityId` / `unitTypeId` để `null` = toàn hệ thống / mọi loại kho. Trường `scope` trong kết quả:
+ `GLOBAL`, `FACILITY`, `UNIT_TYPE`, `FACILITY_UNIT_TYPE`.
+- Kích hoạt khi đã có chính sách **cùng loại, cùng phạm vi**, khoảng hiệu lực giao nhau → **409** với
+ `details.conflictingPolicyIds`. Giao diện hỏi lại người dùng rồi gửi `?replaceExisting=true`: bản cũ được kết thúc
+ hiệu lực ngay trước ngày bản mới bắt đầu (hoặc chuyển `INACTIVE` nếu chưa kịp bắt đầu) — UC20 A2.
+- Chính sách đang áp dụng không sửa trực tiếp: tạo bản mới rồi kích hoạt với `replaceExisting=true`.
+
+Ảnh hưởng tới nghiệp vụ khác:
+
+- **Tiền cọc** (`POST /api/reservations`, `POST /api/availability/check`) lấy chính sách `DEPOSIT` đang áp dụng theo thứ tự
+ ưu tiên BR20. `PERCENTAGE` = % tiền thuê cả kỳ; `FIXED ≥ 1.000` = số tiền VND; `FIXED < 1.000` = số tháng tiền thuê
+ (cách ghi của chính sách seed: `1` = 1 tháng, D16). Bản `DRAFT` không ảnh hưởng.
+- **Khung giá** `PRICE_RANGE` đang áp dụng chặn giá ngoài khung khi đặt giá ở mục 3.
+
+## 3. Bảng giá thuê (UC21) — màn B03
+
+| Phương thức | Đường dẫn | Body / query | Ghi chú |
+|---|---|---|---|
+| GET | `/api/operations/rates` | `?facilityId=&unitTypeId=&includeHistory=false` | Mặc định: giá đang áp dụng + giá đã lên lịch |
+| POST | `/api/operations/rates` | `{ facilityId, unitTypeId, monthlyRate, effectiveFrom? }` | `effectiveFrom` bỏ trống = hôm nay |
+
+- `monthlyRate > 0`, bội số 1.000 VND; `effectiveFrom` không được ở quá khứ.
+- Giá cũ của cùng cơ sở + loại kho tự kết thúc ngay trước ngày giá mới bắt đầu (BR19, không chồng giá).
+ Giá đã lên lịch từ cùng ngày hoặc sau đó bị thay bằng giá mới.
+- Giá đã chốt trong đơn đặt chỗ và hợp đồng **không đổi** (BR14).
+- `isCurrent = true` là giá đang áp dụng hôm nay.
+
+## 4. Báo cáo (UC22, UC23) — màn B04, B05
+
+Bộ lọc chung: `from`, `to` (`yyyy-MM-dd`, giờ Việt Nam; mặc định từ đầu tháng đến hôm nay), `facilityId`, `unitTypeId`.
+
+| Phương thức | Đường dẫn | Trả về |
+|---|---|---|
+| GET | `/api/operations/reports/facilities` | `{ filter, snapshotAt, totals, facilities: [{ facilityId, facilityName, facilityStatus, metrics }] }` |
+| GET | `/api/operations/reports/unit-types` | `{ filter, snapshotAt, totals, unitTypes: [{ unitTypeId, unitTypeName, metrics }] }` |
+| GET | `/api/operations/reports/revenue-trend?months=6` | `{ months: [{ year, month, label, collected, refunded, rentalAndFeeRevenue, depositCollected }] }` |
+| GET | `/api/operations/reports/rental-status` | Số hợp đồng / đơn đặt chỗ / ô kho theo trạng thái |
+| GET | `/api/operations/reports/facilities/{id}/contracts?status=OVERDUE` | Chi tiết một cơ sở: hợp đồng, công nợ, case quá hạn |
+| GET | `/api/operations/reports/export?view=facilities` | Tệp CSV. `view` = `facilities` · `unit-types` · `revenue-trend` |
+
+`metrics` (định nghĩa theo SRS mục 10.2):
+
+| Trường | Ý nghĩa |
+|---|---|
+| `collected` | Tiền thu trong kỳ — mọi khoản trừ REFUND đã thu, kể cả cọc |
+| `refunded` | Tiền hoàn trong kỳ |
+| `netCollected` | Thu ròng = thu − hoàn |
+| `rentalAndFeeRevenue` | Doanh thu thuê và phí — không gồm cọc |
+| `depositCollected` | Cọc thu trong kỳ |
+| `depositHeld` | Cọc còn giữ đến thời điểm báo cáo |
+| `outstanding` | Công nợ hiện tại (khoản PENDING/FAILED > 0) |
+| `totalUnits`, `unitsInUse`, `unitsAvailable`, `unitsReserved`, `unitsUnavailable`, `operableUnits` | Ảnh chụp trạng thái ô kho tại `snapshotAt` |
+| `occupancyRate` | `unitsInUse / operableUnits × 100`; `null` = Không áp dụng |
+| `activeContracts` | Hợp đồng ACTIVE, EXPIRING, OVERDUE, RETURN_PENDING |
+| `overdueCases`, `overdueContracts` | Số case quá hạn chưa xử lý và số hợp đồng quá hạn (không trùng) |
+
+- `totals` luôn bằng tổng các dòng trong cùng bộ lọc (điểm nghiệm thu UC22).
+- Trạng thái kho là **hiện tại**, không phải lịch sử — giao diện ghi rõ "Số liệu kho tại thời điểm …" từ `snapshotAt`.
+- CSV: UTF-8 có BOM (mở bằng Excel giữ tiếng Việt), có dòng tiêu đề báo cáo, kỳ, cơ sở, loại kho, thời điểm chụp, đơn vị;
+ ô bắt đầu bằng `= + - @` được chặn công thức. Giao diện gọi với **cùng bộ lọc** đang xem rồi tải tệp
+ (`Content-Disposition` có tên tệp `bao-cao-...csv`).
+
+Giả định của bản cơ bản (D16): bảng `payments` chưa có `original_payment_id`, và hoàn tiền hiện chỉ có hoàn cọc sau trả kho,
+nên mọi khoản REFUND trừ vào "Cọc còn giữ"; "Doanh thu thuê và phí" không trừ REFUND.
diff --git a/progress.md b/progress.md
index eb4cded..5d72e25 100644
--- a/progress.md
+++ b/progress.md
@@ -17,6 +17,25 @@
---
+## Phiên 3 — 2026-10-14 — Backend khu Quản lý vận hành KD (Claude)
+
+- Tính năng: F24 (role OPERATIONS), F22 (cơ sở, chính sách, bảng giá), F23 (báo cáo + xuất CSV) — phía backend.
+ Nhánh `feature/operations-backend`.
+- Đã xong:
+ - Role `OPERATIONS`, quyền `POLICY_MANAGE`, `REPORT_SYSTEM`, `REPORT_EXPORT`, tài khoản `ops01` / `Ops@123`
+ (`DbSeeder.EnsureOperationsRoleAsync`, chạy lại được với DB cũ).
+ - `/api/operations/*`: cơ sở (UC19), chính sách (UC20–21), bảng giá (UC21), báo cáo theo cơ sở / loại kho / tháng /
+ trạng thái, drill-down hợp đồng, xuất CSV (UC22–23). Hợp đồng API: `docs/operations-api.md`. Không có migration mới.
+ - Đặt chỗ: chặn cơ sở không ACTIVE; tiền cọc và giá chỉ lấy chính sách / giá `ACTIVE` còn hiệu lực (D16).
+- Kiểm chứng:
+ - `dotnet build StorageProject.Core` → Build succeeded, 0 warning.
+ - Không tải được NuGet trong môi trường làm việc → biên dịch file mới / file sửa với lớp giả lập API EF Core → Build succeeded.
+ - **Chưa chạy `dotnet build StorageProject.slnx` đầy đủ và chưa chạy với SQL Server thật.**
+- Bị chặn / rủi ro: giao diện B01–B05 chưa có. Nếu B làm PayOS đổi `Payment.ContractId` thành không bắt buộc thì
+ `OperationsReportService.LoadAsync` cần lọc `p.ContractId != null` (khoản chưa có hợp đồng chưa thuộc cơ sở nào).
+- Phiên sau nên: chạy `dotnet build StorageProject.slnx` + chạy API, đăng nhập `ops01`, thử các request trong
+ `StorageProject.Api.http` mục Vận hành KD; pass thì đổi F24 sang `passing`, F22–F23 chờ giao diện B01–B05.
+
## Phiên 2 — 2026-10-01 — Giao diện theo Figma 30/09, khu Nhân viên / Quản lý cơ sở
- Tính năng: F30 (mới), F21, F11–F20 (phía giao diện). Nhánh `feature/figma-3009-staff-manager`.