From b48284065128fc884c88a0264ea9dfa7d3f6d07a Mon Sep 17 00:00:00 2001 From: Vector Date: Tue, 20 Oct 2026 23:31:04 +0700 Subject: [PATCH 1/3] fix: reconcile payments, enforce unit transitions and fix policy seeding --- DECISIONS.md | 18 + .../SafeSpace-Customer-UI/BE-CONTRACT.md | 4 + .../SafeSpace-Customer-UI/src/state/store.jsx | 17 +- .../Endpoints/ManagerEndpoints.cs | 65 - .../Endpoints/ReservationEndpoints.cs | 10 + .../Endpoints/StaffEndpoints.cs | 41 +- StorageProject.Api/Program.cs | 3 + StorageProject.Api/StorageProject.Api.http | 28 + .../Workers/ExpiredCashHoldWorker.cs | 19 + .../DTOs/Payment/PaymentDtos.cs | 2 +- .../DTOs/Reservation/ReservationDtos.cs | 6 +- StorageProject.Core/Entities/Payment.cs | 4 +- StorageProject.Core/Entities/Reservation.cs | 1 + .../Interfaces/IPayOSService.cs | 1 + .../ReservationContractConfigurations.cs | 6 +- .../Data/DbSeeder.cs | 5 + ...38_ReservationPaymentIntegrity.Designer.cs | 2004 +++++++++++++++++ ...61020154838_ReservationPaymentIntegrity.cs | 109 + .../Migrations/AppDbContextModelSnapshot.cs | 28 +- .../Services/CashHoldExpiry.cs | 34 + .../Services/CheckoutTransaction.cs | 27 + .../Services/FacilityOpsService.Actions.cs | 72 +- .../Services/FacilityOpsService.Board.cs | 4 +- .../Services/FacilityOpsStateStore.cs | 10 +- .../Services/FacilityService.cs | 3 +- .../Services/ManagerService.cs | 67 +- .../Services/OperationsReportService.cs | 8 +- .../Services/PayOSGateway.cs | 63 + .../Services/PayOSService.cs | 453 +--- .../Services/PaymentService.cs | 2 +- .../Services/ReservationAllocation.cs | 58 + .../Services/ReservationService.cs | 31 +- .../Services/ReservationSettlement.cs | 53 + .../Services/StaffService.cs | 212 +- .../Services/UnitStatusRules.cs | 24 + StorageProject.Tests/CheckoutTests.cs | 187 ++ StorageProject.Tests/RouteTests.cs | 32 + .../StorageProject.Tests.csproj | 10 + StorageProject.slnx | 1 + docs/payment-integrity-2026-10-20.md | 66 + feature_list.json | 15 +- progress.md | 10 + 42 files changed, 3024 insertions(+), 789 deletions(-) create mode 100644 StorageProject.Api/Workers/ExpiredCashHoldWorker.cs create mode 100644 StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.Designer.cs create mode 100644 StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.cs create mode 100644 StorageProject.Infrastructure/Services/CashHoldExpiry.cs create mode 100644 StorageProject.Infrastructure/Services/CheckoutTransaction.cs create mode 100644 StorageProject.Infrastructure/Services/PayOSGateway.cs create mode 100644 StorageProject.Infrastructure/Services/ReservationAllocation.cs create mode 100644 StorageProject.Infrastructure/Services/ReservationSettlement.cs create mode 100644 StorageProject.Infrastructure/Services/UnitStatusRules.cs create mode 100644 StorageProject.Tests/CheckoutTests.cs create mode 100644 StorageProject.Tests/RouteTests.cs create mode 100644 StorageProject.Tests/StorageProject.Tests.csproj create mode 100644 docs/payment-integrity-2026-10-20.md diff --git a/DECISIONS.md b/DECISIONS.md index 05cae7c..7610e57 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -149,3 +149,21 @@ - Ghi nhận lịch sử quét mã vào bảng `activity_logs` với `Action = "ACCESS_SCANNED"`, `EntityType = "CONTRACT"`, `EntityId = ContractId`, `NewValue = { result, unit, reason }`, `IpAddress` của máy quét. - Frontend: kết nối `useAccessQr.js` và `endpoints.js` trực tiếp với API backend khi `VITE_USE_API=true`, giữ nguyên mock offline cho môi trường thử nghiệm khi `VITE_USE_API=false`. + +## D23 — Thu tiền đặt kho và dự phòng thanh toán tại cơ sở (20/10/2026) +- Bổ sung cho D19/D21; không đổi số hoặc xoá nội dung quyết định cũ. Phạm vi được yêu cầu: kiểm tiền PayOS, ghi khoản thu, chống lặp, phân bổ, thanh toán tại kho và F12. +- Giữ cách tính hiện tại: khách trả tiền thuê cả kỳ + tiền cọc; không triển khai bỏ cọc trong gói này. +- PayOS: backend tính số tiền; SDK kiểm chữ ký; đối chiếu chính xác orderCode và số tiền. Không tìm đơn bằng cách tách số từ mô tả. Không dùng VietQR mặc định khi PayOS lỗi. +- Khoản thu RENT và DEPOSIT ghi vào payments ngay khi xác nhận, gắn ReservationId; ContractId được phép trống trước khi quản lý phân bổ. Gắn lại đúng bản ghi vào hợp đồng DRAFT, không tạo khoản PAID mới. +- Webhook chỉ xác nhận thanh toán; quản lý chọn ô ở M05. Đơn trả tại kho cũng được phân bổ trước, nhưng chưa thu đủ thì không được bàn giao. +- Chọn trả tại kho phải còn hạn và chưa trả tiền. Nếu đã khởi tạo orderCode, cần PayOS xác nhận link đã huỷ/không tồn tại; không chuyển nếu không kiểm tra được hoặc PayOS đã nhận tiền (kể cả một phần). +- Đơn trả tại kho có trạng thái PENDING_AT_FACILITY và PaymentMethod AT_FACILITY. Giữ chỗ đến hết ngày hẹn nhận kho theo giờ Việt Nam; worker xử lý hết hạn mỗi phút, huỷ phân bổ/hợp đồng nháp chưa thu và trả ô RESERVED về AVAILABLE. Thu tiền và worker dùng cùng khoá giao dịch. +- S09 chỉ là đơn chờ thu tại kho; nhân viên bấm xác nhận khi đã thực nhận tiền mặt. Ghi CASH. API gọi lại không tạo khoản thu mới. +- Tiền PayOS về sau khi đổi phương thức/đóng đơn: ghi PAYMENT_REVIEW_REQUIRED đúng một lần cho orderCode, không cộng vào khoản thu thuê lần nữa. Quản lý kiểm tra khoản tiền thực về và hoàn thủ công theo nhật ký; không tuyên bố đã tự chuyển tiền hoàn. +- Khoá transaction ở SQL Server bằng sp_getapplock, cùng khoá reservation cho webhook/thu tiền/phân bổ; thêm unique index trên ReservationId + PaymentType cho RENT/DEPOSIT. API /api/ops chỉ đăng ký một lần. +- Migration nối khoản RENT/DEPOSIT cũ vào đơn khi liên kết là duy nhất; không xoá hay tự bịa khoản tiền cho các đơn cũ chỉ có PaidAt. Các đơn cũ thiếu bằng chứng thu cần đối chiếu trước khi bàn giao. + +## D24 — Đổi trạng thái ô bằng tay phải có lý do và lịch sử (20/10/2026) +- AVAILABLE, MAINTENANCE, OUT_OF_SERVICE được chuyển qua lại bằng thao tác quản lý vận hành nếu ô không có giữ chỗ/hợp đồng chưa đóng. Mỗi lần đổi phải có lý do 1–255 ký tự và ghi unit_status_history trong cùng transaction. +- RESERVED/ASSIGNED/OCCUPIED/RETURN_PENDING/INSPECTION thuộc luồng phân bổ, bàn giao, trả kho. Không cho dùng form trạng thái để bỏ qua các bước này. +- LOCKED từ giao diện được ánh xạ thành OUT_OF_SERVICE theo tập trạng thái SQL hiện có. Gọi lại cùng trạng thái với lý do hợp lệ không thêm lịch sử trùng. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md index 21e2e7e..e5945f5 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md @@ -108,3 +108,7 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend: Hình dạng dữ liệu giao diện đang dùng nằm ở `src/ops/data.js`; nghiệp vụ (điều kiện chặn, chuyển trạng thái) ở `src/ops/reducer.js` và có test (`tests/ops.test.js`) để backend đối chiếu. + +## Bổ sung 20/10 — thu tiền trước phân bổ và trạng thái ô + +Đã triển khai API chọn trả tại kho, PaymentMethod, ghi khoản thu theo ReservationId rồi gắn ContractId, kiểm chuyển tiếp ô và lịch sử. Xem `docs/payment-integrity-2026-10-20.md` và D23–D24 để biết hợp đồng API, migration, phạm vi test và các ca cần chạy thật. FE không còn dùng confirm-transfer làm fallback cho chọn trả tại kho. Các API /api/ops tương thích được đăng ký duy nhất trong FacilityOpsEndpoints. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx index 4c70b58..21176ec 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx @@ -506,20 +506,9 @@ function ApiProvider({ children }) { } return null; }; - // Ưu tiên endpoint pay-at-facility; backend chưa có → dùng confirm-transfer để đơn vẫn vào hàng chờ thu tiền S09 - const calls = [() => api.payAtFacility(r.api_id), () => api.confirmTransfer(r.api_id)]; - let done = false; - for (const call of calls) { - try { - await call(); - done = true; - break; - } catch (e) { - const exp = await expired(e); - if (exp) return exp; - if (!(e instanceof ApiError && (e.status === 404 || e.status === 405))) throw e; - } - } + try { await api.payAtFacility(r.api_id); } + catch (e) { const exp = await expired(e); if (exp) return exp; throw e; } + const done = true; updateOverlay((o) => ({ ...o, atFacility: { ...o.atFacility, [r.api_id]: Date.now() }, diff --git a/StorageProject.Api/Endpoints/ManagerEndpoints.cs b/StorageProject.Api/Endpoints/ManagerEndpoints.cs index 82c9ebf..4405c4b 100644 --- a/StorageProject.Api/Endpoints/ManagerEndpoints.cs +++ b/StorageProject.Api/Endpoints/ManagerEndpoints.cs @@ -225,71 +225,6 @@ public static RouteGroupBuilder MapManagerEndpoints(this IEndpointRouteBuilder a } }); - // Backward compatibility routes for /api/ops/ - var opsGroup = app.MapGroup("/api/ops").WithTags("Operations (Compatibility)").RequireAuthorization(); - - opsGroup.MapGet("/board", async (ClaimsPrincipal user, IStaffService staffService, IManagerService managerService, CancellationToken ct) => - { - var role = user.GetUserRole(); - if (role.Equals("CUSTOMER", StringComparison.OrdinalIgnoreCase)) return Results.Forbid(); - - var userId = user.GetUserId(); - var isManager = role.Equals("MANAGER", StringComparison.OrdinalIgnoreCase) || role.Equals("ADMIN", StringComparison.OrdinalIgnoreCase); - - if (isManager) - { - var board = await managerService.GetManagerBoardAsync(userId, ct); - return Results.Ok(board); - } - else - { - var board = await staffService.GetStaffBoardAsync(userId, ct); - return Results.Ok(board); - } - }); - - opsGroup.MapPost("/allocations/{id}", async (string id, AllocateUnitRequest request, ClaimsPrincipal user, IManagerService managerService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await managerService.AllocateUnitAsync(userId, id, request, ct); - return Results.Ok(new { message = "Phân bổ kho thành công." }); - }); - - opsGroup.MapPut("/assignments/{id}", async (string id, AssignStaffRequest request, ClaimsPrincipal user, IManagerService managerService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await managerService.AssignStaffAsync(userId, id, request, ct); - return Results.Ok(new { message = "Phân công nhân viên thành công." }); - }); - - opsGroup.MapPost("/renewals/{id}/approve", async (string id, ClaimsPrincipal user, IManagerService managerService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await managerService.ApproveRenewalAsync(userId, id, ct); - return Results.Ok(new { message = "Phê duyệt gia hạn thành công." }); - }); - - opsGroup.MapPost("/renewals/{id}/reject", async (string id, RejectRenewalRequest request, ClaimsPrincipal user, IManagerService managerService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await managerService.RejectRenewalAsync(userId, id, request, ct); - return Results.Ok(new { message = "Từ chối gia hạn thành công." }); - }); - - opsGroup.MapPost("/contracts/{id}/reminders", async (string id, AddReminderRequest request, ClaimsPrincipal user, IManagerService managerService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await managerService.AddContractReminderAsync(userId, id, request, ct); - return Results.Ok(new { message = "Ghi nhận lịch sử nhắc nhở." }); - }); - - opsGroup.MapPost("/contracts/{id}/refund", async (string id, ClaimsPrincipal user, IManagerService managerService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await managerService.ConfirmRefundAsync(userId, id, ct); - return Results.Ok(new { message = "Xác nhận hoàn cọc thành công." }); - }); - return group; } } diff --git a/StorageProject.Api/Endpoints/ReservationEndpoints.cs b/StorageProject.Api/Endpoints/ReservationEndpoints.cs index 915c339..d189fc9 100644 --- a/StorageProject.Api/Endpoints/ReservationEndpoints.cs +++ b/StorageProject.Api/Endpoints/ReservationEndpoints.cs @@ -82,6 +82,16 @@ public static RouteGroupBuilder MapReservationEndpoints(this IEndpointRouteBuild }) .WithSummary("Khách báo đã chuyển khoản: đơn chuyển sang chờ nhân viên đối soát (PENDING_VERIFICATION)"); + group.MapPost("/{id:long}/pay-at-facility", async (long id, ClaimsPrincipal user, IPayOSService payOS, CancellationToken ct) => + { + try { + await payOS.PayAtFacilityAsync(user.GetUserId(), id, ct); + return Results.Ok(new { message = "Đã giữ chỗ, thanh toán tại cửa hàng khi nhận kho." }); + } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { + return Results.BadRequest(new { error = ex.Message }); + } + }); + // PayOS integration endpoints: create QR and check payment status group.MapPost("/create-payos-qr", async (CreatePayOSQrRequest request, ClaimsPrincipal user, IPayOSService payOSService, CancellationToken ct) => { diff --git a/StorageProject.Api/Endpoints/StaffEndpoints.cs b/StorageProject.Api/Endpoints/StaffEndpoints.cs index a8b6394..5fda5c0 100644 --- a/StorageProject.Api/Endpoints/StaffEndpoints.cs +++ b/StorageProject.Api/Endpoints/StaffEndpoints.cs @@ -11,7 +11,7 @@ public static RouteGroupBuilder MapStaffEndpoints(this IEndpointRouteBuilder app { var group = app.MapGroup("/api/staff") .WithTags("Staff Operations") - .RequireAuthorization(); + .RequireAuthorization(policy => policy.RequireRole("STAFF", "MANAGER")); // 1. Staff Board group.MapGet("/board", async (ClaimsPrincipal user, IStaffService staffService, CancellationToken ct) => @@ -184,45 +184,6 @@ public static RouteGroupBuilder MapStaffEndpoints(this IEndpointRouteBuilder app } }); - // Backward compatibility routes for /api/ops/ - var opsGroup = app.MapGroup("/api/ops").WithTags("Operations (Compatibility)").RequireAuthorization(); - opsGroup.MapPost("/payments/{id}/confirm", async (string id, ClaimsPrincipal user, IStaffService staffService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await staffService.ConfirmPaymentAsync(userId, id, ct); - return Results.Ok(new { message = "Xác nhận thanh toán thành công." }); - }); - opsGroup.MapPost("/payments/{id}/mismatch", async (string id, MismatchPaymentRequest request, ClaimsPrincipal user, IStaffService staffService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await staffService.MismatchPaymentAsync(userId, id, request, ct); - return Results.Ok(new { message = "Ghi nhận sai lệch thanh toán." }); - }); - opsGroup.MapPost("/verifications/{id}", async (string id, VerifyCustomerRequest request, ClaimsPrincipal user, IStaffService staffService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await staffService.VerifyCustomerAsync(userId, id, request, ct); - return Results.Ok(new { message = "Xác minh thông tin khách hàng thành công." }); - }); - opsGroup.MapPost("/handovers/{id}/complete", async (string id, CompleteHandoverRequest request, ClaimsPrincipal user, IStaffService staffService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await staffService.CompleteHandoverAsync(userId, id, request, ct); - return Results.Ok(new { message = "Hoàn tất bàn giao kho." }); - }); - opsGroup.MapPost("/returns/{id}/inspection", async (string id, ReturnInspectionRequest request, ClaimsPrincipal user, IStaffService staffService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await staffService.SubmitReturnInspectionAsync(userId, id, request, ct); - return Results.Ok(new { message = "Lưu biên bản kiểm tra trả kho thành công." }); - }); - opsGroup.MapPost("/tickets/{id}/responses", async (string id, TicketResponseRequest request, ClaimsPrincipal user, IStaffService staffService, CancellationToken ct) => - { - var userId = user.GetUserId(); - await staffService.AddTicketResponseAsync(userId, id, request, ct); - return Results.Ok(new { message = "Phản hồi yêu cầu hỗ trợ thành công." }); - }); - return group; } } diff --git a/StorageProject.Api/Program.cs b/StorageProject.Api/Program.cs index 23a847c..2056d5d 100644 --- a/StorageProject.Api/Program.cs +++ b/StorageProject.Api/Program.cs @@ -1,4 +1,5 @@ using System.Text; +using StorageProject.Api.Workers; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; @@ -92,6 +93,8 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddHostedService(); builder.Services.AddScoped(); builder.Services.AddSingleton(new AccessQrOptions( builder.Configuration["AccessQr:Secret"] ?? jwtSecret, diff --git a/StorageProject.Api/StorageProject.Api.http b/StorageProject.Api/StorageProject.Api.http index 45c3143..55c0f96 100644 --- a/StorageProject.Api/StorageProject.Api.http +++ b/StorageProject.Api/StorageProject.Api.http @@ -65,3 +65,31 @@ GET {{StorageProject.Api_HostAddress}}/api/operations/reports/export?view=facili Authorization: Bearer {{opsToken}} ### + +### ==== Bản sửa thanh toán 20/10: thay token và id bằng dữ liệu trên máy thử ==== +@customerToken = +@staffToken = +@managerToken = +@reservationId = 1 + +### Chọn trả tại kho (huỷ link PayOS cũ trước khi đổi phương thức) +POST {{StorageProject.Api_HostAddress}}/api/reservations/{{reservationId}}/pay-at-facility +Authorization: Bearer {{customerToken}} + +### Xác nhận đã thu tiền mặt, gửi lại không tạo tiền trùng +POST {{StorageProject.Api_HostAddress}}/api/staff/payments/{{reservationId}}/confirm +Authorization: Bearer {{staffToken}} + +### Phân bổ ô, gắn khoản thu đã có vào hợp đồng +POST {{StorageProject.Api_HostAddress}}/api/manager/allocations/{{reservationId}} +Authorization: Bearer {{managerToken}} +Content-Type: application/json + +{ "unitCode": "K01" } + +### Đổi trạng thái ô trống, bắt buộc lý do +PUT {{StorageProject.Api_HostAddress}}/api/staff/units/K02/status +Authorization: Bearer {{managerToken}} +Content-Type: application/json + +{ "status": "MAINTENANCE", "reason": "Sửa cửa kho" } diff --git a/StorageProject.Api/Workers/ExpiredCashHoldWorker.cs b/StorageProject.Api/Workers/ExpiredCashHoldWorker.cs new file mode 100644 index 0000000..cde02e5 --- /dev/null +++ b/StorageProject.Api/Workers/ExpiredCashHoldWorker.cs @@ -0,0 +1,19 @@ +using StorageProject.Infrastructure.Data; +using StorageProject.Infrastructure.Services; + +namespace StorageProject.Api.Workers; + +public sealed class ExpiredCashHoldWorker(IServiceScopeFactory scopes, ILogger logger) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1)); + do { + try { + using var scope = scopes.CreateScope(); + await CashHoldExpiry.ExpireAsync(scope.ServiceProvider.GetRequiredService(), stoppingToken); + } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { return; } + catch (Exception ex) { logger.LogError(ex, "Không xử lý được các đơn hết hạn giữ chỗ"); } + } while (await timer.WaitForNextTickAsync(stoppingToken)); + } +} diff --git a/StorageProject.Core/DTOs/Payment/PaymentDtos.cs b/StorageProject.Core/DTOs/Payment/PaymentDtos.cs index f73231d..9baf54a 100644 --- a/StorageProject.Core/DTOs/Payment/PaymentDtos.cs +++ b/StorageProject.Core/DTOs/Payment/PaymentDtos.cs @@ -2,7 +2,7 @@ namespace StorageProject.Core.DTOs.Payment; public record PaymentDto( long PaymentId, - long ContractId, + long? ContractId, long? RenewalId, string PaymentType, decimal Amount, diff --git a/StorageProject.Core/DTOs/Reservation/ReservationDtos.cs b/StorageProject.Core/DTOs/Reservation/ReservationDtos.cs index 760c78f..3187422 100644 --- a/StorageProject.Core/DTOs/Reservation/ReservationDtos.cs +++ b/StorageProject.Core/DTOs/Reservation/ReservationDtos.cs @@ -23,7 +23,8 @@ public record ReservationDto( DateTime? ExpiresAt, DateTime? CancelledAt, string? CancellationReason, - DateTime CreatedAt + DateTime CreatedAt, + string PaymentMethod = "PAYOS" ); public record ReservationDetailDto( @@ -44,5 +45,6 @@ public record ReservationDetailDto( string? AssignedUnitNumber, long? ContractId, string? ContractStatus, - DateTime CreatedAt + DateTime CreatedAt, + string PaymentMethod = "PAYOS" ); diff --git a/StorageProject.Core/Entities/Payment.cs b/StorageProject.Core/Entities/Payment.cs index e4d11ea..f8f05f2 100644 --- a/StorageProject.Core/Entities/Payment.cs +++ b/StorageProject.Core/Entities/Payment.cs @@ -3,7 +3,8 @@ namespace StorageProject.Core.Entities; public class Payment { public long PaymentId { get; set; } - public long ContractId { get; set; } + public long? ContractId { get; set; } + public long? ReservationId { get; set; } public long? RenewalId { get; set; } // DEPOSIT, RENT, RENEWAL, EXTRA_FEE, OVERDUE_FEE, DAMAGE_FEE, CLEANING_FEE, // LOST_KEY_FEE, ACCESS_CARD_FEE, REFUND @@ -19,5 +20,6 @@ public class Payment public DateTime UpdatedAt { get; set; } public RentalContract Contract { get; set; } = null!; + public Reservation Reservation { get; set; } = null!; public ContractRenewal? Renewal { get; set; } } diff --git a/StorageProject.Core/Entities/Reservation.cs b/StorageProject.Core/Entities/Reservation.cs index f361ad2..487c83d 100644 --- a/StorageProject.Core/Entities/Reservation.cs +++ b/StorageProject.Core/Entities/Reservation.cs @@ -14,6 +14,7 @@ public class Reservation public decimal EstimatedAmount { get; set; } public decimal RequiredDeposit { get; set; } // PENDING_PAYMENT, PENDING_VERIFICATION (khách báo đã chuyển khoản, chờ đối soát), CONFIRMED, UNIT_ASSIGNED, CHECKED_IN, CANCELLED, EXPIRED, NO_SHOW + public string PaymentMethod { get; set; } = "PAYOS"; // PAYOS / AT_FACILITY public string Status { get; set; } = "PENDING_PAYMENT"; public string? CancellationReason { get; set; } public long? OrderCode { get; set; } diff --git a/StorageProject.Core/Interfaces/IPayOSService.cs b/StorageProject.Core/Interfaces/IPayOSService.cs index 88512cb..9e11fa2 100644 --- a/StorageProject.Core/Interfaces/IPayOSService.cs +++ b/StorageProject.Core/Interfaces/IPayOSService.cs @@ -5,6 +5,7 @@ namespace StorageProject.Core.Interfaces; public interface IPayOSService { Task CreatePaymentQrAsync(long customerId, CreatePayOSQrRequest request, CancellationToken ct = default); + Task PayAtFacilityAsync(long customerId, long reservationId, CancellationToken ct = default); Task ProcessWebhookAsync(string webhookBodyJson, string? signatureHeader, CancellationToken ct = default); Task GetReservationPaymentStatusAsync(long reservationId, CancellationToken ct = default); } diff --git a/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs b/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs index e0815ce..f1efa1d 100644 --- a/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs +++ b/StorageProject.Infrastructure/Data/Configurations/ReservationContractConfigurations.cs @@ -15,7 +15,7 @@ public void Configure(EntityTypeBuilder b) t.HasCheckConstraint("CK_reservations_estimated_amount", "[EstimatedAmount] >= 0"); t.HasCheckConstraint("CK_reservations_required_deposit", "[RequiredDeposit] >= 0"); t.HasCheckConstraint("CK_reservations_status", - "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','PENDING_AT_FACILITY','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); }); b.HasKey(r => r.ReservationId); b.Property(r => r.ReservationId).UseIdentityColumn(); @@ -27,6 +27,7 @@ public void Configure(EntityTypeBuilder b) b.Property(r => r.RequiredDeposit).IsRequired().HasColumnType("decimal(15,2)"); b.Property(r => r.Status).IsRequired().HasMaxLength(30).HasDefaultValue("PENDING_PAYMENT"); b.Property(r => r.CancellationReason).HasMaxLength(500); + b.Property(r => r.PaymentMethod).IsRequired().HasMaxLength(20).HasDefaultValue("PAYOS"); b.Property(r => r.OrderCode); b.HasIndex(r => r.OrderCode).IsUnique().HasFilter("[OrderCode] IS NOT NULL"); b.Property(r => r.PaymentQrUrl).HasMaxLength(2000); @@ -144,6 +145,9 @@ public void Configure(EntityTypeBuilder b) t.HasCheckConstraint("CK_payments_status", "[Status] IN ('PENDING','PAID','FAILED','REFUNDED','PARTIALLY_REFUNDED')"); }); + b.HasOne(p => p.Reservation).WithMany().HasForeignKey(p => p.ReservationId).OnDelete(DeleteBehavior.Restrict); + b.HasIndex(p => new { p.ReservationId, p.PaymentType }).IsUnique() + .HasFilter("[ReservationId] IS NOT NULL AND [PaymentType] IN ('RENT','DEPOSIT')"); b.HasKey(p => p.PaymentId); b.Property(p => p.PaymentId).UseIdentityColumn(); b.Property(p => p.PaymentType).IsRequired().HasMaxLength(30); diff --git a/StorageProject.Infrastructure/Data/DbSeeder.cs b/StorageProject.Infrastructure/Data/DbSeeder.cs index d3b95d1..d05a1d9 100644 --- a/StorageProject.Infrastructure/Data/DbSeeder.cs +++ b/StorageProject.Infrastructure/Data/DbSeeder.cs @@ -215,6 +215,11 @@ async Task EnsureUserAsync(string username, string email, string fullName, } }; + foreach (var policy in policies) + { + policy.CreatedBy = admin.UserId; + } + context.Policies.AddRange(policies); await context.SaveChangesAsync(); } diff --git a/StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.Designer.cs b/StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.Designer.cs new file mode 100644 index 0000000..4879d09 --- /dev/null +++ b/StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.Designer.cs @@ -0,0 +1,2004 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using StorageProject.Infrastructure.Data; + +#nullable disable + +namespace StorageProject.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20261020154838_ReservationPaymentIntegrity")] + partial class ReservationPaymentIntegrity + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.12") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("StorageProject.Core.Entities.AccessCredential", b => + { + b.Property("CredentialId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("CredentialId")); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CredentialReference") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("CredentialType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("IssuedAt") + .HasColumnType("datetime2"); + + b.Property("IssuedBy") + .HasColumnType("bigint"); + + b.Property("ReturnedAt") + .HasColumnType("datetime2"); + + b.Property("SecretHash") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("ACTIVE"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("CredentialId"); + + b.HasIndex("ContractId"); + + b.HasIndex("IssuedBy"); + + b.HasIndex("UnitId"); + + b.ToTable("access_credentials", null, t => + { + t.HasCheckConstraint("CK_access_credentials_status", "[Status] IN ('ACTIVE','RETURNED','LOST','REVOKED','REPLACED')"); + + t.HasCheckConstraint("CK_access_credentials_type", "[CredentialType] IN ('KEY','LOCK','ACCESS_CARD','ACCESS_CODE')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ActivityLog", b => + { + b.Property("LogId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("LogId")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("EntityId") + .HasColumnType("bigint"); + + b.Property("EntityType") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("nvarchar(80)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("LoggedAt") + .HasColumnType("datetime2"); + + b.Property("NewValue") + .HasColumnType("nvarchar(max)"); + + b.Property("OldValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .HasColumnType("bigint"); + + b.HasKey("LogId"); + + b.HasIndex("UserId"); + + b.ToTable("activity_logs", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ContractRenewal", b => + { + b.Property("RenewalId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("RenewalId")); + + b.Property("ApprovedAt") + .HasColumnType("datetime2"); + + b.Property("ApprovedBy") + .HasColumnType("bigint"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("NewEndDate") + .HasColumnType("date"); + + b.Property("NewMonthlyRate") + .HasColumnType("decimal(15,2)"); + + b.Property("OldEndDate") + .HasColumnType("date"); + + b.Property("OldMonthlyRate") + .HasColumnType("decimal(15,2)"); + + b.Property("RenewalAmount") + .HasColumnType("decimal(15,2)"); + + b.Property("RenewalPeriodMonths") + .HasColumnType("int"); + + b.Property("RequestedAt") + .HasColumnType("datetime2"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("PENDING"); + + b.HasKey("RenewalId"); + + b.HasIndex("ApprovedBy"); + + b.HasIndex("ContractId"); + + b.ToTable("contract_renewals", null, t => + { + t.HasCheckConstraint("CK_contract_renewals_amount", "[RenewalAmount] >= 0"); + + t.HasCheckConstraint("CK_contract_renewals_period", "[RenewalPeriodMonths] > 0"); + + t.HasCheckConstraint("CK_contract_renewals_status", "[Status] IN ('PENDING','APPROVED','REJECTED','PAID','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Facility", b => + { + b.Property("FacilityId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("FacilityId")); + + b.Property("Address") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ClosingTime") + .HasColumnType("time"); + + b.Property("ContactPhone") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("Latitude") + .HasPrecision(9, 6) + .HasColumnType("decimal(9,6)"); + + b.Property("Longitude") + .HasPrecision(9, 6) + .HasColumnType("decimal(9,6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.Property("OpeningTime") + .HasColumnType("time"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("ACTIVE"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.HasKey("FacilityId"); + + b.ToTable("facilities", null, t => + { + t.HasCheckConstraint("CK_facilities_coordinates", "([Latitude] IS NULL AND [Longitude] IS NULL) OR ([Latitude] BETWEEN -90 AND 90 AND [Longitude] BETWEEN -180 AND 180)"); + + t.HasCheckConstraint("CK_facilities_status", "[Status] IN ('ACTIVE','INACTIVE','TEMPORARILY_CLOSED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.HandoverRecord", b => + { + b.Property("HandoverId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("HandoverId")); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("CustomerConfirmed") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("HandoverAt") + .HasColumnType("datetime2"); + + b.Property("InitialCondition") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Notes") + .HasColumnType("nvarchar(max)"); + + b.Property("ScheduledAt") + .HasColumnType("datetime2"); + + b.Property("StaffConfirmed") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("StaffId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("SCHEDULED"); + + b.Property("VerifiedAt") + .HasColumnType("datetime2"); + + b.HasKey("HandoverId"); + + b.HasIndex("ContractId") + .IsUnique(); + + b.HasIndex("StaffId"); + + b.ToTable("handover_records", null, t => + { + t.HasCheckConstraint("CK_handover_records_status", "[Status] IN ('SCHEDULED','VERIFIED','HANDED_OVER','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.LoginHistory", b => + { + b.Property("LoginHistoryId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("LoginHistoryId")); + + b.Property("DeviceInfo") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("LoginAt") + .HasColumnType("datetime2"); + + b.Property("LoginStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LogoutAt") + .HasColumnType("datetime2"); + + b.Property("UserId") + .HasColumnType("bigint"); + + b.HasKey("LoginHistoryId"); + + b.HasIndex("UserId"); + + b.ToTable("login_history", null, t => + { + t.HasCheckConstraint("CK_login_history_status", "[LoginStatus] IN ('SUCCESS','FAILED','BLOCKED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.MaintenanceRequest", b => + { + b.Property("MaintenanceId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("MaintenanceId")); + + b.Property("AssignedStaffId") + .HasColumnType("bigint"); + + b.Property("CompletedAt") + .HasColumnType("datetime2"); + + b.Property("Cost") + .ValueGeneratedOnAdd() + .HasColumnType("decimal(15,2)") + .HasDefaultValue(0m); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("IssueDescription") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("MaintenanceType") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("Notes") + .HasColumnType("nvarchar(max)"); + + b.Property("Priority") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("NORMAL"); + + b.Property("ReportedBy") + .HasColumnType("bigint"); + + b.Property("ScheduledAt") + .HasColumnType("datetime2"); + + b.Property("StartedAt") + .HasColumnType("datetime2"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("OPEN"); + + b.Property("SupportTicketId") + .HasColumnType("bigint"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("MaintenanceId"); + + b.HasIndex("AssignedStaffId"); + + b.HasIndex("ReportedBy"); + + b.HasIndex("SupportTicketId"); + + b.HasIndex("UnitId"); + + b.ToTable("maintenance_requests", null, t => + { + t.HasCheckConstraint("CK_maintenance_requests_priority", "[Priority] IN ('LOW','NORMAL','HIGH','URGENT')"); + + t.HasCheckConstraint("CK_maintenance_requests_status", "[Status] IN ('OPEN','SCHEDULED','IN_PROGRESS','COMPLETED','CANCELLED')"); + + t.HasCheckConstraint("CK_maintenance_requests_type", "[MaintenanceType] IN ('INSPECTION','REPAIR','CLEANING','LOCK','ACCESS_SYSTEM','OTHER')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.OverdueCase", b => + { + b.Property("OverdueCaseId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("OverdueCaseId")); + + b.Property("AssignedStaffId") + .HasColumnType("bigint"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("GraceDeadline") + .HasColumnType("date"); + + b.Property("Notes") + .HasColumnType("nvarchar(max)"); + + b.Property("OpenedAt") + .HasColumnType("datetime2"); + + b.Property("OutstandingAmount") + .ValueGeneratedOnAdd() + .HasColumnType("decimal(15,2)") + .HasDefaultValue(0m); + + b.Property("OverdueFrom") + .HasColumnType("date"); + + b.Property("ResolvedAt") + .HasColumnType("datetime2"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("OPEN"); + + b.HasKey("OverdueCaseId"); + + b.HasIndex("AssignedStaffId"); + + b.HasIndex("ContractId"); + + b.ToTable("overdue_cases", null, t => + { + t.HasCheckConstraint("CK_overdue_cases_status", "[Status] IN ('OPEN','CONTACTED','PAYMENT_PENDING','RETURN_PENDING','RESOLVED','ESCALATED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Payment", b => + { + b.Property("PaymentId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("PaymentId")); + + b.Property("Amount") + .HasColumnType("decimal(15,2)"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("Currency") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(3) + .HasColumnType("nvarchar(3)") + .HasDefaultValue("VND"); + + b.Property("DueDate") + .HasColumnType("date"); + + b.Property("PaidAt") + .HasColumnType("datetime2"); + + b.Property("PaymentMethod") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("PaymentType") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("RenewalId") + .HasColumnType("bigint"); + + b.Property("ReservationId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("PENDING"); + + b.Property("TransactionReference") + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.HasKey("PaymentId"); + + b.HasIndex("ContractId"); + + b.HasIndex("RenewalId"); + + b.HasIndex("TransactionReference") + .IsUnique() + .HasFilter("[TransactionReference] IS NOT NULL"); + + b.HasIndex("ReservationId", "PaymentType") + .IsUnique() + .HasFilter("[ReservationId] IS NOT NULL AND [PaymentType] IN ('RENT','DEPOSIT')"); + + b.ToTable("payments", null, t => + { + t.HasCheckConstraint("CK_payments_amount", "[Amount] >= 0"); + + t.HasCheckConstraint("CK_payments_payment_method", "[PaymentMethod] IN ('CASH','BANK_TRANSFER','CARD','E_WALLET','PAYMENT_GATEWAY')"); + + t.HasCheckConstraint("CK_payments_payment_type", "[PaymentType] IN ('DEPOSIT','RENT','RENEWAL','EXTRA_FEE','OVERDUE_FEE','DAMAGE_FEE','CLEANING_FEE','LOST_KEY_FEE','ACCESS_CARD_FEE','REFUND')"); + + t.HasCheckConstraint("CK_payments_status", "[Status] IN ('PENDING','PAID','FAILED','REFUNDED','PARTIALLY_REFUNDED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Permission", b => + { + b.Property("PermissionId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("PermissionId")); + + b.Property("Description") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PermissionCode") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("nvarchar(80)"); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.HasKey("PermissionId"); + + b.HasIndex("PermissionCode") + .IsUnique(); + + b.ToTable("permissions", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Policy", b => + { + b.Property("PolicyId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("PolicyId")); + + b.Property("CalculationType") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("CreatedBy") + .HasColumnType("bigint"); + + b.Property("EffectiveFrom") + .HasColumnType("date"); + + b.Property("EffectiveTo") + .HasColumnType("date"); + + b.Property("FacilityId") + .HasColumnType("bigint"); + + b.Property("MaxValue") + .HasColumnType("decimal(15,2)"); + + b.Property("MinValue") + .HasColumnType("decimal(15,2)"); + + b.Property("PolicyName") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.Property("PolicyType") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("RuleDescription") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("DRAFT"); + + b.Property("UnitTypeId") + .HasColumnType("bigint"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.Property("Value") + .HasColumnType("decimal(15,2)"); + + b.HasKey("PolicyId"); + + b.HasIndex("CreatedBy"); + + b.HasIndex("FacilityId"); + + b.HasIndex("UnitTypeId"); + + b.ToTable("policies", null, t => + { + t.HasCheckConstraint("CK_policies_calculation_type", "[CalculationType] IS NULL OR [CalculationType] IN ('FIXED','PERCENTAGE','RANGE','RULE')"); + + t.HasCheckConstraint("CK_policies_policy_type", "[PolicyType] IN ('DEPOSIT','RENEWAL','CANCELLATION','RETURN','OVERDUE','EXTRA_FEE','DISCOUNT','FEE_WAIVER','PRICE_RANGE')"); + + t.HasCheckConstraint("CK_policies_status", "[Status] IN ('DRAFT','ACTIVE','INACTIVE','EXPIRED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalContract", b => + { + b.Property("ContractId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("ContractId")); + + b.Property("ActivatedAt") + .HasColumnType("datetime2"); + + b.Property("AgreedMonthlyRate") + .HasColumnType("decimal(15,2)"); + + b.Property("CompletedAt") + .HasColumnType("datetime2"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("CustomerId") + .HasColumnType("bigint"); + + b.Property("DepositAmount") + .HasColumnType("decimal(15,2)"); + + b.Property("EndDate") + .HasColumnType("date"); + + b.Property("ReservationId") + .HasColumnType("bigint"); + + b.Property("StartDate") + .HasColumnType("date"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("DRAFT"); + + b.Property("TerminationReason") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("ContractId"); + + b.HasIndex("CustomerId"); + + b.HasIndex("ReservationId") + .IsUnique(); + + b.HasIndex("UnitId"); + + b.ToTable("rental_contracts", null, t => + { + t.HasCheckConstraint("CK_rental_contracts_dates", "[EndDate] > [StartDate]"); + + t.HasCheckConstraint("CK_rental_contracts_deposit", "[DepositAmount] >= 0"); + + t.HasCheckConstraint("CK_rental_contracts_rate", "[AgreedMonthlyRate] >= 0"); + + t.HasCheckConstraint("CK_rental_contracts_status", "[Status] IN ('DRAFT','ACTIVE','EXPIRING','OVERDUE','RETURN_PENDING','COMPLETED','TERMINATED','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalRate", b => + { + b.Property("RateId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("RateId")); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("EffectiveFrom") + .HasColumnType("date"); + + b.Property("EffectiveTo") + .HasColumnType("date"); + + b.Property("FacilityId") + .HasColumnType("bigint"); + + b.Property("MonthlyRate") + .HasColumnType("decimal(15,2)"); + + b.Property("SetBy") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("DRAFT"); + + b.Property("UnitTypeId") + .HasColumnType("bigint"); + + b.HasKey("RateId"); + + b.HasIndex("FacilityId"); + + b.HasIndex("SetBy"); + + b.HasIndex("UnitTypeId"); + + b.ToTable("rental_rates", null, t => + { + t.HasCheckConstraint("CK_rental_rates_monthly_rate", "[MonthlyRate] > 0"); + + t.HasCheckConstraint("CK_rental_rates_status", "[Status] IN ('DRAFT','ACTIVE','EXPIRED','INACTIVE')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Reservation", b => + { + b.Property("ReservationId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("ReservationId")); + + b.Property("CancellationReason") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("CancelledAt") + .HasColumnType("datetime2"); + + b.Property("CheckInAppointmentAt") + .HasColumnType("datetime2"); + + b.Property("CheckoutUrl") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("CustomerId") + .HasColumnType("bigint"); + + b.Property("EstimatedAmount") + .HasColumnType("decimal(15,2)"); + + b.Property("ExpectedEndDate") + .HasColumnType("date"); + + b.Property("ExpiresAt") + .HasColumnType("datetime2"); + + b.Property("FacilityId") + .HasColumnType("bigint"); + + b.Property("OrderCode") + .HasColumnType("bigint"); + + b.Property("PaidAt") + .HasColumnType("datetime2"); + + b.Property("PaymentMethod") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("PAYOS"); + + b.Property("PaymentQrUrl") + .HasMaxLength(2000) + .HasColumnType("nvarchar(2000)"); + + b.Property("QuotedMonthlyRate") + .HasColumnType("decimal(15,2)"); + + b.Property("RentalPeriodMonths") + .HasColumnType("int"); + + b.Property("RequiredDeposit") + .HasColumnType("decimal(15,2)"); + + b.Property("StartDate") + .HasColumnType("date"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("PENDING_PAYMENT"); + + b.Property("UnitTypeId") + .HasColumnType("bigint"); + + b.HasKey("ReservationId"); + + b.HasIndex("CustomerId"); + + b.HasIndex("FacilityId"); + + b.HasIndex("OrderCode") + .IsUnique() + .HasFilter("[OrderCode] IS NOT NULL"); + + b.HasIndex("UnitTypeId"); + + b.ToTable("reservations", null, t => + { + t.HasCheckConstraint("CK_reservations_estimated_amount", "[EstimatedAmount] >= 0"); + + t.HasCheckConstraint("CK_reservations_quoted_rate", "[QuotedMonthlyRate] >= 0"); + + t.HasCheckConstraint("CK_reservations_rental_period", "[RentalPeriodMonths] > 0"); + + t.HasCheckConstraint("CK_reservations_required_deposit", "[RequiredDeposit] >= 0"); + + t.HasCheckConstraint("CK_reservations_status", "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','PENDING_AT_FACILITY','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ReturnInspection", b => + { + b.Property("InspectionId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("InspectionId")); + + b.Property("CleaningFee") + .ValueGeneratedOnAdd() + .HasColumnType("decimal(15,2)") + .HasDefaultValue(0m); + + b.Property("CleaningRequired") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("ConditionStatus") + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("DamageDescription") + .HasColumnType("nvarchar(max)"); + + b.Property("DamageFee") + .ValueGeneratedOnAdd() + .HasColumnType("decimal(15,2)") + .HasDefaultValue(0m); + + b.Property("InspectedAt") + .HasColumnType("datetime2"); + + b.Property("MaintenanceRequired") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("Notes") + .HasColumnType("nvarchar(max)"); + + b.Property("ScheduledAt") + .HasColumnType("datetime2"); + + b.Property("StaffId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("SCHEDULED"); + + b.HasKey("InspectionId"); + + b.HasIndex("ContractId"); + + b.HasIndex("StaffId"); + + b.ToTable("return_inspections", null, t => + { + t.HasCheckConstraint("CK_return_inspections_condition", "[ConditionStatus] IS NULL OR [ConditionStatus] IN ('GOOD','DIRTY','DAMAGED','MAINTENANCE_REQUIRED')"); + + t.HasCheckConstraint("CK_return_inspections_status", "[Status] IN ('SCHEDULED','IN_PROGRESS','COMPLETED','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Role", b => + { + b.Property("RoleId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("RoleId")); + + b.Property("Description") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("RoleId"); + + b.HasIndex("RoleName") + .IsUnique(); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RolePermission", b => + { + b.Property("RoleId") + .HasColumnType("bigint"); + + b.Property("PermissionId") + .HasColumnType("bigint"); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.ToTable("role_permissions", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.StorageUnit", b => + { + b.Property("UnitId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("UnitId")); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("FacilityId") + .HasColumnType("bigint"); + + b.Property("Floor") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LocationDescription") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("AVAILABLE"); + + b.Property("UnitNumber") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("UnitTypeId") + .HasColumnType("bigint"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.Property("Zone") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("UnitId"); + + b.HasIndex("UnitTypeId"); + + b.HasIndex("FacilityId", "UnitNumber") + .IsUnique(); + + b.ToTable("storage_units", null, t => + { + t.HasCheckConstraint("CK_storage_units_status", "[Status] IN ('AVAILABLE','RESERVED','ASSIGNED','OCCUPIED','RETURN_PENDING','INSPECTION','MAINTENANCE','OUT_OF_SERVICE')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.SupportTicket", b => + { + b.Property("TicketId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("TicketId")); + + b.Property("AssignedAt") + .HasColumnType("datetime2"); + + b.Property("AssignedStaffId") + .HasColumnType("bigint"); + + b.Property("ClosedAt") + .HasColumnType("datetime2"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("CustomerId") + .HasColumnType("bigint"); + + b.Property("Description") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("IssueType") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("Priority") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("NORMAL"); + + b.Property("ResolvedAt") + .HasColumnType("datetime2"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("OPEN"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("TicketId"); + + b.HasIndex("AssignedStaffId"); + + b.HasIndex("ContractId"); + + b.HasIndex("CustomerId"); + + b.HasIndex("UnitId"); + + b.ToTable("support_tickets", null, t => + { + t.HasCheckConstraint("CK_support_tickets_issue_type", "[IssueType] IN ('UNIT','LOCK','ACCESS_CODE','ACCESS_CARD','PAYMENT','STORED_ITEM','OTHER')"); + + t.HasCheckConstraint("CK_support_tickets_priority", "[Priority] IN ('LOW','NORMAL','HIGH','URGENT')"); + + t.HasCheckConstraint("CK_support_tickets_status", "[Status] IN ('OPEN','ASSIGNED','IN_PROGRESS','RESOLVED','CLOSED','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitAssignment", b => + { + b.Property("AssignmentId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("AssignmentId")); + + b.Property("AssignedAt") + .HasColumnType("datetime2"); + + b.Property("AssignedBy") + .HasColumnType("bigint"); + + b.Property("Reason") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ReservationId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("ACTIVE"); + + b.Property("UnassignedAt") + .HasColumnType("datetime2"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("AssignmentId"); + + b.HasIndex("AssignedBy"); + + b.HasIndex("ReservationId"); + + b.HasIndex("UnitId"); + + b.ToTable("unit_assignments", null, t => + { + t.HasCheckConstraint("CK_unit_assignments_status", "[Status] IN ('ACTIVE','REPLACED','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitStatusHistory", b => + { + b.Property("StatusHistoryId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("StatusHistoryId")); + + b.Property("ChangedAt") + .HasColumnType("datetime2"); + + b.Property("ChangedBy") + .HasColumnType("bigint"); + + b.Property("NewStatus") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("OldStatus") + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("Reason") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("StatusHistoryId"); + + b.HasIndex("ChangedBy"); + + b.HasIndex("UnitId"); + + b.ToTable("unit_status_history", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitType", b => + { + b.Property("UnitTypeId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("UnitTypeId")); + + b.Property("Area") + .HasColumnType("decimal(8,2)"); + + b.Property("ClimateControlled") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Height") + .HasColumnType("decimal(8,2)"); + + b.Property("Length") + .HasColumnType("decimal(8,2)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("TypeName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.Property("Width") + .HasColumnType("decimal(8,2)"); + + b.HasKey("UnitTypeId"); + + b.HasIndex("TypeName") + .IsUnique(); + + b.ToTable("unit_types", null, t => + { + t.HasCheckConstraint("CK_unit_types_area", "[Area] > 0"); + + t.HasCheckConstraint("CK_unit_types_height", "[Height] IS NULL OR [Height] > 0"); + + t.HasCheckConstraint("CK_unit_types_length", "[Length] IS NULL OR [Length] > 0"); + + t.HasCheckConstraint("CK_unit_types_status", "[Status] IN ('ACTIVE','INACTIVE')"); + + t.HasCheckConstraint("CK_unit_types_width", "[Width] IS NULL OR [Width] > 0"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.User", b => + { + b.Property("UserId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("UserId")); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("FullName") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Phone") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("ACTIVE"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("UserId"); + + b.HasIndex("Email") + .IsUnique(); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("users", null, t => + { + t.HasCheckConstraint("CK_users_status", "[Status] IN ('ACTIVE','INACTIVE','LOCKED','SUSPENDED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UserFacility", b => + { + b.Property("UserFacilityId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("UserFacilityId")); + + b.Property("AssignedBy") + .HasColumnType("bigint"); + + b.Property("AssignedFrom") + .HasColumnType("date"); + + b.Property("AssignedTo") + .HasColumnType("date"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("FacilityId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("UserId") + .HasColumnType("bigint"); + + b.HasKey("UserFacilityId"); + + b.HasIndex("AssignedBy"); + + b.HasIndex("FacilityId"); + + b.HasIndex("UserId"); + + b.ToTable("user_facilities", null, t => + { + t.HasCheckConstraint("CK_user_facilities_status", "[Status] IN ('ACTIVE','ENDED','SUSPENDED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UserRole", b => + { + b.Property("UserId") + .HasColumnType("bigint"); + + b.Property("RoleId") + .HasColumnType("bigint"); + + b.Property("AssignedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2") + .HasDefaultValueSql("GETUTCDATE()"); + + b.Property("AssignedBy") + .HasColumnType("bigint"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("AssignedBy"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.AccessCredential", b => + { + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("AccessCredentials") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "IssuedByUser") + .WithMany() + .HasForeignKey("IssuedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("AccessCredentials") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Contract"); + + b.Navigation("IssuedByUser"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ActivityLog", b => + { + b.HasOne("StorageProject.Core.Entities.User", "User") + .WithMany("ActivityLogs") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("User"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ContractRenewal", b => + { + b.HasOne("StorageProject.Core.Entities.User", "ApprovedByUser") + .WithMany() + .HasForeignKey("ApprovedBy") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("ContractRenewals") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApprovedByUser"); + + b.Navigation("Contract"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.HandoverRecord", b => + { + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithOne("HandoverRecord") + .HasForeignKey("StorageProject.Core.Entities.HandoverRecord", "ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "Staff") + .WithMany() + .HasForeignKey("StaffId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Contract"); + + b.Navigation("Staff"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.LoginHistory", b => + { + b.HasOne("StorageProject.Core.Entities.User", "User") + .WithMany("LoginHistories") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.MaintenanceRequest", b => + { + b.HasOne("StorageProject.Core.Entities.User", "AssignedStaff") + .WithMany() + .HasForeignKey("AssignedStaffId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.User", "ReportedByUser") + .WithMany() + .HasForeignKey("ReportedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.SupportTicket", "SupportTicket") + .WithMany("MaintenanceRequests") + .HasForeignKey("SupportTicketId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("MaintenanceRequests") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedStaff"); + + b.Navigation("ReportedByUser"); + + b.Navigation("SupportTicket"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.OverdueCase", b => + { + b.HasOne("StorageProject.Core.Entities.User", "AssignedStaff") + .WithMany() + .HasForeignKey("AssignedStaffId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("OverdueCases") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedStaff"); + + b.Navigation("Contract"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Payment", b => + { + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("Payments") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("StorageProject.Core.Entities.ContractRenewal", "Renewal") + .WithMany("Payments") + .HasForeignKey("RenewalId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.Reservation", "Reservation") + .WithMany() + .HasForeignKey("ReservationId") + .OnDelete(DeleteBehavior.Restrict); + + b.Navigation("Contract"); + + b.Navigation("Renewal"); + + b.Navigation("Reservation"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Policy", b => + { + b.HasOne("StorageProject.Core.Entities.User", "CreatedByUser") + .WithMany() + .HasForeignKey("CreatedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.Facility", "Facility") + .WithMany("Policies") + .HasForeignKey("FacilityId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.UnitType", "UnitType") + .WithMany("Policies") + .HasForeignKey("UnitTypeId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("CreatedByUser"); + + b.Navigation("Facility"); + + b.Navigation("UnitType"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalContract", b => + { + b.HasOne("StorageProject.Core.Entities.User", "Customer") + .WithMany("RentalContracts") + .HasForeignKey("CustomerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.Reservation", "Reservation") + .WithOne("RentalContract") + .HasForeignKey("StorageProject.Core.Entities.RentalContract", "ReservationId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("RentalContracts") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Customer"); + + b.Navigation("Reservation"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalRate", b => + { + b.HasOne("StorageProject.Core.Entities.Facility", "Facility") + .WithMany("RentalRates") + .HasForeignKey("FacilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "SetByUser") + .WithMany() + .HasForeignKey("SetBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.UnitType", "UnitType") + .WithMany("RentalRates") + .HasForeignKey("UnitTypeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Facility"); + + b.Navigation("SetByUser"); + + b.Navigation("UnitType"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Reservation", b => + { + b.HasOne("StorageProject.Core.Entities.User", "Customer") + .WithMany("Reservations") + .HasForeignKey("CustomerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.Facility", "Facility") + .WithMany("Reservations") + .HasForeignKey("FacilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.UnitType", "UnitType") + .WithMany("Reservations") + .HasForeignKey("UnitTypeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Customer"); + + b.Navigation("Facility"); + + b.Navigation("UnitType"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ReturnInspection", b => + { + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("ReturnInspections") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "Staff") + .WithMany() + .HasForeignKey("StaffId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Contract"); + + b.Navigation("Staff"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RolePermission", b => + { + b.HasOne("StorageProject.Core.Entities.Permission", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.Role", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.StorageUnit", b => + { + b.HasOne("StorageProject.Core.Entities.Facility", "Facility") + .WithMany("StorageUnits") + .HasForeignKey("FacilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.UnitType", "UnitType") + .WithMany("StorageUnits") + .HasForeignKey("UnitTypeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Facility"); + + b.Navigation("UnitType"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.SupportTicket", b => + { + b.HasOne("StorageProject.Core.Entities.User", "AssignedStaff") + .WithMany() + .HasForeignKey("AssignedStaffId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("SupportTickets") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.User", "Customer") + .WithMany("SupportTickets") + .HasForeignKey("CustomerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("SupportTickets") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("AssignedStaff"); + + b.Navigation("Contract"); + + b.Navigation("Customer"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitAssignment", b => + { + b.HasOne("StorageProject.Core.Entities.User", "AssignedByUser") + .WithMany() + .HasForeignKey("AssignedBy") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("StorageProject.Core.Entities.Reservation", "Reservation") + .WithMany("UnitAssignments") + .HasForeignKey("ReservationId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("UnitAssignments") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedByUser"); + + b.Navigation("Reservation"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitStatusHistory", b => + { + b.HasOne("StorageProject.Core.Entities.User", "ChangedByUser") + .WithMany() + .HasForeignKey("ChangedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("StatusHistories") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ChangedByUser"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UserFacility", b => + { + b.HasOne("StorageProject.Core.Entities.User", "Assigner") + .WithMany() + .HasForeignKey("AssignedBy") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.Facility", "Facility") + .WithMany("UserFacilities") + .HasForeignKey("FacilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "User") + .WithMany("UserFacilities") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Assigner"); + + b.Navigation("Facility"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UserRole", b => + { + b.HasOne("StorageProject.Core.Entities.User", "Assigner") + .WithMany() + .HasForeignKey("AssignedBy") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.Role", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Assigner"); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ContractRenewal", b => + { + b.Navigation("Payments"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Facility", b => + { + b.Navigation("Policies"); + + b.Navigation("RentalRates"); + + b.Navigation("Reservations"); + + b.Navigation("StorageUnits"); + + b.Navigation("UserFacilities"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Permission", b => + { + b.Navigation("RolePermissions"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalContract", b => + { + b.Navigation("AccessCredentials"); + + b.Navigation("ContractRenewals"); + + b.Navigation("HandoverRecord"); + + b.Navigation("OverdueCases"); + + b.Navigation("Payments"); + + b.Navigation("ReturnInspections"); + + b.Navigation("SupportTickets"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Reservation", b => + { + b.Navigation("RentalContract"); + + b.Navigation("UnitAssignments"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Role", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.StorageUnit", b => + { + b.Navigation("AccessCredentials"); + + b.Navigation("MaintenanceRequests"); + + b.Navigation("RentalContracts"); + + b.Navigation("StatusHistories"); + + b.Navigation("SupportTickets"); + + b.Navigation("UnitAssignments"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.SupportTicket", b => + { + b.Navigation("MaintenanceRequests"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitType", b => + { + b.Navigation("Policies"); + + b.Navigation("RentalRates"); + + b.Navigation("Reservations"); + + b.Navigation("StorageUnits"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.User", b => + { + b.Navigation("ActivityLogs"); + + b.Navigation("LoginHistories"); + + b.Navigation("RentalContracts"); + + b.Navigation("Reservations"); + + b.Navigation("SupportTickets"); + + b.Navigation("UserFacilities"); + + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.cs b/StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.cs new file mode 100644 index 0000000..6a60304 --- /dev/null +++ b/StorageProject.Infrastructure/Migrations/20261020154838_ReservationPaymentIntegrity.cs @@ -0,0 +1,109 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace StorageProject.Infrastructure.Migrations +{ + /// + public partial class ReservationPaymentIntegrity : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropCheckConstraint( + name: "CK_reservations_status", + table: "reservations"); + + migrationBuilder.AddColumn( + name: "PaymentMethod", + table: "reservations", + type: "nvarchar(20)", + maxLength: 20, + nullable: false, + defaultValue: "PAYOS"); + + migrationBuilder.AlterColumn( + name: "ContractId", + table: "payments", + type: "bigint", + nullable: true, + oldClrType: typeof(long), + oldType: "bigint"); + + migrationBuilder.AddColumn( + name: "ReservationId", + table: "payments", + type: "bigint", + nullable: true); + + migrationBuilder.AddCheckConstraint( + name: "CK_reservations_status", + table: "reservations", + sql: "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','PENDING_AT_FACILITY','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + + // Link unambiguous existing receipts to their reservation; never delete or fabricate money. + migrationBuilder.Sql(@"UPDATE p SET ReservationId = c.ReservationId + FROM payments p INNER JOIN rental_contracts c ON p.ContractId = c.ContractId + WHERE p.PaymentType IN ('RENT','DEPOSIT') AND NOT EXISTS + (SELECT 1 FROM payments other WHERE other.ContractId = p.ContractId + AND other.PaymentType = p.PaymentType AND other.PaymentId <> p.PaymentId)"); + + migrationBuilder.CreateIndex( + name: "IX_payments_ReservationId_PaymentType", + table: "payments", + columns: new[] { "ReservationId", "PaymentType" }, + unique: true, + filter: "[ReservationId] IS NOT NULL AND [PaymentType] IN ('RENT','DEPOSIT')"); + + migrationBuilder.AddForeignKey( + name: "FK_payments_reservations_ReservationId", + table: "payments", + column: "ReservationId", + principalTable: "reservations", + principalColumn: "ReservationId", + onDelete: ReferentialAction.Restrict); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.Sql(@"IF EXISTS (SELECT 1 FROM payments WHERE ContractId IS NULL) + OR EXISTS (SELECT 1 FROM reservations WHERE Status = 'PENDING_AT_FACILITY') + THROW 51000, N'Không thể hạ migration khi còn khoản thu chưa gắn hợp đồng hoặc đơn chờ thu tại kho.', 1;"); + migrationBuilder.DropForeignKey( + name: "FK_payments_reservations_ReservationId", + table: "payments"); + + migrationBuilder.DropCheckConstraint( + name: "CK_reservations_status", + table: "reservations"); + + migrationBuilder.DropIndex( + name: "IX_payments_ReservationId_PaymentType", + table: "payments"); + + migrationBuilder.DropColumn( + name: "PaymentMethod", + table: "reservations"); + + migrationBuilder.DropColumn( + name: "ReservationId", + table: "payments"); + + migrationBuilder.AlterColumn( + name: "ContractId", + table: "payments", + type: "bigint", + nullable: false, + defaultValue: 0L, + oldClrType: typeof(long), + oldType: "bigint", + oldNullable: true); + + migrationBuilder.AddCheckConstraint( + name: "CK_reservations_status", + table: "reservations", + sql: "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + } + } +} diff --git a/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index 69409e1..c628ab7 100644 --- a/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -498,7 +498,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("Amount") .HasColumnType("decimal(15,2)"); - b.Property("ContractId") + b.Property("ContractId") .HasColumnType("bigint"); b.Property("CreatedAt") @@ -530,6 +530,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("RenewalId") .HasColumnType("bigint"); + b.Property("ReservationId") + .HasColumnType("bigint"); + b.Property("Status") .IsRequired() .ValueGeneratedOnAdd() @@ -554,6 +557,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsUnique() .HasFilter("[TransactionReference] IS NOT NULL"); + b.HasIndex("ReservationId", "PaymentType") + .IsUnique() + .HasFilter("[ReservationId] IS NOT NULL AND [PaymentType] IN ('RENT','DEPOSIT')"); + b.ToTable("payments", null, t => { t.HasCheckConstraint("CK_payments_amount", "[Amount] >= 0"); @@ -845,6 +852,13 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("PaidAt") .HasColumnType("datetime2"); + b.Property("PaymentMethod") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("PAYOS"); + b.Property("PaymentQrUrl") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); @@ -893,7 +907,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) t.HasCheckConstraint("CK_reservations_required_deposit", "[RequiredDeposit] >= 0"); - t.HasCheckConstraint("CK_reservations_status", "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + t.HasCheckConstraint("CK_reservations_status", "[Status] IN ('PENDING_PAYMENT','PENDING_VERIFICATION','PENDING_AT_FACILITY','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); }); }); @@ -1569,17 +1583,23 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") .WithMany("Payments") .HasForeignKey("ContractId") - .OnDelete(DeleteBehavior.Restrict) - .IsRequired(); + .OnDelete(DeleteBehavior.Restrict); b.HasOne("StorageProject.Core.Entities.ContractRenewal", "Renewal") .WithMany("Payments") .HasForeignKey("RenewalId") .OnDelete(DeleteBehavior.SetNull); + b.HasOne("StorageProject.Core.Entities.Reservation", "Reservation") + .WithMany() + .HasForeignKey("ReservationId") + .OnDelete(DeleteBehavior.Restrict); + b.Navigation("Contract"); b.Navigation("Renewal"); + + b.Navigation("Reservation"); }); modelBuilder.Entity("StorageProject.Core.Entities.Policy", b => diff --git a/StorageProject.Infrastructure/Services/CashHoldExpiry.cs b/StorageProject.Infrastructure/Services/CashHoldExpiry.cs new file mode 100644 index 0000000..9748be2 --- /dev/null +++ b/StorageProject.Infrastructure/Services/CashHoldExpiry.cs @@ -0,0 +1,34 @@ +using Microsoft.EntityFrameworkCore; +using StorageProject.Infrastructure.Data; + +namespace StorageProject.Infrastructure.Services; + +public static class CashHoldExpiry +{ + public static async Task ExpireAsync(AppDbContext db, CancellationToken ct = default) + { + var ids = await db.Reservations.AsNoTracking().Where(r => r.Status == "PENDING_AT_FACILITY" && + r.PaidAt == null && r.ExpiresAt <= DateTime.UtcNow).Select(r => r.ReservationId).Take(100).ToListAsync(ct); + foreach (var id in ids) + { + await using var tx = await CheckoutTransaction.BeginAsync(db, $"reservation:{id}", ct); + var r = await db.Reservations.Include(r => r.UnitAssignments).ThenInclude(a => a.Unit) + .Include(r => r.RentalContract).ThenInclude(c => c!.HandoverRecord).SingleAsync(r => r.ReservationId == id, ct); + await db.Entry(r).ReloadAsync(ct); + if (r.Status != "PENDING_AT_FACILITY" || r.PaidAt != null || r.ExpiresAt > DateTime.UtcNow) continue; + await CheckoutTransaction.LockAsync(db, $"inventory:{r.FacilityId}", ct); + foreach (var a in r.UnitAssignments.Where(a => a.Status == "ACTIVE")) + { + a.Status = "CANCELLED"; + if (a.Unit.Status == "RESERVED") a.Unit.Status = "AVAILABLE"; + } + if (r.RentalContract?.Status == "DRAFT") { + r.RentalContract.Status = "CANCELLED"; + if (r.RentalContract.HandoverRecord != null) r.RentalContract.HandoverRecord.Status = "CANCELLED"; + } + r.Status = "EXPIRED"; + ReservationSettlement.Audit(db, null, "CASH_HOLD_EXPIRED", id, new { r.ExpiresAt }); + await db.SaveChangesAsync(ct); await tx.CommitAsync(ct); + } + } +} diff --git a/StorageProject.Infrastructure/Services/CheckoutTransaction.cs b/StorageProject.Infrastructure/Services/CheckoutTransaction.cs new file mode 100644 index 0000000..a637ff2 --- /dev/null +++ b/StorageProject.Infrastructure/Services/CheckoutTransaction.cs @@ -0,0 +1,27 @@ +using System.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; +using StorageProject.Infrastructure.Data; + +namespace StorageProject.Infrastructure.Services; + +public static class CheckoutTransaction +{ + public static async Task BeginAsync(AppDbContext db, string resource, CancellationToken ct) + { + var tx = await db.Database.BeginTransactionAsync(IsolationLevel.Serializable, ct); + try { await LockAsync(db, resource, ct); return tx; } + catch { await tx.DisposeAsync(); throw; } + } + + public static async Task LockAsync(AppDbContext db, string resource, CancellationToken ct) + { + // SQL Server transaction-owned lock works across processes, unlike an in-memory semaphore. + if (db.Database.IsSqlServer()) + await db.Database.ExecuteSqlInterpolatedAsync($@" + DECLARE @result int; + EXEC @result = sp_getapplock @Resource={resource}, @LockMode='Exclusive', + @LockOwner='Transaction', @LockTimeout=10000; + IF @result < 0 THROW 51000, N'Không lấy được khoá giao dịch. Vui lòng thử lại.', 1;", ct); + } +} diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs index 0bafe6c..69f56eb 100644 --- a/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.Actions.cs @@ -77,14 +77,7 @@ private async Task ContractAsync(long facilityId, string code, C // ===================================================================== public async Task ConfirmPaymentAsync(OpsActor actor, string id, CancellationToken ct = default) { - var facility = await FacilityOfAsync(actor, ct); - var r = await ReservationAsync(facility.FacilityId, id, ct); - if (r.Status != "PENDING_VERIFICATION") throw new InvalidOperationException("Khoản này đã được xử lý."); - - // Chưa có ô kho → vào hàng chờ phân bổ của quản lý (M05) - r.Status = "CONFIRMED"; - Log(actor.UserId, LogAction.PaymentConfirmed, LogEntity.Reservation, r.ReservationId, new { amount = r.EstimatedAmount + r.RequiredDeposit }); - await dbContext.SaveChangesAsync(ct); + await new StaffService(dbContext).ConfirmPaymentAsync(actor.UserId, id, ct); } public async Task ReportMismatchAsync(OpsActor actor, string id, OpsNoteRequest request, CancellationToken ct = default) @@ -148,6 +141,8 @@ public async Task CompleteHandoverAsync(OpsActor actor, string id, OpsHandoverRe if (!UnlockMethods.Contains(method)) throw new ArgumentException("Chọn phương thức mở khoá."); var contract = h.Contract; + var reservation = await dbContext.Reservations.SingleAsync(r => r.ReservationId == contract.ReservationId, ct); + await ReservationSettlement.RequirePaidAsync(dbContext, reservation, ct); if (contract.Status != "DRAFT") throw new InvalidOperationException("Hợp đồng không ở trạng thái chờ bàn giao."); var now = NowUtc; @@ -266,66 +261,7 @@ public async Task AllocateAsync(OpsActor actor, string id, OpsAllocateRequest re RequireManager(actor); var facility = await FacilityOfAsync(actor, ct); var r = await ReservationAsync(facility.FacilityId, id, ct); - if (r.Status == "UNIT_ASSIGNED" || r.UnitAssignments.Any(a => a.Status == "ACTIVE")) - { - throw new InvalidOperationException("Đơn này đã được phân bổ kho."); - } - if (r.Status != "CONFIRMED") throw new InvalidOperationException("Đơn chưa được xác nhận thanh toán nên chưa phân bổ được."); - - var unitCode = (request.UnitCode ?? string.Empty).Trim(); - var unit = await dbContext.StorageUnits - .FirstOrDefaultAsync(u => u.FacilityId == facility.FacilityId && u.UnitNumber == unitCode, ct); - if (unit == null || unit.Status != "AVAILABLE" || unit.UnitTypeId != r.UnitTypeId) - { - throw new InvalidOperationException("Kho đã chọn không còn trống hoặc không khớp đơn đặt chỗ."); - } - var busy = await dbContext.RentalContracts.AnyAsync(c => c.UnitId == unit.UnitId - && HeldContractStatuses.Contains(c.Status) - && c.StartDate < r.ExpectedEndDate && c.EndDate > r.StartDate, ct); - if (busy) throw new InvalidOperationException("Kho đã chọn không còn trống hoặc không khớp đơn đặt chỗ."); - - var now = NowUtc; - var code = ReservationCode(r); - var confirmedAt = await dbContext.ActivityLogs - .Where(l => l.EntityType == LogEntity.Reservation && l.EntityId == r.ReservationId && l.Action == LogAction.PaymentConfirmed) - .OrderByDescending(l => l.LoggedAt) - .Select(l => (DateTime?)l.LoggedAt) - .FirstOrDefaultAsync(ct) ?? now; - - dbContext.UnitAssignments.Add(new UnitAssignment - { - ReservationId = r.ReservationId, UnitId = unit.UnitId, AssignedBy = actor.UserId, Status = "ACTIVE", AssignedAt = now - }); - r.Status = "UNIT_ASSIGNED"; - SetUnitStatus(unit, "RESERVED", actor.UserId, $"Phân bổ cho đơn {code}"); - - var contract = new RentalContract - { - ReservationId = r.ReservationId, CustomerId = r.CustomerId, UnitId = unit.UnitId, - StartDate = r.StartDate, EndDate = r.ExpectedEndDate, AgreedMonthlyRate = r.QuotedMonthlyRate, - DepositAmount = r.RequiredDeposit, Status = "DRAFT", CreatedAt = now - }; - // Khoản khách đã chuyển (nhân viên đã đối soát ở S09): cọc + tiền thuê cả kỳ - foreach (var (kind, amount) in new[] { ("DEPOSIT", r.RequiredDeposit), ("RENT", r.EstimatedAmount) }) - { - contract.Payments.Add(new Payment - { - PaymentType = kind, Amount = amount, Currency = "VND", PaymentMethod = "BANK_TRANSFER", - TransactionReference = code, DueDate = r.StartDate, PaidAt = confirmedAt, Status = "PAID", - CreatedAt = now, UpdatedAt = now - }); - } - // Chưa giao cho nhân viên nào: người phụ trách tạm là quản lý (bảng M06 hiện "Cần xử lý") - contract.HandoverRecord = new HandoverRecord - { - StaffId = actor.UserId, - ScheduledAt = r.CheckInAppointmentAt ?? UtcFromLocal(r.StartDate, 9), - Status = "SCHEDULED", - CreatedAt = now - }; - dbContext.RentalContracts.Add(contract); - Log(actor.UserId, LogAction.UnitAllocated, LogEntity.Reservation, r.ReservationId, new { unit = unit.UnitNumber }); - await dbContext.SaveChangesAsync(ct); + await ReservationAllocation.AllocateAsync(dbContext, actor.UserId, facility.FacilityId, r.ReservationId, request.UnitCode ?? "", ct); } // ===================================================================== diff --git a/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs b/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs index d599f22..16953bc 100644 --- a/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs +++ b/StorageProject.Infrastructure/Services/FacilityOpsService.Board.cs @@ -358,11 +358,11 @@ private async Task RevenueAsync(long facilityId, CancellationToke var rows = await dbContext.Payments .AsNoTracking() - .Where(p => p.Contract.Unit.FacilityId == facilityId + .Where(p => (p.ContractId != null ? p.Contract.Unit.FacilityId : p.Reservation.FacilityId) == facilityId && p.PaidAt != null && p.PaidAt >= fromUtc && (p.Status == "PAID" || p.Status == "REFUNDED" || p.Status == "PARTIALLY_REFUNDED") && p.PaymentType != "DEPOSIT" && p.PaymentType != "REFUND") - .Select(p => new { p.Amount, p.PaidAt, Cold = p.Contract.Unit.UnitType.ClimateControlled }) + .Select(p => new { p.Amount, p.PaidAt, Cold = p.ContractId != null ? p.Contract.Unit.UnitType.ClimateControlled : p.Reservation.UnitType.ClimateControlled }) .ToListAsync(ct); static decimal Million(decimal v) => Math.Round(v / 1_000_000m, 1, MidpointRounding.AwayFromZero); diff --git a/StorageProject.Infrastructure/Services/FacilityOpsStateStore.cs b/StorageProject.Infrastructure/Services/FacilityOpsStateStore.cs index d82da80..e0a7c51 100644 --- a/StorageProject.Infrastructure/Services/FacilityOpsStateStore.cs +++ b/StorageProject.Infrastructure/Services/FacilityOpsStateStore.cs @@ -33,10 +33,6 @@ public static long ParseIdNumber(string id) .AsQueryable(); var res = await q.FirstOrDefaultAsync(r => (ids.Contains(r.ReservationId) || (r.OrderCode.HasValue && ids.Contains(r.OrderCode.Value))) && (facilityId <= 0 || r.FacilityId == facilityId), ct); - if (res == null) - { - res = await q.FirstOrDefaultAsync(r => ids.Contains(r.ReservationId) || (r.OrderCode.HasValue && ids.Contains(r.OrderCode.Value)), ct); - } return res; } @@ -52,10 +48,6 @@ public static async Task GetUserFacilityAsync(AppDbContext dbContext, return userFac.Facility; } - var defaultFac = await dbContext.Facilities.FirstOrDefaultAsync(f => f.Name.Contains("Nguyễn Lương Bằng"), ct) - ?? await dbContext.Facilities.FirstOrDefaultAsync(ct) - ?? throw new InvalidOperationException("Không tìm thấy cơ sở kho."); - - return defaultFac; + throw new InvalidOperationException("Tài khoản chưa được phân công cơ sở đang hoạt động."); } } diff --git a/StorageProject.Infrastructure/Services/FacilityService.cs b/StorageProject.Infrastructure/Services/FacilityService.cs index cfde663..46fbbde 100644 --- a/StorageProject.Infrastructure/Services/FacilityService.cs +++ b/StorageProject.Infrastructure/Services/FacilityService.cs @@ -157,7 +157,8 @@ public async Task> GetActiveRatesAsync(long? facili var reservedUnitsCount = await dbContext.Reservations .CountAsync(r => r.FacilityId == request.FacilityId && r.UnitTypeId == request.UnitTypeId - && (r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_VERIFICATION" || r.Status == "CONFIRMED") + && (r.Status == "CONFIRMED" || ((r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_VERIFICATION" || r.Status == "PENDING_AT_FACILITY") && r.ExpiresAt > DateTime.UtcNow)) + && !r.UnitAssignments.Any(a => a.Status == "ACTIVE") && r.StartDate < expectedEndDate && r.ExpectedEndDate > request.StartDate, ct); diff --git a/StorageProject.Infrastructure/Services/ManagerService.cs b/StorageProject.Infrastructure/Services/ManagerService.cs index a76ee42..1e7aece 100644 --- a/StorageProject.Infrastructure/Services/ManagerService.cs +++ b/StorageProject.Infrastructure/Services/ManagerService.cs @@ -31,7 +31,7 @@ public async Task GetManagerBoardAsync(long userId, CancellationTok .Include(r => r.Customer) .Include(r => r.UnitType) .Include(r => r.UnitAssignments).ThenInclude(ua => ua.Unit) - .Where(r => r.FacilityId == fac.FacilityId && (r.Status == "CONFIRMED" || r.Status == "UNIT_ASSIGNED")) + .Where(r => r.FacilityId == fac.FacilityId && (r.Status == "CONFIRMED" || r.Status == "UNIT_ASSIGNED" || (r.Status == "PENDING_AT_FACILITY" && r.ExpiresAt > DateTime.UtcNow))) .OrderByDescending(r => r.CreatedAt) .ToListAsync(ct); @@ -117,11 +117,12 @@ public async Task GetManagerBoardAsync(long userId, CancellationTok var payments = await dbContext.Payments .AsNoTracking() .Include(p => p.Contract).ThenInclude(c => c.Unit).ThenInclude(u => u.UnitType) - .Where(p => p.Contract.Unit.FacilityId == fac.FacilityId && p.Status == "PAID") + .Include(p => p.Reservation).ThenInclude(r => r.UnitType) + .Where(p => (p.ContractId != null ? p.Contract.Unit.FacilityId : p.Reservation.FacilityId) == fac.FacilityId && p.Status == "PAID" && p.PaymentType == "RENT") .ToListAsync(ct); - var normalTotal = payments.Where(p => !p.Contract.Unit.UnitType.ClimateControlled).Sum(p => p.Amount) / 1_000_000m; - var climateTotal = payments.Where(p => p.Contract.Unit.UnitType.ClimateControlled).Sum(p => p.Amount) / 1_000_000m; + var normalTotal = payments.Where(p => !(p.ContractId != null ? p.Contract.Unit.UnitType.ClimateControlled : p.Reservation.UnitType.ClimateControlled)).Sum(p => p.Amount) / 1_000_000m; + var climateTotal = payments.Where(p => (p.ContractId != null ? p.Contract.Unit.UnitType.ClimateControlled : p.Reservation.UnitType.ClimateControlled)).Sum(p => p.Amount) / 1_000_000m; var revenueMonths = payments .Where(p => p.PaidAt.HasValue) @@ -165,36 +166,9 @@ public async Task GetManagerBoardAsync(long userId, CancellationTok public async Task AllocateUnitAsync(long userId, string id, AllocateUnitRequest request, CancellationToken ct = default) { var fac = await FacilityOpsStateStore.GetUserFacilityAsync(dbContext, userId, ct); - var r = await FacilityOpsStateStore.FindReservationByIdAsync(dbContext, id, fac.FacilityId, ct); - if (r == null) throw new InvalidOperationException("Không tìm thấy đơn phân bổ."); - - var unit = await dbContext.StorageUnits - .FirstOrDefaultAsync(u => u.FacilityId == fac.FacilityId && u.UnitNumber == request.UnitCode, ct); - if (unit == null || unit.Status != "AVAILABLE") - { - throw new InvalidOperationException("Kho không hợp lệ hoặc không trống."); - } - - unit.Status = "RESERVED"; - unit.UpdatedAt = DateTime.UtcNow; - - var existingAssignments = await dbContext.UnitAssignments - .Where(ua => ua.ReservationId == r.ReservationId) - .ToListAsync(ct); - foreach (var a in existingAssignments) a.Status = "INACTIVE"; - - dbContext.UnitAssignments.Add(new UnitAssignment - { - ReservationId = r.ReservationId, - UnitId = unit.UnitId, - AssignedBy = userId, - Status = "ACTIVE", - AssignedAt = DateTime.UtcNow, - Reason = "Quản lý cơ sở phân bổ kho" - }); - - r.Status = "CONFIRMED"; - await dbContext.SaveChangesAsync(ct); + var r = await FacilityOpsStateStore.FindReservationByIdAsync(dbContext, id, fac.FacilityId, ct) + ?? throw new InvalidOperationException("Không tìm thấy đơn phân bổ."); + await ReservationAllocation.AllocateAsync(dbContext, userId, fac.FacilityId, r.ReservationId, request.UnitCode, ct); } public async Task AssignStaffAsync(long userId, string id, AssignStaffRequest request, CancellationToken ct = default) @@ -362,18 +336,8 @@ public async Task UpdateUnitAsync(long userId, string id, UpdateStor if (!string.IsNullOrWhiteSpace(request.UnitNumber)) unit.UnitNumber = request.UnitNumber; if (!string.IsNullOrWhiteSpace(request.Floor)) unit.Floor = request.Floor; - if (!string.IsNullOrWhiteSpace(request.Status)) - { - unit.Status = request.Status.ToUpperInvariant() switch - { - "EMPTY" => "AVAILABLE", - "ACTIVE" => "OCCUPIED", - "WAITING_HANDOVER" => "RESERVED", - "MAINTENANCE" => "MAINTENANCE", - "LOCKED" => "LOCKED", - _ => request.Status.ToUpperInvariant() - }; - } + if (!string.IsNullOrWhiteSpace(request.Status) && UnitStatusRules.Normalize(request.Status) != unit.Status) + throw new InvalidOperationException("Đổi trạng thái bằng thao tác trạng thái riêng và nhập lý do."); unit.UpdatedAt = DateTime.UtcNow; await dbContext.SaveChangesAsync(ct); @@ -397,15 +361,6 @@ public async Task UpdateUnitAsync(long userId, string id, UpdateStor public async Task LockUnitAsync(long userId, string id, LockUnitRequest request, CancellationToken ct = default) { - var fac = await FacilityOpsStateStore.GetUserFacilityAsync(dbContext, userId, ct); - var unit = await dbContext.StorageUnits - .FirstOrDefaultAsync(u => u.FacilityId == fac.FacilityId && u.UnitNumber == id, ct); - if (unit == null) - { - throw new InvalidOperationException($"Không tìm thấy ô kho {id}."); - } - unit.Status = "LOCKED"; - unit.UpdatedAt = DateTime.UtcNow; - await dbContext.SaveChangesAsync(ct); + await staffService.UpdateUnitStatusAsync(userId, id, new UpdateUnitStatusRequest { Status = "OUT_OF_SERVICE", Reason = request.Reason }, ct); } } diff --git a/StorageProject.Infrastructure/Services/OperationsReportService.cs b/StorageProject.Infrastructure/Services/OperationsReportService.cs index 592f1a6..01931aa 100644 --- a/StorageProject.Infrastructure/Services/OperationsReportService.cs +++ b/StorageProject.Infrastructure/Services/OperationsReportService.cs @@ -49,14 +49,14 @@ private async Task LoadAsync(long? facilityId, long? unitTypeId, Cancell if (facilityId.HasValue) { - payments = payments.Where(p => p.Contract.Unit.FacilityId == facilityId); + payments = payments.Where(p => (p.ContractId != null ? p.Contract.Unit.FacilityId : p.Reservation.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); + payments = payments.Where(p => (p.ContractId != null ? p.Contract.Unit.UnitTypeId : p.Reservation.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); @@ -64,7 +64,9 @@ private async Task LoadAsync(long? facilityId, long? unitTypeId, Cancell 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), + p.ContractId != null ? p.Contract.Unit.FacilityId : p.Reservation.FacilityId, + p.ContractId != null ? p.Contract.Unit.UnitTypeId : p.Reservation.UnitTypeId, + p.ContractId != null ? p.Contract.Status : p.Reservation.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)); diff --git a/StorageProject.Infrastructure/Services/PayOSGateway.cs b/StorageProject.Infrastructure/Services/PayOSGateway.cs new file mode 100644 index 0000000..4ac4f76 --- /dev/null +++ b/StorageProject.Infrastructure/Services/PayOSGateway.cs @@ -0,0 +1,63 @@ +using System.Text.Json; +using Microsoft.Extensions.Configuration; +using PayOS; +using PayOS.Models.V2.PaymentRequests; +using PayOS.Models.Webhooks; + +namespace StorageProject.Infrastructure.Services; + +public record VerifiedReservationPayment(long OrderCode, decimal Amount); +public record CheckoutLink(string Url, string Qr); +public interface IPayOSGateway +{ + void EnsureConfigured(); + Task CreateAsync(long orderCode, int amount, long reservationId, long expiresAt, string returnUrl, string cancelUrl); + Task CancelAsync(long orderCode); + Task VerifyAsync(string body); +} + +public sealed class SdkPayOSGateway(IConfiguration config) : IPayOSGateway +{ + private PayOSClient Client() + { + var clientId = config["PayOS:ClientId"]; + var apiKey = config["PayOS:ApiKey"]; + var checksum = config["PayOS:ChecksumKey"]; + if (new[] { clientId, apiKey, checksum }.Any(x => string.IsNullOrWhiteSpace(x) || x.StartsWith("YOUR_"))) + throw new InvalidOperationException("PayOS chưa được cấu hình. Vui lòng chọn thanh toán tại cửa hàng."); + return new PayOSClient(new PayOSOptions { ClientId = clientId!, ApiKey = apiKey!, ChecksumKey = checksum! }); + } + + public void EnsureConfigured() => _ = Client(); + + public async Task CreateAsync(long orderCode, int amount, long reservationId, long expiresAt, string returnUrl, string cancelUrl) + { + var result = await Client().PaymentRequests.CreateAsync(new CreatePaymentLinkRequest { + OrderCode = orderCode, Amount = amount, Description = $"Dat kho #{reservationId}", + ReturnUrl = returnUrl, CancelUrl = cancelUrl, ExpiredAt = (int)expiresAt + }); + return new CheckoutLink(result.CheckoutUrl, result.QrCode); + } + + public async Task CancelAsync(long orderCode) + { + var client = Client(); + PayOS.Models.V2.PaymentRequests.PaymentLink existing; + try { existing = await client.PaymentRequests.GetAsync(orderCode); } + catch (PayOS.Exceptions.NotFoundException) { return; } // PayOS confirms that no payable link exists. + if (existing.AmountPaid > 0 || existing.Status.ToString().ToUpperInvariant() == "PAID") + throw new InvalidOperationException("PayOS đã nhận tiền. Hãy chờ cập nhật thanh toán, không chuyển sang trả tại kho."); + if (existing.Status.ToString().ToUpperInvariant() == "CANCELLED") return; + var cancelled = await client.PaymentRequests.CancelAsync(orderCode, "Khach chon thanh toan tai cua hang"); + if (cancelled.Status.ToString().ToUpperInvariant() != "CANCELLED") + throw new InvalidOperationException("Chưa huỷ được link PayOS. Vui lòng thử lại trước khi đổi phương thức."); + } + + public async Task VerifyAsync(string body) + { + var webhook = JsonSerializer.Deserialize(body, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }) + ?? throw new InvalidOperationException("Thông báo PayOS không hợp lệ."); + var data = await Client().Webhooks.VerifyAsync(webhook); + return webhook.Code == "00" && data.Code == "00" ? new VerifiedReservationPayment(data.OrderCode, data.Amount) : null; + } +} diff --git a/StorageProject.Infrastructure/Services/PayOSService.cs b/StorageProject.Infrastructure/Services/PayOSService.cs index c54037f..47f79fc 100644 --- a/StorageProject.Infrastructure/Services/PayOSService.cs +++ b/StorageProject.Infrastructure/Services/PayOSService.cs @@ -1,384 +1,129 @@ using System.Text.Json; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; -using PayOS; -using PayOS.Models.V2.PaymentRequests; -using PayOS.Models.Webhooks; using StorageProject.Core.DTOs.Payment; +using StorageProject.Core.DTOs.Reservation; using StorageProject.Core.Entities; using StorageProject.Core.Interfaces; using StorageProject.Infrastructure.Data; namespace StorageProject.Infrastructure.Services; -public class PayOSService : IPayOSService +public class PayOSService(AppDbContext dbContext, IPayOSGateway gateway, ILogger logger) : IPayOSService { - private readonly AppDbContext _dbContext; - private readonly IConfiguration _configuration; - private readonly ILogger _logger; - private readonly PayOSClient? _payOSClient; - private readonly string _clientId; - private readonly string _apiKey; - private readonly string _checksumKey; - - public PayOSService(AppDbContext dbContext, IConfiguration configuration, ILogger logger) + public async Task CreatePaymentQrAsync(long customerId, CreatePayOSQrRequest request, CancellationToken ct = default) { - _dbContext = dbContext; - _configuration = configuration; - _logger = logger; - - _clientId = _configuration["PayOS:ClientId"] ?? ""; - _apiKey = _configuration["PayOS:ApiKey"] ?? ""; - _checksumKey = _configuration["PayOS:ChecksumKey"] ?? ""; - - if (!string.IsNullOrWhiteSpace(_clientId) && - !string.IsNullOrWhiteSpace(_apiKey) && - !string.IsNullOrWhiteSpace(_checksumKey) && - !_clientId.StartsWith("YOUR_") && - !_apiKey.StartsWith("YOUR_")) - { - try - { - var options = new PayOSOptions - { - ClientId = _clientId, - ApiKey = _apiKey, - ChecksumKey = _checksumKey - }; - _payOSClient = new PayOSClient(options); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Could not initialize PayOSClient with configured credentials."); - } - } + var id = request.ReservationId; + if (!id.HasValue && request.FacilityId.HasValue && request.UnitTypeId.HasValue) + { + var created = await new ReservationService(dbContext).CreateReservationAsync(customerId, + new CreateReservationRequest(request.FacilityId.Value, request.UnitTypeId.Value, + request.StartDate ?? DateOnly.FromDateTime(DateTime.UtcNow.AddHours(7)), request.RentalPeriodMonths ?? 1), ct); + id = created.ReservationId; + } + if (id is null or <= 0) throw new ArgumentException("Cần mã đơn đặt chỗ hợp lệ."); + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"reservation:{id}", ct); + var r = await dbContext.Reservations.SingleOrDefaultAsync(r => r.ReservationId == id && r.CustomerId == customerId, ct) + ?? throw new InvalidOperationException("Không tìm thấy đơn đặt chỗ của bạn."); + if (r.Status != "PENDING_PAYMENT" || r.PaymentMethod != "PAYOS" || r.PaidAt != null) + throw new InvalidOperationException("Đơn không còn ở trạng thái chờ PayOS."); + if (r.ExpiresAt <= DateTime.UtcNow) throw new InvalidOperationException("Đơn đã hết thời gian giữ chỗ."); + var amount = ReservationSettlement.Amount(r); + if (amount <= 0 || amount != decimal.Truncate(amount) || amount > int.MaxValue) + throw new InvalidOperationException("Số tiền thanh toán VND không hợp lệ."); + if (request.Amount.HasValue && request.Amount != amount) + throw new ArgumentException("Số tiền phải khớp tiền thuê và tiền cọc do máy chủ tính."); + var expiry = r.ExpiresAt ?? DateTime.UtcNow.AddMinutes(15); + if (r.OrderCode != null && !string.IsNullOrEmpty(r.CheckoutUrl) && !string.IsNullOrEmpty(r.PaymentQrUrl)) + return new CreatePayOSQrResponse(r.ReservationId, r.OrderCode.Value, r.CheckoutUrl, r.PaymentQrUrl, amount, expiry); + + gateway.EnsureConfigured(); + // Commit the identifier before calling the external system. A timeout must not create another order code. + if (r.OrderCode == null) { + r.OrderCode = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() * 100 + Random.Shared.Next(100); + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + await tx.DisposeAsync(); + return await CreatePaymentQrAsync(customerId, request with { ReservationId = id }, ct); + } + CheckoutLink link; + try { + link = await gateway.CreateAsync(r.OrderCode.Value, (int)amount, r.ReservationId, + new DateTimeOffset(DateTime.SpecifyKind(expiry, DateTimeKind.Utc)).ToUnixTimeSeconds(), + request.ReturnUrl ?? $"http://localhost:5173/#/reservations/{r.ReservationId}", + request.CancelUrl ?? $"http://localhost:5173/#/reservations/{r.ReservationId}"); + } catch (Exception ex) { + throw new InvalidOperationException("Không tạo được link PayOS. Kiểm tra cấu hình hoặc chọn thanh toán tại cửa hàng.", ex); + } + r.CheckoutUrl = link.Url; + r.PaymentQrUrl = link.Qr; + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + return new CreatePayOSQrResponse(r.ReservationId, r.OrderCode.Value, link.Url, link.Qr, amount, expiry); } - public async Task CreatePaymentQrAsync(long customerId, CreatePayOSQrRequest request, CancellationToken ct = default) + public async Task PayAtFacilityAsync(long customerId, long reservationId, CancellationToken ct = default) { - Reservation? reservation = null; - - if (request.ReservationId.HasValue && request.ReservationId.Value > 0) - { - reservation = await _dbContext.Reservations - .FirstOrDefaultAsync(r => r.ReservationId == request.ReservationId.Value && r.CustomerId == customerId, ct); - - if (reservation == null) - { - throw new InvalidOperationException("Không tìm thấy đơn đặt chỗ tương ứng với tài khoản."); - } - } - else if (request.FacilityId.HasValue && request.UnitTypeId.HasValue) - { - var facility = await _dbContext.Facilities.FindAsync([request.FacilityId.Value], ct) - ?? throw new InvalidOperationException("Không tìm thấy cơ sở kho."); - - var unitType = await _dbContext.UnitTypes.FindAsync([request.UnitTypeId.Value], ct) - ?? throw new InvalidOperationException("Không tìm thấy loại phòng kho."); - - var today = DateOnly.FromDateTime(DateTime.UtcNow); - var rentalPeriod = request.RentalPeriodMonths.GetValueOrDefault(1); - if (rentalPeriod <= 0) rentalPeriod = 1; - - var activeRate = await _dbContext.RentalRates - .Where(r => r.FacilityId == request.FacilityId.Value - && r.UnitTypeId == request.UnitTypeId.Value - && r.EffectiveFrom <= today - && (r.EffectiveTo == null || r.EffectiveTo >= today)) - .OrderByDescending(r => r.EffectiveFrom) - .FirstOrDefaultAsync(ct) - ?? throw new InvalidOperationException("Chưa có bảng giá áp dụng cho loại kho này."); - - var expectedEndDate = (request.StartDate ?? today).AddMonths(rentalPeriod); - var monthlyRate = activeRate.MonthlyRate; - var estimatedAmount = monthlyRate * rentalPeriod; - var requiredDeposit = monthlyRate; - - reservation = new Reservation - { - CustomerId = customerId, - FacilityId = request.FacilityId.Value, - UnitTypeId = request.UnitTypeId.Value, - StartDate = request.StartDate ?? today, - ExpectedEndDate = expectedEndDate, - RentalPeriodMonths = rentalPeriod, - QuotedMonthlyRate = monthlyRate, - EstimatedAmount = estimatedAmount, - RequiredDeposit = requiredDeposit, - Status = "PENDING_PAYMENT", - ExpiresAt = DateTime.UtcNow.AddHours(24), - CreatedAt = DateTime.UtcNow - }; - - _dbContext.Reservations.Add(reservation); - await _dbContext.SaveChangesAsync(ct); - } - else - { - throw new ArgumentException("Yêu cầu cần có ReservationId hoặc thông tin FacilityId + UnitTypeId."); - } - - if (reservation.Status != "PENDING_PAYMENT" && reservation.Status != "CONFIRMED") - { - throw new InvalidOperationException($"Không thể tạo mã thanh toán cho đơn đặt chỗ có trạng thái '{reservation.Status}'."); - } - - long orderCode = reservation.OrderCode ?? long.Parse(DateTime.UtcNow.ToString("yyMMddHHmmss") + Random.Shared.Next(10, 99)); - int amount = (int)(reservation.EstimatedAmount + (reservation.RequiredDeposit > 0 ? reservation.RequiredDeposit : 0)); - if (request.Amount.HasValue && request.Amount.Value > 0) - { - amount = (int)request.Amount.Value; - } - - string checkoutUrl = reservation.CheckoutUrl ?? ""; - string qrCode = reservation.PaymentQrUrl ?? ""; - bool hasValidPayOS = !string.IsNullOrEmpty(checkoutUrl) && checkoutUrl.StartsWith("https://pay.payos.vn", StringComparison.OrdinalIgnoreCase); - - // Reuse existing valid PayOS link immediately without regenerating - if (hasValidPayOS && !string.IsNullOrEmpty(qrCode)) - { - return new CreatePayOSQrResponse( - reservation.ReservationId, - orderCode, - checkoutUrl, - qrCode, - amount, - reservation.ExpiresAt ?? DateTime.UtcNow.AddMinutes(15) - ); - } - - if (!hasValidPayOS || string.IsNullOrEmpty(qrCode)) - { - if (_payOSClient != null) - { - try - { - // Reuse existing orderCode if already assigned to reservation to prevent link desync - if (!reservation.OrderCode.HasValue || reservation.OrderCode.Value <= 0) - { - orderCode = long.Parse(DateTime.UtcNow.ToString("yyMMddHHmmss") + Random.Shared.Next(10, 99)); - } - else - { - orderCode = reservation.OrderCode.Value; - } - - var items = new List - { - new PaymentLinkItem - { - Name = $"Dat kho #{reservation.ReservationId}", - Quantity = 1, - Price = amount - } - }; - - var paymentLinkRequest = new CreatePaymentLinkRequest - { - OrderCode = orderCode, - Amount = amount, - Description = $"Dat kho #{reservation.ReservationId}", - Items = items, - CancelUrl = request.CancelUrl ?? "http://localhost:5173/checkout/cancel", - ReturnUrl = request.ReturnUrl ?? $"http://localhost:5173/confirmation/{reservation.ReservationId}", - ExpiredAt = (int)DateTimeOffset.UtcNow.AddMinutes(15).ToUnixTimeSeconds() - }; - - var createResult = await _payOSClient.PaymentRequests.CreateAsync(paymentLinkRequest); - checkoutUrl = createResult.CheckoutUrl ?? ""; - qrCode = createResult.QrCode ?? ""; - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Failed to call PayOS SDK createPaymentLink for OrderCode {OrderCode}. Falling back to default QR format.", orderCode); - } - } - - if (string.IsNullOrEmpty(qrCode)) - { - qrCode = $"https://img.vietqr.io/image/MB-0335012345-compact2.png?amount={amount}&addInfo=SSFRMS%20{orderCode}&accountName=SAFE%20SPACE"; - } - if (string.IsNullOrEmpty(checkoutUrl)) - { - checkoutUrl = request.ReturnUrl ?? $"http://localhost:5173/confirmation/{reservation.ReservationId}"; - } - - reservation.OrderCode = orderCode; - reservation.CheckoutUrl = checkoutUrl; - reservation.PaymentQrUrl = qrCode; - await _dbContext.SaveChangesAsync(ct); - } - - return new CreatePayOSQrResponse( - reservation.ReservationId, - orderCode, - checkoutUrl, - qrCode, - amount, - DateTime.UtcNow.AddMinutes(15) - ); + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"reservation:{reservationId}", ct); + var r = await dbContext.Reservations.SingleOrDefaultAsync(r => r.ReservationId == reservationId && r.CustomerId == customerId, ct) + ?? throw new InvalidOperationException("Không tìm thấy đơn đặt chỗ của bạn."); + if (r.Status == "PENDING_AT_FACILITY" && r.PaymentMethod == "AT_FACILITY") return; + if (r.PaidAt != null || r.Status != "PENDING_PAYMENT") + throw new InvalidOperationException("Đơn đã được xử lý, không thể đổi sang thanh toán tại kho."); + if (r.ExpiresAt <= DateTime.UtcNow) throw new InvalidOperationException("Đơn đã hết thời gian giữ chỗ."); + // Do not announce a switch until PayOS confirms cancellation. Keep OrderCode for delayed webhooks. + if (r.OrderCode.HasValue) + { + try { await gateway.CancelAsync(r.OrderCode.Value); } + catch (Exception ex) { throw new InvalidOperationException("Chưa xác nhận huỷ link PayOS. Đơn vẫn chờ PayOS; vui lòng thử lại.", ex); } + } + r.PaymentMethod = "AT_FACILITY"; + r.Status = "PENDING_AT_FACILITY"; + // Hold until the end of the scheduled check-in day (Vietnam time), never indefinitely. + var checkInDay = r.CheckInAppointmentAt.HasValue + ? DateOnly.FromDateTime(r.CheckInAppointmentAt.Value.AddHours(7)) : r.StartDate; + r.ExpiresAt = checkInDay.AddDays(1).ToDateTime(TimeOnly.MinValue).AddHours(-7); + ReservationSettlement.Audit(dbContext, customerId, "PAY_AT_FACILITY_SELECTED", r.ReservationId, new { r.OrderCode, r.ExpiresAt }); + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); } public async Task ProcessWebhookAsync(string webhookBodyJson, string? signatureHeader, CancellationToken ct = default) { - if (_payOSClient == null) - { - _logger.LogError("PayOSClient is not initialized. Cannot securely verify webhook signature."); - return false; - } - - Webhook? webhookModel; - try - { - webhookModel = JsonSerializer.Deserialize(webhookBodyJson); - } - catch (JsonException ex) - { - _logger.LogWarning(ex, "Failed to parse PayOS webhook payload as JSON."); - return false; - } - - if (webhookModel == null) - { - _logger.LogWarning("PayOS webhook payload deserialized to null."); - return false; - } - - WebhookData verifiedData; - try - { - verifiedData = await _payOSClient.Webhooks.VerifyAsync(webhookModel); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "PayOS webhook signature verification failed."); - return false; - } - - if (verifiedData == null) - { - _logger.LogWarning("PayOS webhook verification returned null data."); - return false; - } - - // Webhook signature verified. Check transaction code. - if (webhookModel.Code != "00") - { - _logger.LogInformation("PayOS webhook verified, but payment code is '{Code}' (Description: {Description}). Skipping database updates.", - webhookModel.Code, webhookModel.Description); - return true; - } - - long orderCode = verifiedData.OrderCode; - if (orderCode <= 0) - { - _logger.LogWarning("Verified PayOS webhook contains invalid OrderCode: {OrderCode}.", orderCode); - return false; - } - - var reservation = await _dbContext.Reservations - .Include(r => r.UnitAssignments) - .FirstOrDefaultAsync(r => r.OrderCode == orderCode, ct); - - // Fallback: If not found by OrderCode, attempt to extract reservationId from description - // (e.g. PayOS description: "Dat kho #25" or "Dat kho 25") - if (reservation == null) - { - long extractedId = 0; - var desc = verifiedData.Description ?? ""; - var match = System.Text.RegularExpressions.Regex.Match(desc, @"(?:Dat kho #?|kho\s*#?|#)(\d+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase); - if (match.Success && long.TryParse(match.Groups[1].Value, out var parsedId)) - { - extractedId = parsedId; - } - - if (extractedId > 0) - { - reservation = await _dbContext.Reservations - .Include(r => r.UnitAssignments) - .FirstOrDefaultAsync(r => r.ReservationId == extractedId, ct); - - if (reservation != null) - { - _logger.LogInformation("Matched Reservation {ReservationId} via description '{Description}' for OrderCode {OrderCode}.", - reservation.ReservationId, desc, orderCode); - // Sync OrderCode to the one actually paid on PayOS - reservation.OrderCode = orderCode; - } - } - } - - if (reservation == null) - { - _logger.LogWarning("Verified PayOS webhook received for OrderCode {OrderCode} (Desc: '{Desc}'), but no matching reservation found. Acknowledging webhook.", - orderCode, verifiedData.Description); + VerifiedReservationPayment? verified; + try { verified = await gateway.VerifyAsync(webhookBodyJson); } + catch (Exception ex) { logger.LogWarning(ex, "PayOS signature verification failed"); return false; } + if (verified == null) return true; + var id = await dbContext.Reservations.AsNoTracking().Where(r => r.OrderCode == verified.OrderCode) + .Select(r => (long?)r.ReservationId).SingleOrDefaultAsync(ct); + // Never recover an order by parsing unstructured description text. + if (id == null) { logger.LogWarning("Unknown PayOS order {OrderCode}", verified.OrderCode); return false; } + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"reservation:{id}", ct); + var r = await dbContext.Reservations.Include(r => r.UnitAssignments).SingleAsync(r => r.ReservationId == id, ct); + if (verified.Amount != ReservationSettlement.Amount(r)) return false; + if (r.PaymentMethod == "PAYOS" && r.PaidAt != null) + { + await tx.CommitAsync(ct); // Re-delivery of the same verified order: no additional money or allocation. return true; } - - // Idempotency: skip if already confirmed or in subsequent status - if (reservation.Status != "PENDING_PAYMENT") + if (r.PaymentMethod == "AT_FACILITY" || r.Status != "PENDING_PAYMENT" || r.ExpiresAt <= DateTime.UtcNow) { - _logger.LogInformation("Reservation {ReservationId} (OrderCode {OrderCode}) is already in status '{Status}'. Skipping duplicate webhook processing.", - reservation.ReservationId, orderCode, reservation.Status); - return true; + var detail = JsonSerializer.Serialize(new { verified.OrderCode, verified.Amount, reason = "Tiền về sau đổi phương thức/đóng đơn; cần kiểm tra hoàn thủ công" }); + if (!await dbContext.ActivityLogs.AnyAsync(l => l.EntityType == "RESERVATION" && l.EntityId == id && + l.Action == "PAYMENT_REVIEW_REQUIRED" && l.NewValue == detail, ct)) + dbContext.ActivityLogs.Add(new ActivityLog { EntityType = "RESERVATION", EntityId = id, + Action = "PAYMENT_REVIEW_REQUIRED", NewValue = detail, LoggedAt = DateTime.UtcNow }); } - - reservation.Status = "CONFIRMED"; - reservation.PaidAt = DateTime.UtcNow; - - // Idempotent assignment: Only assign if no ACTIVE assignment exists - bool hasActiveAssignment = reservation.UnitAssignments.Any(ua => ua.Status == "ACTIVE"); - if (!hasActiveAssignment) - { - var assignedUnit = await _dbContext.StorageUnits - .FirstOrDefaultAsync(u => u.FacilityId == reservation.FacilityId && - u.UnitTypeId == reservation.UnitTypeId && - u.Status == "AVAILABLE", ct); - - if (assignedUnit != null) - { - assignedUnit.Status = "RESERVED"; - assignedUnit.UpdatedAt = DateTime.UtcNow; - - _dbContext.UnitAssignments.Add(new UnitAssignment - { - ReservationId = reservation.ReservationId, - UnitId = assignedUnit.UnitId, - AssignedBy = null, // System automated assignment - Status = "ACTIVE", - AssignedAt = DateTime.UtcNow, - Reason = "Tự động gán kho sau khi thanh toán VietQR thành công" - }); - } - else - { - _logger.LogWarning("No AVAILABLE storage unit found for FacilityId {FacilityId}, UnitTypeId {UnitTypeId} for Reservation {ReservationId}.", - reservation.FacilityId, reservation.UnitTypeId, reservation.ReservationId); - } - } - - await _dbContext.SaveChangesAsync(ct); - _logger.LogInformation("Successfully confirmed reservation {ReservationId} (OrderCode {OrderCode}) via verified PayOS Webhook.", - reservation.ReservationId, orderCode); - + else await ReservationSettlement.RecordAsync(dbContext, r, "PAYMENT_GATEWAY", $"PAYOS:{verified.OrderCode}", null, ct); + // Manager allocates the physical unit. The webhook only settles the reservation. + await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); return true; } public async Task GetReservationPaymentStatusAsync(long reservationId, CancellationToken ct = default) { - var reservation = await _dbContext.Reservations - .AsNoTracking() - .FirstOrDefaultAsync(r => r.ReservationId == reservationId, ct); - - if (reservation == null) return null; - - bool isPaid = reservation.Status is "CONFIRMED" or "UNIT_ASSIGNED" or "CHECKED_IN"; - return new ReservationPaymentStatusDto( - reservation.ReservationId, - reservation.Status, - isPaid, - reservation.PaidAt - ); + var r = await dbContext.Reservations.AsNoTracking().SingleOrDefaultAsync(r => r.ReservationId == reservationId, ct); + return r == null ? null : new ReservationPaymentStatusDto(r.ReservationId, r.Status, r.PaidAt != null, r.PaidAt); } } diff --git a/StorageProject.Infrastructure/Services/PaymentService.cs b/StorageProject.Infrastructure/Services/PaymentService.cs index 53f8cc1..46a411d 100644 --- a/StorageProject.Infrastructure/Services/PaymentService.cs +++ b/StorageProject.Infrastructure/Services/PaymentService.cs @@ -44,7 +44,7 @@ public async Task> GetContractPaymentsAsync(long custo var p = await dbContext.Payments .AsNoTracking() .Include(x => x.Contract) - .Where(x => x.PaymentId == paymentId && x.Contract.CustomerId == customerId) + .Where(x => x.PaymentId == paymentId && ((x.ContractId != null && x.Contract.CustomerId == customerId) || (x.ReservationId != null && x.Reservation.CustomerId == customerId))) .FirstOrDefaultAsync(ct); if (p == null) return null; diff --git a/StorageProject.Infrastructure/Services/ReservationAllocation.cs b/StorageProject.Infrastructure/Services/ReservationAllocation.cs new file mode 100644 index 0000000..3f08484 --- /dev/null +++ b/StorageProject.Infrastructure/Services/ReservationAllocation.cs @@ -0,0 +1,58 @@ +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.Entities; +using StorageProject.Infrastructure.Data; + +namespace StorageProject.Infrastructure.Services; + +public static class ReservationAllocation +{ + public static async Task AllocateAsync(AppDbContext db, long actor, long facilityId, long reservationId, + string unitCode, CancellationToken ct) + { + await using var tx = await CheckoutTransaction.BeginAsync(db, $"reservation:{reservationId}", ct); + await CheckoutTransaction.LockAsync(db, $"inventory:{facilityId}", ct); + var r = await db.Reservations.Include(r => r.UnitAssignments).Include(r => r.RentalContract) + .SingleOrDefaultAsync(r => r.ReservationId == reservationId && r.FacilityId == facilityId, ct) + ?? throw new InvalidOperationException("Không tìm thấy đơn tại cơ sở của bạn."); + var atFacility = r.Status == "PENDING_AT_FACILITY" && r.PaymentMethod == "AT_FACILITY"; + if (!atFacility && (r.Status is not ("CONFIRMED" or "UNIT_ASSIGNED"))) + throw new InvalidOperationException("Chỉ phân bổ đơn đã thanh toán hoặc đơn chờ thu tại kho."); + if (atFacility && r.ExpiresAt <= DateTime.UtcNow) throw new InvalidOperationException("Đơn chờ thu đã hết hạn giữ chỗ."); + if (!atFacility) await ReservationSettlement.RequirePaidAsync(db, r, ct); + var unit = await db.StorageUnits.SingleOrDefaultAsync(u => u.FacilityId == facilityId && u.UnitNumber == unitCode, ct) + ?? throw new InvalidOperationException("Không tìm thấy ô kho tại cơ sở."); + if (unit.UnitTypeId != r.UnitTypeId) throw new InvalidOperationException("Ô kho không đúng loại khách đã đặt."); + var current = r.UnitAssignments.SingleOrDefault(a => a.Status == "ACTIVE"); + if (current != null) + { + if (current.UnitId != unit.UnitId) throw new InvalidOperationException("Đơn đã phân bổ ô khác, không được phân bổ thêm."); + await tx.CommitAsync(ct); + return; + } + if (unit.Status != "AVAILABLE" || await db.RentalContracts.AnyAsync(c => c.UnitId == unit.UnitId && + c.Status != "CANCELLED" && c.Status != "COMPLETED" && c.Status != "TERMINATED" && + c.StartDate < r.ExpectedEndDate && c.EndDate > r.StartDate, ct)) + throw new InvalidOperationException("Ô kho không còn trống trong kỳ thuê."); + var contract = r.RentalContract; + if (contract != null) throw new InvalidOperationException("Đơn đã có hợp đồng, cần kiểm tra phân bổ cũ."); + var now = DateTime.UtcNow; + contract = new RentalContract { ReservationId = r.ReservationId, CustomerId = r.CustomerId, + UnitId = unit.UnitId, StartDate = r.StartDate, EndDate = r.ExpectedEndDate, + AgreedMonthlyRate = r.QuotedMonthlyRate, DepositAmount = r.RequiredDeposit, Status = "DRAFT", CreatedAt = now, + HandoverRecord = new HandoverRecord { StaffId = actor, ScheduledAt = r.CheckInAppointmentAt ?? + r.StartDate.ToDateTime(new TimeOnly(9, 0)).AddHours(-7), Status = "SCHEDULED", CreatedAt = now } }; + db.RentalContracts.Add(contract); + foreach (var payment in await db.Payments.Where(p => p.ReservationId == r.ReservationId).ToListAsync(ct)) + payment.Contract = contract; + db.UnitAssignments.Add(new UnitAssignment { ReservationId = r.ReservationId, UnitId = unit.UnitId, + AssignedBy = actor, AssignedAt = now, Status = "ACTIVE", Reason = "Quản lý phân bổ ô" }); + db.UnitStatusHistories.Add(new UnitStatusHistory { UnitId = unit.UnitId, ChangedBy = actor, + OldStatus = unit.Status, NewStatus = "RESERVED", ChangedAt = now, Reason = $"Phân bổ đơn {r.ReservationId}" }); + unit.Status = "RESERVED"; + unit.UpdatedAt = now; + if (!atFacility) r.Status = "UNIT_ASSIGNED"; + ReservationSettlement.Audit(db, actor, "UNIT_ALLOCATED", r.ReservationId, new { unit.UnitNumber }); + await db.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + } +} diff --git a/StorageProject.Infrastructure/Services/ReservationService.cs b/StorageProject.Infrastructure/Services/ReservationService.cs index f40105f..7a8ecc3 100644 --- a/StorageProject.Infrastructure/Services/ReservationService.cs +++ b/StorageProject.Infrastructure/Services/ReservationService.cs @@ -34,7 +34,8 @@ public async Task> GetMyReservationsAsync(long cus r.ExpiresAt, r.CancelledAt, r.CancellationReason, - r.CreatedAt + r.CreatedAt, + r.PaymentMethod )) .ToListAsync(ct); } @@ -74,7 +75,8 @@ public async Task> GetMyReservationsAsync(long cus assignedUnit, contract?.ContractId, contract?.Status, - r.CreatedAt + r.CreatedAt, + r.PaymentMethod ); } @@ -113,6 +115,7 @@ public async Task CreateReservationAsync(long customerId, Create .FirstOrDefaultAsync(ct) ?? throw new InvalidOperationException("Chưa có bảng giá áp dụng cho cơ sở và loại kho này."); + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"inventory:{request.FacilityId}", ct); // Check availability var expectedEndDate = request.StartDate.AddMonths(request.RentalPeriodMonths); var availableUnitsCount = await dbContext.StorageUnits @@ -123,7 +126,8 @@ public async Task CreateReservationAsync(long customerId, Create var existingReservationsCount = await dbContext.Reservations .CountAsync(r => r.FacilityId == request.FacilityId && r.UnitTypeId == request.UnitTypeId - && (r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_VERIFICATION" || r.Status == "CONFIRMED") + && (r.Status == "CONFIRMED" || ((r.Status == "PENDING_PAYMENT" || r.Status == "PENDING_VERIFICATION" || r.Status == "PENDING_AT_FACILITY") && r.ExpiresAt > DateTime.UtcNow)) + && !r.UnitAssignments.Any(a => a.Status == "ACTIVE") && r.StartDate < expectedEndDate && r.ExpectedEndDate > request.StartDate, ct); @@ -152,12 +156,13 @@ public async Task CreateReservationAsync(long customerId, Create EstimatedAmount = estimatedAmount, RequiredDeposit = requiredDeposit, Status = "PENDING_PAYMENT", - ExpiresAt = DateTime.UtcNow.AddHours(24), + ExpiresAt = DateTime.UtcNow.AddMinutes(15), CreatedAt = DateTime.UtcNow }; dbContext.Reservations.Add(reservation); await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); return new ReservationDto( reservation.ReservationId, @@ -175,18 +180,20 @@ public async Task CreateReservationAsync(long customerId, Create reservation.ExpiresAt, reservation.CancelledAt, reservation.CancellationReason, - reservation.CreatedAt + reservation.CreatedAt, + reservation.PaymentMethod ); } public async Task CancelReservationAsync(long customerId, long reservationId, string reason, CancellationToken ct = default) { + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"reservation:{reservationId}", ct); var reservation = await dbContext.Reservations .Where(r => r.ReservationId == reservationId && r.CustomerId == customerId) .FirstOrDefaultAsync(ct) ?? throw new InvalidOperationException("Không tìm thấy đơn đặt chỗ hợp lệ."); - if (reservation.Status != "PENDING_PAYMENT" && reservation.Status != "CONFIRMED") + if (reservation.Status != "PENDING_PAYMENT" && reservation.Status != "CONFIRMED" && reservation.Status != "PENDING_AT_FACILITY") { throw new InvalidOperationException($"Không thể hủy đơn đặt chỗ ở trạng thái '{reservation.Status}'."); } @@ -194,8 +201,15 @@ public async Task CancelReservationAsync(long customerId, long reservationId, st reservation.Status = "CANCELLED"; reservation.CancelledAt = DateTime.UtcNow; reservation.CancellationReason = reason; - + foreach (var a in await dbContext.UnitAssignments.Include(a => a.Unit).Where(a => a.ReservationId == reservationId && a.Status == "ACTIVE").ToListAsync(ct)) + { + a.Status = "CANCELLED"; + if (a.Unit.Status == "RESERVED") a.Unit.Status = "AVAILABLE"; + } + var draft = await dbContext.RentalContracts.SingleOrDefaultAsync(c => c.ReservationId == reservationId && c.Status == "DRAFT", ct); + if (draft != null) draft.Status = "CANCELLED"; await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); } /// @@ -256,6 +270,7 @@ public async Task ConfirmTransferAsync(long customerId, long res r.ExpiresAt, r.CancelledAt, r.CancellationReason, - r.CreatedAt + r.CreatedAt, + r.PaymentMethod ); } diff --git a/StorageProject.Infrastructure/Services/ReservationSettlement.cs b/StorageProject.Infrastructure/Services/ReservationSettlement.cs new file mode 100644 index 0000000..950e22e --- /dev/null +++ b/StorageProject.Infrastructure/Services/ReservationSettlement.cs @@ -0,0 +1,53 @@ +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using StorageProject.Core.Entities; +using StorageProject.Infrastructure.Data; + +namespace StorageProject.Infrastructure.Services; + +// Call inside the reservation transaction. Allocation attaches these rows; it never recreates them. +public static class ReservationSettlement +{ + public static decimal Amount(Reservation r) => r.EstimatedAmount + r.RequiredDeposit; + + public static async Task RecordAsync(AppDbContext db, Reservation r, string method, string reference, + long? actor, CancellationToken ct) + { + var rows = await db.Payments.Where(p => p.ReservationId == r.ReservationId && + (p.PaymentType == "RENT" || p.PaymentType == "DEPOSIT")).ToListAsync(ct); + var now = r.PaidAt ?? DateTime.UtcNow; + foreach (var (kind, amount) in new[] { ("RENT", r.EstimatedAmount), ("DEPOSIT", r.RequiredDeposit) }) + { + if (amount == 0) continue; + var row = rows.SingleOrDefault(p => p.PaymentType == kind); + if (row != null) + { + if (row.Amount != amount || row.Status != "PAID" || row.PaymentMethod != method) + throw new InvalidOperationException("Khoản thu đã tồn tại nhưng không khớp. Cần kiểm tra giao dịch."); + continue; + } + db.Payments.Add(new Payment { + ReservationId = r.ReservationId, ContractId = r.RentalContract?.ContractId, + PaymentType = kind, Amount = amount, PaymentMethod = method, + TransactionReference = $"{reference}:{kind}", Status = "PAID", PaidAt = now, + DueDate = r.StartDate, CreatedAt = now, UpdatedAt = now + }); + } + r.PaidAt = now; + r.Status = r.UnitAssignments.Any(a => a.Status == "ACTIVE") ? "UNIT_ASSIGNED" : "CONFIRMED"; + Audit(db, actor, "PAYMENT_CONFIRMED", r.ReservationId, new { method, reference, amount = Amount(r) }); + } + + public static async Task RequirePaidAsync(AppDbContext db, Reservation r, CancellationToken ct) + { + var rows = await db.Payments.Where(p => p.ReservationId == r.ReservationId && p.Status == "PAID" && + (p.PaymentType == "RENT" || p.PaymentType == "DEPOSIT")).ToListAsync(ct); + var paid = rows.Sum(p => p.Amount); + if (r.PaidAt == null || paid != Amount(r)) + throw new InvalidOperationException("Đơn chưa có đủ khoản thu đã xác nhận. Không được bàn giao kho."); + } + + public static void Audit(AppDbContext db, long? actor, string action, long id, object detail) => + db.ActivityLogs.Add(new ActivityLog { UserId = actor, Action = action, EntityType = "RESERVATION", + EntityId = id, NewValue = JsonSerializer.Serialize(detail), LoggedAt = DateTime.UtcNow }); +} diff --git a/StorageProject.Infrastructure/Services/StaffService.cs b/StorageProject.Infrastructure/Services/StaffService.cs index ace63bc..7389f4c 100644 --- a/StorageProject.Infrastructure/Services/StaffService.cs +++ b/StorageProject.Infrastructure/Services/StaffService.cs @@ -104,12 +104,9 @@ public async Task GetStaffBoardAsync(long userId, CancellationToken }).ToList(); // 3. Payments (Đối soát thanh toán từ Reservations trong DB) - var reservations = await dbContext.Reservations - .AsNoTracking() - .Include(r => r.Customer) - .Include(r => r.UnitType) - .Where(r => r.FacilityId == fac.FacilityId && - (r.Status == "PENDING_VERIFICATION" || r.Status == "PENDING_PAYMENT" || r.Status == "CONFIRMED" || r.Status == "MISMATCH")) + var reservations = await dbContext.Reservations.AsNoTracking().Include(r => r.Customer).Include(r => r.UnitType) + .Where(r => r.FacilityId == fac.FacilityId && r.PaymentMethod == "AT_FACILITY" && + r.Status == "PENDING_AT_FACILITY" && r.ExpiresAt > DateTime.UtcNow) .OrderByDescending(r => r.CreatedAt) .ToListAsync(ct); @@ -128,7 +125,7 @@ public async Task GetStaffBoardAsync(long userId, CancellationToken Id = $"SS-{r.CreatedAt:yyyyMMdd}-{r.ReservationId:D4}", Customer = r.Customer.FullName, Amount = totalAmount, - Method = "Chuyển khoản ngân hàng", + Method = "Thanh toán tại kho", ReportedAt = r.CreatedAt.ToString("yyyy-MM-ddTHH:mm:ss"), Memo = r.OrderCode.HasValue ? $"SSFRMS {r.OrderCode}" : $"SSFRMS {r.ReservationId}", Offer = $"Kho {r.UnitType.TypeName} · {(r.UnitType.ClimateControlled ? "Kiểm soát nhiệt độ" : "Thường")}", @@ -144,6 +141,7 @@ public async Task GetStaffBoardAsync(long userId, CancellationToken .AsNoTracking() .Include(r => r.Customer) .Include(r => r.UnitAssignments).ThenInclude(ua => ua.Unit) + .Include(r => r.RentalContract).ThenInclude(c => c!.HandoverRecord) .Where(r => r.FacilityId == fac.FacilityId && r.UnitAssignments.Any(ua => ua.Status == "ACTIVE")) .OrderByDescending(r => r.CreatedAt) .ToListAsync(ct); @@ -158,7 +156,7 @@ public async Task GetStaffBoardAsync(long userId, CancellationToken Customer = r.Customer.FullName, Unit = assign.Unit.UnitNumber, Appointment = $"{r.StartDate:yyyy-MM-dd}T09:00:00", - Status = r.Status == "CHECKED_IN" ? "DONE" : "TODO", + Status = r.RentalContract?.HandoverRecord?.Status is "VERIFIED" or "HANDED_OVER" ? "DONE" : "TODO", DocType = "Căn cước công dân", DocLast4 = null, VerifiedAt = r.Status == "CHECKED_IN" ? r.CreatedAt.ToString("yyyy-MM-ddTHH:mm:ss") : null @@ -169,7 +167,7 @@ public async Task GetStaffBoardAsync(long userId, CancellationToken .AsNoTracking() .Include(h => h.Contract).ThenInclude(c => c.Customer) .Include(h => h.Contract).ThenInclude(c => c.Unit) - .Where(h => h.Contract.Unit.FacilityId == fac.FacilityId) + .Where(h => h.Contract.Unit.FacilityId == fac.FacilityId && h.Status != "CANCELLED") .OrderByDescending(h => h.ScheduledAt) .ToListAsync(ct); @@ -179,7 +177,7 @@ public async Task GetStaffBoardAsync(long userId, CancellationToken VerificationId = $"XM-{(h.Contract.ReservationId > 0 ? h.Contract.ReservationId : h.HandoverId):D4}", Unit = h.Contract.Unit.UnitNumber, Customer = h.Contract.Customer.FullName, - Status = h.HandoverAt.HasValue ? "COMPLETED" : "WAITING", + Status = h.HandoverAt.HasValue ? "DONE" : "WAITING", Method = "PIN" }).ToList(); @@ -281,44 +279,19 @@ public async Task GetStaffBoardAsync(long userId, CancellationToken public async Task ConfirmPaymentAsync(long userId, string id, CancellationToken ct = default) { var fac = await FacilityOpsStateStore.GetUserFacilityAsync(dbContext, userId, ct); - var r = await FacilityOpsStateStore.FindReservationByIdAsync(dbContext, id, fac.FacilityId, ct); - if (r == null) - { - throw new InvalidOperationException("Không tìm thấy thông tin đặt chỗ / thanh toán."); - } - if (r.Status == "CONFIRMED") - { - throw new InvalidOperationException("không xác nhận hai lần"); - } - - r.Status = "CONFIRMED"; - r.PaidAt = DateTime.UtcNow; - - // Auto assign available unit if none assigned yet - if (!r.UnitAssignments.Any(ua => ua.Status == "ACTIVE")) - { - var unit = await dbContext.StorageUnits - .FirstOrDefaultAsync(u => u.FacilityId == fac.FacilityId && - u.UnitTypeId == r.UnitTypeId && - u.Status == "AVAILABLE", ct); - if (unit != null) - { - unit.Status = "RESERVED"; - unit.UpdatedAt = DateTime.UtcNow; - - dbContext.UnitAssignments.Add(new UnitAssignment - { - ReservationId = r.ReservationId, - UnitId = unit.UnitId, - AssignedBy = userId, - Status = "ACTIVE", - AssignedAt = DateTime.UtcNow, - Reason = "Nhân viên xác nhận đối soát thanh toán" - }); - } - } - + var found = await FacilityOpsStateStore.FindReservationByIdAsync(dbContext, id, fac.FacilityId, ct) + ?? throw new InvalidOperationException("Không tìm thấy đơn tại cơ sở."); + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"reservation:{found.ReservationId}", ct); + await dbContext.Entry(found).ReloadAsync(ct); + await dbContext.Entry(found).Collection(r => r.UnitAssignments).LoadAsync(ct); + await dbContext.Entry(found).Reference(r => r.RentalContract).LoadAsync(ct); + if (found.PaymentMethod != "AT_FACILITY") throw new InvalidOperationException("Đơn PayOS phải được xác nhận qua webhook."); + if (found.PaidAt != null) { await tx.CommitAsync(ct); return; } + if (found.Status != "PENDING_AT_FACILITY" || found.ExpiresAt <= DateTime.UtcNow) + throw new InvalidOperationException("Đơn không còn chờ thu tại kho hoặc đã hết hạn."); + await ReservationSettlement.RecordAsync(dbContext, found, "CASH", $"CASH:{found.ReservationId}", userId, ct); await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); } public async Task MismatchPaymentAsync(long userId, string id, MismatchPaymentRequest request, CancellationToken ct = default) @@ -354,13 +327,19 @@ public async Task VerifyCustomerAsync(long userId, string id, VerifyCustomerRequ var r = await FacilityOpsStateStore.FindReservationByIdAsync(dbContext, id, fac.FacilityId, ct); if (r != null) { - r.Status = "CHECKED_IN"; + await ReservationSettlement.RequirePaidAsync(dbContext, r, ct); + var record = await dbContext.HandoverRecords.SingleOrDefaultAsync(h => h.Contract.ReservationId == r.ReservationId, ct) + ?? throw new InvalidOperationException("Đơn chưa được quản lý phân bổ và lập lịch bàn giao."); + if (record.Status == "HANDED_OVER") return; + record.Status = "VERIFIED"; + record.Notes = $"Đã xác minh giấy tờ kết thúc {docNo[^4..]}"; await dbContext.SaveChangesAsync(ct); } } public async Task CompleteHandoverAsync(long userId, string id, CompleteHandoverRequest request, CancellationToken ct = default) { + var fac = await FacilityOpsStateStore.GetUserFacilityAsync(dbContext, userId, ct); var num = FacilityOpsStateStore.ParseIdNumber(id); var now = DateTime.UtcNow; @@ -369,10 +348,15 @@ public async Task CompleteHandoverAsync(long userId, string id, CompleteHandover .Include(h => h.Contract).ThenInclude(c => c.Unit) .Include(h => h.Contract).ThenInclude(c => c.AccessCredentials) .Include(h => h.Contract).ThenInclude(c => c.Reservation) - .FirstOrDefaultAsync(h => h.HandoverId == num || h.ContractId == num, ct); + .FirstOrDefaultAsync(h => h.HandoverId == num && h.Contract.Unit.FacilityId == fac.FacilityId, ct); if (handover != null) { + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"reservation:{handover.Contract.ReservationId}", ct); + await dbContext.Entry(handover.Contract.Reservation).ReloadAsync(ct); + await ReservationSettlement.RequirePaidAsync(dbContext, handover.Contract.Reservation, ct); + if (handover.Status == "HANDED_OVER") { await tx.CommitAsync(ct); return; } + if (handover.Status != "VERIFIED") throw new InvalidOperationException("Cần xác minh khách hàng trước khi bàn giao."); handover.Status = "HANDED_OVER"; handover.StaffConfirmed = true; handover.CustomerConfirmed = true; @@ -411,95 +395,11 @@ public async Task CompleteHandoverAsync(long userId, string id, CompleteHandover } } await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); return; } - // 2. Thử tìm theo Reservation - var fac = await FacilityOpsStateStore.GetUserFacilityAsync(dbContext, userId, ct); - var r = await FacilityOpsStateStore.FindReservationByIdAsync(dbContext, id, fac.FacilityId, ct); - if (r != null) - { - var assignment = r.UnitAssignments.FirstOrDefault(ua => ua.Status == "ACTIVE"); - if (assignment != null) - { - var unit = assignment.Unit; - unit.Status = "OCCUPIED"; - unit.UpdatedAt = now; - - var contract = await dbContext.RentalContracts - .Include(c => c.HandoverRecord) - .Include(c => c.AccessCredentials) - .FirstOrDefaultAsync(c => c.ReservationId == r.ReservationId, ct); - - if (contract == null) - { - contract = new RentalContract - { - ReservationId = r.ReservationId, - CustomerId = r.CustomerId, - UnitId = unit.UnitId, - StartDate = r.StartDate, - EndDate = r.ExpectedEndDate, - AgreedMonthlyRate = r.QuotedMonthlyRate, - DepositAmount = r.RequiredDeposit, - Status = "ACTIVE", - CreatedAt = now, - ActivatedAt = now - }; - dbContext.RentalContracts.Add(contract); - await dbContext.SaveChangesAsync(ct); - } - else - { - contract.Status = "ACTIVE"; - contract.ActivatedAt ??= now; - } - - var hRecord = contract.HandoverRecord ?? await dbContext.HandoverRecords.FirstOrDefaultAsync(h => h.ContractId == contract.ContractId, ct); - if (hRecord == null) - { - hRecord = new HandoverRecord - { - ContractId = contract.ContractId, - StaffId = userId, - ScheduledAt = now, - VerifiedAt = now, - HandoverAt = now, - InitialCondition = "Đã kiểm tra và bàn giao kho", - Notes = $"Phương thức mở khóa: {request.UnlockMethod}", - CustomerConfirmed = true, - StaffConfirmed = true, - Status = "HANDED_OVER" - }; - dbContext.HandoverRecords.Add(hRecord); - } - else - { - hRecord.StaffId = userId; - hRecord.StaffConfirmed = true; - hRecord.CustomerConfirmed = true; - hRecord.HandoverAt = now; - hRecord.Status = "HANDED_OVER"; - hRecord.Notes = $"Phương thức mở khóa: {request.UnlockMethod}"; - } - - if (!contract.AccessCredentials.Any(a => a.Status == "ACTIVE")) - { - var method = (request.UnlockMethod ?? "CARD").ToUpperInvariant(); - dbContext.AccessCredentials.Add(new AccessCredential - { - ContractId = contract.ContractId, - UnitId = unit.UnitId, - IssuedBy = userId, - CredentialType = method == "CARD" ? "ACCESS_CARD" : "ACCESS_CODE", - CredentialReference = $"{method}-{unit.UnitNumber}-{now.AddHours(7):yyMMdd}", - IssuedAt = now, - Status = "ACTIVE" - }); - } - } - await dbContext.SaveChangesAsync(ct); - } + throw new InvalidOperationException("Không tìm thấy lịch bàn giao. Quản lý cần phân bổ kho trước."); } public async Task SubmitReturnInspectionAsync(long userId, string id, ReturnInspectionRequest request, CancellationToken ct = default) @@ -543,31 +443,27 @@ public async Task AddTicketResponseAsync(long userId, string id, TicketResponseR public async Task UpdateUnitStatusAsync(long userId, string id, UpdateUnitStatusRequest request, CancellationToken ct = default) { - if (string.IsNullOrWhiteSpace(request.Status)) - { - throw new ArgumentException("Trạng thái kho không được để trống."); - } var fac = await FacilityOpsStateStore.GetUserFacilityAsync(dbContext, userId, ct); - var unit = await dbContext.StorageUnits - .FirstOrDefaultAsync(u => u.FacilityId == fac.FacilityId && (u.UnitNumber == id || u.UnitId == FacilityOpsStateStore.ParseIdNumber(id)), ct); - if (unit == null) - { - throw new InvalidOperationException($"Không tìm thấy kho {id}."); + await using var tx = await CheckoutTransaction.BeginAsync(dbContext, $"inventory:{fac.FacilityId}", ct); + var number = FacilityOpsStateStore.ParseIdNumber(id); + var unit = await dbContext.StorageUnits.SingleOrDefaultAsync(u => u.FacilityId == fac.FacilityId && + (u.UnitNumber == id || u.UnitId == number), ct) ?? throw new InvalidOperationException("Không tìm thấy ô kho."); + var next = UnitStatusRules.Normalize(request.Status ?? ""); + UnitStatusRules.Validate(unit.Status, next, request.Reason); + var held = await dbContext.UnitAssignments.AnyAsync(a => a.UnitId == unit.UnitId && a.Status == "ACTIVE" && + a.Reservation.Status != "CANCELLED" && a.Reservation.Status != "EXPIRED" && a.Reservation.Status != "NO_SHOW" && + (a.Reservation.RentalContract == null || (a.Reservation.RentalContract.Status != "COMPLETED" && a.Reservation.RentalContract.Status != "TERMINATED" && a.Reservation.RentalContract.Status != "CANCELLED")), ct) + || await dbContext.RentalContracts.AnyAsync(c => c.UnitId == unit.UnitId && c.Status != "COMPLETED" && + c.Status != "CANCELLED" && c.Status != "TERMINATED", ct); + if (held) throw new InvalidOperationException("Ô đang được giữ hoặc có hợp đồng chưa đóng, không được đổi trạng thái bằng tay."); + if (unit.Status != next) { + dbContext.UnitStatusHistories.Add(new UnitStatusHistory { UnitId = unit.UnitId, ChangedBy = userId, + OldStatus = unit.Status, NewStatus = next, Reason = request.Reason!.Trim(), ChangedAt = DateTime.UtcNow }); + unit.Status = next; + unit.UpdatedAt = DateTime.UtcNow; + await dbContext.SaveChangesAsync(ct); } - - var dbStatus = request.Status.ToUpperInvariant() switch - { - "EMPTY" => "AVAILABLE", - "ACTIVE" => "OCCUPIED", - "WAITING_HANDOVER" => "RESERVED", - "MAINTENANCE" => "MAINTENANCE", - "LOCKED" => "LOCKED", - _ => request.Status.ToUpperInvariant() - }; - - unit.Status = dbStatus; - unit.UpdatedAt = DateTime.UtcNow; - await dbContext.SaveChangesAsync(ct); + await tx.CommitAsync(ct); } public async Task RevokeCredentialAsync(long userId, string id, CancellationToken ct = default) diff --git a/StorageProject.Infrastructure/Services/UnitStatusRules.cs b/StorageProject.Infrastructure/Services/UnitStatusRules.cs new file mode 100644 index 0000000..6f3fefc --- /dev/null +++ b/StorageProject.Infrastructure/Services/UnitStatusRules.cs @@ -0,0 +1,24 @@ +namespace StorageProject.Infrastructure.Services; + +public static class UnitStatusRules +{ + // Lifecycle transitions RESERVED/OCCUPIED/INSPECTION are owned by allocation/handover/return services. + public static string Normalize(string status) => status.Trim().ToUpperInvariant() switch { + "EMPTY" => "AVAILABLE", "ACTIVE" => "OCCUPIED", "WAITING_HANDOVER" => "RESERVED", + "LOCKED" => "OUT_OF_SERVICE", var value => value + }; + + public static void Validate(string current, string next, string? reason) + { + if (string.IsNullOrWhiteSpace(reason) || reason.Trim().Length > 255) + throw new ArgumentException("Nhập lý do từ 1 đến 255 ký tự."); + if (current == next) return; + var allowed = current switch { + "AVAILABLE" => next is "MAINTENANCE" or "OUT_OF_SERVICE", + "MAINTENANCE" => next is "AVAILABLE" or "OUT_OF_SERVICE", + "OUT_OF_SERVICE" => next is "AVAILABLE" or "MAINTENANCE", + _ => false + }; + if (!allowed) throw new InvalidOperationException("Không được đổi trạng thái này bằng tay. Hãy dùng luồng phân bổ, bàn giao hoặc trả kho."); + } +} diff --git a/StorageProject.Tests/CheckoutTests.cs b/StorageProject.Tests/CheckoutTests.cs new file mode 100644 index 0000000..eedaeb8 --- /dev/null +++ b/StorageProject.Tests/CheckoutTests.cs @@ -0,0 +1,187 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using StorageProject.Core.DTOs.Ops; +using StorageProject.Core.Entities; +using StorageProject.Infrastructure.Data; +using StorageProject.Infrastructure.Services; +using Xunit; + +namespace StorageProject.Tests; + +public sealed class CheckoutTests +{ + private sealed class TestDb(DbContextOptions options) : AppDbContext(options) + { + protected override void OnModelCreating(ModelBuilder b) + { + base.OnModelCreating(b); + foreach (var p in b.Model.GetEntityTypes().SelectMany(t => t.GetProperties())) + if (p.GetDefaultValueSql() != null) p.SetDefaultValueSql(null); + } + } + private sealed class Gateway : IPayOSGateway + { + public VerifiedReservationPayment? Payment = new(12345, 4000000); + public bool RejectSignature; + public bool FailCancel; + public int Cancellations; + public void EnsureConfigured() { } + public Task CancelAsync(long id) { if (FailCancel) throw new InvalidOperationException(); Cancellations++; return Task.CompletedTask; } + public Task CreateAsync(long code, int amount, long id, long expiry, string ret, string cancel) => Task.FromResult(new CheckoutLink("https://pay.payos.vn/test", "qr")); + public Task VerifyAsync(string body) { + if (RejectSignature) throw new InvalidOperationException("bad signature"); + return Task.FromResult(Payment); + } + } + private sealed class Fixture : IAsyncDisposable + { + public SqliteConnection Connection = new("Data Source=:memory:"); + public AppDbContext Db = null!; + public Gateway Gateway = new(); + public Reservation Order = null!; + public PayOSService PayOS => new(Db, Gateway, NullLogger.Instance); + public static async Task Create() + { + var f = new Fixture(); await f.Connection.OpenAsync(); + f.Db = new TestDb(new DbContextOptionsBuilder().UseSqlite(f.Connection).Options); + await f.Db.Database.EnsureCreatedAsync(); + var user = new User { Username = "test", Email = "test@example.com", FullName = "Test", PasswordHash = "x" }; + var customer = new User { Username = "customer", Email = "customer@example.com", FullName = "Customer", PasswordHash = "x" }; + var facility = new Facility { Name = "Test", Address = "Test", Status = "ACTIVE" }; + var type = new UnitType { TypeName = "Test", Area = 10, Status = "ACTIVE" }; + f.Db.AddRange(user, customer, facility, type); await f.Db.SaveChangesAsync(); + f.Db.UserFacilities.Add(new UserFacility { UserId = user.UserId, FacilityId = facility.FacilityId, + AssignedBy = user.UserId, AssignedFrom = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-1)), Status = "ACTIVE" }); + f.Db.StorageUnits.Add(new StorageUnit { FacilityId = facility.FacilityId, UnitTypeId = type.UnitTypeId, + UnitNumber = "K01", Status = "AVAILABLE" }); + f.Order = new Reservation { CustomerId = customer.UserId, FacilityId = facility.FacilityId, UnitTypeId = type.UnitTypeId, + StartDate = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(2)), ExpectedEndDate = DateOnly.FromDateTime(DateTime.UtcNow.AddMonths(3)), + RentalPeriodMonths = 3, EstimatedAmount = 3000000, RequiredDeposit = 1000000, QuotedMonthlyRate = 1000000, + Status = "PENDING_PAYMENT", OrderCode = 12345, ExpiresAt = DateTime.UtcNow.AddMinutes(15), CreatedAt = DateTime.UtcNow }; + f.Db.Reservations.Add(f.Order); await f.Db.SaveChangesAsync(); return f; + } + public async ValueTask DisposeAsync() { await Db.DisposeAsync(); await Connection.DisposeAsync(); } + } + + [Fact] public async Task WrongAmountDoesNotConfirmOrWriteMoney() { + await using var f = await Fixture.Create(); f.Gateway.Payment = new(12345, 1); + Assert.False(await f.PayOS.ProcessWebhookAsync("{}", null)); + Assert.Empty(await f.Db.Payments.ToListAsync()); Assert.Equal("PENDING_PAYMENT", f.Order.Status); + } + [Fact] public async Task InvalidSignatureAndUnknownOrderDoNotWriteMoney() { + await using var f = await Fixture.Create(); f.Gateway.RejectSignature = true; + Assert.False(await f.PayOS.ProcessWebhookAsync("{}", null)); f.Gateway.RejectSignature = false; f.Gateway.Payment = new(999, 4000000); + Assert.False(await f.PayOS.ProcessWebhookAsync("{}", null)); Assert.Empty(await f.Db.Payments.ToListAsync()); + } + [Fact] public async Task DuplicateWebhookAndAllocationKeepTwoReceiptRows() { + await using var f = await Fixture.Create(); + Assert.True(await f.PayOS.ProcessWebhookAsync("{}", null)); Assert.True(await f.PayOS.ProcessWebhookAsync("{}", null)); + var before = await f.Db.Payments.OrderBy(p => p.PaymentId).Select(p => p.PaymentId).ToListAsync(); Assert.Equal(2, before.Count); + Assert.Equal(4000000, (await f.Db.Payments.ToListAsync()).Sum(p => p.Amount)); + Assert.Empty(await f.Db.UnitAssignments.ToListAsync()); + await ReservationAllocation.AllocateAsync(f.Db, 1, f.Order.FacilityId, f.Order.ReservationId, "K01", default); + await ReservationAllocation.AllocateAsync(f.Db, 1, f.Order.FacilityId, f.Order.ReservationId, "K01", default); + Assert.Equal(before, await f.Db.Payments.OrderBy(p => p.PaymentId).Select(p => p.PaymentId).ToListAsync()); + Assert.All(await f.Db.Payments.ToListAsync(), p => Assert.NotNull(p.ContractId)); + Assert.Single(await f.Db.RentalContracts.ToListAsync()); Assert.Single(await f.Db.UnitAssignments.ToListAsync()); + } + [Fact] public async Task CashCollectionIsIdempotentAndLatePayosNeedsReview() { + await using var f = await Fixture.Create(); f.Order.CheckoutUrl = "https://pay.payos.vn/test"; await f.Db.SaveChangesAsync(); + await f.PayOS.PayAtFacilityAsync(f.Order.CustomerId, f.Order.ReservationId); Assert.Equal(1, f.Gateway.Cancellations); + await ReservationAllocation.AllocateAsync(f.Db, 1, f.Order.FacilityId, f.Order.ReservationId, "K01", default); + Assert.Empty(await f.Db.Payments.ToListAsync()); + await Assert.ThrowsAsync(() => new StaffService(f.Db).CompleteHandoverAsync(1, "BG-0001", new CompleteHandoverRequest { UnlockMethod = "CARD" })); + var staff = new StaffService(f.Db); await staff.ConfirmPaymentAsync(1, "SS-0001"); await staff.ConfirmPaymentAsync(1, "SS-0001"); + Assert.True(await f.PayOS.ProcessWebhookAsync("{}", null)); Assert.True(await f.PayOS.ProcessWebhookAsync("{}", null)); + Assert.Equal(2, await f.Db.Payments.CountAsync()); Assert.All(await f.Db.Payments.ToListAsync(), p => Assert.Equal("CASH", p.PaymentMethod)); + Assert.Single(await f.Db.ActivityLogs.Where(l => l.Action == "PAYMENT_REVIEW_REQUIRED").ToListAsync()); + } + [Fact] public async Task FailedCancellationDoesNotSwitchMethod() { + await using var f = await Fixture.Create(); f.Order.CheckoutUrl = "https://pay.payos.vn/test"; await f.Db.SaveChangesAsync(); f.Gateway.FailCancel = true; + await Assert.ThrowsAsync(() => f.PayOS.PayAtFacilityAsync(f.Order.CustomerId, f.Order.ReservationId)); + Assert.Equal("PAYOS", f.Order.PaymentMethod); Assert.Equal("PENDING_PAYMENT", f.Order.Status); + } + [Fact] public async Task OtherCustomerCannotSwitchAndExpiredHoldCannotBeCollected() { + await using var f = await Fixture.Create(); await Assert.ThrowsAsync(() => f.PayOS.PayAtFacilityAsync(1, f.Order.ReservationId)); + await f.PayOS.PayAtFacilityAsync(f.Order.CustomerId, f.Order.ReservationId); f.Order.ExpiresAt = DateTime.UtcNow.AddMinutes(-1); await f.Db.SaveChangesAsync(); + await Assert.ThrowsAsync(() => new StaffService(f.Db).ConfirmPaymentAsync(1, "SS-0001")); + Assert.Empty(await f.Db.Payments.ToListAsync()); + } + [Fact] public async Task UnitMaintenanceWritesHistoryAndRefusesOccupiedUnit() { + await using var f = await Fixture.Create(); var staff = new StaffService(f.Db); + await Assert.ThrowsAsync(() => staff.UpdateUnitStatusAsync(1, "K01", new UpdateUnitStatusRequest { Status = "MAINTENANCE" })); + await staff.UpdateUnitStatusAsync(1, "K01", new UpdateUnitStatusRequest { Status = "MAINTENANCE", Reason = "Sửa cửa" }); + await staff.UpdateUnitStatusAsync(1, "K01", new UpdateUnitStatusRequest { Status = "AVAILABLE", Reason = "Đã sửa xong" }); + Assert.Equal(2, await f.Db.UnitStatusHistories.CountAsync()); + var u = await f.Db.StorageUnits.SingleAsync(); u.Status = "OCCUPIED"; await f.Db.SaveChangesAsync(); + await Assert.ThrowsAsync(() => staff.UpdateUnitStatusAsync(1, "K01", new UpdateUnitStatusRequest { Status = "AVAILABLE", Reason = "Sai luồng" })); + Assert.Equal("OCCUPIED", u.Status); + } + + [Fact] public async Task CashHoldExpiryReleasesUnitAndCancelsDraft() { + await using var f = await Fixture.Create(); + await f.PayOS.PayAtFacilityAsync(f.Order.CustomerId, f.Order.ReservationId); + await ReservationAllocation.AllocateAsync(f.Db, 1, f.Order.FacilityId, f.Order.ReservationId, "K01", default); + f.Order.ExpiresAt = DateTime.UtcNow.AddMinutes(-1); await f.Db.SaveChangesAsync(); + await CashHoldExpiry.ExpireAsync(f.Db); + Assert.Equal("EXPIRED", f.Order.Status); + Assert.Equal("AVAILABLE", (await f.Db.StorageUnits.SingleAsync()).Status); + Assert.Equal("CANCELLED", (await f.Db.RentalContracts.SingleAsync()).Status); + Assert.Empty(await f.Db.Payments.ToListAsync()); + } + [Fact] public async Task PaidOrderCannotSwitchToCashAndPayosCannotBeConfirmedAtCounter() { + await using var f = await Fixture.Create(); + await Assert.ThrowsAsync(() => new StaffService(f.Db).ConfirmPaymentAsync(1, "SS-0001")); + Assert.True(await f.PayOS.ProcessWebhookAsync("{}", null)); + await Assert.ThrowsAsync(() => f.PayOS.PayAtFacilityAsync(f.Order.CustomerId, f.Order.ReservationId)); + Assert.Equal(2, await f.Db.Payments.CountAsync()); + } + [Fact] public async Task SecondAllocationCannotTakeAlreadyHeldUnit() { + await using var f = await Fixture.Create(); + await f.PayOS.PayAtFacilityAsync(f.Order.CustomerId, f.Order.ReservationId); + await ReservationAllocation.AllocateAsync(f.Db, 1, f.Order.FacilityId, f.Order.ReservationId, "K01", default); + var other = new Reservation { CustomerId = f.Order.CustomerId, FacilityId = f.Order.FacilityId, UnitTypeId = f.Order.UnitTypeId, + StartDate = f.Order.StartDate, ExpectedEndDate = f.Order.ExpectedEndDate, RentalPeriodMonths = 3, + Status = "PENDING_AT_FACILITY", PaymentMethod = "AT_FACILITY", ExpiresAt = DateTime.UtcNow.AddDays(1) }; + f.Db.Reservations.Add(other); await f.Db.SaveChangesAsync(); + await Assert.ThrowsAsync(() => ReservationAllocation.AllocateAsync(f.Db, 1, f.Order.FacilityId, other.ReservationId, "K01", default)); + Assert.Single(await f.Db.UnitAssignments.ToListAsync()); + } + [Fact] public async Task ClientAmountOverrideIsRejected() { + await using var f = await Fixture.Create(); + var request = new StorageProject.Core.DTOs.Payment.CreatePayOSQrRequest(null,null,null,f.Order.ReservationId,null,null,1,null,null); + await Assert.ThrowsAsync(() => f.PayOS.CreatePaymentQrAsync(f.Order.CustomerId, request)); + Assert.Empty(await f.Db.Payments.ToListAsync()); + } + [Fact] public async Task RealSdkRejectsInvalidSignature() { + var config = new Microsoft.Extensions.Configuration.ConfigurationBuilder().AddInMemoryCollection(new Dictionary { + ["PayOS:ClientId"] = "test-client", ["PayOS:ApiKey"] = "test-key", ["PayOS:ChecksumKey"] = "test-checksum" + }).Build(); + var gateway = new SdkPayOSGateway(config); + await Assert.ThrowsAnyAsync(() => gateway.VerifyAsync("{\"code\":\"00\",\"success\":true,\"data\":{\"orderCode\":12345,\"amount\":4000000,\"code\":\"00\"},\"signature\":\"invalid\"}")); + } + + [Fact] public void SqlServerModelMatchesMigrationSnapshot() { + using var db = new AppDbContext(new DbContextOptionsBuilder() + .UseSqlServer("Server=unused;Database=unused;Integrated Security=true;TrustServerCertificate=true").Options); + Assert.False(db.Database.HasPendingModelChanges()); + } + + [Fact] public async Task CashPaymentVerificationAndHandoverUseTheSameReceipts() { + await using var f = await Fixture.Create(); + await f.PayOS.PayAtFacilityAsync(f.Order.CustomerId, f.Order.ReservationId); + await ReservationAllocation.AllocateAsync(f.Db, 1, f.Order.FacilityId, f.Order.ReservationId, "K01", default); + var staff = new StaffService(f.Db); + await staff.ConfirmPaymentAsync(1, "SS-0001"); + await staff.VerifyCustomerAsync(1, "XM-0001", new VerifyCustomerRequest { DocType = "CCCD", DocNumber = "123456789012", PhotoMatched = true, InfoMatched = true }); + var board = await staff.GetStaffBoardAsync(1); + Assert.Equal("DONE", Assert.Single(board.Verifications).Status); + await staff.CompleteHandoverAsync(1, "BG-0001", new CompleteHandoverRequest { UnlockMethod = "CARD" }); + Assert.Equal("ACTIVE", (await f.Db.RentalContracts.SingleAsync()).Status); + Assert.Equal("CHECKED_IN", f.Order.Status); + Assert.Equal(2, await f.Db.Payments.CountAsync()); + Assert.Equal("DONE", Assert.Single((await staff.GetStaffBoardAsync(1)).Handovers).Status); + } +} diff --git a/StorageProject.Tests/RouteTests.cs b/StorageProject.Tests/RouteTests.cs new file mode 100644 index 0000000..2258c06 --- /dev/null +++ b/StorageProject.Tests/RouteTests.cs @@ -0,0 +1,32 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using StorageProject.Api.Endpoints; +using StorageProject.Core.Interfaces; +using StorageProject.Infrastructure.Services; +using Xunit; + +namespace StorageProject.Tests; + +public sealed class RouteTests +{ + [Fact] public void CheckoutAndOpsRoutesAreUnique() + { + var builder = WebApplication.CreateBuilder(); + builder.Services.AddAuthorization(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); + var app = builder.Build(); + app.MapReservationEndpoints(); app.MapStaffEndpoints(); app.MapManagerEndpoints(); app.MapFacilityOpsEndpoints(); + var routes = ((IEndpointRouteBuilder)app).DataSources.SelectMany(s => s.Endpoints).OfType() + .SelectMany(e => (e.Metadata.GetMetadata()?.HttpMethods ?? ["ANY"]) + .Select(method => $"{method} {e.RoutePattern.RawText}")).ToList(); + Assert.DoesNotContain(routes.GroupBy(r => r), g => g.Count() > 1); + Assert.Contains("POST /api/reservations/{id:long}/pay-at-facility", routes); + Assert.Contains("PUT /api/staff/units/{id}/status", routes); + Assert.Single(routes, r => r == "GET /api/ops/board"); + } +} diff --git a/StorageProject.Tests/StorageProject.Tests.csproj b/StorageProject.Tests/StorageProject.Tests.csproj new file mode 100644 index 0000000..b4936e9 --- /dev/null +++ b/StorageProject.Tests/StorageProject.Tests.csproj @@ -0,0 +1,10 @@ + + net10.0enableenabletruefalse + + + + + all + + + diff --git a/StorageProject.slnx b/StorageProject.slnx index 09a4ca3..9c7358b 100644 --- a/StorageProject.slnx +++ b/StorageProject.slnx @@ -2,4 +2,5 @@ + diff --git a/docs/payment-integrity-2026-10-20.md b/docs/payment-integrity-2026-10-20.md new file mode 100644 index 0000000..dcfb773 --- /dev/null +++ b/docs/payment-integrity-2026-10-20.md @@ -0,0 +1,66 @@ +# Kiểm tra bản sửa thanh toán và trạng thái ô kho + +Nguồn main: 242f70158d4299da4c5206181ba52389461b0fa3. Xem D23–D24. Gói này không triển khai thanh toán gia hạn, phí trả kho, phản hồi ticket hay tự động hoàn tiền. + +## Thay đổi API + +- POST `/api/reservations/{id}/pay-at-facility`: JWT chủ đơn, đơn chưa thanh toán/còn hạn; trả 200 sau khi chuyển PENDING_AT_FACILITY. Nếu PayOS huỷ link thất bại thì trả 400 và giữ phương thức cũ. Gọi lại cùng lựa chọn trả 200. +- POST `/api/staff/payments/{id}/confirm`: JWT STAFF/MANAGER đúng cơ sở, xác nhận đã thu tiền mặt. Chỉ nhận đơn AT_FACILITY chưa hết hạn; gọi lại cùng khoản đã thu trả 200, không thêm tiền. `/api/ops/payments/{id}/confirm` dùng chung xử lý. +- POST `/api/manager/allocations/{id}`: đơn đã thu đủ hoặc chờ thu tại kho, ô đúng cơ sở/loại/còn trống. Tạo đúng một hợp đồng nháp; gắn khoản thu có sẵn. `/api/ops/allocations/{id}` dùng chung xử lý. +- PUT `/api/staff/units/{id}/status`: `{ "status": "MAINTENANCE", "reason": "Sửa cửa" }`. Lý do bắt buộc, chỉ chuyển trạng thái vận hành thủ công, ghi lịch sử. Khoá ô qua API manager cũng đi qua quy tắc này. +- ReservationDto và ReservationDetailDto thêm `paymentMethod`. PaymentDto.ContractId có thể null trước khi phân bổ; các endpoint trả thanh toán của hợp đồng vẫn gắn hợp đồng như trước. +- Chữ ký webhook được kiểm bằng SDK PayOS 2.1.0; không có API bỏ qua chữ ký. Fake gateway chỉ nằm trong project test, không đăng ký ở chương trình chạy thật. + +## Chạy kiểm chứng + +Từ thư mục có StorageProject.slnx: + +```powershell +dotnet restore +dotnet build StorageProject.slnx -m:1 +dotnet test StorageProject.slnx -m:1 +dotnet run --project StorageProject.Api --launch-profile http +``` + +BE tự chạy migration mới ReservationPaymentIntegrity khi khởi động. Không reset database. Cần .NET SDK 10, SQL Server, tài khoản có quyền cập nhật schema và connection string đúng trên máy bạn. Các cảnh báo NU1902/NU1903 về dependency đã tồn tại từ bản nguồn, không được coi là build error. + +Ở terminal khác: + +```powershell +cd SafeSpace-Customer-UI\SafeSpace-Customer-UI +npm ci +npm test +npm run test:render +npm run test:business +npm run build +npm run dev +``` + +## Kịch bản bắt buộc trên SQL Server và PayOS thật + +1. Tạo đơn, tạo QR PayOS. Kiểm số tiền bằng tiền thuê + cọc trong DB. Đổi amount trong request tạo QR phải bị từ chối. +2. Trả đúng tiền. Sau webhook: đơn CONFIRMED, bảng payments có RENT + DEPOSIT (bỏ qua dòng giá trị 0), chưa tự gán ô. Gửi lại chính thông báo có chữ ký đó: không thêm payments và không thêm phân bổ. +3. Gửi chữ ký sai, đúng chữ ký nhưng sai tiền hoặc orderCode không có: không xác nhận, không ghi payments. Muốn kiểm sai tiền có chữ ký hợp lệ phải dùng giao dịch test/fixture hợp lệ, không sửa payload đã ký rồi coi đó là kiểm số tiền. +4. Quản lý phân bổ đúng loại kho ở M05: có một assignment, một hợp đồng DRAFT. PaymentId trước và sau phân bổ giữ nguyên. Bấm lại không tạo hợp đồng/thu thêm; chọn ô khác khi đã phân bổ bị chặn. +5. Đơn khác chọn trả tại kho: link PayOS cũ phải được huỷ/không tồn tại; đăng nhập lại hoặc trình duyệt khác vẫn thấy chọn trả tại kho. S09 chỉ hiện đơn chờ thu tại kho. M05 phân bổ được, nhưng S03 không bàn giao khi chưa thu tiền. +6. Nhân viên thực thu và xác nhận S09; bấm hai lần: chỉ hai khoản RENT/DEPOSIT, tổng đúng. Xác minh khách rồi bàn giao được. +7. Kiểm PayOS thanh toán đến muộn sau khi chọn/trả tại kho: không thêm khoản thu thuê; activity_logs có PAYMENT_REVIEW_REQUIRED. Webhook gửi lại không thêm log trùng. Quản lý đối chiếu và hoàn thủ công, đây không phải lệnh tự hoàn của PayOS. +8. Chạy đồng thời hai request xác nhận tiền, hoặc hai quản lý phân bổ cùng một ô: SQL Server chỉ cho một kết quả; request còn lại trả kết quả cũ hoặc lỗi, không ghi trùng. Các test SQLite không thay thế kiểm khoá SQL Server này. +9. Với đơn trả tại kho chưa thu trên DB phát triển, đặt ExpiresAt về quá khứ, đợi worker tối đa một phút: EXPIRED, assignment/hợp đồng nháp CANCELLED, ô AVAILABLE. Không sửa ngày của dữ liệu thật để thử. +10. M02 đổi ô trống sang bảo trì rồi mở lại, nhập lý do: DB có lịch sử old/new/actor/reason/time. Bỏ lý do, đổi ô đang thuê thành trống, đổi ô đã giữ sang bảo trì đều bị chặn. +11. Token khác cơ sở không thu/phân bổ/sửa ô được; CUSTOMER không gọi được API staff. +12. Thử migration trên bản sao DB đang có dữ liệu và DB mới. So sánh số dòng/khoản thu trước sau; không có khoản tiền tự sinh cho đơn cũ thiếu payments. + +## SQL đối chiếu + +```sql +SELECT ReservationId, ContractId, PaymentType, Amount, PaymentMethod, TransactionReference, Status +FROM payments WHERE ReservationId = ORDER BY PaymentId; +SELECT ReservationId, PaymentType, COUNT(*) AS RowCount +FROM payments WHERE ReservationId IS NOT NULL AND PaymentType IN ('RENT','DEPOSIT') +GROUP BY ReservationId, PaymentType HAVING COUNT(*) > 1; +SELECT * FROM activity_logs WHERE Action = 'PAYMENT_REVIEW_REQUIRED' ORDER BY LoggedAt DESC; +SELECT * FROM unit_status_history ORDER BY ChangedAt DESC; +``` + +Các đơn PENDING_VERIFICATION đời cũ không được tự coi là tiền mặt đã thu. Đơn cũ có PaidAt nhưng thiếu payments cần thành viên nhóm đối chiếu, không tự tạo tiền chỉ để qua điều kiện bàn giao. Gói này cũng không sửa các lỗi riêng của quy trình trả kho/hoàn cọc đã được liệt kê ở lần rà soát trước. diff --git a/feature_list.json b/feature_list.json index c536776..2f2b56d 100644 --- a/feature_list.json +++ b/feature_list.json @@ -2,7 +2,7 @@ "_readme": "Danh sách tính năng = ranh giới phạm vi cho AI agent. Mỗi mục: behavior (hành vi), verification (lệnh/cách kiểm chứng), state. state: not_started -> active -> passing | blocked. Chỉ đổi sang passing khi verification pass và ghi evidence. Mỗi phiên chỉ một mục active.", "_fe": "cd SafeSpace-Customer-UI/SafeSpace-Customer-UI && npm test && npm run test:render && npm run build", "_be": "dotnet build StorageProject.slnx", - "updated": "2026-10-16", + "updated": "2026-10-20", "features": [ { "id": "F01", "flow": 1, "uc": ["UC01"], "actor": "Khách hàng", @@ -253,6 +253,19 @@ "state": "passing", "depends_on": ["F32", "F33"], "evidence": "2026-10-16: Đã triển khai IAccessService, AccessService (HMAC-SHA256 sinh QR và backupCode), AccessEndpoints (GET /api/contracts/{id}/access-qr, POST /api/access/scan); kết nối useAccessQr.js và endpoints.js; test_full_flow.ps1 kiểm chứng thành công từ bàn giao kho đến quét mã mở cửa và ghi activity_logs; dotnet build và npm test pass." + }, + { + "id": "F35", + "flow": [ + 1, + 5, + 6 + ], + "actor": "Khách hàng / Nhân viên / Quản lý", + "behavior": "Bản sửa theo yêu cầu: kiểm số tiền PayOS, ghi khoản thu trước hợp đồng, chống lặp và phân bổ, dự phòng tại kho, D23–D24, F12 có lý do/lịch sử", + "state": "active", + "verification": "dotnet build StorageProject.slnx -m:1; dotnet test StorageProject.slnx -m:1; kiểm chứng SQL Server/PayOS thật theo docs/payment-integrity-2026-10-20.md", + "evidence": "2026-10-20: build BE PASS; xUnit 15/15; FE 67/67; business 9/9; render 92 route; build FE và init.sh PASS. SQLite + kiểm model SQL Server; chờ SQL Server/PayOS thật nên chưa passing." } ] } diff --git a/progress.md b/progress.md index 531fd5a..3a61772 100644 --- a/progress.md +++ b/progress.md @@ -319,3 +319,13 @@ - Kiểm chứng: 42 test gốc, 10 test QR, 9 test business pass; 76 route SSR pass; Vite build pass. - Browser Chromium: popup 480x598, QR, kết quả mở cửa, từ chối hết hạn, icon 96px, Escape, Đóng, khóa chưa bàn giao, mobile 390px, không pageerror. - Chưa có backend QR; hướng dẫn C07-QR-HUONG-DAN.md. + +## 2026-10-20 — F35 kiểm khoản thu và phân bổ, thanh toán tại kho, F12 + +- Theo yêu cầu người dùng sửa cùng gói: PayOS kiểm số tiền và orderCode, ghi RENT/DEPOSIT vào payments trước khi có hợp đồng; gắn lại PaymentId khi phân bổ, không thu thêm. Bỏ phân bổ tự động khỏi webhook. Chuyển trả tại kho huỷ link trước khi đổi, S09 thu tiền mặt, xử lý callback muộn bằng PAYMENT_REVIEW_REQUIRED. +- D23–D24 bổ sung, không sửa số/nội dung D19–D22. Trạng thái ô bằng tay có lý do, quy tắc và unit_status_history. Xoá các route /api/ops trùng trong Staff/Manager để giữ một bộ đăng ký; các thao tác thu tiền/phân bổ tương thích dùng chung xử lý. +- Migration mới 20261020154838_ReservationPaymentIntegrity: PaymentMethod, PENDING_AT_FACILITY, Payment.ReservationId, ContractId optional, unique index khoản thu. Nối các dòng cũ không mơ hồ; không xoá database/dữ liệu. Worker thu hồi giữ chỗ tại kho hết hạn. Không sửa migration cũ. +- Chặn xác minh/bàn giao chưa có đủ khoản thu, đồng bộ trạng thái xác minh từ HandoverRecord thay vì đánh dấu CHECKED_IN trước khi bàn giao. Test luồng chọn trả tại kho → phân bổ → thu → xác minh → bàn giao giữ nguyên hai khoản thu. +- Kiểm chứng: .NET SDK 10.0.100; dotnet build StorageProject.slnx -m:1 PASS; xUnit 15/15 PASS (SQLite, adapter SDK chữ ký sai, model SQL Server khớp snapshot, route không trùng); npm test 67/67 PASS; test:business 9/9 PASS; test:render 92 route PASS; npm run build PASS; bash init.sh PASS với dotnet build/test chạy m:1 do giới hạn tiến trình của môi trường; git diff --check PASS; sinh được SQL upgrade từ migration toạ độ tới migration mới. +- Giới hạn kiểm chứng: chưa chạy SQL Server thật, chưa thử PayOS/ngrok bằng key thật, chưa kiểm khoá/đồng thời trên SQL Server hay migration trên dữ liệu DB của nhóm. F35 giữ active, không tuyên bố 7 flow hoàn tất. Các cảnh báo dependency NU1902/NU1903 và nullable Board.cs:317 đã có từ nguồn. +- Chỉ bàn giao ZIP/bản vá để người dùng áp dụng và chạy thử trước khi tự push nhánh. Không push/PR/merge từ phiên này. From addb06e9f37f5d1dd22f0799a668a509b2549a7e Mon Sep 17 00:00:00 2001 From: Vector Date: Wed, 21 Oct 2026 00:10:29 +0700 Subject: [PATCH 2/3] refactor: organize frontend by role --- .github/copilot-instructions.md | 3 + AGENTS.md | 10 +- DECISIONS.md | 5 + README.md | 8 +- .../ADMIN-FLOW-COVERAGE.md | 12 +- .../SafeSpace-Customer-UI/AGENTS.md | 10 + .../SafeSpace-Customer-UI/BACKEND-TODO.md | 8 +- .../SafeSpace-Customer-UI/BE-CONTRACT.md | 18 +- .../BUSINESS-FLOW-COVERAGE.md | 6 +- .../CUSTOMER-FLOW-COVERAGE.md | 60 +- .../SafeSpace-Customer-UI/FRONTEND-MAP.md | 177 ++++++ .../OPS-FLOW-COVERAGE.md | 2 +- .../SafeSpace-Customer-UI/README.md | 16 +- .../SafeSpace-Customer-UI/mock/mock-api.mjs | 4 +- .../SafeSpace-Customer-UI/package.json | 3 +- .../scripts/check-structure.mjs | 36 ++ .../src/admin/AdminLogs.jsx | 143 ----- .../src/{CustomerApp.jsx => app/App.jsx} | 100 ++-- .../src/{ => app}/config/api.js | 0 .../src/{ => app}/config/geo.js | 0 .../src/{ => app}/config/media.js | 0 .../src/{ => app}/config/payment.js | 0 .../src/{data/seed.js => app/data/appSeed.js} | 4 +- .../src/{lib => app}/router.js | 0 .../store.jsx => app/state/AppProvider.jsx} | 32 +- .../reducer.js => app/state/appReducer.js} | 6 +- .../state/appSelectors.js} | 2 +- .../admin/AdminLayout.jsx} | 12 +- .../admin/AdminRoutes.jsx} | 28 +- .../admin/api/adminApi.js} | 2 +- .../admin/permissions/PermissionListPage.jsx} | 12 +- .../admin/users/CreateUserPage.jsx} | 18 +- .../admin/users/UserDetailPage.jsx} | 16 +- .../admin/users/UserListPage.jsx} | 16 +- .../admin/utils/adminUtils.js} | 4 +- .../src/features/auth/LoginPage.jsx | 63 ++ .../src/features/auth/RegisterPage.jsx | 62 ++ .../auth/components/ForgotPasswordDialog.jsx | 42 ++ .../src/features/auth/utils/safeNext.js | 3 + .../business/BusinessLayout.jsx} | 10 +- .../business/BusinessRoutes.jsx} | 28 +- .../business/api/businessApi.js} | 4 +- .../business/business.css} | 0 .../components/BusinessComponents.jsx} | 8 +- .../dashboard/BusinessDashboardPage.jsx} | 14 +- .../facilities/FacilityManagementPage.jsx} | 18 +- .../business/facilities/facilityForm.js} | 0 .../business/policies/PolicySettingsPage.jsx} | 18 +- .../business/policies/policyActions.js} | 6 +- .../business/policies/policyFields.js} | 2 +- .../business/pricing/PricingPage.jsx} | 18 +- .../business/reports/BusinessReportPage.jsx} | 20 +- .../business/reports/reportExport.js} | 0 .../business/utils/businessFormat.js} | 2 +- .../customer/access/AccessQrModal.jsx | 51 ++ .../customer/access/DoorScannerPage.jsx} | 8 +- .../customer/access/accessApi.js} | 4 +- .../customer/access}/useAccessQr.js | 10 +- .../customer/contracts/RenewalRequestPage.jsx | 54 ++ .../contracts/RentedUnitDetailPage.jsx | 137 +++++ .../customer/contracts/RentedUnitListPage.jsx | 42 ++ .../customer/contracts/ReturnRequestPage.jsx | 57 ++ .../contracts/components/ContractNotFound.jsx | 12 + .../dashboard/CustomerDashboardPage.jsx} | 20 +- .../facilities/FacilityDetailPage.jsx} | 24 +- .../customer/facilities/FacilityListPage.jsx} | 20 +- .../customer/facilities/FacilityMapPage.jsx} | 24 +- .../customer/help/HelpPage.jsx} | 44 +- .../customer/home/HomePage.jsx} | 16 +- .../customer/payments/CheckoutFailedPage.jsx | 26 + .../customer/payments/CheckoutPage.jsx} | 120 +--- .../customer/payments/PaymentListPage.jsx} | 14 +- .../customer/pricing/PublicPricingPage.jsx | 40 ++ .../customer/profile/CustomerProfilePage.jsx} | 10 +- .../customer/requests/RequestSentPage.jsx | 22 + .../reservations/ReservationDetailPage.jsx | 69 +++ .../reservations/ReservationListPage.jsx} | 18 +- .../components/ReservationNotFound.jsx | 12 + .../customer/support/SupportPage.jsx} | 14 +- .../FacilityOperationsLayout.jsx} | 12 +- .../FacilityOperationsRoutes.jsx | 68 +++ .../api/facilityOperationsApi.js} | 2 +- .../FacilityOperationsComponents.jsx} | 4 +- .../components/StaffTasks.jsx} | 14 +- .../data/facilityOperationsSeed.js} | 2 +- .../state/FacilityOperationsProvider.jsx} | 8 +- .../state/facilityOperationsReducer.js} | 2 +- .../facility-operations/utils/unitStateTag.js | 4 + .../allocations/UnitAllocationPage.jsx | 66 +++ .../assignments/StaffAssignmentPage.jsx | 63 ++ .../manager/components/PageHeaderBlock.jsx | 12 + .../manager/contracts/ContractListPage.jsx | 82 +++ .../dashboard/ManagerDashboardPage.jsx | 71 +++ .../manager/renewals/RenewalApprovalPage.jsx | 70 +++ .../manager/reports/FacilityReportPage.jsx | 75 +++ .../manager/results/ManagerResultPage.jsx | 29 + .../manager/units/UnitManagementPage.jsx | 131 +++++ .../staff/dashboard/StaffDashboardPage.jsx | 39 ++ .../handovers/CustomerVerificationPage.jsx | 74 +++ .../features/staff/handovers/HandoverPage.jsx | 68 +++ .../features/staff/hooks/useStaffIdentity.js | 9 + .../payments/PaymentConfirmationPage.jsx | 74 +++ .../staff/results/StaffResultPage.jsx | 29 + .../staff/returns/ReturnInspectionPage.jsx | 70 +++ .../staff/support/StaffSupportPage.jsx | 75 +++ .../SafeSpace-Customer-UI/src/main.jsx | 4 +- .../src/ops/ManagerPages.jsx | 556 ------------------ .../SafeSpace-Customer-UI/src/ops/OpsApp.jsx | 56 -- .../src/ops/StaffPages.jsx | 410 ------------- .../SafeSpace-Customer-UI/src/pages/Auth.jsx | 159 ----- .../SafeSpace-Customer-UI/src/pages/Units.jsx | 348 ----------- .../mappers.js => shared/api/apiMappers.js} | 6 +- .../api/customerApi.js} | 2 +- .../{api/http.js => shared/api/httpClient.js} | 2 +- .../src/{ => shared}/components/AccessQr.jsx | 14 +- .../src/{ => shared}/components/Header.jsx | 8 +- .../src/{ => shared}/components/Inline.jsx | 4 +- .../components/PayOSEmbeddedModal.jsx | 4 +- .../src/{ => shared}/components/PaymentQr.jsx | 6 +- .../{ => shared}/components/PayosModal.jsx | 8 +- .../src/{ => shared}/components/Photo.jsx | 4 +- .../src/{ => shared}/components/Pickers.jsx | 2 +- .../src/{ => shared}/components/QrCode.jsx | 2 +- .../src/{ => shared}/components/SearchBar.jsx | 6 +- .../src/{ => shared}/components/UI.jsx | 2 +- .../src/{ => shared}/components/UnitMap.jsx | 4 +- .../hooks/useBrowserEvents.js} | 0 .../src/{ => shared}/styles/access-qr.css | 0 .../src/{ => shared}/styles/ss.css | 0 .../src/{lib => shared/utils}/access.js | 0 .../src/{lib => shared/utils}/catalog.js | 0 .../src/{lib => shared/utils}/format.js | 0 .../src/{lib => shared/utils}/roles.js | 0 .../src/{lib => shared/utils}/status.js | 0 .../src/{lib => shared/utils}/units.js | 0 .../src/{lib => shared/utils}/vietqr.js | 0 .../tests/access.test.js | 2 +- .../SafeSpace-Customer-UI/tests/admin.test.js | 4 +- .../tests/api-mappers.test.js | 2 +- .../tests/business-frontend.test.mjs | 14 +- .../tests/ops-api.test.mjs | 2 +- .../SafeSpace-Customer-UI/tests/ops.test.js | 4 +- .../tests/payment-access.test.js | 6 +- .../tests/payment-api.test.mjs | 6 +- .../tests/reducer.test.js | 12 +- .../tests/render.test.mjs | 14 +- .../SafeSpace-Customer-UI/tests/units.test.js | 8 +- docs/architecture.md | 36 +- docs/conventions.md | 13 +- docs/frontend-naming.md | 60 ++ feature_list.json | 10 + progress.md | 10 + 152 files changed, 2621 insertions(+), 2301 deletions(-) create mode 100644 .github/copilot-instructions.md create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/AGENTS.md create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/FRONTEND-MAP.md create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/check-structure.mjs delete mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminLogs.jsx rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{CustomerApp.jsx => app/App.jsx} (64%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => app}/config/api.js (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => app}/config/geo.js (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => app}/config/media.js (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => app}/config/payment.js (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{data/seed.js => app/data/appSeed.js} (98%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{lib => app}/router.js (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{state/store.jsx => app/state/AppProvider.jsx} (97%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{state/reducer.js => app/state/appReducer.js} (99%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{state/selectors.js => app/state/appSelectors.js} (98%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{admin/AdminShell.jsx => features/admin/AdminLayout.jsx} (95%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{admin/AdminApp.jsx => features/admin/AdminRoutes.jsx} (80%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{api/admin.js => features/admin/api/adminApi.js} (97%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{admin/AdminPermissions.jsx => features/admin/permissions/PermissionListPage.jsx} (94%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{admin/AdminCreateUser.jsx => features/admin/users/CreateUserPage.jsx} (97%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{admin/AdminUserDetail.jsx => features/admin/users/UserDetailPage.jsx} (96%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{admin/AdminUsers.jsx => features/admin/users/UserListPage.jsx} (97%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{admin/util.js => features/admin/utils/adminUtils.js} (97%) create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/LoginPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/RegisterPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/components/ForgotPasswordDialog.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/utils/safeNext.js rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{business/BusinessShell.jsx => features/business/BusinessLayout.jsx} (96%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{business/BusinessApp.jsx => features/business/BusinessRoutes.jsx} (51%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{api/business.js => features/business/api/businessApi.js} (96%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{business/design.css => features/business/business.css} (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{business/parts.jsx => features/business/components/BusinessComponents.jsx} (96%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{business/Overview.jsx => features/business/dashboard/BusinessDashboardPage.jsx} (90%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{business/Facilities.jsx => features/business/facilities/FacilityManagementPage.jsx} (93%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{business/facility-form.js => features/business/facilities/facilityForm.js} (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{business/Policies.jsx => features/business/policies/PolicySettingsPage.jsx} (81%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{business/actions.js => features/business/policies/policyActions.js} (87%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{business/policy-fields.js => features/business/policies/policyFields.js} (98%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{business/Pricing.jsx => features/business/pricing/PricingPage.jsx} (94%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{business/Reports.jsx => features/business/reports/BusinessReportPage.jsx} (94%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{business/export.js => features/business/reports/reportExport.js} (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{business/format.js => features/business/utils/businessFormat.js} (99%) create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/AccessQrModal.jsx rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{pages/Door.jsx => features/customer/access/DoorScannerPage.jsx} (93%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{api/payment-access.js => features/customer/access/accessApi.js} (97%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{state => features/customer/access}/useAccessQr.js (88%) create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RenewalRequestPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitDetailPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitListPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ReturnRequestPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/components/ContractNotFound.jsx rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{pages/Overview.jsx => features/customer/dashboard/CustomerDashboardPage.jsx} (90%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{pages/FacilityDetail.jsx => features/customer/facilities/FacilityDetailPage.jsx} (94%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{pages/FindList.jsx => features/customer/facilities/FacilityListPage.jsx} (89%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{pages/FindMap.jsx => features/customer/facilities/FacilityMapPage.jsx} (91%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{pages/Public.jsx => features/customer/help/HelpPage.jsx} (61%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{pages/Home.jsx => features/customer/home/HomePage.jsx} (96%) create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/CheckoutFailedPage.jsx rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{pages/Checkout.jsx => features/customer/payments/CheckoutPage.jsx} (62%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{pages/Payments.jsx => features/customer/payments/PaymentListPage.jsx} (91%) create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/pricing/PublicPricingPage.jsx rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{pages/Profile.jsx => features/customer/profile/CustomerProfilePage.jsx} (93%) create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/requests/RequestSentPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/ReservationDetailPage.jsx rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{pages/Reservations.jsx => features/customer/reservations/ReservationListPage.jsx} (92%) create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/components/ReservationNotFound.jsx rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{pages/Support.jsx => features/customer/support/SupportPage.jsx} (95%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ops/OpsShell.jsx => features/facility-operations/FacilityOperationsLayout.jsx} (94%) create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/FacilityOperationsRoutes.jsx rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ops/api.js => features/facility-operations/api/facilityOperationsApi.js} (98%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ops/util.jsx => features/facility-operations/components/FacilityOperationsComponents.jsx} (91%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ops/tasks.jsx => features/facility-operations/components/StaffTasks.jsx} (95%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ops/data.js => features/facility-operations/data/facilityOperationsSeed.js} (99%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ops/store.jsx => features/facility-operations/state/FacilityOperationsProvider.jsx} (95%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ops/reducer.js => features/facility-operations/state/facilityOperationsReducer.js} (99%) create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/unitStateTag.js create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/allocations/UnitAllocationPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/assignments/StaffAssignmentPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/components/PageHeaderBlock.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/contracts/ContractListPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/dashboard/ManagerDashboardPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/renewals/RenewalApprovalPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/reports/FacilityReportPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/results/ManagerResultPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/units/UnitManagementPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/dashboard/StaffDashboardPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/handovers/CustomerVerificationPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/handovers/HandoverPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/hooks/useStaffIdentity.js create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/payments/PaymentConfirmationPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/results/StaffResultPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/returns/ReturnInspectionPage.jsx create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/staff/support/StaffSupportPage.jsx delete mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/ManagerPages.jsx delete mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/OpsApp.jsx delete mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/StaffPages.jsx delete mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Auth.jsx delete mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Units.jsx rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{api/mappers.js => shared/api/apiMappers.js} (99%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{api/endpoints.js => shared/api/customerApi.js} (98%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{api/http.js => shared/api/httpClient.js} (97%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => shared}/components/AccessQr.jsx (91%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => shared}/components/Header.jsx (96%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => shared}/components/Inline.jsx (92%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => shared}/components/PayOSEmbeddedModal.jsx (98%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => shared}/components/PaymentQr.jsx (96%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => shared}/components/PayosModal.jsx (94%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => shared}/components/Photo.jsx (99%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => shared}/components/Pickers.jsx (98%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => shared}/components/QrCode.jsx (97%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => shared}/components/SearchBar.jsx (91%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => shared}/components/UI.jsx (99%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => shared}/components/UnitMap.jsx (94%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{lib/hooks.js => shared/hooks/useBrowserEvents.js} (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => shared}/styles/access-qr.css (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{ => shared}/styles/ss.css (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{lib => shared/utils}/access.js (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{lib => shared/utils}/catalog.js (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{lib => shared/utils}/format.js (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{lib => shared/utils}/roles.js (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{lib => shared/utils}/status.js (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{lib => shared/utils}/units.js (100%) rename SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/{lib => shared/utils}/vietqr.js (100%) create mode 100644 docs/frontend-naming.md diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..c2bae97 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,3 @@ +# Repository instructions + +Read `AGENTS.md` first. For frontend changes, follow `docs/frontend-naming.md` and `SafeSpace-Customer-UI/SafeSpace-Customer-UI/AGENTS.md`. Consult the frontend `FRONTEND-MAP.md` before creating files. Run `npm run check:structure` in the frontend directory. diff --git a/AGENTS.md b/AGENTS.md index 6ca55a3..0ccf77f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,6 +20,8 @@ 12. **AI không được tự `git push`, tạo Pull Request hay merge lên repo này.** Chỉ sửa code và commit trên máy; giao lại cho thành viên nhóm (patch / file zip / hướng dẫn lệnh) để người đó tự kiểm tra rồi tự push. +13. **Khi sửa FE, đọc bắt buộc `docs/frontend-naming.md`, `SafeSpace-Customer-UI/SafeSpace-Customer-UI/AGENTS.md` và `FRONTEND-MAP.md` cùng thư mục.** Không tạo lại thư mục cũ; chạy `npm run check:structure` trước khi bàn giao. + ## 2. Dự án là gì Hệ thống quản lý và cho thuê kho tự phục vụ **SafeSpace** cho 5 nhóm người dùng @@ -36,10 +38,10 @@ Hệ thống quản lý và cho thuê kho tự phục vụ **SafeSpace** cho 5 n | `StorageProject.Core/` | Entities, DTOs, `Interfaces/IServices.cs` | | `StorageProject.Infrastructure/` | EF Core `AppDbContext`, `Migrations/`, `DbSeeder.cs`, `Services/*Service.cs` | | `SafeSpace-Customer-UI/SafeSpace-Customer-UI/` | React 19 + Vite: khách hàng, nhân viên, quản lý cơ sở, quản trị | -| `…/src/ops/` | Khu Nhân viên `#/staff` + Quản lý cơ sở `#/manager` (gọi `/api/ops/*`, D15) | -| `…/src/state/reducer.js` | Nghiệp vụ phía giao diện (hàm thuần, có test) | -| `…/src/state/store.jsx` | Phiên đăng nhập, 2 chế độ: API / lưu trình duyệt | -| `…/src/api/` | Gọi API + `mappers.js` chuyển dữ liệu backend → giao diện | +| `…/src/features/facility-operations/` | Khu Nhân viên `#/staff` + Quản lý cơ sở `#/manager` (gọi `/api/ops/*`, D15) | +| `…/src/app/state/appReducer.js` | Nghiệp vụ phía giao diện (hàm thuần, có test) | +| `…/src/app/state/AppProvider.jsx` | Phiên đăng nhập, 2 chế độ: API / lưu trình duyệt | +| `…/src/shared/api/` | Gọi API + `mappers.js` chuyển dữ liệu backend → giao diện | | `…/BE-CONTRACT.md` | Endpoint giao diện cần backend bổ sung | | `…/BACKEND-TODO.md` | Việc backend còn thiếu, xếp ưu tiên A/B/C, mẫu JSON `GET /api/ops/board` | | `docs/facility-ops-api.md`, `docs/operations-api.md` | API khu Nhân viên / Quản lý cơ sở và khu Vận hành KD | diff --git a/DECISIONS.md b/DECISIONS.md index 7610e57..c1d5c7d 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -167,3 +167,8 @@ - AVAILABLE, MAINTENANCE, OUT_OF_SERVICE được chuyển qua lại bằng thao tác quản lý vận hành nếu ô không có giữ chỗ/hợp đồng chưa đóng. Mỗi lần đổi phải có lý do 1–255 ký tự và ghi unit_status_history trong cùng transaction. - RESERVED/ASSIGNED/OCCUPIED/RETURN_PENDING/INSPECTION thuộc luồng phân bổ, bàn giao, trả kho. Không cho dùng form trạng thái để bỏ qua các bước này. - LOCKED từ giao diện được ánh xạ thành OUT_OF_SERVICE theo tập trạng thái SQL hiện có. Gọi lại cùng trạng thái với lý do hợp lệ không thêm lịch sử trùng. + + +## D25 — 2026-10-20: Tổ chức FE theo vai trò và chức năng + +Theo yêu cầu nhóm, dùng src/app, src/features//, src/shared, src/assets. Tách từng Page từ các file tổng StaffPages/ManagerPages/Units/Auth/Checkout/Public; giữ code dùng chung Staff/Manager ở facility-operations. Giữ URL, API, localStorage và nghiệp vụ. Không đổi hai cấp thư mục gốc FE để không phá lệnh chạy/CI. docs/frontend-naming.md và FRONTEND-MAP.md là hướng dẫn bắt buộc; npm run check:structure kiểm tra quy ước cơ bản. diff --git a/README.md b/README.md index 017e1a3..5f3969d 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ Giao diện SafeSpace hỗ trợ cơ chế hoạt động linh hoạt (dual-mode ``` ┌─────────────────────────────────────────────────────────────┐ -│ App Startup (CustomerApp.jsx) │ +│ App Startup (App.jsx) │ │ ────────────────────────────────────────────────────── │ │ 1. loadServerData() → GET /api/facilities, /unit-types │ │ ├── Success → isLiveApi = true, load real data │ @@ -141,7 +141,7 @@ Giao diện SafeSpace hỗ trợ cơ chế hoạt động linh hoạt (dual-mode ```text SSFRMS/ ├── StorageProject.Api/ # .NET 9 Minimal API, Middleware, Endpoints -│ ├── Endpoints/ # Auth, Facility, Reservation, Contract, Payment, Support... +│ ├── Endpoints/ # Auth, Facility, Reservation, Contract, Payment, SupportPage... │ └── appsettings.json # Cấu hình DB, JWT ├── StorageProject.Core/ # Domain Entities, DTOs, Service Interfaces ├── StorageProject.Infrastructure/ # EF Core DbContext, Migrations, DbSeeder, Service Implementations @@ -149,9 +149,9 @@ SSFRMS/ │ └── SafeSpace-Customer-UI/ # React + Vite Frontend │ ├── src/ │ │ ├── components/ # UI Components (AuthModal, ActionModal, UI Elements) -│ │ ├── pages/ # Pages: FindStorage, Overview, Records, Support +│ │ ├── pages/ # Pages: FindStorage, CustomerDashboardPage, Records, SupportPage │ │ ├── services/ # API Clients & Service Adapters -│ │ ├── CustomerApp.jsx # App Root & State Management +│ │ ├── App.jsx # App Root & State Management │ │ └── customer.css # SafeSpace Modern Design System │ └── .env # Environment Config (VITE_API_URL) └── README.md # Hướng dẫn dự án diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/ADMIN-FLOW-COVERAGE.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/ADMIN-FLOW-COVERAGE.md index f4ab795..0493a3e 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/ADMIN-FLOW-COVERAGE.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/ADMIN-FLOW-COVERAGE.md @@ -8,12 +8,12 @@ tài khoản khác mở `#/admin` sẽ thấy "Không có quyền truy cập". T | Figma | Route | Component | API | |---|---|---|---| -| A01 Quản lý tài khoản | `#/admin` | `admin/AdminUsers.jsx` | `GET dashboard/stats`, `GET users?page&pageSize&searchTerm&status&roleId`, `GET roles`, `GET users/{id}/facilities` (cột Cơ sở phụ trách) | -| (thêm) Chi tiết tài khoản | `#/admin/users/:id` | `admin/AdminUserDetail.jsx` | `GET/PUT users/{id}`, `POST users/{id}/reset-password`, `POST/DELETE users/{id}/roles`, `GET users/{id}/facilities`, `POST user-facilities`, `PUT user-facilities/{id}/status` | -| A02 Thêm & phân quyền tài khoản | `#/admin/new` | `admin/AdminCreateUser.jsx` | `POST users` (+ `POST user-facilities` khi là Nhân viên / Quản lý) | -| A03 Cấu hình quyền truy cập | `#/admin/permissions` | `admin/AdminPermissions.jsx` | `GET roles`, `GET permissions`, `POST/DELETE roles/{id}/permissions` | -| A04 Nhật ký hoạt động | `#/admin/logs` | `admin/AdminLogs.jsx` | `GET logs/login-history`, `GET logs/activity-logs` | -| Thông báo / admin | (chuông) | `admin/AdminShell.jsx` | `GET dashboard/stats`, `GET logs/login-history` | +| A01 Quản lý tài khoản | `#/admin` | `src/features/admin/users/UserListPage.jsx` | `GET dashboard/stats`, `GET users?page&pageSize&searchTerm&status&roleId`, `GET roles`, `GET users/{id}/facilities` (cột Cơ sở phụ trách) | +| (thêm) Chi tiết tài khoản | `#/admin/users/:id` | `src/features/admin/users/UserDetailPage.jsx` | `GET/PUT users/{id}`, `POST users/{id}/reset-password`, `POST/DELETE users/{id}/roles`, `GET users/{id}/facilities`, `POST user-facilities`, `PUT user-facilities/{id}/status` | +| A02 Thêm & phân quyền tài khoản | `#/admin/new` | `src/features/admin/users/CreateUserPage.jsx` | `POST users` (+ `POST user-facilities` khi là Nhân viên / Quản lý) | +| A03 Cấu hình quyền truy cập | `#/admin/permissions` | `src/features/admin/permissions/PermissionListPage.jsx` | `GET roles`, `GET permissions`, `POST/DELETE roles/{id}/permissions` | +| A04 Nhật ký hoạt động | `#/admin/logs` | `src/features/admin/logs/AuditLogPage.jsx` | `GET logs/login-history`, `GET logs/activity-logs` | +| Thông báo / admin | (chuông) | `src/features/admin/AdminLayout.jsx` | `GET dashboard/stats`, `GET logs/login-history` | ## Khác Figma vì backend - **A02**: Figma "Gửi lời mời qua email" nhưng backend chưa gửi email → form có thêm **Tên đăng nhập** (gợi ý từ email) diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/AGENTS.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/AGENTS.md new file mode 100644 index 0000000..2ef4d0a --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/AGENTS.md @@ -0,0 +1,10 @@ +# Hướng dẫn AI khi sửa frontend + +1. Đọc `../../AGENTS.md` và `../../docs/frontend-naming.md` trước khi sửa. +2. Tra `FRONTEND-MAP.md` để xác định đúng vai trò, chức năng, route, provider và API. +3. Dùng `src/features///Page.jsx`; mỗi file một màn hình. +4. Code chung Staff/Manager đặt ở `features/facility-operations`; code toàn app ở `app`, tiện ích chung ở `shared`. +5. Không tái tạo các thư mục nguồn cũ. Không giữ file copy hoặc re-export ở đường dẫn cũ. +6. Cập nhật import, test và bản đồ khi thêm/đổi tên màn hình. Giữ nguyên URL, API và localStorage trừ khi task yêu cầu. +7. Chạy `npm run check:structure`, `npm test`, `npm run test:business`, `npm run test:render`, `npm run build` và init theo hướng dẫn gốc. +8. Không tự push/PR/merge. Bàn giao patch chứa cả thao tác xóa file cũ và thêm file mới. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md index 1048b2c..31c7c47 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BACKEND-TODO.md @@ -9,7 +9,7 @@ endpoint mục A–B; `tests/ops-api.test.mjs` kiểm tra từng endpoint). Back ## Mới 16/10/2026 — API cho các màn đồng bộ Figma (PayOS, thanh toán tại kho, QR mở cửa, F12) -Giao diện **đã gọi sẵn** các endpoint dưới đây (`src/api/endpoints.js`, `src/api/payment-access.js`, `src/ops/api.js`). +Giao diện **đã gọi sẵn** các endpoint dưới đây (`src/shared/api/customerApi.js`, `src/features/customer/access/accessApi.js`, `src/features/facility-operations/api/facilityOperationsApi.js`). Backend chưa có route → giao diện **không báo lỗi**: hiện thông báo thay thế (bảng cột "Khi chưa có") cho tới khi backend làm xong. Máy chủ giả lập đã làm đủ (`npm run dev:mock`), `tests/payment-api.test.mjs` kiểm tra từng endpoint. Làm đúng tên route + tên trường JSON là giao diện chạy ngay, không phải sửa giao diện. JSON camelCase như các endpoint đang có. @@ -127,7 +127,7 @@ Bảng trong DB đã có sẵn (`HandoverRecord`, `ReturnInspection`, `UnitAssig | M07 | `POST /api/ops/contracts/{id}/refund` | — | Chỉ sau biên bản trả kho. Hoàn cọc = cọc − khoản còn nợ; kho → `AVAILABLE`; hợp đồng đóng | | M01/M02/M04 | (trong `GET /api/ops/board`) | — | `units` (12 ô của cơ sở, D17), `revenue` 6 tháng + cơ cấu theo loại kho, tỷ lệ lấp đầy tính từ `units` | -Luật nghiệp vụ chi tiết (điều kiện chặn, chuyển trạng thái) xem `src/ops/reducer.js` — có test `tests/ops.test.js`. +Luật nghiệp vụ chi tiết (điều kiện chặn, chuyển trạng thái) xem `src/features/facility-operations/state/facilityOperationsReducer.js` — có test `tests/ops.test.js`. ### A4. Khách báo đã chuyển khoản (Figma C04) - [x] `POST /api/reservations/{id}/confirm-transfer` → đơn `PENDING_PAYMENT` chuyển `PENDING_VERIFICATION` (để hiện ở @@ -140,8 +140,8 @@ Luật nghiệp vụ chi tiết (điều kiện chặn, chuyển trạng thái) | Việc | Endpoint / thay đổi | Giao diện đang tạm làm gì | |---|---|---| -| Sơ đồ 10 ô kho (C03b-sđ) | `GET /api/facilities/{id}/units` → `unitId, unitNumber, floor, zone, unitTypeId, status` (công khai, không lộ khách thuê) | Tự xếp 10 ô theo loại kho, số ô trống lấy từ availability (`src/lib/units.js`) | -| Bản đồ cơ sở (C02m) | Thêm `latitude, longitude` vào `Facility` + `FacilityDto` (cần migration) | Toạ độ gán cứng theo tên cơ sở (`src/config/geo.js`) | +| Sơ đồ 10 ô kho (C03b-sđ) | `GET /api/facilities/{id}/units` → `unitId, unitNumber, floor, zone, unitTypeId, status` (công khai, không lộ khách thuê) | Tự xếp 10 ô theo loại kho, số ô trống lấy từ availability (`src/shared/utils/units.js`) | +| Bản đồ cơ sở (C02m) | Thêm `latitude, longitude` vào `Facility` + `FacilityDto` (cần migration) | Toạ độ gán cứng theo tên cơ sở (`src/app/config/geo.js`) | | Đăng ký trả kho (C09) | `POST /api/contracts/{id}/move-out` `{ date, slot, note }` → tạo lịch trả kho (hiện ở S04 của nhân viên) | Lưu trong trình duyệt | | Thông báo (chuông) | `GET /api/notifications`, `POST /api/notifications/read` `{ ids? }` | Lưu trong trình duyệt | | Hồ sơ (C13) | `PUT /api/auth/profile` `{ fullName }`, `POST /api/auth/change-password`, `POST /api/auth/forgot-password` | Đổi tên lưu cục bộ; đổi / quên mật khẩu đang khoá | diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md index e5945f5..8b2dd55 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md @@ -3,7 +3,7 @@ # BE-CONTRACT — những gì giao diện khách hàng cần từ backend Giao diện bám Figma nên **khác luồng backend cũ (v3)** ở vài điểm. Tài liệu này là danh sách để sửa BE cho khớp. -Toàn bộ nghiệp vụ hiện nằm ở `src/state/reducer.js`; mỗi lệnh (`CREATE_RESERVATION`, `CONFIRM_TRANSFER`, ...) +Toàn bộ nghiệp vụ hiện nằm ở `src/app/state/appReducer.js`; mỗi lệnh (`CREATE_RESERVATION`, `CONFIRM_TRANSFER`, ...) tương ứng một endpoint dưới đây, nên thay bằng lời gọi API là đủ. ## 0. Hiện trạng nối API @@ -64,7 +64,7 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend: - **Ledger (khoản thu)**: `RECONCILED` Đã thanh toán · `PENDING_VERIFICATION` Chờ thanh toán tại cửa hàng · `DEPOSIT_HELD` Đang giữ cọc · `RENEWAL_PENDING` Chờ duyệt yêu cầu · `UNPAID` Chờ thanh toán (khoản `RENEWAL` chưa trả có nút "Thanh toán" → C11q) · `REFUNDED` - **Appointment**: `kind` = `CHECK_IN` | `MOVE_OUT`; `status` = `CONFIRMED` | `PENDING` | `DONE` | `CANCELLED` - **Ticket**: `OPEN` · `IN_PROGRESS` · `RESOLVED` · `CANCELLED`; `topic` = `ACCESS|LOCK|UNIT|PAYMENT|ITEMS|SCHEDULE|OTHER` -- **Renewal**: `PENDING` | `APPROVED` | `REJECTED` — **Return**: `PENDING` | `SCHEDULED` | `COMPLETED` +- **Renewal**: `PENDING` | `APPROVED` | `REJECTED` — **ReturnRequestPage**: `PENDING` | `SCHEDULED` | `COMPLETED` ## 3. Endpoint cần có @@ -93,21 +93,21 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend: - Tài khoản nhận chuyển khoản đang cấu hình ở `.env` (`VITE_BANK_*`); nếu mỗi cơ sở nhận tiền riêng thì trả kèm theo đơn. - Khoảng cách "Cách bạn X km" cần vị trí khách; hiện lấy từ dữ liệu cơ sở. -- Ảnh cơ sở đang là file tĩnh trong `public/images/`; khi có API ảnh (`GET /api/facilities/{id}/photos`), thay các hàm trong `src/config/media.js`. +- Ảnh cơ sở đang là file tĩnh trong `public/images/`; khi có API ảnh (`GET /api/facilities/{id}/photos`), thay các hàm trong `src/app/config/media.js`. - Khu Nhân viên cơ sở (S01–S09) và Quản lý cơ sở (M01–M08) đã có giao diện, đang chạy trên dữ liệu trong trình duyệt - (`src/ops/`). Endpoint cần có ở mục 5. + (`src/features/facility-operations/`). Endpoint cần có ở mục 5. - Kho dữ liệu cục bộ lưu cả mật khẩu để đăng nhập được khi chưa có server; khi nối API, bỏ trường này. ## 5. Endpoint cho sơ đồ ô kho, bản đồ và khu vận hành (giao diện đã sẵn, đang dùng dữ liệu cục bộ) | Màn | Endpoint đề xuất | Thay ở | |---|---|---| -| C03b-sđ | `GET /api/facilities/{id}/units` → `unitNumber, zone, floor, sizeM2, unitTypeId, status` (StorageUnit) | `unitsFor()` trong `src/lib/units.js`; `fromBackendStatus()` đã map trạng thái | -| C02m | **Đã có** `latitude, longitude` trong `GET /api/facilities` (nhập ở B05a) | `mapCatalog` gán `lat/lng`; `coordsOf()` trong `src/config/geo.js` chỉ dùng toạ độ dự phòng khi cơ sở chưa có toạ độ | -| S01–S09, M01–M08 | `/api/ops/*` — **đã chốt hợp đồng ở `BACKEND-TODO.md` mục A2–A3**, giao diện gọi qua `src/ops/api.js` | `src/ops/store.jsx` | +| C03b-sđ | `GET /api/facilities/{id}/units` → `unitNumber, zone, floor, sizeM2, unitTypeId, status` (StorageUnit) | `unitsFor()` trong `src/shared/utils/units.js`; `fromBackendStatus()` đã map trạng thái | +| C02m | **Đã có** `latitude, longitude` trong `GET /api/facilities` (nhập ở B05a) | `mapCatalog` gán `lat/lng`; `coordsOf()` trong `src/app/config/geo.js` chỉ dùng toạ độ dự phòng khi cơ sở chưa có toạ độ | +| S01–S09, M01–M08 | `/api/ops/*` — **đã chốt hợp đồng ở `BACKEND-TODO.md` mục A2–A3**, giao diện gọi qua `src/features/facility-operations/api/facilityOperationsApi.js` | `src/features/facility-operations/state/FacilityOperationsProvider.jsx` | -Hình dạng dữ liệu giao diện đang dùng nằm ở `src/ops/data.js`; nghiệp vụ (điều kiện chặn, chuyển trạng thái) ở -`src/ops/reducer.js` và có test (`tests/ops.test.js`) để backend đối chiếu. +Hình dạng dữ liệu giao diện đang dùng nằm ở `src/features/facility-operations/data/facilityOperationsSeed.js`; nghiệp vụ (điều kiện chặn, chuyển trạng thái) ở +`src/features/facility-operations/state/facilityOperationsReducer.js` và có test (`tests/ops.test.js`) để backend đối chiếu. ## Bổ sung 20/10 — thu tiền trước phân bổ và trạng thái ô diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BUSINESS-FLOW-COVERAGE.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BUSINESS-FLOW-COVERAGE.md index a16af20..510ac35 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BUSINESS-FLOW-COVERAGE.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BUSINESS-FLOW-COVERAGE.md @@ -4,12 +4,12 @@ Nguồn: Figma section 436:13803; operations-api(3).md do người dùng cung c | Màn | Component | Route | API | |---|---|---|---| -| B01 Tổng quan | business/Overview.jsx | business | GET facilities, reports/facilities, reports/revenue-trend | +| B01 Tổng quan | business/CustomerDashboardPage.jsx | business | GET facilities, reports/facilities, reports/revenue-trend | | B02 Chính sách | business/Policies.jsx | business/policies | GET/POST policies; POST policies/{id}/activate; PUT cho DRAFT | -| B03 Giá & phí | business/Pricing.jsx | business/pricing | GET unit-types, policies, facilities; POST policies và activate | +| B03 Giá & phí | business/PublicPricingPage.jsx | business/pricing | GET unit-types, policies, facilities; POST policies và activate | | B04 Báo cáo | business/Reports.jsx | business/reports | GET reports/facilities, unit-types, revenue-trend, rental-status, export | | B05 Cơ sở | business/Facilities.jsx | business/facilities | GET facilities, rates; điều hướng sang reports với facilityId | -| Header/session | business/BusinessShell.jsx | các route KD | JWT và logout của store chung; notice tổng hợp từ API được tài liệu mô tả | +| Header/session | business/BusinessLayout.jsx | các route KD | JWT và logout của store chung; notice tổng hợp từ API được tài liệu mô tả | Không thêm endpoint ngoài hợp đồng. Không sửa endpoint hay schema backend. Màn Figma không có nút CRUD cơ sở hoặc bảng giá từng cơ sở nên không thêm các nút này vào UI. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md index b1842de..a5e6a13 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/CUSTOMER-FLOW-COVERAGE.md @@ -4,36 +4,36 @@ Nguồn: file Figma "SafeSpace - Modern UI" (section Khách hàng + Trang chủ | Figma | Route | Component | Ghi chú | |---|---|---|---| -| START Trang chủ | `#/home` | `pages/Home.jsx` | Hero tối, 3 điểm nổi bật, 12 cơ sở phân trang 9/trang, CTA đăng ký / đăng nhập | -| A01 Đăng nhập | `#/login` | `pages/Auth.jsx` | Trang riêng; "Quên mật khẩu?" mở hộp thoại; giữ `?next=` để quay lại | -| A02 Đăng ký | `#/register` | `pages/Auth.jsx` | Họ tên, email, SĐT, mật khẩu, xác nhận mật khẩu; tự vào vai trò Khách hàng | -| P01 Bảng giá | `#/pricing` | `pages/Public.jsx` | Giá "Từ" tính từ dữ liệu cơ sở | -| P02 Hướng dẫn | `#/guide` | `pages/Public.jsx` | Accordion +/− | -| C01 Dashboard | `#/overview` | `pages/Overview.jsx` | 3 số liệu, kho đang thuê, hành động nhanh, mốc sắp tới, hoạt động | -| C02 Tìm & đặt kho | `#/find` | `pages/FindList.jsx` | Hiện tất cả cơ sở; lọc loại kho / diện tích / khu vực; chip; sắp xếp; phân trang | -| C02a–f, C03 | `#/find?type=&band=&area=` | `pages/FindList.jsx` | Các trạng thái chọn + kết quả lọc + trail 01→04 | -| Nút Danh sách · Bản đồ | `#/find` ↔ `#/find/map` | `components/Inline.jsx` (`ViewToggle`) | Góc trên phải của C02 và C02m, giữ bộ lọc khi chuyển | -| C01/C06/C14-trống | `#/overview`, `#/units`, `#/reservations` | `components/Inline.jsx` (`EmptyInline`) | Khách chưa có kho / đơn: một dòng thông báo + nút "Tìm & đặt kho" | -| C02m, C02m-1, C02m-2 | `#/find/map` | `pages/FindMap.jsx` | Chỉ có thanh tìm kho + bản đồ Leaflet/OSM (không có danh sách thẻ, Figma 01/10); bấm logo mở "Thông tin cơ sở" + "Xem chi tiết cơ sở" + "Chỉ đường" | -| C03b, C03b-1..3 | `#/find/:id` | `pages/FacilityDetail.jsx` | Loại kho, diện tích, gói 1/3/6 tháng, lịch chọn ngày, chi phí; khối "Chỉ đường đến cơ sở" mở Google Maps (toạ độ D20, chưa có thì theo địa chỉ) | -| C03b-sđ (13 cơ sở) | `#/find/:id?view=map&unit=K01` | `pages/FacilityDetail.jsx`, `components/UnitMap.jsx` | Nút "Xem sơ đồ & tình trạng kho" ↔ "← Xem ảnh & tiện ích"; 10 ô; tóm tắt đổi theo ô; ô không trống → nút xám "Ô này hiện không khả dụng" | -| C03c-1..4 | (lightbox) | `components/Photo.jsx` | 5 ảnh: ảnh cơ sở + 4 ảnh bên trong kho (đã bỏ sơ đồ mặt bằng); ← → / Esc | -| C04 Đặt chỗ & Thanh toán | `#/checkout/:id` | `pages/Checkout.jsx` | Chọn "Thanh toán QR" / "Tại cửa hàng". QR PayOS từ `POST /api/reservations/{id}/payos`, tiền thuê + cọc, đếm ngược 10:00, hỏi trạng thái 3 giây/lần rồi tự sang C05 (D19). Đã bỏ "Tôi đã chuyển khoản" | -| C04c Thanh toán tại cửa hàng | `#/checkout/:id` (chọn "Tại cửa hàng") | `pages/Checkout.jsx` | Giữ chỗ 24 giờ, "Xác nhận đặt chỗ" → `pay-at-facility` (chưa có thì `confirm-transfer`) → C05c | -| C04b Không thành công | `#/checkout/:id/failed` | `pages/Checkout.jsx` | Hết giờ → đơn tự huỷ, kể cả khi đã đóng tab | -| C05 / C05c Xác nhận | `#/confirmation/:id` | `pages/Checkout.jsx` | QR: "Đã thanh toán"; tại cửa hàng: "Đã giữ chỗ cho bạn", số tiền, hạn 24 giờ, "Chờ thanh toán tại cửa hàng" | -| C06 Kho của tôi | `#/units` | `pages/Units.jsx` | | -| C07 / C07b Hợp đồng | `#/units/:id` | `pages/Units.jsx` | Chưa bàn giao (F29): "Xem / Đổi lịch nhận kho", khoá gia hạn, trả kho, mở cửa. Đã bàn giao: "Mở cửa kho" mở C07q. Gia hạn / trả kho khoá khi đang có yêu cầu chờ | -| C07q QR mở cửa | (popup ở `#/units/:id`) | `pages/Units.jsx` (`AccessQrModal`) | `GET /api/contracts/{id}/access-qr`: QR, mã dự phòng, ô kho, hiệu lực; link "Mô phỏng quét ở cửa kho" | -| C07r1 / C07r2 Máy quét | `#/door?unit=&code=` | `pages/Door.jsx` | Mô phỏng máy quét (không cần đăng nhập): `POST /api/access/scan` → "Mở cửa" / "Từ chối" kèm lý do | -| C08 / C08b Gia hạn | `#/units/:id/renew` | `pages/Units.jsx` | Chọn 1/3/6 tháng; chỉ trả tiền thuê kỳ mới, cọc chuyển sang kỳ mới | -| C09 / C09b Trả kho | `#/units/:id/return` | `pages/Units.jsx` | Ngày (lịch), khung giờ, ghi chú, đối chiếu cọc | -| C10 Yêu cầu đã gửi | `#/sent?type=&contract=` | `pages/Units.jsx` | | -| C11 / C11b Thanh toán & lịch hẹn | `#/payments` | `pages/Payments.jsx` | Thẻ lịch hẹn + bảng khoản thu; khoản gia hạn đã duyệt có nút "Thanh toán" → C11q (`components/PayosModal.jsx`, `POST /api/payments/{id}/payos`); trả xong hiện thông báo C11b | -| C12 Hỗ trợ | `#/support` | `pages/Support.jsx` | Có ảnh đính kèm (tối đa 3, 5 MB); danh sách yêu cầu bên phải; khối "Phản hồi của nhân viên" từ `responses[]` của `GET /api/tickets/{id}` | -| C13, C13a–d, toast | `#/profile` | `pages/Profile.jsx` | Chỉ sửa tên; email / SĐT chỉ đọc (SĐT che bớt); hộp thoại "Đã hiểu" | -| C14 / C14a / C14b Đơn đặt chỗ | `#/reservations`, `#/reservations/:id` | `pages/Reservations.jsx`, `pages/Checkout.jsx` | Nút "Huỷ đơn" (đơn chưa nhận kho) → hộp thoại C14a: đã trả, phí huỷ, số tiền hoàn (`cancel-preview`); huỷ xong "Đã huỷ · Đang hoàn tiền" | -| Popup thông báo (public / customer, đã đọc) | (header) | `components/Header.jsx` | | +| START Trang chủ | `#/home` | `src/features/customer/home/HomePage.jsx` | Hero tối, 3 điểm nổi bật, 12 cơ sở phân trang 9/trang, CTA đăng ký / đăng nhập | +| A01 Đăng nhập | `#/login` | `src/features/auth/LoginPage.jsx`, `src/features/auth/RegisterPage.jsx` | Trang riêng; "Quên mật khẩu?" mở hộp thoại; giữ `?next=` để quay lại | +| A02 Đăng ký | `#/register` | `src/features/auth/LoginPage.jsx`, `src/features/auth/RegisterPage.jsx` | Họ tên, email, SĐT, mật khẩu, xác nhận mật khẩu; tự vào vai trò Khách hàng | +| P01 Bảng giá | `#/pricing` | `src/features/customer/pricing/PublicPricingPage.jsx`, `src/features/customer/help/HelpPage.jsx` | Giá "Từ" tính từ dữ liệu cơ sở | +| P02 Hướng dẫn | `#/guide` | `src/features/customer/pricing/PublicPricingPage.jsx`, `src/features/customer/help/HelpPage.jsx` | Accordion +/− | +| C01 Dashboard | `#/overview` | `src/features/customer/dashboard/CustomerDashboardPage.jsx` | 3 số liệu, kho đang thuê, hành động nhanh, mốc sắp tới, hoạt động | +| C02 Tìm & đặt kho | `#/find` | `src/features/customer/facilities/FacilityListPage.jsx` | Hiện tất cả cơ sở; lọc loại kho / diện tích / khu vực; chip; sắp xếp; phân trang | +| C02a–f, C03 | `#/find?type=&band=&area=` | `src/features/customer/facilities/FacilityListPage.jsx` | Các trạng thái chọn + kết quả lọc + trail 01→04 | +| Nút Danh sách · Bản đồ | `#/find` ↔ `#/find/map` | `src/shared/components/Inline.jsx` (`ViewToggle`) | Góc trên phải của C02 và C02m, giữ bộ lọc khi chuyển | +| C01/C06/C14-trống | `#/overview`, `#/units`, `#/reservations` | `src/shared/components/Inline.jsx` (`EmptyInline`) | Khách chưa có kho / đơn: một dòng thông báo + nút "Tìm & đặt kho" | +| C02m, C02m-1, C02m-2 | `#/find/map` | `src/features/customer/facilities/FacilityMapPage.jsx` | Chỉ có thanh tìm kho + bản đồ Leaflet/OSM (không có danh sách thẻ, Figma 01/10); bấm logo mở "Thông tin cơ sở" + "Xem chi tiết cơ sở" + "Chỉ đường" | +| C03b, C03b-1..3 | `#/find/:id` | `src/features/customer/facilities/FacilityDetailPage.jsx` | Loại kho, diện tích, gói 1/3/6 tháng, lịch chọn ngày, chi phí; khối "Chỉ đường đến cơ sở" mở Google Maps (toạ độ D20, chưa có thì theo địa chỉ) | +| C03b-sđ (13 cơ sở) | `#/find/:id?view=map&unit=K01` | `src/features/customer/facilities/FacilityDetailPage.jsx`, `src/shared/components/UnitMap.jsx` | Nút "Xem sơ đồ & tình trạng kho" ↔ "← Xem ảnh & tiện ích"; 10 ô; tóm tắt đổi theo ô; ô không trống → nút xám "Ô này hiện không khả dụng" | +| C03c-1..4 | (lightbox) | `src/shared/components/Photo.jsx` | 5 ảnh: ảnh cơ sở + 4 ảnh bên trong kho (đã bỏ sơ đồ mặt bằng); ← → / Esc | +| C04 Đặt chỗ & Thanh toán | `#/checkout/:id` | `src/features/customer/payments/CheckoutPage.jsx` | Chọn "Thanh toán QR" / "Tại cửa hàng". QR PayOS từ `POST /api/reservations/{id}/payos`, tiền thuê + cọc, đếm ngược 10:00, hỏi trạng thái 3 giây/lần rồi tự sang C05 (D19). Đã bỏ "Tôi đã chuyển khoản" | +| C04c Thanh toán tại cửa hàng | `#/checkout/:id` (chọn "Tại cửa hàng") | `src/features/customer/payments/CheckoutPage.jsx` | Giữ chỗ 24 giờ, "Xác nhận đặt chỗ" → `pay-at-facility` (chưa có thì `confirm-transfer`) → C05c | +| C04b Không thành công | `#/checkout/:id/failed` | `src/features/customer/payments/CheckoutPage.jsx` | Hết giờ → đơn tự huỷ, kể cả khi đã đóng tab | +| C05 / C05c Xác nhận | `#/confirmation/:id` | `src/features/customer/payments/CheckoutPage.jsx` | QR: "Đã thanh toán"; tại cửa hàng: "Đã giữ chỗ cho bạn", số tiền, hạn 24 giờ, "Chờ thanh toán tại cửa hàng" | +| C06 Kho của tôi | `#/units` | `src/features/customer/contracts/RentedUnitListPage.jsx` | | +| C07 / C07b Hợp đồng | `#/units/:id` | `src/features/customer/contracts/RentedUnitListPage.jsx` | Chưa bàn giao (F29): "Xem / Đổi lịch nhận kho", khoá gia hạn, trả kho, mở cửa. Đã bàn giao: "Mở cửa kho" mở C07q. Gia hạn / trả kho khoá khi đang có yêu cầu chờ | +| C07q QR mở cửa | (popup ở `#/units/:id`) | `src/features/customer/contracts/RentedUnitListPage.jsx` (`AccessQrModal`) | `GET /api/contracts/{id}/access-qr`: QR, mã dự phòng, ô kho, hiệu lực; link "Mô phỏng quét ở cửa kho" | +| C07r1 / C07r2 Máy quét | `#/door?unit=&code=` | `src/features/customer/access/DoorScannerPage.jsx` | Mô phỏng máy quét (không cần đăng nhập): `POST /api/access/scan` → "Mở cửa" / "Từ chối" kèm lý do | +| C08 / C08b Gia hạn | `#/units/:id/renew` | `src/features/customer/contracts/RentedUnitListPage.jsx` | Chọn 1/3/6 tháng; chỉ trả tiền thuê kỳ mới, cọc chuyển sang kỳ mới | +| C09 / C09b Trả kho | `#/units/:id/return` | `src/features/customer/contracts/RentedUnitListPage.jsx` | Ngày (lịch), khung giờ, ghi chú, đối chiếu cọc | +| C10 Yêu cầu đã gửi | `#/sent?type=&contract=` | `src/features/customer/contracts/RentedUnitListPage.jsx` | | +| C11 / C11b Thanh toán & lịch hẹn | `#/payments` | `src/features/customer/payments/PaymentListPage.jsx` | Thẻ lịch hẹn + bảng khoản thu; khoản gia hạn đã duyệt có nút "Thanh toán" → C11q (`src/shared/components/PayosModal.jsx`, `POST /api/payments/{id}/payos`); trả xong hiện thông báo C11b | +| C12 Hỗ trợ | `#/support` | `src/features/customer/support/SupportPage.jsx` | Có ảnh đính kèm (tối đa 3, 5 MB); danh sách yêu cầu bên phải; khối "Phản hồi của nhân viên" từ `responses[]` của `GET /api/tickets/{id}` | +| C13, C13a–d, toast | `#/profile` | `src/features/customer/profile/CustomerProfilePage.jsx` | Chỉ sửa tên; email / SĐT chỉ đọc (SĐT che bớt); hộp thoại "Đã hiểu" | +| C14 / C14a / C14b Đơn đặt chỗ | `#/reservations`, `#/reservations/:id` | `src/features/customer/reservations/ReservationListPage.jsx`, `src/features/customer/payments/CheckoutPage.jsx` | Nút "Huỷ đơn" (đơn chưa nhận kho) → hộp thoại C14a: đã trả, phí huỷ, số tiền hoàn (`cancel-preview`); huỷ xong "Đã huỷ · Đang hoàn tiền" | +| Popup thông báo (public / customer, đã đọc) | (header) | `src/shared/components/Header.jsx` | | ## Chỗ Figma tự mâu thuẫn, code chọn như sau - C04 ghi cần chuyển 3.450.000 đ nhưng C03b/C14 ghi "Tổng ban đầu" 4.600.000 đ → chuyển **4.600.000 đ** (tiền thuê + cọc). diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/FRONTEND-MAP.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/FRONTEND-MAP.md new file mode 100644 index 0000000..ec50b68 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/FRONTEND-MAP.md @@ -0,0 +1,177 @@ +# Bản đồ frontend SafeSpace + +Đường dẫn trong bảng tính từ thư mục này. Mở `src/features/` rồi chọn vai trò và chức năng. Quy tắc: `../../docs/frontend-naming.md`. + +## Điểm bắt đầu + +| Việc cần tìm | File | +|---|---| +| Khởi động React | `src/main.jsx` | +| Route tổng và phân quyền trang | `src/app/App.jsx` | +| Đọc/chuyển URL hash | `src/app/router.js` | +| Phiên đăng nhập, dữ liệu chung, lệnh khách hàng | `src/app/state/AppProvider.jsx` | +| API khách hàng và HTTP/JWT | `src/shared/api/customerApi.js`, `src/shared/api/httpClient.js` | +| Chuyển dữ liệu BE sang FE | `src/shared/api/apiMappers.js` | +| Staff/Manager: route, dữ liệu và thao tác | `src/features/facility-operations/FacilityOperationsRoutes.jsx`, `state/FacilityOperationsProvider.jsx`, `api/facilityOperationsApi.js` | +| Admin: route và API | `src/features/admin/AdminRoutes.jsx`, `api/adminApi.js` | +| Business: route và API | `src/features/business/BusinessRoutes.jsx`, `api/businessApi.js` | + +## Tìm màn hình theo chức năng + +| Vai trò / chức năng | File màn hình | +|---|---| +| Quản trị / Nhật ký — AuditLogPage | `src/features/admin/logs/AuditLogPage.jsx` | +| Quản trị / Phân quyền — PermissionListPage | `src/features/admin/permissions/PermissionListPage.jsx` | +| Quản trị / Tài khoản — CreateUserPage | `src/features/admin/users/CreateUserPage.jsx` | +| Quản trị / Tài khoản — UserDetailPage | `src/features/admin/users/UserDetailPage.jsx` | +| Quản trị / Tài khoản — UserListPage | `src/features/admin/users/UserListPage.jsx` | +| Đăng nhập / đăng ký — LoginPage | `src/features/auth/LoginPage.jsx` | +| Đăng nhập / đăng ký — RegisterPage | `src/features/auth/RegisterPage.jsx` | +| Vận hành kinh doanh / Tổng quan — BusinessDashboardPage | `src/features/business/dashboard/BusinessDashboardPage.jsx` | +| Vận hành kinh doanh / Cơ sở kho — FacilityManagementPage | `src/features/business/facilities/FacilityManagementPage.jsx` | +| Vận hành kinh doanh / Chính sách — PolicySettingsPage | `src/features/business/policies/PolicySettingsPage.jsx` | +| Vận hành kinh doanh / Bảng giá — PricingPage | `src/features/business/pricing/PricingPage.jsx` | +| Vận hành kinh doanh / Báo cáo — BusinessReportPage | `src/features/business/reports/BusinessReportPage.jsx` | +| Khách hàng / Mở cửa kho — DoorScannerPage | `src/features/customer/access/DoorScannerPage.jsx` | +| Khách hàng / Hợp đồng / kho đang thuê — RenewalRequestPage | `src/features/customer/contracts/RenewalRequestPage.jsx` | +| Khách hàng / Hợp đồng / kho đang thuê — RentedUnitDetailPage | `src/features/customer/contracts/RentedUnitDetailPage.jsx` | +| Khách hàng / Hợp đồng / kho đang thuê — RentedUnitListPage | `src/features/customer/contracts/RentedUnitListPage.jsx` | +| Khách hàng / Hợp đồng / kho đang thuê — ReturnRequestPage | `src/features/customer/contracts/ReturnRequestPage.jsx` | +| Khách hàng / Tổng quan — CustomerDashboardPage | `src/features/customer/dashboard/CustomerDashboardPage.jsx` | +| Khách hàng / Cơ sở kho — FacilityDetailPage | `src/features/customer/facilities/FacilityDetailPage.jsx` | +| Khách hàng / Cơ sở kho — FacilityListPage | `src/features/customer/facilities/FacilityListPage.jsx` | +| Khách hàng / Cơ sở kho — FacilityMapPage | `src/features/customer/facilities/FacilityMapPage.jsx` | +| Khách hàng / Hướng dẫn — HelpPage | `src/features/customer/help/HelpPage.jsx` | +| Khách hàng / Trang chủ — HomePage | `src/features/customer/home/HomePage.jsx` | +| Khách hàng / Thanh toán — CheckoutFailedPage | `src/features/customer/payments/CheckoutFailedPage.jsx` | +| Khách hàng / Thanh toán — CheckoutPage | `src/features/customer/payments/CheckoutPage.jsx` | +| Khách hàng / Thanh toán — PaymentListPage | `src/features/customer/payments/PaymentListPage.jsx` | +| Khách hàng / Bảng giá — PublicPricingPage | `src/features/customer/pricing/PublicPricingPage.jsx` | +| Khách hàng / Hồ sơ — CustomerProfilePage | `src/features/customer/profile/CustomerProfilePage.jsx` | +| Khách hàng / Yêu cầu — RequestSentPage | `src/features/customer/requests/RequestSentPage.jsx` | +| Khách hàng / Đặt chỗ — ReservationDetailPage | `src/features/customer/reservations/ReservationDetailPage.jsx` | +| Khách hàng / Đặt chỗ — ReservationListPage | `src/features/customer/reservations/ReservationListPage.jsx` | +| Khách hàng / Hỗ trợ — SupportPage | `src/features/customer/support/SupportPage.jsx` | +| Quản lý cơ sở / Phân bổ kho — UnitAllocationPage | `src/features/manager/allocations/UnitAllocationPage.jsx` | +| Quản lý cơ sở / Phân công — StaffAssignmentPage | `src/features/manager/assignments/StaffAssignmentPage.jsx` | +| Quản lý cơ sở / Hợp đồng / kho đang thuê — ContractListPage | `src/features/manager/contracts/ContractListPage.jsx` | +| Quản lý cơ sở / Tổng quan — ManagerDashboardPage | `src/features/manager/dashboard/ManagerDashboardPage.jsx` | +| Quản lý cơ sở / Gia hạn — RenewalApprovalPage | `src/features/manager/renewals/RenewalApprovalPage.jsx` | +| Quản lý cơ sở / Báo cáo — FacilityReportPage | `src/features/manager/reports/FacilityReportPage.jsx` | +| Quản lý cơ sở / Kết quả — ManagerResultPage | `src/features/manager/results/ManagerResultPage.jsx` | +| Quản lý cơ sở / Quản lý ô kho — UnitManagementPage | `src/features/manager/units/UnitManagementPage.jsx` | +| Nhân viên / Tổng quan — StaffDashboardPage | `src/features/staff/dashboard/StaffDashboardPage.jsx` | +| Nhân viên / Xác minh / bàn giao — CustomerVerificationPage | `src/features/staff/handovers/CustomerVerificationPage.jsx` | +| Nhân viên / Xác minh / bàn giao — HandoverPage | `src/features/staff/handovers/HandoverPage.jsx` | +| Nhân viên / Thanh toán — PaymentConfirmationPage | `src/features/staff/payments/PaymentConfirmationPage.jsx` | +| Nhân viên / Kết quả — StaffResultPage | `src/features/staff/results/StaffResultPage.jsx` | +| Nhân viên / Trả kho — ReturnInspectionPage | `src/features/staff/returns/ReturnInspectionPage.jsx` | +| Nhân viên / Hỗ trợ — StaffSupportPage | `src/features/staff/support/StaffSupportPage.jsx` | + +## Các URL thường dùng + +| Muốn mở | URL hash | +|---|---| +| Tìm cơ sở / bản đồ / chi tiết | `#/find`, `#/find/map`, `#/find/:id` | +| Đặt chỗ / thanh toán / kết quả | `#/reservations`, `#/checkout/:id`, `#/confirmation/:id` | +| Kho thuê / gia hạn / trả kho | `#/units`, `#/units/:id/renew`, `#/units/:id/return` | +| Nhân viên thu tiền / xác minh / bàn giao | `#/staff/reconcile`, `#/staff/verify`, `#/staff/handover` | +| Quản lý ô / phân bổ / gia hạn | `#/manager/units`, `#/manager/allocate`, `#/manager/renewals` | +| Vận hành kinh doanh / quản trị | `#/business`, `#/admin` | + +## Ví dụ lần theo code + +- Chỉ đường: `features/customer/facilities/FacilityDetailPage.jsx`; bản đồ tìm cơ sở: `FacilityMapPage.jsx`; toạ độ mặc định: `app/config/geo.js`. +- Thanh toán khách: `features/customer/payments/CheckoutPage.jsx` → `app/state/AppProvider.jsx` → `shared/api/customerApi.js` → BE. +- Thu tiền tại quầy: `features/staff/payments/PaymentConfirmationPage.jsx` → `features/facility-operations/state/FacilityOperationsProvider.jsx` → `api/facilityOperationsApi.js`. +- Các đường dẫn rút gọn trong ví dụ tính theo thư mục feature được nêu; bảng màn hình phía trên có đường dẫn đầy đủ. + +## Chuyển từ đường dẫn cũ + +| File cũ | Vị trí mới | +|---|---| +| `src/CustomerApp.jsx` | `src/app/App.jsx` | +| `src/admin/AdminApp.jsx` | `src/features/admin/AdminRoutes.jsx` | +| `src/admin/AdminCreateUser.jsx` | `src/features/admin/users/CreateUserPage.jsx` | +| `src/admin/AdminLogs.jsx` | `src/features/admin/logs/AuditLogPage.jsx` | +| `src/admin/AdminPermissions.jsx` | `src/features/admin/permissions/PermissionListPage.jsx` | +| `src/admin/AdminShell.jsx` | `src/features/admin/AdminLayout.jsx` | +| `src/admin/AdminUserDetail.jsx` | `src/features/admin/users/UserDetailPage.jsx` | +| `src/admin/AdminUsers.jsx` | `src/features/admin/users/UserListPage.jsx` | +| `src/admin/util.js` | `src/features/admin/utils/adminUtils.js` | +| `src/api/admin.js` | `src/features/admin/api/adminApi.js` | +| `src/api/business.js` | `src/features/business/api/businessApi.js` | +| `src/api/endpoints.js` | `src/shared/api/customerApi.js` | +| `src/api/http.js` | `src/shared/api/httpClient.js` | +| `src/api/mappers.js` | `src/shared/api/apiMappers.js` | +| `src/api/payment-access.js` | `src/features/customer/access/accessApi.js` | +| `src/business/BusinessApp.jsx` | `src/features/business/BusinessRoutes.jsx` | +| `src/business/BusinessShell.jsx` | `src/features/business/BusinessLayout.jsx` | +| `src/business/Facilities.jsx` | `src/features/business/facilities/FacilityManagementPage.jsx` | +| `src/business/Overview.jsx` | `src/features/business/dashboard/BusinessDashboardPage.jsx` | +| `src/business/Policies.jsx` | `src/features/business/policies/PolicySettingsPage.jsx` | +| `src/business/Pricing.jsx` | `src/features/business/pricing/PricingPage.jsx` | +| `src/business/Reports.jsx` | `src/features/business/reports/BusinessReportPage.jsx` | +| `src/business/actions.js` | `src/features/business/policies/policyActions.js` | +| `src/business/design.css` | `src/features/business/business.css` | +| `src/business/export.js` | `src/features/business/reports/reportExport.js` | +| `src/business/facility-form.js` | `src/features/business/facilities/facilityForm.js` | +| `src/business/format.js` | `src/features/business/utils/businessFormat.js` | +| `src/business/parts.jsx` | `src/features/business/components/BusinessComponents.jsx` | +| `src/business/policy-fields.js` | `src/features/business/policies/policyFields.js` | +| `src/components/AccessQr.jsx` | `src/shared/components/AccessQr.jsx` | +| `src/components/Header.jsx` | `src/shared/components/Header.jsx` | +| `src/components/Inline.jsx` | `src/shared/components/Inline.jsx` | +| `src/components/PayOSEmbeddedModal.jsx` | `src/shared/components/PayOSEmbeddedModal.jsx` | +| `src/components/PaymentQr.jsx` | `src/shared/components/PaymentQr.jsx` | +| `src/components/PayosModal.jsx` | `src/shared/components/PayosModal.jsx` | +| `src/components/Photo.jsx` | `src/shared/components/Photo.jsx` | +| `src/components/Pickers.jsx` | `src/shared/components/Pickers.jsx` | +| `src/components/QrCode.jsx` | `src/shared/components/QrCode.jsx` | +| `src/components/SearchBar.jsx` | `src/shared/components/SearchBar.jsx` | +| `src/components/UI.jsx` | `src/shared/components/UI.jsx` | +| `src/components/UnitMap.jsx` | `src/shared/components/UnitMap.jsx` | +| `src/config/api.js` | `src/app/config/api.js` | +| `src/config/geo.js` | `src/app/config/geo.js` | +| `src/config/media.js` | `src/app/config/media.js` | +| `src/config/payment.js` | `src/app/config/payment.js` | +| `src/data/seed.js` | `src/app/data/appSeed.js` | +| `src/lib/access.js` | `src/shared/utils/access.js` | +| `src/lib/catalog.js` | `src/shared/utils/catalog.js` | +| `src/lib/format.js` | `src/shared/utils/format.js` | +| `src/lib/hooks.js` | `src/shared/hooks/useBrowserEvents.js` | +| `src/lib/roles.js` | `src/shared/utils/roles.js` | +| `src/lib/router.js` | `src/app/router.js` | +| `src/lib/status.js` | `src/shared/utils/status.js` | +| `src/lib/units.js` | `src/shared/utils/units.js` | +| `src/lib/vietqr.js` | `src/shared/utils/vietqr.js` | +| `src/ops/OpsApp.jsx` | `src/features/facility-operations/FacilityOperationsRoutes.jsx` | +| `src/ops/OpsShell.jsx` | `src/features/facility-operations/FacilityOperationsLayout.jsx` | +| `src/ops/api.js` | `src/features/facility-operations/api/facilityOperationsApi.js` | +| `src/ops/data.js` | `src/features/facility-operations/data/facilityOperationsSeed.js` | +| `src/ops/reducer.js` | `src/features/facility-operations/state/facilityOperationsReducer.js` | +| `src/ops/store.jsx` | `src/features/facility-operations/state/FacilityOperationsProvider.jsx` | +| `src/ops/tasks.jsx` | `src/features/facility-operations/components/StaffTasks.jsx` | +| `src/ops/util.jsx` | `src/features/facility-operations/components/FacilityOperationsComponents.jsx` | +| `src/pages/Door.jsx` | `src/features/customer/access/DoorScannerPage.jsx` | +| `src/pages/FacilityDetail.jsx` | `src/features/customer/facilities/FacilityDetailPage.jsx` | +| `src/pages/FindList.jsx` | `src/features/customer/facilities/FacilityListPage.jsx` | +| `src/pages/FindMap.jsx` | `src/features/customer/facilities/FacilityMapPage.jsx` | +| `src/pages/Home.jsx` | `src/features/customer/home/HomePage.jsx` | +| `src/pages/Overview.jsx` | `src/features/customer/dashboard/CustomerDashboardPage.jsx` | +| `src/pages/Payments.jsx` | `src/features/customer/payments/PaymentListPage.jsx` | +| `src/pages/Profile.jsx` | `src/features/customer/profile/CustomerProfilePage.jsx` | +| `src/pages/Reservations.jsx` | `src/features/customer/reservations/ReservationListPage.jsx` | +| `src/pages/Support.jsx` | `src/features/customer/support/SupportPage.jsx` | +| `src/state/reducer.js` | `src/app/state/appReducer.js` | +| `src/state/selectors.js` | `src/app/state/appSelectors.js` | +| `src/state/store.jsx` | `src/app/state/AppProvider.jsx` | +| `src/state/useAccessQr.js` | `src/features/customer/access/useAccessQr.js` | +| `src/styles/access-qr.css` | `src/shared/styles/access-qr.css` | +| `src/styles/ss.css` | `src/shared/styles/ss.css` | +| `src/ops/StaffPages.jsx` | `src/features/staff/hooks/useStaffIdentity.js`, `src/features/staff/dashboard/StaffDashboardPage.jsx`, `src/features/staff/payments/PaymentConfirmationPage.jsx`, `src/features/staff/handovers/CustomerVerificationPage.jsx`, `src/features/staff/handovers/HandoverPage.jsx`, `src/features/staff/returns/ReturnInspectionPage.jsx`, `src/features/staff/support/StaffSupportPage.jsx`, `src/features/staff/results/StaffResultPage.jsx`, `src/features/facility-operations/utils/unitStateTag.js` | +| `src/ops/ManagerPages.jsx` | `src/features/manager/dashboard/ManagerDashboardPage.jsx`, `src/features/manager/units/UnitManagementPage.jsx`, `src/features/manager/allocations/UnitAllocationPage.jsx`, `src/features/manager/components/PageHeaderBlock.jsx`, `src/features/manager/assignments/StaffAssignmentPage.jsx`, `src/features/manager/renewals/RenewalApprovalPage.jsx`, `src/features/manager/contracts/ContractListPage.jsx`, `src/features/manager/reports/FacilityReportPage.jsx`, `src/features/manager/results/ManagerResultPage.jsx` | +| `src/pages/Units.jsx` | `src/features/customer/contracts/components/ContractNotFound.jsx`, `src/features/customer/contracts/RentedUnitListPage.jsx`, `src/features/customer/access/AccessQrModal.jsx`, `src/features/customer/contracts/RentedUnitDetailPage.jsx`, `src/features/customer/contracts/RenewalRequestPage.jsx`, `src/features/customer/contracts/ReturnRequestPage.jsx`, `src/features/customer/requests/RequestSentPage.jsx` | +| `src/pages/Checkout.jsx` | `src/features/customer/reservations/components/ReservationNotFound.jsx`, `src/features/customer/payments/CheckoutPage.jsx`, `src/features/customer/payments/CheckoutFailedPage.jsx`, `src/features/customer/reservations/ReservationDetailPage.jsx` | +| `src/pages/Auth.jsx` | `src/features/auth/utils/safeNext.js`, `src/features/auth/components/ForgotPasswordDialog.jsx`, `src/features/auth/LoginPage.jsx`, `src/features/auth/RegisterPage.jsx` | +| `src/pages/Public.jsx` | `src/features/customer/pricing/PublicPricingPage.jsx`, `src/features/customer/help/HelpPage.jsx` | diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/OPS-FLOW-COVERAGE.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/OPS-FLOW-COVERAGE.md index c8db328..620d1ad 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/OPS-FLOW-COVERAGE.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/OPS-FLOW-COVERAGE.md @@ -1,7 +1,7 @@ # Đối chiếu Figma ↔ code: Nhân viên cơ sở & Quản lý cơ sở Nguồn: file Figma "SafeSpace - Modern UI", section *SafeSpace · Nhân viên cơ sở* và *SafeSpace · Quản lý cơ sở*. -Dữ liệu: `src/ops/data.js` (khởi tạo) · nghiệp vụ: `src/ops/reducer.js` (có test) · lưu: `src/ops/store.jsx`. +Dữ liệu: `src/features/facility-operations/data/facilityOperationsSeed.js` (khởi tạo) · nghiệp vụ: `src/features/facility-operations/state/facilityOperationsReducer.js` (có test) · lưu: `src/features/facility-operations/state/FacilityOperationsProvider.jsx`. ## Nhân viên cơ sở (`#/staff`) diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md index 8001a44..b32b31d 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/README.md @@ -1,3 +1,5 @@ +> **Tìm code:** đọc [FRONTEND-MAP.md](FRONTEND-MAP.md). Quy tắc đặt tên: [frontend-naming.md](../../docs/frontend-naming.md). + # SafeSpace — Giao diện khách hàng & quản trị hệ thống React + Vite, bám theo file Figma **SafeSpace - Modern UI**: Trang chủ, Đăng nhập, Đăng ký, Bảng giá, @@ -65,10 +67,10 @@ Muốn làm lại từ đầu: xoá `safespace.ops.v1` và `safespace.customer.v | Thanh toán QR PayOS (C04, C11q), thanh toán tại cửa hàng (C04c), QR mở cửa + máy quét `#/door` (C07q/C07r), phản hồi hỗ trợ (C12), xem trước hoàn tiền (C14a), đổi trạng thái ô (M02a) | Giao diện **gọi sẵn** endpoint theo `BACKEND-TODO.md` mục "Mới 16/10"; backend chưa có (404/405) → hiện thông báo thay thế, thanh toán tại cửa hàng tự dùng `confirm-transfer`. Thử đủ luồng: `MOCK_OPS=1 npm run dev:mock`; thử như backend chưa cập nhật: thêm `MOCK_LEGACY=1` | | Đăng ký trả kho, thông báo, đổi tên hiển thị, ảnh đính kèm hỗ trợ | Backend **chưa có API** → lưu trong trình duyệt theo từng tài khoản | | Đổi mật khẩu, quên mật khẩu | Backend chưa có API → giao diện hướng dẫn liên hệ quản trị viên | -| Sơ đồ tình trạng 10 ô kho, toạ độ cơ sở trên bản đồ | Backend chưa có API → sinh cố định theo cơ sở (`src/lib/units.js`, `src/config/geo.js`) | -| Toàn bộ khu Nhân viên / Quản lý cơ sở | Đăng nhập qua API (vai trò `STAFF` / `MANAGER` trong JWT); dữ liệu vận hành lưu trong trình duyệt (`src/ops/`) cho đến khi backend có API (xem mục 5 của `BE-CONTRACT.md`) | +| Sơ đồ tình trạng 10 ô kho, toạ độ cơ sở trên bản đồ | Backend chưa có API → sinh cố định theo cơ sở (`src/shared/utils/units.js`, `src/app/config/geo.js`) | +| Toàn bộ khu Nhân viên / Quản lý cơ sở | Đăng nhập qua API (vai trò `STAFF` / `MANAGER` trong JWT); dữ liệu vận hành lưu trong trình duyệt (`src/features/facility-operations/`) cho đến khi backend có API (xem mục 5 của `BE-CONTRACT.md`) | -Khi backend bổ sung API cho các dòng cuối, chỉ cần sửa `src/state/store.jsx` (nhánh `ApiProvider`), xem `BE-CONTRACT.md`. +Khi backend bổ sung API cho các dòng cuối, chỉ cần sửa `src/app/state/AppProvider.jsx` (nhánh `ApiProvider`), xem `BE-CONTRACT.md`. ## Kiểm tra @@ -84,7 +86,7 @@ npm run build # xuất bản dist/ (đường dẫn tương đối, đặ Toàn bộ ảnh nằm sẵn trong `public/images/` (đã nén JPG, tổng ~3,9 MB): ảnh hero trang chủ, ảnh mặt tiền 9 cơ sở, 4 ảnh bên trong kho và 3 sơ đồ mặt bằng. Khi bấm xem một cơ sở, thư viện ảnh gồm ảnh cơ sở và 4 ảnh bên trong kho (sơ đồ mặt bằng không còn trong thư viện theo Figma 30/09; file vẫn giữ trong `public/images/plans/`). Chi tiết ở -`public/images/README.md`; đổi cách gán ảnh ở `src/config/media.js`. +`public/images/README.md`; đổi cách gán ảnh ở `src/app/config/media.js`. ## Thanh toán @@ -96,14 +98,14 @@ chuyển khoản; ứng dụng ngân hàng quét là điền sẵn cả ba. Đơ ``` src/ - CustomerApp.jsx router + chặn trang cần đăng nhập + App.jsx router + chặn trang cần đăng nhập pages/ mỗi màn Figma một component (xem CUSTOMER-FLOW-COVERAGE.md) components/ Header + thông báo, lịch chọn ngày, thư viện ảnh, mã QR, UI dùng chung state/reducer.js nghiệp vụ (thuần, có test) state/store.jsx phiên đăng nhập; 2 chế độ: dữ liệu trong trình duyệt / API backend api/ gọi API (http.js, endpoints.js, admin.js) + chuyển dữ liệu backend → giao diện (mappers.js) - admin/ khu quản trị: AdminShell, AdminUsers, AdminUserDetail, AdminCreateUser, AdminPermissions, AdminLogs - ops/ khu nhân viên & quản lý cơ sở: OpsShell, StaffPages, ManagerPages, data (khởi tạo), reducer (nghiệp vụ), store + admin/ khu quản trị: AdminLayout, UserListPage, UserDetailPage, CreateUserPage, PermissionListPage, AuditLogPage + ops/ khu nhân viên & quản lý cơ sở: FacilityOperationsLayout, StaffPages, ManagerPages, data (khởi tạo), reducer (nghiệp vụ), store data/seed.js dữ liệu khởi tạo: 12 cơ sở, khách hàng Nguyễn Thị Mai config/ địa chỉ API, ảnh, tài khoản nhận chuyển khoản ``` diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs index e4782e8..898a7a6 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-api.mjs @@ -3,8 +3,8 @@ // Dữ liệu nằm trong bộ nhớ, tắt là mất. Không thay thế backend thật. import http from "node:http"; import { handleBusiness, seedBusiness } from "./mock-business.mjs"; -import { createOpsData } from "../src/ops/data.js"; -import { reduceOps } from "../src/ops/reducer.js"; +import { createOpsData } from "../src/features/facility-operations/data/facilityOperationsSeed.js"; +import { reduceOps } from "../src/features/facility-operations/state/facilityOperationsReducer.js"; const pad = (n) => String(n).padStart(2, "0"); const iso = (d) => d.toISOString(); // DateTime.UtcNow trả về khi vừa tạo: có "Z" diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json index 27daabb..de3873f 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/package.json @@ -11,7 +11,8 @@ "preview": "vite preview --host 127.0.0.1", "test": "node --test tests/reducer.test.js tests/api-mappers.test.js tests/admin.test.js tests/ops.test.js tests/units.test.js tests/ops-api.test.mjs tests/payment-access.test.js tests/payment-api.test.mjs tests/access.test.js", "test:render": "node tests/render.test.mjs", - "dev:mock": "node scripts/dev-mock.mjs" + "dev:mock": "node scripts/dev-mock.mjs", + "check:structure": "node scripts/check-structure.mjs" }, "dependencies": { "@fontsource/inter": "^5.3.0", diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/check-structure.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/check-structure.mjs new file mode 100644 index 0000000..0bf92f3 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/scripts/check-structure.mjs @@ -0,0 +1,36 @@ +import { readdirSync, readFileSync } from 'node:fs'; +import { dirname, join, basename, relative } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = join(dirname(fileURLToPath(import.meta.url)), '..', 'src'); +const allowed = new Set(['main.jsx', 'app', 'features', 'shared', 'assets']); +const errors = []; +for (const entry of readdirSync(root)) { + if (!allowed.has(entry)) errors.push(`Unexpected src entry: ${entry}`); +} +function inspect(directory) { + for (const entry of readdirSync(directory, { withFileTypes: true })) { + const file = join(directory, entry.name); + const name = relative(root, file); + if (entry.isDirectory()) { + if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(entry.name)) errors.push(`Use kebab-case directory: ${name}`); + inspect(file); + } else if (entry.name.endsWith('.jsx')) { + if (entry.name !== 'main.jsx' && !/^[A-Z][A-Za-z0-9]*\.jsx$/.test(entry.name)) errors.push(`Use PascalCase JSX filename: ${name}`); + if (entry.name.endsWith('Page.jsx')) { + const source = readFileSync(file, 'utf8'); + const component = basename(file, '.jsx'); + if (!new RegExp(`export (?:default )?function ${component}\\b`).test(source)) errors.push(`Export a page component named ${component}: ${name}`); + const pages = [...source.matchAll(/export (?:default )?function (\w+Page)\b/g)]; + if (pages.length !== 1) errors.push(`Keep one page per file: ${name}`); + } + } else if (entry.name.endsWith('.js') && !/^[a-z][A-Za-z0-9]*\.js$/.test(entry.name)) { + errors.push(`Use camelCase JS filename: ${name}`); + } + } +} +inspect(root); +if (errors.length) { + console.error(errors.join('\n')); + process.exitCode = 1; +} else console.log('Frontend structure and page naming: PASS'); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminLogs.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminLogs.jsx deleted file mode 100644 index 9dc0387..0000000 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminLogs.jsx +++ /dev/null @@ -1,143 +0,0 @@ -import React, { useMemo, useState } from "react"; -import { adminApi } from "../api/admin"; -import { parseUtc } from "../api/mappers"; -import { DatePicker, Pagination } from "../components/Pickers"; -import { Notice } from "../components/UI"; -import { ACTION_GROUPS, roleLabel, sortRoles } from "../lib/roles"; -import { useApp } from "../state/store"; -import { dateTime, describeActivity, useLoad } from "./util"; - -const TABS = [ - ["all", "Tất cả"], - ["login", "Đăng nhập"], - ["data", "Thay đổi dữ liệu"], - ["access", "Phân quyền"], -]; -const PAGE_SIZE = 10; -const FETCH = 100; // số bản ghi mới nhất lấy mỗi loại để gộp / lọc ở trình duyệt - -// Ngày địa phương → mốc UTC để gửi backend -const startOf = (d) => (d ? new Date(`${d}T00:00:00`).toISOString() : undefined); -const endOf = (d) => (d ? new Date(`${d}T23:59:59`).toISOString() : undefined); - -export default function AdminLogs() { - const { onApiError } = useApp(); - const [tab, setTab] = useState("all"); - const [from, setFrom] = useState(""); - const [to, setTo] = useState(""); - const [page, setPage] = useState(1); - - const users = useLoad(async () => { - const res = await adminApi.users({ page: 1, pageSize: 500 }); - return new Map(res.items.map((u) => [u.userId, u])); - }, [], onApiError); - - const logs = useLoad(async () => { - const range = { fromDate: startOf(from), toDate: endOf(to) }; - if (tab === "login") return { login: await adminApi.loginHistory({ page, pageSize: PAGE_SIZE, ...range }) }; - const [login, activity] = await Promise.all([ - tab === "all" ? adminApi.loginHistory({ page: 1, pageSize: FETCH, ...range }) : null, - adminApi.activityLogs({ page: 1, pageSize: FETCH, ...range }), - ]); - return { login, activity }; - }, [tab, from, to, tab === "login" ? page : 0], onApiError); - - const userMap = users.data || new Map(); - const nameOf = (id) => userMap.get(id)?.fullName; - const rolesOf = (id) => sortRoles(userMap.get(id)?.roles || []).map(roleLabel).join(", ") || "—"; - - const rows = useMemo(() => { - const d = logs.data; - if (!d) return []; - const loginRows = (d.login?.items || []).map((h) => ({ - id: `L${h.loginHistoryId}`, - at: h.loginAt, - userId: h.userId, - user: h.fullName || h.username, - action: `${h.loginStatus === "SUCCESS" ? "Đăng nhập thành công" : `Đăng nhập ${h.loginStatus === "FAILED" ? "thất bại" : h.loginStatus.toLowerCase()}`}${h.logoutAt ? ` · đăng xuất ${dateTime(h.logoutAt).slice(11)}` : ""}`, - ip: h.ipAddress || "—", - device: h.deviceInfo, - })); - if (tab === "login") return loginRows; - const group = ACTION_GROUPS[tab]; - const actRows = (d.activity?.items || []) - .filter((a) => !group || group.includes(a.action)) - .map((a) => ({ - id: `A${a.logId}`, - at: a.loggedAt, - userId: a.userId, - user: a.userId ? nameOf(a.userId) || a.username || `#${a.userId}` : "Hệ thống", - action: describeActivity(a, nameOf), - ip: a.ipAddress || "—", - })); - return [...loginRows, ...actRows].sort((x, y) => (parseUtc(y.at)?.getTime() || 0) - (parseUtc(x.at)?.getTime() || 0)); - }, [logs.data, tab, userMap]); // eslint-disable-line react-hooks/exhaustive-deps - - const serverPaged = tab === "login"; - const total = serverPaged ? logs.data?.login?.totalItems || 0 : rows.length; - const pages = Math.max(1, Math.ceil(total / PAGE_SIZE)); - const current = Math.min(page, pages); - const shown = serverPaged ? rows : rows.slice((current - 1) * PAGE_SIZE, current * PAGE_SIZE); - const first = (current - 1) * PAGE_SIZE + 1; - - const pick = (fn) => (v) => { - fn(v); - setPage(1); - }; - - return ( -
-
-
-

Lịch sử đăng nhập & nhật ký hoạt động

-

Theo dõi đăng nhập, thay đổi dữ liệu tài khoản và phân quyền trong hệ thống.

-
-
- -
-
- {TABS.map(([k, label]) => ( - - ))} -
-
- - - {(from || to) && ( - - )} -
-
- - {logs.error && {logs.error}} -
- - - - - - {shown.map((r) => ( - - - - - - - - ))} - {!logs.loading && shown.length === 0 && ( - - )} - {logs.loading && !logs.data && ( - - )} - -
Thời gianNgười dùngVai tròHành độngĐịa chỉ IP
{dateTime(r.at)}{r.user}{r.userId ? rolesOf(r.userId) : "—"}{r.action}{r.ip}
Chưa có hoạt động trong khoảng thời gian này.
Đang tải nhật ký…
-
- - {!serverPaged && total >= FETCH &&

Hiển thị {FETCH} bản ghi mới nhất mỗi loại. Dùng bộ lọc ngày để xem các mốc cũ hơn.

} -
- ); -} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/App.jsx similarity index 64% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/App.jsx index f528eb0..b182e73 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/CustomerApp.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/App.jsx @@ -8,31 +8,39 @@ import "@fontsource/inter/latin-700.css"; import "@fontsource/inter/vietnamese-700.css"; import "@fontsource/inter/latin-800.css"; import "@fontsource/inter/vietnamese-800.css"; -import "./styles/ss.css"; +import "../shared/styles/ss.css"; import React, { useEffect } from "react"; -import Header from "./components/Header"; -import { Button, Empty, Icon, LinkButton } from "./components/UI"; -import { go, parseRoute, useRoute } from "./lib/router"; -import { Login, Register } from "./pages/Auth"; -import { Checkout, CheckoutFailed, ReservationSummary } from "./pages/Checkout"; -import FacilityDetail from "./pages/FacilityDetail"; -import FindList from "./pages/FindList"; -import FindMap from "./pages/FindMap"; -import Home from "./pages/Home"; -import Overview from "./pages/Overview"; -import Door from "./pages/Door"; -import Payments from "./pages/Payments"; -import Profile from "./pages/Profile"; -import { Guide, Pricing } from "./pages/Public"; -import AdminApp from "./admin/AdminApp"; -import BusinessApp from "./business/BusinessApp"; -import { homeFor, isBusinessRoles, isManagerRoles, isOpsRoles, isStaffRoles } from "./lib/roles"; -import OpsApp from "./ops/OpsApp"; -import { OpsProvider } from "./ops/store"; -import Reservations from "./pages/Reservations"; -import Support from "./pages/Support"; -import { Renew, Return, Sent, UnitDetail, Units } from "./pages/Units"; -import { AppProvider, useApp } from "./state/store"; +import Header from "../shared/components/Header.jsx"; +import { Button, Empty, Icon, LinkButton } from "../shared/components/UI.jsx"; +import { go, parseRoute, useRoute } from "./router.js"; +import { LoginPage } from "../features/auth/LoginPage.jsx"; +import { RegisterPage } from "../features/auth/RegisterPage.jsx"; +import { CheckoutPage } from "../features/customer/payments/CheckoutPage.jsx"; +import { CheckoutFailedPage } from "../features/customer/payments/CheckoutFailedPage.jsx"; +import { ReservationDetailPage } from "../features/customer/reservations/ReservationDetailPage.jsx"; +import FacilityDetailPage from "../features/customer/facilities/FacilityDetailPage.jsx"; +import FacilityListPage from "../features/customer/facilities/FacilityListPage.jsx"; +import FacilityMapPage from "../features/customer/facilities/FacilityMapPage.jsx"; +import HomePage from "../features/customer/home/HomePage.jsx"; +import CustomerDashboardPage from "../features/customer/dashboard/CustomerDashboardPage.jsx"; +import DoorScannerPage from "../features/customer/access/DoorScannerPage.jsx"; +import PaymentListPage from "../features/customer/payments/PaymentListPage.jsx"; +import CustomerProfilePage from "../features/customer/profile/CustomerProfilePage.jsx"; +import { HelpPage } from "../features/customer/help/HelpPage.jsx"; +import { PublicPricingPage } from "../features/customer/pricing/PublicPricingPage.jsx"; +import AdminRoutes from "../features/admin/AdminRoutes.jsx"; +import BusinessRoutes from "../features/business/BusinessRoutes.jsx"; +import { homeFor, isBusinessRoles, isManagerRoles, isOpsRoles, isStaffRoles } from "../shared/utils/roles.js"; +import FacilityOperationsRoutes from "../features/facility-operations/FacilityOperationsRoutes.jsx"; +import { OpsProvider } from "../features/facility-operations/state/FacilityOperationsProvider.jsx"; +import ReservationListPage from "../features/customer/reservations/ReservationListPage.jsx"; +import SupportPage from "../features/customer/support/SupportPage.jsx"; +import { RenewalRequestPage } from "../features/customer/contracts/RenewalRequestPage.jsx"; +import { ReturnRequestPage } from "../features/customer/contracts/ReturnRequestPage.jsx"; +import { RequestSentPage } from "../features/customer/requests/RequestSentPage.jsx"; +import { RentedUnitDetailPage } from "../features/customer/contracts/RentedUnitDetailPage.jsx"; +import { RentedUnitListPage } from "../features/customer/contracts/RentedUnitListPage.jsx"; +import { AppProvider, useApp } from "./state/AppProvider.jsx"; const TITLES = { home: "Trang chủ", @@ -63,26 +71,26 @@ const PRIVATE = ["overview", "units", "reservations", "payments", "support", "pr function renderPage({ page, parts, query }) { const [a, b] = parts; switch (page) { - case "home": return ; - case "login": return ; - case "register": return ; - case "pricing": return ; - case "guide": return ; - case "find": return a === "map" ? : a ? : ; - case "checkout": return b === "failed" ? : ; - case "confirmation": return ; - case "overview": return ; - case "reservations": return a ? : ; + case "home": return ; + case "login": return ; + case "register": return ; + case "pricing": return ; + case "guide": return ; + case "find": return a === "map" ? : a ? : ; + case "checkout": return b === "failed" ? : ; + case "confirmation": return ; + case "overview": return ; + case "reservations": return a ? : ; case "units": - if (a && b === "renew") return ; - if (a && b === "return") return ; - return a ? : ; - case "sent": return ; - case "payments": return ; - case "support": return ; - case "profile": return ; + if (a && b === "renew") return ; + if (a && b === "return") return ; + return a ? : ; + case "sent": return ; + case "payments": return ; + case "support": return ; + case "profile": return ; // C07r: máy quét ở cửa kho (mô phỏng), không cần đăng nhập như thiết bị gắn tại cơ sở - case "door": return ; + case "door": return ; default: return (
@@ -160,13 +168,13 @@ function Shell() {

Đang tải dữ liệu…

) : isAdminPage ? ( - adminBody || + adminBody || ) : isBusinessPage ? ( - businessBody || + businessBody || ) : isOpsPage ? ( opsAllowed ? ( - + ) : (
@@ -191,7 +199,7 @@ function Shell() { ); } -export default function CustomerApp() { +export default function App() { return ( diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/api.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/api.js similarity index 100% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/api.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/api.js diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/geo.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/geo.js similarity index 100% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/geo.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/geo.js diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/media.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/media.js similarity index 100% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/media.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/media.js diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/payment.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/payment.js similarity index 100% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/config/payment.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/config/payment.js diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/data/seed.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/data/appSeed.js similarity index 98% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/data/seed.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/data/appSeed.js index 3c2e0b8..8d8593b 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/data/seed.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/data/appSeed.js @@ -1,5 +1,5 @@ -import { localOffers } from "../lib/catalog.js"; -import { addDays, addMonths, today } from "../lib/format.js"; +import { localOffers } from "../../shared/utils/catalog.js"; +import { addDays, addMonths, today } from "../../shared/utils/format.js"; export const SEED_EMAIL = "mai.nguyen@example.com"; export const SEED_PASSWORD = "SafeSpace@123"; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/router.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/router.js similarity index 100% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/lib/router.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/router.js diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx similarity index 97% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx index 21176ec..1c40c43 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/AppProvider.jsx @@ -1,20 +1,20 @@ import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; -import { api } from "../api/endpoints"; -import { ApiError, setToken } from "../api/http"; -import { isUnsupported, localAccessCode, normAccess, normCancelPreview, normPayos, normScan } from "../api/payment-access"; -import { bankAccount } from "../config/payment"; -import { vietQrPayload } from "../lib/vietqr"; -import { composeData, emptyOverlay, mapCatalog, reservationCode, reservationsToExpire, ticketCode, usernameFromEmail } from "../api/mappers"; -import { API_URL, USE_API } from "../config/api"; -import { paymentTimeoutSeconds } from "../config/media"; -import { createEmptyData, createSeedData } from "../data/seed"; -import { RENTAL_PLANS, offerByKey } from "../lib/catalog"; -import { isEmail, localDate, shortCode, timeoutLabel } from "../lib/format"; -import { TICKET_TOPICS } from "../lib/status"; -import { isAdminRoles, isCustomerRoles, isOpsRoles, isBusinessRoles, rolesFromToken } from "../lib/roles"; -import { OPS_ACCOUNTS, OPS_PASSWORD } from "../ops/data"; -import { cancelPreviewOf, reduce, sweepExpired, validateRegister } from "./reducer"; -import { pendingRenewal, pendingReturn } from "./selectors"; +import { api } from "../../shared/api/customerApi.js"; +import { ApiError, setToken } from "../../shared/api/httpClient.js"; +import { isUnsupported, localAccessCode, normAccess, normCancelPreview, normPayos, normScan } from "../../features/customer/access/accessApi.js"; +import { bankAccount } from "../config/payment.js"; +import { vietQrPayload } from "../../shared/utils/vietqr.js"; +import { composeData, emptyOverlay, mapCatalog, reservationCode, reservationsToExpire, ticketCode, usernameFromEmail } from "../../shared/api/apiMappers.js"; +import { API_URL, USE_API } from "../config/api.js"; +import { paymentTimeoutSeconds } from "../config/media.js"; +import { createEmptyData, createSeedData } from "../data/appSeed.js"; +import { RENTAL_PLANS, offerByKey } from "../../shared/utils/catalog.js"; +import { isEmail, localDate, shortCode, timeoutLabel } from "../../shared/utils/format.js"; +import { TICKET_TOPICS } from "../../shared/utils/status.js"; +import { isAdminRoles, isCustomerRoles, isOpsRoles, isBusinessRoles, rolesFromToken } from "../../shared/utils/roles.js"; +import { OPS_ACCOUNTS, OPS_PASSWORD } from "../../features/facility-operations/data/facilityOperationsSeed.js"; +import { cancelPreviewOf, reduce, sweepExpired, validateRegister } from "./appReducer.js"; +import { pendingRenewal, pendingReturn } from "./appSelectors.js"; const AppContext = createContext(null); export const useApp = () => useContext(AppContext); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/reducer.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appReducer.js similarity index 99% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/reducer.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appReducer.js index e1493ae..0383e8f 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/reducer.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appReducer.js @@ -1,4 +1,4 @@ -import { RENTAL_PLANS, SIZE_BANDS, offerByKey, quote } from "../lib/catalog.js"; +import { RENTAL_PLANS, SIZE_BANDS, offerByKey, quote } from "../../shared/utils/catalog.js"; import { addDays, addMonths, @@ -7,8 +7,8 @@ import { localDate, shortCode, timeoutLabel, -} from "../lib/format.js"; -import { TICKET_TOPICS } from "../lib/status.js"; +} from "../../shared/utils/format.js"; +import { TICKET_TOPICS } from "../../shared/utils/status.js"; export class DomainError extends Error { constructor(message, code = "INVALID") { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/selectors.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appSelectors.js similarity index 98% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/selectors.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appSelectors.js index 3cca7eb..4f3af27 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/selectors.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/app/state/appSelectors.js @@ -1,4 +1,4 @@ -import { daysBetween, localDate } from "../lib/format.js"; +import { daysBetween, localDate } from "../../shared/utils/format.js"; // Luôn trả về một cơ sở (dự phòng khi dữ liệu máy chủ chỉ có tên cơ sở) export const facilityOf = (data, id, name) => diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminShell.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminLayout.jsx similarity index 95% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminShell.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminLayout.jsx index f598204..a5eefaa 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminShell.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminLayout.jsx @@ -1,9 +1,9 @@ import React, { useEffect, useRef, useState } from "react"; -import { Icon } from "../components/UI"; -import { go, href } from "../lib/router"; -import { useApp } from "../state/store"; -import { adminApi } from "../api/admin"; -import { dateTime } from "./util"; +import { Icon } from "../../shared/components/UI.jsx"; +import { go, href } from "../../app/router.js"; +import { useApp } from "../../app/state/AppProvider.jsx"; +import { adminApi } from "./api/adminApi.js"; +import { dateTime } from "./utils/adminUtils.js"; const TABS = [ ["", "Tài khoản"], @@ -152,7 +152,7 @@ function UserMenu() { ); } -export default function AdminShell({ tab, children }) { +export default function AdminLayout({ tab, children }) { return ( <>
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminApp.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminRoutes.jsx similarity index 80% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminApp.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminRoutes.jsx index 907799a..a5f94a7 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminApp.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/AdminRoutes.jsx @@ -12,16 +12,16 @@ */ import React from "react"; -import { Empty, LinkButton } from "../components/UI"; -import AdminCreateUser from "./AdminCreateUser"; -import AdminLogs from "./AdminLogs"; -import AdminPermissions from "./AdminPermissions"; -import AdminShell from "./AdminShell"; -import AdminUserDetail from "./AdminUserDetail"; -import AdminUsers from "./AdminUsers"; +import { Empty, LinkButton } from "../../shared/components/UI.jsx"; +import CreateUserPage from "./users/CreateUserPage.jsx"; +import AuditLogPage from "./logs/AuditLogPage.jsx"; +import PermissionListPage from "./permissions/PermissionListPage.jsx"; +import AdminLayout from "./AdminLayout.jsx"; +import UserDetailPage from "./users/UserDetailPage.jsx"; +import UserListPage from "./users/UserListPage.jsx"; // Định tuyến khu quản trị: #/admin, #/admin/users/:id, #/admin/new, #/admin/permissions, #/admin/logs -export default function AdminApp({ parts }) { +export default function AdminRoutes({ parts }) { // Lấy hai phần đầu tiên của đường dẫn. // a: tên chức năng đang truy cập (users, new, logs,...). @@ -39,32 +39,32 @@ export default function AdminApp({ parts }) { // TRƯỜNG HỢP 1: Admin truy cập #/admin // Không có phần đường dẫn bổ sung (!a). // Hiển thị trang danh sách người dùng mặc định. - if (!a) body = ; + if (!a) body = ; // TRƯỜNG HỢP 2: Admin truy cập #/admin/users/:id // a phải là "users" và b phải có giá trị. // Hiển thị trang chi tiết của người dùng có ID tương ứng. // key={b} giúp React tạo lại component khi ID thay đổi. else if (a === "users" && b) - body = ; + body = ; // TRƯỜNG HỢP 3: Admin truy cập #/admin/new // Chọn tab "new" và hiển thị form tạo tài khoản mới. else if (a === "new") { tab = "new"; - body = ; + body = ; // TRƯỜNG HỢP 4: Admin truy cập #/admin/permissions // Chọn tab "permissions" và hiển thị trang quản lý phân quyền. } else if (a === "permissions") { tab = "permissions"; - body = ; + body = ; // TRƯỜNG HỢP 5: Admin truy cập #/admin/logs // Chọn tab "logs" và hiển thị nhật ký hệ thống. } else if (a === "logs") { tab = "logs"; - body = ; + body = ; // TRƯỜNG HỢP 6: URL không khớp với chức năng nào. // Hiển thị thông báo không tìm thấy trang. @@ -82,5 +82,5 @@ export default function AdminApp({ parts }) { // tab: truyền mục menu hiện tại cho AdminShell. // body: nội dung trang được chọn ở các điều kiện phía trên. // {body} được truyền vào AdminShell thông qua children. - return {body}; + return {body}; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/admin.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/api/adminApi.js similarity index 97% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/admin.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/api/adminApi.js index 797d2ec..a0cc66e 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/admin.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/api/adminApi.js @@ -1,5 +1,5 @@ // Endpoint khu quản trị (StorageProject.Api/Endpoints/AdminEndpoints.cs), yêu cầu vai trò ADMIN. -import { request } from "./http.js"; +import { request } from "../../../shared/api/httpClient.js"; const q = (params = {}) => { const s = new URLSearchParams(); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminPermissions.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/permissions/PermissionListPage.jsx similarity index 94% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminPermissions.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/permissions/PermissionListPage.jsx index a340c21..63996ca 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminPermissions.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/permissions/PermissionListPage.jsx @@ -1,13 +1,13 @@ import React, { useMemo, useState } from "react"; -import { adminApi } from "../api/admin"; -import { Button, Modal, Notice } from "../components/UI"; -import { ROLE_SCOPE, roleLabel, sortRoles } from "../lib/roles"; -import { useApp } from "../state/store"; -import { useLoad } from "./util"; +import { adminApi } from "../api/adminApi.js"; +import { Button, Modal, Notice } from "../../../shared/components/UI.jsx"; +import { ROLE_SCOPE, roleLabel, sortRoles } from "../../../shared/utils/roles.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { useLoad } from "../utils/adminUtils.js"; const key = (roleId, permissionId) => `${roleId}:${permissionId}`; -export default function AdminPermissions() { +export default function PermissionListPage() { const { onApiError, notify } = useApp(); const res = useLoad(async () => { const [roles, permissions] = await Promise.all([adminApi.roles(), adminApi.permissions()]); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminCreateUser.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/CreateUserPage.jsx similarity index 97% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminCreateUser.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/CreateUserPage.jsx index f433b57..ba0271b 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminCreateUser.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/CreateUserPage.jsx @@ -15,14 +15,14 @@ import React, { useState } from "react"; -import { adminApi } from "../api/admin"; -import { Select } from "../components/Pickers"; -import { Button, Field, Modal, Notice } from "../components/UI"; -import { isEmail, isPhone, today } from "../lib/format"; -import { FACILITY_ROLES, roleLabel, sortRoles } from "../lib/roles"; -import { go } from "../lib/router"; -import { useApp } from "../state/store"; -import { tempPassword, useLoad, usernameFrom } from "./util"; +import { adminApi } from "../api/adminApi.js"; +import { Select } from "../../../shared/components/Pickers.jsx"; +import { Button, Field, Modal, Notice } from "../../../shared/components/UI.jsx"; +import { isEmail, isPhone, today } from "../../../shared/utils/format.js"; +import { FACILITY_ROLES, roleLabel, sortRoles } from "../../../shared/utils/roles.js"; +import { go } from "../../../app/router.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { tempPassword, useLoad, usernameFrom } from "../utils/adminUtils.js"; /* * EMPTY - DỮ LIỆU FORM MẶC ĐỊNH @@ -33,7 +33,7 @@ import { tempPassword, useLoad, usernameFrom } from "./util"; const EMPTY = { fullName: "", email: "", phone: "", username: "", password: "", roleId: "", facilityId: "" }; -export default function AdminCreateUser() { +export default function CreateUserPage() { // onApiError: xử lý lỗi liên quan đến API, đặc biệt HTTP 401. // notify: hiển thị thông báo toast trên giao diện. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminUserDetail.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserDetailPage.jsx similarity index 96% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminUserDetail.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserDetailPage.jsx index 5573f07..a452784 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminUserDetail.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserDetailPage.jsx @@ -1,11 +1,11 @@ import React, { useEffect, useState } from "react"; -import { adminApi } from "../api/admin"; -import { DatePicker, Select } from "../components/Pickers"; -import { Button, Empty, Field, LinkButton, Modal, Notice, StatusTag } from "../components/UI"; -import { isEmail, isPhone, today } from "../lib/format"; -import { ASSIGNMENT_STATUS, USER_STATUS, needsFacility, roleLabel, sortRoles } from "../lib/roles"; -import { useApp } from "../state/store"; -import { dateOnlyLabel, dateTime, tempPassword, useLoad } from "./util"; +import { adminApi } from "../api/adminApi.js"; +import { DatePicker, Select } from "../../../shared/components/Pickers.jsx"; +import { Button, Empty, Field, LinkButton, Modal, Notice, StatusTag } from "../../../shared/components/UI.jsx"; +import { isEmail, isPhone, today } from "../../../shared/utils/format.js"; +import { ASSIGNMENT_STATUS, USER_STATUS, needsFacility, roleLabel, sortRoles } from "../../../shared/utils/roles.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { dateOnlyLabel, dateTime, tempPassword, useLoad } from "../utils/adminUtils.js"; function InfoCard({ user, onSaved }) { const { onApiError, notify } = useApp(); @@ -252,7 +252,7 @@ function FacilityCard({ user, facilities, rows, onSaved }) { ); } -export default function AdminUserDetail({ id }) { +export default function UserDetailPage({ id }) { const { onApiError } = useApp(); const res = useLoad(async () => { const [user, roles, facilities, assignments] = await Promise.all([adminApi.user(id), adminApi.roles(), adminApi.facilities(), adminApi.userFacilities(id)]); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminUsers.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserListPage.jsx similarity index 97% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminUsers.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserListPage.jsx index f8b0419..c633994 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/AdminUsers.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/users/UserListPage.jsx @@ -13,17 +13,17 @@ */ import React, { useEffect, useMemo, useState } from "react"; -import { adminApi } from "../api/admin"; -import { Pagination, Select } from "../components/Pickers"; -import { Empty, LinkButton, Notice, StatusTag } from "../components/UI"; -import { USER_STATUS, needsFacility, roleLabel, sortRoles } from "../lib/roles"; -import { go, href } from "../lib/router"; -import { useApp } from "../state/store"; -import { useLoad } from "./util"; +import { adminApi } from "../api/adminApi.js"; +import { Pagination, Select } from "../../../shared/components/Pickers.jsx"; +import { Empty, LinkButton, Notice, StatusTag } from "../../../shared/components/UI.jsx"; +import { USER_STATUS, needsFacility, roleLabel, sortRoles } from "../../../shared/utils/roles.js"; +import { go, href } from "../../../app/router.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { useLoad } from "../utils/adminUtils.js"; const PAGE_SIZE = 10; -export default function AdminUsers() { +export default function UserListPage() { // Lấy hàm xử lý lỗi API từ Context. // Ví dụ: kết thúc phiên khi token hết hạn (HTTP 401). diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/util.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/utils/adminUtils.js similarity index 97% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/util.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/utils/adminUtils.js index 89063db..49a95f6 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/admin/util.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/admin/utils/adminUtils.js @@ -1,6 +1,6 @@ import { useCallback, useEffect, useRef, useState } from "react"; -import { parseUtc } from "../api/mappers.js"; -import { ASSIGNMENT_STATUS, USER_STATUS, actionLabel, roleLabel } from "../lib/roles.js"; +import { parseUtc } from "../../../shared/api/apiMappers.js"; +import { ASSIGNMENT_STATUS, USER_STATUS, actionLabel, roleLabel } from "../../../shared/utils/roles.js"; const pad = (n) => String(n).padStart(2, "0"); export function dateTime(v) { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/LoginPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/LoginPage.jsx new file mode 100644 index 0000000..3f92b03 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/LoginPage.jsx @@ -0,0 +1,63 @@ +import React, { useEffect, useState } from "react"; +import { Button, Field } from "../../shared/components/UI.jsx"; +import { go, href } from "../../app/router.js"; +import { homeFor, isOpsRoles, isBusinessRoles } from "../../shared/utils/roles.js"; +import { useApp } from "../../app/state/AppProvider.jsx"; +import { safeNext } from "./utils/safeNext.js"; +import { ForgotPassword } from "./components/ForgotPasswordDialog.jsx"; + +export function LoginPage({ query }) { + const { login, authed, isAdmin, roles } = useApp(); + const next = safeNext(query.get("next")); + const [form, setForm] = useState({ identifier: "", password: "" }); + const [errors, setErrors] = useState({}); + const [forgot, setForgot] = useState(false); + const [busy, setBusy] = useState(false); + + useEffect(() => { + if (authed) go(isAdmin || isOpsRoles(roles) || isBusinessRoles(roles) ? homeFor(roles) : next, { replace: true }); + }, [authed, isAdmin, roles, next]); + + const set = (k, v) => { + setForm({ ...form, [k]: v }); + setErrors({}); + }; + const submit = async (e) => { + e.preventDefault(); + const err = {}; + if (!form.identifier.trim()) err.identifier = "Vui lòng nhập tên đăng nhập hoặc email."; + if (!form.password) err.password = "Vui lòng nhập mật khẩu."; + if (Object.keys(err).length) return setErrors(err); + setBusy(true); + const res = await login(form); + setBusy(false); + if (!res.ok) return setErrors({ form: res.error }); + const home = homeFor(res.roles || []); + go(home === "overview" ? next : next.startsWith(home) ? next : home); + }; + + return ( +
+
+

Đăng nhập

+

Dành cho khách hàng đã có tài khoản và nhân viên được cấp quyền.

+ {errors.form &&

{errors.form}

} + + set("identifier", e.target.value)} /> + + + set("password", e.target.value)} /> + + + +

+ Nhân viên: nhập đúng tên đăng nhập và mật khẩu được cấp trước để vào đúng giao diện vai trò của bạn — Nhân viên cơ sở, Quản lý cơ sở, Vận hành, hoặc Quản trị hệ thống. +

+

+ Chưa có tài khoản? Đăng ký +

+
+ {forgot && setForgot(false)} />} +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/RegisterPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/RegisterPage.jsx new file mode 100644 index 0000000..f7c9daa --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/RegisterPage.jsx @@ -0,0 +1,62 @@ +import React, { useEffect, useState } from "react"; +import { Button, Field, Icon } from "../../shared/components/UI.jsx"; +import { go, href } from "../../app/router.js"; +import { useApp } from "../../app/state/AppProvider.jsx"; +import { safeNext } from "./utils/safeNext.js"; + +export function RegisterPage({ query }) { + const { register, authed } = useApp(); + const next = safeNext(query.get("next")); + const [form, setForm] = useState({ name: "", email: "", phone: "", password: "", confirm: "" }); + const [errors, setErrors] = useState({}); + const [busy, setBusy] = useState(false); + + useEffect(() => { + if (authed) go(next, { replace: true }); + }, [authed, next]); + + const set = (k, v) => { + setForm({ ...form, [k]: v }); + setErrors((p) => ({ ...p, [k]: undefined, form: undefined })); + }; + const submit = async (e) => { + e.preventDefault(); + setBusy(true); + const res = await register(form); + setBusy(false); + if (!res.ok) return setErrors(res.errors); + go(next); + }; + + return ( +
+
+

Tạo tài khoản khách hàng

+

Điền thông tin bên dưới để bắt đầu thuê kho cùng SafeSpace.

+ {errors.form &&

{errors.form}

} + + set("name", e.target.value)} /> + + + set("email", e.target.value)} /> + + + set("phone", e.target.value)} /> + + + set("password", e.target.value)} /> + + + set("confirm", e.target.value)} /> + + +

+ Tài khoản mới sẽ tự động vào vai trò Khách hàng. +

+

+ Đã có tài khoản? Đăng nhập +

+
+
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/components/ForgotPasswordDialog.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/components/ForgotPasswordDialog.jsx new file mode 100644 index 0000000..1430a8e --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/components/ForgotPasswordDialog.jsx @@ -0,0 +1,42 @@ +import React, { useState } from "react"; +import { Button, Field, Modal } from "../../../shared/components/UI.jsx"; +import { isEmail } from "../../../shared/utils/format.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; + +export function ForgotPassword({ onClose }) { + const { supports } = useApp(); + const [email, setEmail] = useState(""); + const [error, setError] = useState(""); + const [sent, setSent] = useState(false); + const submit = (e) => { + e.preventDefault(); + if (!isEmail(email)) return setError("Nhập email hợp lệ để nhận hướng dẫn."); + setSent(true); + }; + return ( + + {!supports.forgotPassword ? ( + <> +

Vui lòng liên hệ quản trị viên hoặc nhân viên cơ sở SafeSpace để được đặt lại mật khẩu.

+ + + ) : sent ? ( + <> +

Nếu email đã đăng ký, SafeSpace sẽ gửi hướng dẫn đặt lại mật khẩu trong ít phút.

+ + + ) : ( +
+

Nhập email đã đăng ký. Chúng tôi sẽ gửi hướng dẫn đặt lại mật khẩu.

+ + { setEmail(e.target.value); setError(""); }} /> + +
+ + +
+
+ )} +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/utils/safeNext.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/utils/safeNext.js new file mode 100644 index 0000000..2fd240b --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/auth/utils/safeNext.js @@ -0,0 +1,3 @@ +import React from "react"; + +export const safeNext = (next) => (next && !/^(login|register)/.test(next) ? next : "overview"); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessShell.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/BusinessLayout.jsx similarity index 96% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessShell.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/BusinessLayout.jsx index 61c70a6..cdbbd5a 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessShell.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/BusinessLayout.jsx @@ -1,8 +1,8 @@ -import "./design.css"; +import "./business.css"; import React, { useEffect, useRef, useState } from "react"; -import { businessApi } from "../api/business"; -import { go, href } from "../lib/router"; -import { useApp } from "../state/store"; +import { businessApi } from "./api/businessApi.js"; +import { go, href } from "../../app/router.js"; +import { useApp } from "../../app/state/AppProvider.jsx"; function useOutside(open, setOpen, ref) { useEffect(() => { @@ -156,7 +156,7 @@ function Bell() { ); } -export default function BusinessShell({ active, children }) { +export default function BusinessLayout({ active, children }) { return (
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessApp.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/BusinessRoutes.jsx similarity index 51% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessApp.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/BusinessRoutes.jsx index 49c477c..0896d35 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/BusinessApp.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/BusinessRoutes.jsx @@ -1,31 +1,31 @@ import React from "react"; -import { Empty, LinkButton } from "../components/UI"; -import BusinessShell from "./BusinessShell"; -import BusinessFacilities from "./Facilities"; -import BusinessOverview from "./Overview"; -import BusinessPolicies from "./Policies"; -import BusinessPricing from "./Pricing"; -import BusinessReports from "./Reports"; +import { Empty, LinkButton } from "../../shared/components/UI.jsx"; +import BusinessLayout from "./BusinessLayout.jsx"; +import FacilityManagementPage from "./facilities/FacilityManagementPage.jsx"; +import BusinessDashboardPage from "./dashboard/BusinessDashboardPage.jsx"; +import PolicySettingsPage from "./policies/PolicySettingsPage.jsx"; +import PricingPage from "./pricing/PricingPage.jsx"; +import BusinessReportPage from "./reports/BusinessReportPage.jsx"; // Khu Quản lý vận hành KD (Figma B01–B05), role OPERATIONS: // #/business · #/business/facilities · #/business/policies · #/business/pricing · #/business/reports -export default function BusinessApp({ parts, query }) { +export default function BusinessRoutes({ parts, query }) { const [a] = parts; let active = "business"; let body; - if (!a) body = ; + if (!a) body = ; else if (a === "facilities") { active = "business/facilities"; - body = ; + body = ; } else if (a === "policies") { active = "business/policies"; - body = ; + body = ; } else if (a === "pricing") { active = "business/pricing"; - body = ; + body = ; } else if (a === "reports") { active = "business/reports"; - body = ; + body = ; } else { active = ""; body = ( @@ -36,5 +36,5 @@ export default function BusinessApp({ parts, query }) {
); } - return {body}; + return {body}; } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/business.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/api/businessApi.js similarity index 96% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/business.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/api/businessApi.js index 781fbbb..0b58990 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/business.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/api/businessApi.js @@ -1,7 +1,7 @@ // Endpoint khu Quản lý vận hành kinh doanh (StorageProject.Api/Endpoints/OperationsEndpoints.cs), role OPERATIONS. // Hợp đồng chi tiết: docs/operations-api.md. -import { request, ApiError } from "./http.js"; -import { API_URL } from "../config/api.js"; +import { request, ApiError } from "../../../shared/api/httpClient.js"; +import { API_URL } from "../../../app/config/api.js"; async function requestFile(path, { fallbackName = "bao-cao.csv" } = {}) { let token; try { token = JSON.parse(localStorage.getItem('safespace.customer.session'))?.token; } catch { /* absent session */ } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/design.css b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/business.css similarity index 100% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/design.css rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/business.css diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/parts.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/components/BusinessComponents.jsx similarity index 96% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/parts.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/components/BusinessComponents.jsx index 2f22da0..be9ec73 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/parts.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/components/BusinessComponents.jsx @@ -1,8 +1,8 @@ import React, { useState } from "react"; -import { Select } from "../components/Pickers"; -import { Button, Empty, Field, Modal } from "../components/UI"; -import { today } from "../lib/format"; -import { CALC_TYPES, POLICY_TYPES, parseMoney } from "./format"; +import { Select } from "../../../shared/components/Pickers.jsx"; +import { Button, Empty, Field, Modal } from "../../../shared/components/UI.jsx"; +import { today } from "../../../shared/utils/format.js"; +import { CALC_TYPES, POLICY_TYPES, parseMoney } from "../utils/businessFormat.js"; // Trạng thái tải chung cho các màn B01–B05 export function LoadState({ load, children }) { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Overview.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/dashboard/BusinessDashboardPage.jsx similarity index 90% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Overview.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/dashboard/BusinessDashboardPage.jsx index c7c53de..c6281f0 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Overview.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/dashboard/BusinessDashboardPage.jsx @@ -1,13 +1,13 @@ import React from "react"; -import { businessApi } from "../api/business"; -import { LinkButton } from "../components/UI"; -import { useLoad, dateTime } from "../admin/util"; -import { useApp } from "../state/store"; -import { areaOf, growthLabel, rateLabel, shortMoney } from "./format"; -import { LoadState } from "./parts"; +import { businessApi } from "../api/businessApi.js"; +import { LinkButton } from "../../../shared/components/UI.jsx"; +import { useLoad, dateTime } from "../../admin/utils/adminUtils.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { areaOf, growthLabel, rateLabel, shortMoney } from "../utils/businessFormat.js"; +import { LoadState } from "../components/BusinessComponents.jsx"; // B01 · Tổng quan toàn hệ thống — số liệu tháng này từ /reports/facilities + /reports/revenue-trend -export default function BusinessOverview() { +export default function BusinessDashboardPage() { const { onApiError } = useApp(); const load = useLoad( async () => { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Facilities.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/facilities/FacilityManagementPage.jsx similarity index 93% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Facilities.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/facilities/FacilityManagementPage.jsx index 0c36700..ddafc2f 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Facilities.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/facilities/FacilityManagementPage.jsx @@ -1,12 +1,12 @@ import React, { useState } from "react"; -import { businessApi } from "../api/business"; -import { Button, Field, Modal, Notice } from "../components/UI"; -import { useLoad } from "../admin/util"; -import { go, href, qs } from "../lib/router"; -import { useApp } from "../state/store"; -import { FACILITY_STATUS, areaOf, rateLabel, shortFacility } from "./format"; -import { LoadState } from "./parts"; -import { coordinateLabel, facilityToForm, formToRequest, splitCoordinates } from "./facility-form"; +import { businessApi } from "../api/businessApi.js"; +import { Button, Field, Modal, Notice } from "../../../shared/components/UI.jsx"; +import { useLoad } from "../../admin/utils/adminUtils.js"; +import { go, href, qs } from "../../../app/router.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { FACILITY_STATUS, areaOf, rateLabel, shortFacility } from "../utils/businessFormat.js"; +import { LoadState } from "../components/BusinessComponents.jsx"; +import { coordinateLabel, facilityToForm, formToRequest, splitCoordinates } from "./facilityForm.js"; // B05a · Sửa thông tin cơ sở (tên, địa chỉ, điện thoại, giờ ra vào, toạ độ ghim bản đồ) function EditFacilityDialog({ facility, onClose, onSaved }) { @@ -81,7 +81,7 @@ function EditFacilityDialog({ facility, onClose, onSaved }) { } // B05: select a facility and open its business report; no unrelated CRUD controls. -export default function BusinessFacilities({ query }) { +export default function FacilityManagementPage({ query }) { const { onApiError } = useApp(); const load = useLoad(async () => { const [facilities, rates] = await Promise.all([businessApi.facilities(), businessApi.rates()]); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/facility-form.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/facilities/facilityForm.js similarity index 100% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/facility-form.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/facilities/facilityForm.js diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Policies.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/PolicySettingsPage.jsx similarity index 81% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Policies.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/PolicySettingsPage.jsx index 1b4beb9..16f7c6e 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Policies.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/PolicySettingsPage.jsx @@ -1,14 +1,14 @@ import React, { useState } from 'react'; -import { businessApi } from '../api/business'; -import { Button, Field } from '../components/UI'; -import { useLoad } from '../admin/util'; -import { today } from '../lib/format'; -import { useApp } from '../state/store'; -import { createPolicy, replacePolicy } from './actions'; -import { LoadState, useConfirm } from './parts'; -import { POLICY_SECTIONS, fieldPolicy, fieldValue, policyJobs } from './policy-fields'; +import { businessApi } from "../api/businessApi.js"; +import { Button, Field } from "../../../shared/components/UI.jsx"; +import { useLoad } from "../../admin/utils/adminUtils.js"; +import { today } from "../../../shared/utils/format.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { createPolicy, replacePolicy } from "./policyActions.js"; +import { LoadState, useConfirm } from "../components/BusinessComponents.jsx"; +import { POLICY_SECTIONS, fieldPolicy, fieldValue, policyJobs } from "./policyFields.js"; -export default function BusinessPolicies() { +export default function PolicySettingsPage() { const { notify, onApiError } = useApp(); const load = useLoad(() => businessApi.policies({}), [], onApiError); const [drafts, setDrafts] = useState({}); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/actions.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/policyActions.js similarity index 87% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/actions.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/policyActions.js index 4ed266f..67df3a8 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/actions.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/policyActions.js @@ -1,6 +1,6 @@ -import { businessApi } from '../api/business.js'; -import { ApiError } from '../api/http.js'; -import { POLICY_TYPES } from './format.js'; +import { businessApi } from "../api/businessApi.js"; +import { ApiError } from "../../../shared/api/httpClient.js"; +import { POLICY_TYPES } from "../utils/businessFormat.js"; export async function activateWithConfirm(policy,ask){ try{await businessApi.activatePolicy(policy.policyId);return true;} catch(e){ diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/policy-fields.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/policyFields.js similarity index 98% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/policy-fields.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/policyFields.js index c1d3b91..ca85d71 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/policy-fields.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/policies/policyFields.js @@ -1,4 +1,4 @@ -import { policyValueLabel, replacementOf, parseMoney } from './format.js'; +import { policyValueLabel, replacementOf, parseMoney } from "../utils/businessFormat.js"; export const POLICY_SECTIONS = [ {title:'Đặt cọc',fields:[{key:'deposit',label:'Mức đặt cọc mặc định',type:'DEPOSIT',numeric:true},{key:'refund',label:'Hoàn cọc trong vòng',type:'RETURN'}]}, {title:'Gia hạn',fields:[{key:'reminder',label:'Thông báo trước khi hết hạn',type:'RENEWAL',numeric:true},{key:'renewals',label:'Số lần gia hạn tối đa',type:'RENEWAL'}]}, diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Pricing.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/pricing/PricingPage.jsx similarity index 94% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Pricing.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/pricing/PricingPage.jsx index ce5caf7..1a6bd12 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Pricing.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/pricing/PricingPage.jsx @@ -1,12 +1,12 @@ import React, { useCallback, useState } from "react"; -import { businessApi } from "../api/business"; -import { Button, Tag } from "../components/UI"; -import { useLoad } from "../admin/util"; -import { money, today } from "../lib/format"; -import { useApp } from "../state/store"; -import { createPolicy, replacePolicy } from "./actions"; -import { POLICY_STATUS, parseMoney, policyFor, policyValueLabel, replacementOf } from "./format"; -import { LoadState, PolicyForm, useConfirm } from "./parts"; +import { businessApi } from "../api/businessApi.js"; +import { Button, Tag } from "../../../shared/components/UI.jsx"; +import { useLoad } from "../../admin/utils/adminUtils.js"; +import { money, today } from "../../../shared/utils/format.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { createPolicy, replacePolicy } from "../policies/policyActions.js"; +import { POLICY_STATUS, parseMoney, policyFor, policyValueLabel, replacementOf } from "../utils/businessFormat.js"; +import { LoadState, PolicyForm, useConfirm } from "../components/BusinessComponents.jsx"; // Ba cột chính sách theo loại kho (Figma B03): khung giá, phí dịch vụ / tháng, phí quá hạn / ngày const COLUMNS = [ @@ -23,7 +23,7 @@ function cellDraft(policy, col) { } // B03 · Quản lý giá & phí (UC21): khung giá / phí theo loại kho, giảm giá / miễn phí -export default function BusinessPricing() { +export default function PricingPage() { const { notify, onApiError } = useApp(); const load = useLoad( async () => { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Reports.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/reports/BusinessReportPage.jsx similarity index 94% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Reports.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/reports/BusinessReportPage.jsx index 12439ef..15267cc 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Reports.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/reports/BusinessReportPage.jsx @@ -1,10 +1,10 @@ import React, { useState } from "react"; -import { businessApi } from "../api/business"; -import { Button } from "../components/UI"; -import { useLoad } from "../admin/util"; -import { go, qs } from "../lib/router"; -import { today } from "../lib/format"; -import { useApp } from "../state/store"; +import { businessApi } from "../api/businessApi.js"; +import { Button } from "../../../shared/components/UI.jsx"; +import { useLoad } from "../../admin/utils/adminUtils.js"; +import { go, qs } from "../../../app/router.js"; +import { today } from "../../../shared/utils/format.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; import { CONTRACT_STATUS_LABELS, RESERVATION_STATUS_LABELS, @@ -13,9 +13,9 @@ import { rateLabel, shortFacility, shortMoney, -} from "./format"; -import { parseCsv, downloadWorkbook } from "./export"; -import { BarChart, LoadState } from "./parts"; +} from "../utils/businessFormat.js"; +import { parseCsv, downloadWorkbook } from "./reportExport.js"; +import { BarChart, LoadState } from "../components/BusinessComponents.jsx"; const VIEWS = [ ["facilities", "Theo cơ sở"], @@ -143,7 +143,7 @@ function StatusView({ data }) { } // B04 · Báo cáo toàn hệ thống (UC22, UC23): theo cơ sở / loại kho / doanh thu / tình trạng thuê, xuất XLSX (CSV từ API được chuyển thành workbook; trạng thái dùng snapshot đang xem) -export default function BusinessReports({ query }) { +export default function BusinessReportPage({ query }) { const { notify, onApiError } = useApp(); const now = today(); const view = VIEWS.some(([k]) => k === query.get("view")) ? query.get("view") : "facilities"; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/export.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/reports/reportExport.js similarity index 100% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/export.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/reports/reportExport.js diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/format.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/utils/businessFormat.js similarity index 99% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/format.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/utils/businessFormat.js index 32f78e9..b626b4f 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/format.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/business/utils/businessFormat.js @@ -1,5 +1,5 @@ // Hàm thuần cho khu Quản lý vận hành KD (B01–B05) — có test ở tests/business.test.js. -import { money, today } from "../lib/format.js"; +import { money, today } from "../../../shared/utils/format.js"; const comma = (n, digits = 1) => Number(n).toFixed(digits).replace(".", ","); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/AccessQrModal.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/AccessQrModal.jsx new file mode 100644 index 0000000..a103167 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/AccessQrModal.jsx @@ -0,0 +1,51 @@ +import React, { useEffect, useState } from "react"; +import QrCode from "../../../shared/components/QrCode.jsx"; +import { Button, Modal, Notice } from "../../../shared/components/UI.jsx"; +import { typeLabel } from "../../../shared/utils/catalog.js"; +import { dateLabel } from "../../../shared/utils/format.js"; +import { href, qs } from "../../../app/router.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; + +export function AccessQrModal({ c, facility, onClose }) { + const { services } = useApp(); + const [state, setState] = useState({ status: "loading" }); + useEffect(() => { + let alive = true; + services.accessQr(c).then((res) => { + if (!alive) return; + if (res.ok) setState({ status: "ready", access: res.access }); + else setState({ status: res.unsupported ? "unsupported" : "error", error: res.error }); + }); + return () => { + alive = false; + }; + }, []); // eslint-disable-line react-hooks/exhaustive-deps + const a = state.access; + const where = [facility.name, c.location].filter(Boolean).join(" · "); + return ( + +

{where}

+ {state.status === "unsupported" ? ( + Mã QR mở cửa đang được cơ sở kích hoạt. Trong lúc chờ, dùng thẻ ra vào đã nhận khi bàn giao hoặc liên hệ nhân viên trực. + ) : state.status === "error" ? ( + {state.error} + ) : ( + + )} + {a && ( +
+ {a.backup &&
Mã dự phòng
{a.backup}
} +
Ô kho
{a.unit || c.unit_number} · {a.unit_type || typeLabel(c.type)}
+
Hiệu lực đến
{dateLabel(a.valid_until || c.end_date)}
+
+ )} +

Đưa mã vào máy quét ở cửa kho. Nếu không quét được, nhập mã dự phòng. Mã hết hiệu lực khi trả kho hoặc hợp đồng hết hạn.

+ {a && ( + Mô phỏng quét ở cửa kho → + )} +
+ +
+
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Door.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/DoorScannerPage.jsx similarity index 93% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Door.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/DoorScannerPage.jsx index 7353f7e..011e73a 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Door.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/DoorScannerPage.jsx @@ -1,11 +1,11 @@ import React, { useEffect, useState } from "react"; -import { Button, Field, Icon, Notice } from "../components/UI"; -import { dateTimeLabel } from "../lib/format"; -import { useApp } from "../state/store"; +import { Button, Field, Icon, Notice } from "../../../shared/components/UI.jsx"; +import { dateTimeLabel } from "../../../shared/utils/format.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; // C07r1 / C07r2 — Mô phỏng máy quét QR ở cửa kho (D21: mô phỏng, không dùng thiết bị thật). // Nhận mã từ QR mở cửa (C07q) hoặc mã dự phòng, gọi POST /api/access/scan, hiện "Mở cửa" / "Từ chối". -export default function Door({ query }) { +export default function DoorScannerPage({ query }) { const { services } = useApp(); const unit = query.get("unit") || ""; const [code, setCode] = useState(query.get("code") || ""); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/payment-access.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/accessApi.js similarity index 97% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/payment-access.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/accessApi.js index 3b40d51..7ed96be 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/payment-access.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/accessApi.js @@ -1,8 +1,8 @@ // Chuẩn hoá dữ liệu backend cho các màn mới: PayOS (C04, C11q), QR mở cửa (C07q), máy quét cửa kho (C07r), // xem trước hoàn tiền khi huỷ (C14a). Hàm thuần, có test (tests/payment-access.test.js). // Hợp đồng JSON đầy đủ ở BACKEND-TODO.md mục P (PayOS), Q (QR mở cửa), H (huỷ đơn). -import { ApiError } from "./http.js"; -import { parseUtc } from "./mappers.js"; +import { ApiError } from "../../../shared/api/httpClient.js"; +import { parseUtc } from "../../../shared/api/apiMappers.js"; // Backend chưa có endpoint (bản cũ) → giao diện hiện thông báo thay vì báo lỗi export const isUnsupported = (e) => e instanceof ApiError && (e.status === 404 || e.status === 405 || e.status === 501); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/useAccessQr.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/useAccessQr.js similarity index 88% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/useAccessQr.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/useAccessQr.js index 8b9d188..3949888 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/useAccessQr.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/access/useAccessQr.js @@ -1,9 +1,9 @@ import { useCallback } from "react"; -import { useApp } from "./store"; -import { USE_API } from "../config/api"; -import { api } from "../api/endpoints"; -import { today } from "../lib/format"; -import { accessError, validateAccess } from "../lib/access"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { USE_API } from "../../../app/config/api.js"; +import { api } from "../../../shared/api/customerApi.js"; +import { today } from "../../../shared/utils/format.js"; +import { accessError, validateAccess } from "../../../shared/utils/access.js"; export function useAccessQr(id) { const { data } = useApp(); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RenewalRequestPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RenewalRequestPage.jsx new file mode 100644 index 0000000..1b419f6 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RenewalRequestPage.jsx @@ -0,0 +1,54 @@ +import React, { useState } from "react"; +import { Select } from "../../../shared/components/Pickers.jsx"; +import { Button, Field, LinkButton, Notice, PageHeader } from "../../../shared/components/UI.jsx"; +import { RENTAL_PLANS } from "../../../shared/utils/catalog.js"; +import { addMonths, dateLabel, money } from "../../../shared/utils/format.js"; +import { go } from "../../../app/router.js"; +import { contractOf } from "../../../app/state/appSelectors.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { NotFound } from "./components/ContractNotFound.jsx"; + +export function RenewalRequestPage({ id }) { + const { data, dispatch } = useApp(); + const c = contractOf(data, id); + const [months, setMonths] = useState(3); + const [error, setError] = useState(""); + const [busy, setBusy] = useState(false); + if (!c) return ; + const newEnd = addMonths(c.end_date, months); + const submit = async (e) => { + e.preventDefault(); + setBusy(true); + const res = await dispatch("REQUEST_RENEWAL", { contract_id: id, months }); + setBusy(false); + if (!res.ok) return setError(res.error); + go(`sent?type=renew&contract=${encodeURIComponent(id)}`); + }; + return ( +
+ +
+ + + + + + +

Chi phí dự kiến

+

+ {months} × {money(c.monthly_rate)} = {money(months * c.monthly_rate)}. Chỉ trả tiền thuê kỳ mới qua mã QR sau khi yêu cầu được duyệt. Tiền cọc đang giữ được chuyển sang kỳ mới, không thu thêm. +

+

Ngày kết thúc mới dự kiến {dateLabel(newEnd)}

+ {error && {error}} +
+ + Quay lại hợp đồng +
+
+
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitDetailPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitDetailPage.jsx new file mode 100644 index 0000000..ddfe777 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitDetailPage.jsx @@ -0,0 +1,137 @@ +import React, { useState } from "react"; +import { Button, LinkButton, Notice, PageHeader, StatusTag, Tag } from "../../../shared/components/UI.jsx"; +import { typeLabel } from "../../../shared/utils/catalog.js"; +import { dateLabel, money, rangeLabel } from "../../../shared/utils/format.js"; +import { CONTRACT_STATUS, LEDGER_STATUS } from "../../../shared/utils/status.js"; +import { contractOf, contractStatus, facilityOf, pendingRenewal, pendingReturn } from "../../../app/state/appSelectors.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { NotFound } from "./components/ContractNotFound.jsx"; +import { AccessQrModal } from "../access/AccessQrModal.jsx"; + +export function RentedUnitDetailPage({ id }) { + const { data, dispatch, notify } = useApp(); + const [confirming, setConfirming] = useState(false); + const [qrOpen, setQrOpen] = useState(false); + const c = contractOf(data, id); + if (!c) return ; + const f = facilityOf(data, c.facility_id, c.facility_name); + const renewal = pendingRenewal(data, id); + const ret = pendingReturn(data, id); + const rent = [...data.ledger].reverse().find((l) => l.contract_id === id && (l.kind === "RENT" || /-RENT$/.test(l.ref))); + const pickup = data.appointments.find((a) => a.kind === "CHECK_IN" && (a.contract_id === id || (c.reservation_id && a.reservation_id === c.reservation_id)) && a.status !== "CANCELLED"); + const confirmHandover = async () => { + setConfirming(true); + const res = await dispatch("CONFIRM_HANDOVER", { contract_id: id }); + setConfirming(false); + notify(res.ok ? "Đã xác nhận nhận bàn giao kho." : res.error, res.ok ? "success" : "error"); + }; + const status = contractStatus(c); + const ended = status === "ENDED"; + const handed = c.handed_over; + const busy = Boolean(renewal || ret); + const pickupText = pickup ? `${dateLabel(pickup.date)} · ${pickup.slot}` : null; + return ( +
+ + {!handed && !ended && ( +
+ + + Chưa nhận kho{pickupText ? ` · Lịch nhận ${pickupText}` : ""} +
+ Mang giấy tờ đã đăng ký{c.reservation_id ? ` và mã đặt chỗ ${c.reservation_id}` : ""} đến {f.name}. Gia hạn, trả kho và mở cửa kho dùng được sau khi nhân viên bàn giao. +
+
+
+ )} +
+
+ {handed || ended ? : Chờ nhận kho} +

{typeLabel(c.type)}{c.size_m2 ? ` · ${c.size_m2} m²` : ""}

+

+ {c.location ? `${c.location} · ` : ""}Kho {c.unit_number} +
+ Kỳ thuê: {rangeLabel(c.start_date, c.end_date)} +
+ Khách hàng: {data.user.full_name} +

+ + + + + + + + + +
Khoản mụcGiá trị
Tiền thuê mỗi tháng{money(c.monthly_rate)}
Tiền cọc đang giữ{money(c.deposit)}
Thanh toán kỳ này{rent ? LEDGER_STATUS[rent.status][0] : "—"}
+ {c.handover_pending_customer && ( + + Cơ sở đã bàn giao kho. Vui lòng kiểm tra và xác nhận đã nhận kho.{" "} + + + )} +

Thông tin ra vào

+

+ {ended + ? "Hợp đồng đã kết thúc, mã mở cửa không còn hiệu lực." + : handed + ? "Mở cửa bằng QR: bấm \"Mở cửa kho\" rồi đưa mã vào máy quét ở cửa. QR chỉ dùng được khi hợp đồng còn hiệu lực và hết hiệu lực khi trả kho." + : `Khóa và mã truy cập được bàn giao khi nhận kho${pickupText ? ` ngày ${pickupText}` : " theo lịch hẹn"}.`} +

+
+ +
+ {qrOpen && setQrOpen(false)} />} +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitListPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitListPage.jsx new file mode 100644 index 0000000..829ac94 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/RentedUnitListPage.jsx @@ -0,0 +1,42 @@ +import React from "react"; +import { EmptyInline } from "../../../shared/components/Inline.jsx"; +import { PageHeader, StatusTag } from "../../../shared/components/UI.jsx"; +import { typeLabel } from "../../../shared/utils/catalog.js"; +import { dateLabel } from "../../../shared/utils/format.js"; +import { siteLabel } from "../../../shared/hooks/useBrowserEvents.js"; +import { href } from "../../../app/router.js"; +import { CONTRACT_STATUS } from "../../../shared/utils/status.js"; +import { contractStatus, facilityOf } from "../../../app/state/appSelectors.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; + +export function RentedUnitListPage() { + const { data } = useApp(); + return ( +
+ + {data.contracts.length === 0 ? ( + + ) : ( +
+ {data.contracts.map((c) => { + const f = facilityOf(data, c.facility_id, c.facility_name); + return ( +
+ +

{c.unit_number} · {typeLabel(c.type)}

+

{siteLabel(f)}{c.size_m2 ? ` · ${c.size_m2} m²` : ""}

+

Thời hạn hợp đồng

+

+ Ngày kết thúc: {dateLabel(c.end_date)} +
+ {c.handed_over ? "Đã bàn giao" : "Chờ bàn giao"} · Ra vào {f.hours} +

+ Xem hợp đồng & quản lý +
+ ); + })} +
+ )} +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ReturnRequestPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ReturnRequestPage.jsx new file mode 100644 index 0000000..c9f4059 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/ReturnRequestPage.jsx @@ -0,0 +1,57 @@ +import React, { useState } from "react"; +import { DatePicker, Select } from "../../../shared/components/Pickers.jsx"; +import { Button, Field, LinkButton, Notice, PageHeader } from "../../../shared/components/UI.jsx"; +import { addDays, money, today } from "../../../shared/utils/format.js"; +import { go } from "../../../app/router.js"; +import { contractOf } from "../../../app/state/appSelectors.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { NotFound } from "./components/ContractNotFound.jsx"; + +export const RETURN_SLOTS = ["09:00–09:30", "10:00–10:30", "14:00–14:30", "15:30–16:00"]; + +export function ReturnRequestPage({ id }) { + const { data, dispatch } = useApp(); + const c = contractOf(data, id); + const [date, setDate] = useState(() => (c && c.end_date >= today() ? c.end_date : addDays(today(), 1))); + const [slot, setSlot] = useState(RETURN_SLOTS[0]); + const [notes, setNotes] = useState(""); + const [error, setError] = useState(""); + if (!c) return ; + const submit = async (e) => { + e.preventDefault(); + const res = await dispatch("REQUEST_RETURN", { contract_id: id, date, slot, notes }); + if (!res.ok) return setError(res.error); + go(`sent?type=return&contract=${encodeURIComponent(id)}`); + }; + return ( +
+ +
+
+ { setDate(v); setError(""); }} /> + + + +
+ + setNotes(e.target.value)} /> + +

Trước khi trả kho

+

Dọn hết đồ · Trả thẻ/chìa khóa · Có mặt để kiểm tra cùng nhân viên.

+

Đối chiếu tiền cọc

+

+ Cọc đang giữ: {money(c.deposit)}. Khoản hoàn thực tế được xác nhận sau kiểm tra và trừ các khoản còn phải trả theo chính sách. +

+ {error && {error}} +
+ + Quay lại hợp đồng +
+
+
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/components/ContractNotFound.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/components/ContractNotFound.jsx new file mode 100644 index 0000000..c9cef9a --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/contracts/components/ContractNotFound.jsx @@ -0,0 +1,12 @@ +import React from "react"; +import { Empty, LinkButton } from "../../../../shared/components/UI.jsx"; + +export function NotFound() { + return ( +
+ + Về kho của tôi + +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Overview.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/dashboard/CustomerDashboardPage.jsx similarity index 90% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Overview.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/dashboard/CustomerDashboardPage.jsx index a8e7c47..abfcb07 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Overview.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/dashboard/CustomerDashboardPage.jsx @@ -1,11 +1,11 @@ import React from "react"; -import { EmptyInline } from "../components/Inline"; -import { LinkButton } from "../components/UI"; -import { typeLabel } from "../lib/catalog"; -import { dateLabel, dayMonth } from "../lib/format"; -import { siteLabel } from "../lib/hooks"; -import { href } from "../lib/router"; -import { CONTRACT_STATUS } from "../lib/status"; +import { EmptyInline } from "../../../shared/components/Inline.jsx"; +import { LinkButton } from "../../../shared/components/UI.jsx"; +import { typeLabel } from "../../../shared/utils/catalog.js"; +import { dateLabel, dayMonth } from "../../../shared/utils/format.js"; +import { siteLabel } from "../../../shared/hooks/useBrowserEvents.js"; +import { href } from "../../../app/router.js"; +import { CONTRACT_STATUS } from "../../../shared/utils/status.js"; import { activeContracts, contractStatus, @@ -16,12 +16,12 @@ import { pendingReturn, unpaidCount, upcomingAppointments, -} from "../state/selectors"; -import { useApp } from "../state/store"; +} from "../../../app/state/appSelectors.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; const TONES = { amber: "#b45309", green: "#047857", blue: "#2563eb" }; -export default function Overview() { +export default function CustomerDashboardPage() { const { data } = useApp(); const now = new Date(); const active = activeContracts(data, now); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FacilityDetail.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/facilities/FacilityDetailPage.jsx similarity index 94% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FacilityDetail.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/facilities/FacilityDetailPage.jsx index fd779c2..dd3deb2 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FacilityDetail.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/facilities/FacilityDetailPage.jsx @@ -1,17 +1,17 @@ import React, { useEffect, useMemo, useState } from "react"; -import { Lightbox, Photo } from "../components/Photo"; -import { GALLERY } from "../config/media"; -import { DatePicker, Select } from "../components/Pickers"; -import { directionsUrl } from "../api/payment-access"; -import { Button, Empty, Field, Icon, LinkButton, Notice } from "../components/UI"; -import UnitMap from "../components/UnitMap"; -import { RENTAL_PLANS, UNIT_TYPES, offerTypes, pickOffer, quote } from "../lib/catalog"; -import { UNIT_STATUS, unitsFor } from "../lib/units"; -import { dateLabel, money, today } from "../lib/format"; -import { go, href, qs } from "../lib/router"; -import { useApp } from "../state/store"; +import { Lightbox, Photo } from "../../../shared/components/Photo.jsx"; +import { GALLERY } from "../../../app/config/media.js"; +import { DatePicker, Select } from "../../../shared/components/Pickers.jsx"; +import { directionsUrl } from "../access/accessApi.js"; +import { Button, Empty, Field, Icon, LinkButton, Notice } from "../../../shared/components/UI.jsx"; +import UnitMap from "../../../shared/components/UnitMap.jsx"; +import { RENTAL_PLANS, UNIT_TYPES, offerTypes, pickOffer, quote } from "../../../shared/utils/catalog.js"; +import { UNIT_STATUS, unitsFor } from "../../../shared/utils/units.js"; +import { dateLabel, money, today } from "../../../shared/utils/format.js"; +import { go, href, qs } from "../../../app/router.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; -export default function FacilityDetail({ id, query }) { +export default function FacilityDetailPage({ id, query }) { const { data, authed, dispatch, checkAvailability } = useApp(); const facility = data.facilities.find((f) => f.facility_id === Number(id)); const startQuery = query.get("start"); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FindList.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/facilities/FacilityListPage.jsx similarity index 89% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FindList.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/facilities/FacilityListPage.jsx index 2aa4550..95aabe5 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FindList.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/facilities/FacilityListPage.jsx @@ -1,13 +1,13 @@ import React from "react"; -import SearchBar from "../components/SearchBar"; -import { ViewToggle } from "../components/Inline"; -import { Photo } from "../components/Photo"; -import { Pagination, Select } from "../components/Pickers"; -import { Empty, LinkButton, PageHeader } from "../components/UI"; -import { BUDGET_LIMIT, areaLabel, displayOffer, searchFacilities, typeLabel } from "../lib/catalog"; -import { money } from "../lib/format"; -import { go, href, qs } from "../lib/router"; -import { useApp } from "../state/store"; +import SearchBar from "../../../shared/components/SearchBar.jsx"; +import { ViewToggle } from "../../../shared/components/Inline.jsx"; +import { Photo } from "../../../shared/components/Photo.jsx"; +import { Pagination, Select } from "../../../shared/components/Pickers.jsx"; +import { Empty, LinkButton, PageHeader } from "../../../shared/components/UI.jsx"; +import { BUDGET_LIMIT, areaLabel, displayOffer, searchFacilities, typeLabel } from "../../../shared/utils/catalog.js"; +import { money } from "../../../shared/utils/format.js"; +import { go, href, qs } from "../../../app/router.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; const PER_PAGE = 9; @@ -22,7 +22,7 @@ export const filtersFromQuery = (q) => ({ const compactLabel = (s) => s.replaceAll(" – ", "–"); -export default function FindList({ query }) { +export default function FacilityListPage({ query }) { const { data } = useApp(); const filters = filtersFromQuery(query); const page = Math.max(1, Number(query.get("page")) || 1); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FindMap.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/facilities/FacilityMapPage.jsx similarity index 91% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FindMap.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/facilities/FacilityMapPage.jsx index 76d139c..10cc6b4 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/FindMap.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/facilities/FacilityMapPage.jsx @@ -1,15 +1,15 @@ import React, { useEffect, useMemo, useRef, useState } from "react"; -import { Photo } from "../components/Photo"; -import SearchBar from "../components/SearchBar"; -import { ViewToggle } from "../components/Inline"; -import { directionsUrl } from "../api/payment-access"; -import { Icon, PageHeader } from "../components/UI"; -import { HCMC_CENTER, coordsOf } from "../config/geo"; -import { areaLabel, minRate, offerTypes, searchFacilities, typeLabel } from "../lib/catalog"; -import { money } from "../lib/format"; -import { go, href, qs } from "../lib/router"; -import { useApp } from "../state/store"; -import { filtersFromQuery } from "./FindList"; +import { Photo } from "../../../shared/components/Photo.jsx"; +import SearchBar from "../../../shared/components/SearchBar.jsx"; +import { ViewToggle } from "../../../shared/components/Inline.jsx"; +import { directionsUrl } from "../access/accessApi.js"; +import { Icon, PageHeader } from "../../../shared/components/UI.jsx"; +import { HCMC_CENTER, coordsOf } from "../../../app/config/geo.js"; +import { areaLabel, minRate, offerTypes, searchFacilities, typeLabel } from "../../../shared/utils/catalog.js"; +import { money } from "../../../shared/utils/format.js"; +import { go, href, qs } from "../../../app/router.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { filtersFromQuery } from "./FacilityListPage.jsx"; // Nhãn loại kho & diện tích trên thẻ / popup: "Kho thường · Kho lạnh | Cỡ M · 15 m² · Cỡ L · 30 m²" function specLabel(f) { @@ -22,7 +22,7 @@ const MARKER_HTML = ` searchFacilities(data.facilities, filters), [data.facilities, filters.type, filters.band, filters.area]); // eslint-disable-line react-hooks/exhaustive-deps diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Public.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/help/HelpPage.jsx similarity index 61% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Public.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/help/HelpPage.jsx index 3e39f6c..d79d790 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Public.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/help/HelpPage.jsx @@ -1,45 +1,7 @@ import React, { useState } from "react"; -import { Icon, LinkButton, PageHeader } from "../components/UI"; -import { SIZE_BANDS, minRate } from "../lib/catalog"; -import { money } from "../lib/format"; -import { useApp } from "../state/store"; +import { Icon, LinkButton, PageHeader } from "../../../shared/components/UI.jsx"; -export function Pricing() { - const { data } = useApp(); - return ( -
- -
- {SIZE_BANDS.map((b) => { - const from = (type) => { - const rates = data.facilities.map((f) => minRate(f, { band: b.id, type })).filter((x) => x != null); - return rates.length ? Math.min(...rates) : null; - }; - const normal = from("normal"); - const cold = from("climate"); - return ( -
-

{b.name}

- {b.short} -

{normal == null ? "Xem giá theo cơ sở" : `Từ ${money(normal)} / tháng`}

- {cold != null &&

Kho lạnh từ {money(cold)} / tháng

} -

{b.note}

- Tìm kho phù hợp -
- ); - })} -
-
-

Tiền thuê, tiền cọc và phí phát sinh

-

- Bảng tổng hợp trước thanh toán hiển thị tiền thuê theo kỳ, cọc và phí áp dụng. Tiền cọc được đối chiếu khi trả kho; phí gia hạn, huỷ hoặc quá hạn áp dụng theo chính sách hợp đồng. -

-
- - ); -} - -const FAQ = [ +export const FAQ = [ { q: "Tôi chọn kho như thế nào?", a: "Chọn loại kho, diện tích và khu vực để tìm cơ sở phù hợp. Gói thuê (1, 3 hoặc 6 tháng) và ngày bắt đầu được chọn ở trang chi tiết cơ sở.", @@ -62,7 +24,7 @@ const FAQ = [ }, ]; -export function Guide() { +export function HelpPage() { const [open, setOpen] = useState(null); return (
diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Home.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/home/HomePage.jsx similarity index 96% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Home.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/home/HomePage.jsx index 5fba6a6..f336a5a 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Home.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/home/HomePage.jsx @@ -1,11 +1,11 @@ import React, { useState } from "react"; -import { Photo } from "../components/Photo"; -import { Select } from "../components/Pickers"; -import { Icon, LinkButton } from "../components/UI"; -import { SIZE_BANDS, UNIT_TYPES, areaLabel, listAreas, minRate } from "../lib/catalog"; -import { money } from "../lib/format"; -import { go, href, qs } from "../lib/router"; -import { useApp } from "../state/store"; +import { Photo } from "../../../shared/components/Photo.jsx"; +import { Select } from "../../../shared/components/Pickers.jsx"; +import { Icon, LinkButton } from "../../../shared/components/UI.jsx"; +import { SIZE_BANDS, UNIT_TYPES, areaLabel, listAreas, minRate } from "../../../shared/utils/catalog.js"; +import { money } from "../../../shared/utils/format.js"; +import { go, href, qs } from "../../../app/router.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; // Trang chủ theo Figma "START · SafeSpace / Trang chủ" (14/10): // hero ảnh + tìm kho theo khu vực → số liệu → 4 loại kho → 3 bước → cơ sở theo khu vực → kêu gọi → footer. @@ -106,7 +106,7 @@ function FacilityCard({ f }) { ); } -export default function Home() { +export default function HomePage() { const { data, authed } = useApp(); const facilities = data.facilities; const [area, setArea] = useState(""); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/CheckoutFailedPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/CheckoutFailedPage.jsx new file mode 100644 index 0000000..10d4d5d --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/CheckoutFailedPage.jsx @@ -0,0 +1,26 @@ +import React, { useEffect } from "react"; +import { DetailList, Icon, LinkButton } from "../../../shared/components/UI.jsx"; +import { go } from "../../../app/router.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { NotFound } from "../reservations/components/ReservationNotFound.jsx"; + +export function CheckoutFailedPage({ id }) { + const { data } = useApp(); + const r = data.reservations.find((x) => x.reservation_id === id); + useEffect(() => { + if (r && r.status !== "CANCELLED") go(r.status === "PENDING_PAYMENT" ? `checkout/${id}` : `confirmation/${id}`, { replace: true }); + }, [r?.status, id]); + if (!r) return ; + return ( +
+
+ +

Đặt chỗ không thành công

+

Chúng tôi chưa nhận được thanh toán trong thời gian giữ chỗ, nên đơn đặt chỗ đã được huỷ.

+ + Về trang chủ + Xem cơ sở khác +
+
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Checkout.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/CheckoutPage.jsx similarity index 62% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Checkout.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/CheckoutPage.jsx index d557fd7..518cbb9 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Checkout.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/CheckoutPage.jsx @@ -1,33 +1,22 @@ import React, { useCallback, useEffect, useState } from "react"; -import { Photo } from "../components/Photo"; -import { Button, DetailList, Empty, Icon, LinkButton, Notice } from "../components/UI"; -import QrCode from "../components/QrCode"; -import { bandLabel, typeLabel } from "../lib/catalog"; -import { dateLabel, formatCountdown, money, rangeLabel } from "../lib/format"; -import { useNow, shortName } from "../lib/hooks"; -import { go } from "../lib/router"; -import { RESERVATION_STATUS } from "../lib/status"; -import { facilityOf } from "../state/selectors"; -import { useApp } from "../state/store"; +import { Photo } from "../../../shared/components/Photo.jsx"; +import { Button, Notice } from "../../../shared/components/UI.jsx"; +import QrCode from "../../../shared/components/QrCode.jsx"; +import { formatCountdown, money } from "../../../shared/utils/format.js"; +import { useNow } from "../../../shared/hooks/useBrowserEvents.js"; +import { go } from "../../../app/router.js"; +import { facilityOf } from "../../../app/state/appSelectors.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { NotFound } from "../reservations/components/ReservationNotFound.jsx"; -function NotFound() { - return ( -
- - Xem đơn đặt chỗ của tôi - -
- ); -} - -const PAY_METHODS = [ +export const PAY_METHODS = [ ["qr", "Thanh toán QR", "Thanh toán ngay"], ["store", "Tại cửa hàng", "Trả khi nhận kho"], ]; -const POLL_MS = 3000; -// C04 — Đặt chỗ & Thanh toán: QR PayOS (tự xác nhận qua webhook, trang tự chuyển) hoặc C04c — thanh toán tại cửa hàng -export function Checkout({ id }) { +export const POLL_MS = 3000; + +export function CheckoutPage({ id }) { const { data, dispatch, timeoutSeconds, services } = useApp(); const r = data.reservations.find((x) => x.reservation_id === id); const facility = r && facilityOf(data, r.facility_id, r.facility_name); @@ -216,86 +205,3 @@ export function Checkout({ id }) {
); } - -// C04b — Đặt chỗ không thành công -export function CheckoutFailed({ id }) { - const { data } = useApp(); - const r = data.reservations.find((x) => x.reservation_id === id); - useEffect(() => { - if (r && r.status !== "CANCELLED") go(r.status === "PENDING_PAYMENT" ? `checkout/${id}` : `confirmation/${id}`, { replace: true }); - }, [r?.status, id]); - if (!r) return ; - return ( -
-
- -

Đặt chỗ không thành công

-

Chúng tôi chưa nhận được thanh toán trong thời gian giữ chỗ, nên đơn đặt chỗ đã được huỷ.

- - Về trang chủ - Xem cơ sở khác -
-
- ); -} - -// C05 (đã thanh toán QR) / C05c (giữ chỗ, thanh toán tại cửa hàng) và chi tiết đơn từ Đặt chỗ của tôi -export function ReservationSummary({ id, mode = "confirmation" }) { - const { data } = useApp(); - const now = useNow(1000); - const r = data.reservations.find((x) => x.reservation_id === id); - if (!r) return ; - const facility = facilityOf(data, r.facility_id, r.facility_name); - const isDetail = mode === "detail"; - const waiting = r.status === "PENDING_PAYMENT" && r.expires_at && new Date(r.expires_at) > now; - const atStore = r.status === "PENDING_VERIFICATION"; - const statusText = - r.status === "CANCELLED" && r.refund_status === "PENDING" - ? "Đã huỷ · Đang hoàn tiền" - : !isDetail && r.status === "CONFIRMED" - ? "Đã thanh toán" - : RESERVATION_STATUS[r.status][0]; - const titles = { - PENDING_PAYMENT: "Đơn đang chờ thanh toán", - PENDING_VERIFICATION: "Đã giữ chỗ cho bạn", - CONFIRMED: "Đơn đặt chỗ đã được xác nhận", - CHECKED_IN: "Bạn đã nhận kho", - CANCELLED: "Đơn đặt chỗ đã huỷ", - }; - const rows = [ - ["Cơ sở", facility.district && /^SafeSpace/.test(facility.name) ? `SafeSpace ${facility.district} — ${shortName(facility)}` : facility.name], - ["Kỳ thuê", `${rangeLabel(r.start_date, r.end_date)} · ${r.months} tháng`], - ]; - if (isDetail) { - rows.push(["Loại kho", `${typeLabel(r.type)} · ${r.size_label || bandLabel(r.band)}`], ["Tổng ban đầu", money(r.initial_total)]); - if (r.cancel_reason) rows.push(["Lý do huỷ", r.cancel_reason]); - if (r.refund_amount) rows.push(["Số tiền hoàn", money(r.refund_amount)]); - } - if (atStore) rows.push(["Số tiền thanh toán (thuê + cọc)", money(r.initial_total)], ["Hạn giữ chỗ", "24 giờ kể từ khi đặt"]); - rows.push(["Trạng thái", statusText]); - - return ( -
-
- - - -

{isDetail ? titles[r.status] : atStore ? "Đã giữ chỗ cho bạn" : "Đã nhận thông tin đặt chỗ"}

-

Mã đặt chỗ #{r.reservation_id}

- - {atStore && ( - Vui lòng đến cơ sở và thanh toán bằng tiền mặt hoặc thẻ tại quầy trong thời gian giữ chỗ. Quá hạn, đơn đặt chỗ sẽ tự huỷ. - )} - {waiting && Tiếp tục thanh toán} - {isDetail ? ( - <> - {r.status === "CONFIRMED" && Xem lịch nhận kho} - Về đơn đặt chỗ - - ) : ( - Về Dashboard - )} -
-
- ); -} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Payments.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/PaymentListPage.jsx similarity index 91% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Payments.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/PaymentListPage.jsx index e025c90..ea04b0a 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Payments.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/payments/PaymentListPage.jsx @@ -1,13 +1,13 @@ import React, { useState } from "react"; -import PayosModal from "../components/PayosModal"; -import { Button, Empty, LinkButton, Notice, PageHeader, StatusTag } from "../components/UI"; -import { dateLabel, money } from "../lib/format"; -import { APPOINTMENT_STATUS, LEDGER_STATUS } from "../lib/status"; -import { facilityOf } from "../state/selectors"; -import { useApp } from "../state/store"; +import PayosModal from "../../../shared/components/PayosModal.jsx"; +import { Button, Empty, LinkButton, Notice, PageHeader, StatusTag } from "../../../shared/components/UI.jsx"; +import { dateLabel, money } from "../../../shared/utils/format.js"; +import { APPOINTMENT_STATUS, LEDGER_STATUS } from "../../../shared/utils/status.js"; +import { facilityOf } from "../../../app/state/appSelectors.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; // C11 — Thanh toán & lịch hẹn. Khoản gia hạn đã duyệt có nút "Thanh toán" mở QR PayOS (C11q), trả xong → C11b. -export default function Payments() { +export default function PaymentListPage() { const { data } = useApp(); const [paying, setPaying] = useState(null); const [paid, setPaid] = useState(null); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/pricing/PublicPricingPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/pricing/PublicPricingPage.jsx new file mode 100644 index 0000000..f52d5ff --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/pricing/PublicPricingPage.jsx @@ -0,0 +1,40 @@ +import React from "react"; +import { LinkButton, PageHeader } from "../../../shared/components/UI.jsx"; +import { SIZE_BANDS, minRate } from "../../../shared/utils/catalog.js"; +import { money } from "../../../shared/utils/format.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; + +export function PublicPricingPage() { + const { data } = useApp(); + return ( +
+ +
+ {SIZE_BANDS.map((b) => { + const from = (type) => { + const rates = data.facilities.map((f) => minRate(f, { band: b.id, type })).filter((x) => x != null); + return rates.length ? Math.min(...rates) : null; + }; + const normal = from("normal"); + const cold = from("climate"); + return ( +
+

{b.name}

+ {b.short} +

{normal == null ? "Xem giá theo cơ sở" : `Từ ${money(normal)} / tháng`}

+ {cold != null &&

Kho lạnh từ {money(cold)} / tháng

} +

{b.note}

+ Tìm kho phù hợp +
+ ); + })} +
+
+

Tiền thuê, tiền cọc và phí phát sinh

+

+ Bảng tổng hợp trước thanh toán hiển thị tiền thuê theo kỳ, cọc và phí áp dụng. Tiền cọc được đối chiếu khi trả kho; phí gia hạn, huỷ hoặc quá hạn áp dụng theo chính sách hợp đồng. +

+
+
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Profile.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/profile/CustomerProfilePage.jsx similarity index 93% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Profile.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/profile/CustomerProfilePage.jsx index f0a87ef..38b326d 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Profile.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/profile/CustomerProfilePage.jsx @@ -1,10 +1,10 @@ import React, { useState } from "react"; -import { Button, Dialog, Field, PageHeader } from "../components/UI"; -import { go } from "../lib/router"; -import { maskPhone } from "../lib/format"; -import { useApp } from "../state/store"; +import { Button, Dialog, Field, PageHeader } from "../../../shared/components/UI.jsx"; +import { go } from "../../../app/router.js"; +import { maskPhone } from "../../../shared/utils/format.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; -export default function Profile() { +export default function CustomerProfilePage() { const { data, dispatch, logout, supports } = useApp(); const { user } = data; const [name, setName] = useState(user.full_name); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/requests/RequestSentPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/requests/RequestSentPage.jsx new file mode 100644 index 0000000..4dfb46b --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/requests/RequestSentPage.jsx @@ -0,0 +1,22 @@ +import React from "react"; +import { LinkButton, PageHeader, Tag } from "../../../shared/components/UI.jsx"; + +export function RequestSentPage({ query }) { + const contract = query.get("contract"); + return ( +
+ +
+ Chờ cơ sở xác nhận +

Tiếp theo

+

+ Nhân viên hoặc quản lý kiểm tra thông tin và phản hồi qua thông báo. Trạng thái thuê kho hiện tại vẫn được giữ cho đến khi yêu cầu được xử lý. +

+
+ Về kho của tôi + {contract && Xem hợp đồng} +
+
+
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/ReservationDetailPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/ReservationDetailPage.jsx new file mode 100644 index 0000000..235f215 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/ReservationDetailPage.jsx @@ -0,0 +1,69 @@ +import React from "react"; +import { DetailList, Icon, LinkButton, Notice } from "../../../shared/components/UI.jsx"; +import { bandLabel, typeLabel } from "../../../shared/utils/catalog.js"; +import { money, rangeLabel } from "../../../shared/utils/format.js"; +import { useNow, shortName } from "../../../shared/hooks/useBrowserEvents.js"; +import { RESERVATION_STATUS } from "../../../shared/utils/status.js"; +import { facilityOf } from "../../../app/state/appSelectors.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; +import { NotFound } from "./components/ReservationNotFound.jsx"; + +export function ReservationDetailPage({ id, mode = "confirmation" }) { + const { data } = useApp(); + const now = useNow(1000); + const r = data.reservations.find((x) => x.reservation_id === id); + if (!r) return ; + const facility = facilityOf(data, r.facility_id, r.facility_name); + const isDetail = mode === "detail"; + const waiting = r.status === "PENDING_PAYMENT" && r.expires_at && new Date(r.expires_at) > now; + const atStore = r.status === "PENDING_VERIFICATION"; + const statusText = + r.status === "CANCELLED" && r.refund_status === "PENDING" + ? "Đã huỷ · Đang hoàn tiền" + : !isDetail && r.status === "CONFIRMED" + ? "Đã thanh toán" + : RESERVATION_STATUS[r.status][0]; + const titles = { + PENDING_PAYMENT: "Đơn đang chờ thanh toán", + PENDING_VERIFICATION: "Đã giữ chỗ cho bạn", + CONFIRMED: "Đơn đặt chỗ đã được xác nhận", + CHECKED_IN: "Bạn đã nhận kho", + CANCELLED: "Đơn đặt chỗ đã huỷ", + }; + const rows = [ + ["Cơ sở", facility.district && /^SafeSpace/.test(facility.name) ? `SafeSpace ${facility.district} — ${shortName(facility)}` : facility.name], + ["Kỳ thuê", `${rangeLabel(r.start_date, r.end_date)} · ${r.months} tháng`], + ]; + if (isDetail) { + rows.push(["Loại kho", `${typeLabel(r.type)} · ${r.size_label || bandLabel(r.band)}`], ["Tổng ban đầu", money(r.initial_total)]); + if (r.cancel_reason) rows.push(["Lý do huỷ", r.cancel_reason]); + if (r.refund_amount) rows.push(["Số tiền hoàn", money(r.refund_amount)]); + } + if (atStore) rows.push(["Số tiền thanh toán (thuê + cọc)", money(r.initial_total)], ["Hạn giữ chỗ", "24 giờ kể từ khi đặt"]); + rows.push(["Trạng thái", statusText]); + + return ( +
+
+ + + +

{isDetail ? titles[r.status] : atStore ? "Đã giữ chỗ cho bạn" : "Đã nhận thông tin đặt chỗ"}

+

Mã đặt chỗ #{r.reservation_id}

+ + {atStore && ( + Vui lòng đến cơ sở và thanh toán bằng tiền mặt hoặc thẻ tại quầy trong thời gian giữ chỗ. Quá hạn, đơn đặt chỗ sẽ tự huỷ. + )} + {waiting && Tiếp tục thanh toán} + {isDetail ? ( + <> + {r.status === "CONFIRMED" && Xem lịch nhận kho} + Về đơn đặt chỗ + + ) : ( + Về Dashboard + )} +
+
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Reservations.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/ReservationListPage.jsx similarity index 92% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Reservations.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/ReservationListPage.jsx index cdef2af..5eb9114 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Reservations.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/ReservationListPage.jsx @@ -1,12 +1,12 @@ import React, { useEffect, useState } from "react"; -import { EmptyInline } from "../components/Inline"; -import { Button, Field, LinkButton, Modal, Notice, PageHeader } from "../components/UI"; -import { dateLabel, money, shortCode } from "../lib/format"; -import { shortName } from "../lib/hooks"; -import { href } from "../lib/router"; -import { RESERVATION_STATUS } from "../lib/status"; -import { facilityOf, sortedReservations } from "../state/selectors"; -import { useApp } from "../state/store"; +import { EmptyInline } from "../../../shared/components/Inline.jsx"; +import { Button, Field, LinkButton, Modal, Notice, PageHeader } from "../../../shared/components/UI.jsx"; +import { dateLabel, money, shortCode } from "../../../shared/utils/format.js"; +import { shortName } from "../../../shared/hooks/useBrowserEvents.js"; +import { href } from "../../../app/router.js"; +import { RESERVATION_STATUS } from "../../../shared/utils/status.js"; +import { facilityOf, sortedReservations } from "../../../app/state/appSelectors.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; // Đơn khách tự huỷ được: chờ thanh toán, hoặc đã thanh toán nhưng chưa nhận kho (cùng quy tắc backend: // ReservationService.CancelReservationAsync nhận PENDING_PAYMENT / CONFIRMED) @@ -83,7 +83,7 @@ function CancelDialog({ r, onDone, onClose }) { } // C14 — Đơn đặt chỗ của tôi (C14b sau khi huỷ) -export default function Reservations() { +export default function ReservationListPage() { const { data } = useApp(); const [cancelling, setCancelling] = useState(null); const [done, setDone] = useState(null); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/components/ReservationNotFound.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/components/ReservationNotFound.jsx new file mode 100644 index 0000000..d023795 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/reservations/components/ReservationNotFound.jsx @@ -0,0 +1,12 @@ +import React from "react"; +import { Empty, LinkButton } from "../../../../shared/components/UI.jsx"; + +export function NotFound() { + return ( +
+ + Xem đơn đặt chỗ của tôi + +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Support.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/support/SupportPage.jsx similarity index 95% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Support.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/support/SupportPage.jsx index 080cb4d..87dbe01 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/pages/Support.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/customer/support/SupportPage.jsx @@ -1,10 +1,10 @@ import React, { useRef, useState } from "react"; -import { Select } from "../components/Pickers"; -import { Button, Dialog, Field, Modal, Notice, PageHeader, StatusTag } from "../components/UI"; -import { dateTimeLabel } from "../lib/format"; -import { TICKET_STATUS, TICKET_TOPICS } from "../lib/status"; -import { facilityOf } from "../state/selectors"; -import { useApp } from "../state/store"; +import { Select } from "../../../shared/components/Pickers.jsx"; +import { Button, Dialog, Field, Modal, Notice, PageHeader, StatusTag } from "../../../shared/components/UI.jsx"; +import { dateTimeLabel } from "../../../shared/utils/format.js"; +import { TICKET_STATUS, TICKET_TOPICS } from "../../../shared/utils/status.js"; +import { facilityOf } from "../../../app/state/appSelectors.js"; +import { useApp } from "../../../app/state/AppProvider.jsx"; const MAX_FILES = 3; const MAX_MB = 5; @@ -78,7 +78,7 @@ function TicketCard({ t }) { ); } -export default function Support({ query }) { +export default function SupportPage({ query }) { const { data, dispatch, mode } = useApp(); const [busy, setBusy] = useState(false); const preContract = query.get("contract"); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/OpsShell.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/FacilityOperationsLayout.jsx similarity index 94% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/OpsShell.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/FacilityOperationsLayout.jsx index 072da3c..ddb6702 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/OpsShell.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/FacilityOperationsLayout.jsx @@ -1,9 +1,9 @@ import React, { useEffect, useRef, useState } from "react"; -import { Icon } from "../components/UI"; -import { go, href } from "../lib/router"; -import { whenLabel } from "../state/selectors"; -import { useApp } from "../state/store"; -import { useOps } from "./store"; +import { Icon } from "../../shared/components/UI.jsx"; +import { go, href } from "../../app/router.js"; +import { whenLabel } from "../../app/state/appSelectors.js"; +import { useApp } from "../../app/state/AppProvider.jsx"; +import { useOps } from "./state/FacilityOperationsProvider.jsx"; export const STAFF_TABS = [ ["staff", "Công việc ngày"], @@ -115,7 +115,7 @@ function UserMenu({ roleLabel, tone, facilityName }) { } // Khung chung khu vận hành (Figma S01 / M01): logo, tên + vai trò, chuông, thanh điều hướng theo vai trò -export default function OpsShell({ role, active, children }) { +export default function FacilityOperationsLayout({ role, active, children }) { const { mode } = useApp(); const { source, ops } = useOps(); const staff = role === "STAFF"; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/FacilityOperationsRoutes.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/FacilityOperationsRoutes.jsx new file mode 100644 index 0000000..77c81c7 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/FacilityOperationsRoutes.jsx @@ -0,0 +1,68 @@ +import React from "react"; +import { Empty, LinkButton } from "../../shared/components/UI.jsx"; +import { UnitAllocationPage } from "../manager/allocations/UnitAllocationPage.jsx"; +import { StaffAssignmentPage } from "../manager/assignments/StaffAssignmentPage.jsx"; +import { ContractListPage } from "../manager/contracts/ContractListPage.jsx"; +import { ManagerResultPage } from "../manager/results/ManagerResultPage.jsx"; +import { ManagerDashboardPage } from "../manager/dashboard/ManagerDashboardPage.jsx"; +import { RenewalApprovalPage } from "../manager/renewals/RenewalApprovalPage.jsx"; +import { FacilityReportPage } from "../manager/reports/FacilityReportPage.jsx"; +import { UnitManagementPage } from "../manager/units/UnitManagementPage.jsx"; +import FacilityOperationsLayout from "./FacilityOperationsLayout.jsx"; +import { StaffResultPage } from "../staff/results/StaffResultPage.jsx"; +import { HandoverPage } from "../staff/handovers/HandoverPage.jsx"; +import { PaymentConfirmationPage } from "../staff/payments/PaymentConfirmationPage.jsx"; +import { ReturnInspectionPage } from "../staff/returns/ReturnInspectionPage.jsx"; +import { StaffSupportPage } from "../staff/support/StaffSupportPage.jsx"; +import { StaffDashboardPage } from "../staff/dashboard/StaffDashboardPage.jsx"; +import { CustomerVerificationPage } from "../staff/handovers/CustomerVerificationPage.jsx"; +import { useMe } from "../staff/hooks/useStaffIdentity.js"; +import { StaffTaskList } from "./components/StaffTasks.jsx"; + +// Tab nhân viên: không có ?id → lưới 3x3 các việc của tab; có ?id → màn xử lý chi tiết +const LIST_KIND = { reconcile: "reconcile", verify: "verify", handover: "handover", return: "return", support: "support" }; +function StaffTab({ kind, Detail, query }) { + const me = useMe(); + return query.get("id") ? : ; +} + +// #/staff/... (Figma S01–S09) #/manager/... (Figma M01–M08) +const STAFF = { + "": [StaffDashboardPage, "staff"], + reconcile: [PaymentConfirmationPage, "staff/reconcile"], + verify: [CustomerVerificationPage, "staff/verify"], + handover: [HandoverPage, "staff/handover"], + return: [ReturnInspectionPage, "staff/return"], + support: [StaffSupportPage, "staff/support"], + done: [StaffResultPage, "staff"], +}; +const MANAGER = { + "": [ManagerDashboardPage, "manager"], + units: [UnitManagementPage, "manager/units"], + allocate: [UnitAllocationPage, "manager/allocate"], + assign: [StaffAssignmentPage, "manager/assign"], + renewals: [RenewalApprovalPage, "manager/renewals"], + contracts: [ContractListPage, "manager/contracts"], + report: [FacilityReportPage, "manager/report"], + done: [ManagerResultPage, "manager"], +}; + +export default function FacilityOperationsRoutes({ role, parts, query }) { + const staff = role === "STAFF"; + const table = staff ? STAFF : MANAGER; + const hit = table[parts[0] || ""]; + const [Page, active] = hit || [null, ""]; + return ( + + {Page ? ( + staff && LIST_KIND[parts[0]] ? : + ) : ( +
+ + Về trang chính + +
+ )} +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/api.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/api/facilityOperationsApi.js similarity index 98% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/api.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/api/facilityOperationsApi.js index 4a6b75d..9f2eaef 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/api.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/api/facilityOperationsApi.js @@ -1,7 +1,7 @@ // API khu vận hành (Nhân viên cơ sở / Quản lý cơ sở): StorageProject.Api/Endpoints/FacilityOpsEndpoints.cs, // tài liệu ở docs/facility-ops-api.md; mock/mock-api.mjs (MOCK_OPS=1) chạy cùng hợp đồng để thử không cần .NET. // Backend cũ trả 404 cho GET /api/ops/board → giao diện dùng dữ liệu cục bộ trong trình duyệt (ops/store.jsx). -import { request } from "../api/http.js"; +import { request } from "../../../shared/api/httpClient.js"; const enc = encodeURIComponent; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/util.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/components/FacilityOperationsComponents.jsx similarity index 91% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/util.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/components/FacilityOperationsComponents.jsx index 651edb9..a5b5fd1 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/util.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/components/FacilityOperationsComponents.jsx @@ -1,6 +1,6 @@ import React from "react"; -import { dayMonth, localDate, timeLabel } from "../lib/format"; -import { go, qs } from "../lib/router"; +import { dayMonth, localDate, timeLabel } from "../../../shared/utils/format.js"; +import { go, qs } from "../../../app/router.js"; // "Hôm nay · 14:00", "20/09 · 09:00" export function slotLabel(isoDateTime, now = new Date()) { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/tasks.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/components/StaffTasks.jsx similarity index 95% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/tasks.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/components/StaffTasks.jsx index 213d929..41d4db9 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/tasks.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/components/StaffTasks.jsx @@ -1,11 +1,11 @@ import React from "react"; -import { Pagination } from "../components/Pickers"; -import { Icon } from "../components/UI"; -import { dateLabel, money, today } from "../lib/format"; -import { go, href, qs } from "../lib/router"; -import { TICKET_STATE } from "./reducer"; -import { useOps } from "./store"; -import { slotLabel } from "./util"; +import { Pagination } from "../../../shared/components/Pickers.jsx"; +import { Icon } from "../../../shared/components/UI.jsx"; +import { dateLabel, money, today } from "../../../shared/utils/format.js"; +import { go, href, qs } from "../../../app/router.js"; +import { TICKET_STATE } from "../state/facilityOperationsReducer.js"; +import { useOps } from "../state/FacilityOperationsProvider.jsx"; +import { slotLabel } from "./FacilityOperationsComponents.jsx"; // Trong câu: "Hẹn hôm nay · 14:00" const slot = (iso) => slotLabel(iso).replace(/^Hôm nay/, "hôm nay"); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/data.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/data/facilityOperationsSeed.js similarity index 99% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/data.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/data/facilityOperationsSeed.js index 889be99..47fff49 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/data.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/data/facilityOperationsSeed.js @@ -1,7 +1,7 @@ // Dữ liệu vận hành tại cơ sở cho khu Nhân viên (S01–S09) và Quản lý cơ sở (M01–M08) khi chạy không backend // (VITE_USE_API=false) hoặc máy chủ giả lập. Có backend thì dữ liệu lấy từ GET /api/ops/board (ops/api.js); // hình dạng dữ liệu hai bên giống nhau. -import { addDays, addMonths, today } from "../lib/format.js"; +import { addDays, addMonths, today } from "../../../shared/utils/format.js"; export const OPS_PASSWORD = "SafeSpace@123"; // Tài khoản dùng khi chạy không cần backend (VITE_USE_API=false) diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/store.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/state/FacilityOperationsProvider.jsx similarity index 95% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/store.jsx rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/state/FacilityOperationsProvider.jsx index b6f6735..1be2156 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/store.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/state/FacilityOperationsProvider.jsx @@ -1,8 +1,8 @@ import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; -import { ApiError } from "../api/http"; -import { callAction, loadBoard } from "./api"; -import { createOpsData } from "./data"; -import { reduceOps } from "./reducer"; +import { ApiError } from "../../../shared/api/httpClient.js"; +import { callAction, loadBoard } from "../api/facilityOperationsApi.js"; +import { createOpsData } from "../data/facilityOperationsSeed.js"; +import { reduceOps } from "./facilityOperationsReducer.js"; // Kho dữ liệu vận hành cho khu Nhân viên & Quản lý cơ sở. // - mode "api": đọc GET /api/ops/board, mỗi thao tác gọi endpoint tương ứng (ops/api.js) rồi nạp lại. diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/reducer.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/state/facilityOperationsReducer.js similarity index 99% rename from SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/reducer.js rename to SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/state/facilityOperationsReducer.js index 24fd5ea..9fd65e5 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/ops/reducer.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/state/facilityOperationsReducer.js @@ -1,5 +1,5 @@ // Nghiệp vụ vận hành tại cơ sở (thuần, có test). Mỗi action trả { state, result } hoặc ném OpsError. -import { dateLabel, money } from "../lib/format.js"; +import { dateLabel, money } from "../../../shared/utils/format.js"; export class OpsError extends Error {} const fail = (m) => { diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/unitStateTag.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/unitStateTag.js new file mode 100644 index 0000000..1612c99 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/facility-operations/utils/unitStateTag.js @@ -0,0 +1,4 @@ +import React from "react"; +import { UNIT_STATE } from "../data/facilityOperationsSeed.js"; + +export const unitStateTag = (s) => UNIT_STATE[s] || [s, "gray"]; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/allocations/UnitAllocationPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/allocations/UnitAllocationPage.jsx new file mode 100644 index 0000000..bb2dd78 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/allocations/UnitAllocationPage.jsx @@ -0,0 +1,66 @@ +import React, { useState } from "react"; +import { Button, Empty, LinkButton, Notice, Tag } from "../../../shared/components/UI.jsx"; +import { dateTimeLabel, rangeLabel } from "../../../shared/utils/format.js"; +import { go } from "../../../app/router.js"; +import { candidateUnits } from "../../facility-operations/state/facilityOperationsReducer.js"; +import { useOps } from "../../facility-operations/state/FacilityOperationsProvider.jsx"; +import { QueuePicker } from "../../facility-operations/components/FacilityOperationsComponents.jsx"; +import { PageHeaderBlock } from "../components/PageHeaderBlock.jsx"; + +export function UnitAllocationPage({ query }) { + const { ops, run } = useOps(); + const pending = ops.allocations.filter((a) => a.status === "PENDING"); + const a = ops.allocations.find((x) => x.id === query.get("id")) || pending[0]; + const units = a ? candidateUnits(ops, a) : []; + const [pick, setPick] = useState(null); + const chosen = units.find((u) => u.code === pick) || units[0]; + if (!a) + return ( +
+ + Về tổng quan + +
+ ); + const submit = async () => { + const r = await run("ALLOCATE", { id: a.id, unit: chosen?.code }, `Đã phân bổ kho ${chosen?.code}`); + if (r.ok) go("manager/done?kind=allocate"); + }; + return ( +
+ `${x.id.slice(-4)} · ${x.customer}`} /> + +
+ Đã thanh toán + {a.id} · {a.customer} + {a.offer} · {rangeLabel(a.start, a.end)} + Lịch nhận dự kiến: {dateTimeLabel(a.pickup)} +
+ {a.status === "DONE" ? ( + Đã phân bổ kho {a.unit} lúc {dateTimeLabel(a.allocated_at)}. Nhân viên sẽ xác minh và bàn giao theo lịch hẹn. + ) : units.length === 0 ? ( + Không còn kho trống khớp loại kho và diện tích trong kỳ thuê. Liên hệ khách để đổi lựa chọn hoặc cơ sở. + ) : ( + <> +
+ + + + {units.map((u) => ( + setPick(u.code)} className={chosen?.code === u.code ? "is-picked" : ""}> + + + + + + + ))} + +
ChọnMã khoDiện tích / tầngTình trạngKhả dụng
setPick(u.code)} aria-label={`Chọn kho ${u.code}`} />{u.code}{u.area} m² · Tầng {u.floor}Sẵn sàngTrống toàn kỳ
+
+ + + )} +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/assignments/StaffAssignmentPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/assignments/StaffAssignmentPage.jsx new file mode 100644 index 0000000..9739dbe --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/assignments/StaffAssignmentPage.jsx @@ -0,0 +1,63 @@ +import React, { useState } from "react"; +import { Select } from "../../../shared/components/Pickers.jsx"; +import { Button, Field, Notice, Tag } from "../../../shared/components/UI.jsx"; +import { go } from "../../../app/router.js"; +import { ASSIGN_STATE } from "../../facility-operations/state/facilityOperationsReducer.js"; +import { useOps } from "../../facility-operations/state/FacilityOperationsProvider.jsx"; +import { slotLabel } from "../../facility-operations/components/FacilityOperationsComponents.jsx"; +import { PageHeaderBlock } from "../components/PageHeaderBlock.jsx"; + +export function StaffAssignmentPage() { + const { ops, run } = useOps(); + const open = ops.assignments.filter((a) => a.status !== "DONE"); + const [task, setTask] = useState(() => (open.find((a) => a.status === "OPEN") || open[0])?.id || ""); + const [staff, setStaff] = useState(ops.staff[0]?.staff_id || ""); + const staffName = (id) => ops.staff.find((s) => s.staff_id === id)?.full_name || "Chưa phân công"; + const busyCount = (id) => ops.assignments.filter((a) => a.staff === id && a.status !== "DONE").length; + const submit = async (e) => { + e.preventDefault(); + const r = await run("ASSIGN", { id: task, staff }, `Đã phân công ${staffName(staff)}`); + if (r.ok) go("manager/done?kind=assign"); + }; + return ( +
+ +
+ + + + {ops.assignments.map((a) => ( + + + + + + + ))} + +
Công việcLịch hẹnNhân viênTrạng thái
{a.title}{slotLabel(a.when)}{staffName(a.staff)}{ASSIGN_STATE[a.status][0]}
+
+ {open.length > 0 ? ( +
+ + + + + + + +
+ ) : ( + Tất cả công việc đã hoàn tất. + )} +
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/components/PageHeaderBlock.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/components/PageHeaderBlock.jsx new file mode 100644 index 0000000..5b55271 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/components/PageHeaderBlock.jsx @@ -0,0 +1,12 @@ +import React from "react"; + +export function PageHeaderBlock({ title, text }) { + return ( +
+
+

{title}

+ {text &&

{text}

} +
+
+ ); +} diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/contracts/ContractListPage.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/contracts/ContractListPage.jsx new file mode 100644 index 0000000..431cd72 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/features/manager/contracts/ContractListPage.jsx @@ -0,0 +1,82 @@ +import React, { useState } from "react"; +import { Button, Field, LinkButton, Notice, Tag } from "../../../shared/components/UI.jsx"; +import { dateLabel, dateTimeLabel, daysBetween, today } from "../../../shared/utils/format.js"; +import { go, qs } from "../../../app/router.js"; +import { useOps } from "../../facility-operations/state/FacilityOperationsProvider.jsx"; +import { PageHeaderBlock } from "../components/PageHeaderBlock.jsx"; + +export const CONTRACT_STATE = (c) => + c.state === "OVERDUE" + ? [`Quá hạn ${Math.max(1, daysBetween(c.end, today()))} ngày`, "red"] + : c.state === "RENEWAL" + ? ["Cần duyệt", "amber"] + : c.state === "RETURNED" + ? ["Chờ hoàn cọc", "blue"] + : ["Đã xử lý", "green"]; + +export function ContractListPage({ query }) { + const { ops, run } = useOps(); + const sel = ops.contracts.find((c) => c.id === query.get("id")) || ops.contracts.find((c) => c.state === "RETURNED") || ops.contracts[0]; + const [note, setNote] = useState(""); + const mismatch = ops.payments.filter((p) => p.status === "MISMATCH"); + return ( +
+ + {mismatch.map((p) => ( + Nhân viên báo sai lệch thanh toán đơn {p.id} ({p.customer}): {p.note} + ))} +
+ + + + {ops.contracts.map((c) => { + const [label, tone] = CONTRACT_STATE(c); + return ( + go(`manager/contracts${qs({ id: c.id })}`, { replace: true })}> + + + + + + ); + })} + +
Hợp đồng / kháchKho / ngày hết hạnKhoản cần xử lýTrạng thái
{c.id} · {c.customer}{c.unit} · {dateLabel(c.end)}{c.due}{label}
+
+ {sel && ( +
+

{sel.id} · Bước tiếp theo

+ {sel.state === "RETURNED" ? ( + <> +

Nhân viên đã gửi biên bản trả kho {sel.unit}. Đối chiếu khoản còn nợ rồi xác nhận số tiền hoàn cọc.

+ + + ) : sel.state === "RENEWAL" ? ( + <> +

Khách đã gửi yêu cầu gia hạn. Duyệt hoặc từ chối trong vòng 24 giờ.

+ Xem yêu cầu gia hạn + + ) : sel.state === "CLOSED" || sel.state === "RESOLVED" ? ( + {sel.due} + ) : ( + <> +

Kiểm tra thanh toán và trao đổi với khách trước khi áp dụng biện pháp xử lý. Ghi nhận liên hệ, phí phát sinh và quyết định của quản lý.

+ +