Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`).

Expand Down
11 changes: 11 additions & 0 deletions DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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ở.

4 changes: 2 additions & 2 deletions SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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ó.

---

Expand Down
2 changes: 1 addition & 1 deletion SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
168 changes: 168 additions & 0 deletions StorageProject.Api/Endpoints/OperationsEndpoints.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Khu Quản lý vận hành kinh doanh (Business Operations Manager) — UC19–UC23.
/// Chỉ role OPERATIONS; sai vai trò trả 403.
/// </summary>
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");
}

/// <summary>Kỳ mặc định: từ đầu tháng hiện tại đến hôm nay (giờ Việt Nam).</summary>
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 });

/// <summary>Quy ước lỗi chung (docs/conventions.md): 400 { error }, 404 { error }, 409 { error, details }.</summary>
private static async Task<IResult> Run(Func<Task<IResult>> 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 });
}
}
}
5 changes: 4 additions & 1 deletion StorageProject.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -88,6 +88,8 @@
builder.Services.AddScoped<ISupportTicketService, SupportTicketService>();
builder.Services.AddScoped<IHandoverService, HandoverService>();
builder.Services.AddScoped<IAdminService, AdminService>();
builder.Services.AddScoped<IOperationsService, OperationsService>();
builder.Services.AddScoped<IOperationsReportService, OperationsReportService>();

var app = builder.Build();

Expand Down Expand Up @@ -117,6 +119,7 @@
app.MapRenewalEndpoints();
app.MapSupportTicketEndpoints();
app.MapAdminEndpoints();
app.MapOperationsEndpoints();

// Root status check
app.MapGet("/health", () => Results.Ok(new
Expand Down
65 changes: 63 additions & 2 deletions StorageProject.Api/StorageProject.Api.http
Original file line number Diff line number Diff line change
@@ -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 = <dán giá trị "token" trả về từ /api/auth/login>

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

###
Loading