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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
4 changes: 4 additions & 0 deletions SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
17 changes: 3 additions & 14 deletions SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/state/store.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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() },
Expand Down
65 changes: 0 additions & 65 deletions StorageProject.Api/Endpoints/ManagerEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
10 changes: 10 additions & 0 deletions StorageProject.Api/Endpoints/ReservationEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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) =>
{
Expand Down
41 changes: 1 addition & 40 deletions StorageProject.Api/Endpoints/StaffEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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) =>
Expand Down Expand Up @@ -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;
}
}
3 changes: 3 additions & 0 deletions StorageProject.Api/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text;
using StorageProject.Api.Workers;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
Expand Down Expand Up @@ -92,6 +93,8 @@
builder.Services.AddScoped<IOperationsService, OperationsService>();
builder.Services.AddScoped<IOperationsReportService, OperationsReportService>();
builder.Services.AddScoped<IFacilityOpsService, FacilityOpsService>();
builder.Services.AddScoped<IPayOSGateway, SdkPayOSGateway>();
builder.Services.AddHostedService<ExpiredCashHoldWorker>();
builder.Services.AddScoped<IPayOSService, PayOSService>();
builder.Services.AddSingleton(new AccessQrOptions(
builder.Configuration["AccessQr:Secret"] ?? jwtSecret,
Expand Down
28 changes: 28 additions & 0 deletions StorageProject.Api/StorageProject.Api.http
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <token-khach>
@staffToken = <token-staff>
@managerToken = <token-manager>
@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" }
19 changes: 19 additions & 0 deletions StorageProject.Api/Workers/ExpiredCashHoldWorker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using StorageProject.Infrastructure.Data;
using StorageProject.Infrastructure.Services;

namespace StorageProject.Api.Workers;

public sealed class ExpiredCashHoldWorker(IServiceScopeFactory scopes, ILogger<ExpiredCashHoldWorker> 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<AppDbContext>(), 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));
}
}
2 changes: 1 addition & 1 deletion StorageProject.Core/DTOs/Payment/PaymentDtos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ namespace StorageProject.Core.DTOs.Payment;

public record PaymentDto(
long PaymentId,
long ContractId,
long? ContractId,
long? RenewalId,
string PaymentType,
decimal Amount,
Expand Down
6 changes: 4 additions & 2 deletions StorageProject.Core/DTOs/Reservation/ReservationDtos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ public record ReservationDto(
DateTime? ExpiresAt,
DateTime? CancelledAt,
string? CancellationReason,
DateTime CreatedAt
DateTime CreatedAt,
string PaymentMethod = "PAYOS"
);

public record ReservationDetailDto(
Expand All @@ -44,5 +45,6 @@ public record ReservationDetailDto(
string? AssignedUnitNumber,
long? ContractId,
string? ContractStatus,
DateTime CreatedAt
DateTime CreatedAt,
string PaymentMethod = "PAYOS"
);
4 changes: 3 additions & 1 deletion StorageProject.Core/Entities/Payment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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; }
}
1 change: 1 addition & 0 deletions StorageProject.Core/Entities/Reservation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down
1 change: 1 addition & 0 deletions StorageProject.Core/Interfaces/IPayOSService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ namespace StorageProject.Core.Interfaces;
public interface IPayOSService
{
Task<CreatePayOSQrResponse> CreatePaymentQrAsync(long customerId, CreatePayOSQrRequest request, CancellationToken ct = default);
Task PayAtFacilityAsync(long customerId, long reservationId, CancellationToken ct = default);
Task<bool> ProcessWebhookAsync(string webhookBodyJson, string? signatureHeader, CancellationToken ct = default);
Task<ReservationPaymentStatusDto?> GetReservationPaymentStatusAsync(long reservationId, CancellationToken ct = default);
}
Loading