[CLAUDE] Workflow: LeaveBalance business logic — trừ phép khi duyệt + số dư (Phase 11 P11-B)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 4m8s
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 4m8s
Số dư phép theo (User × LeaveType × Year) + trừ tự động khi đơn nghỉ duyệt cuối. Policy: cho phép vượt số dư (âm) + cảnh báo (anh main chốt), tích hợp vào trang đơn nghỉ. Schema (Mig 42 AddLeaveBalances — pure additive, 1 bảng): - LeaveBalance: UserId + LeaveTypeId + Year + EntitledDays + UsedDays + AdjustmentDays. UNIQUE (UserId,LeaveTypeId,Year), FK LeaveType Restrict, decimal(5,2). Remaining = Entitled + Adjustment − Used (computed, không store). Deduction hook (ApproveLeaveRequestHandler nhánh terminal DaDuyet — exactly-once): - Upsert LeaveBalance(RequesterUserId, LeaveTypeId, StartDate.Year), auto-create từ LeaveType.DaysPerYear, UsedDays += NumDays. Guard Status!=DaGuiDuyet chặn re-approve. FK invariant guard (em main thêm sau test reveal FK risk): - Create + UpdateDraft validate LeaveTypeId tồn tại (AnyAsync) → ConflictException. Đóng cửa vào — bogus type không thể tới deduction FK insert (tránh 500 kẹt đơn). CQRS LeaveBalanceFeatures.cs: GetMy (self, lazy merge active LeaveType) + GetUser (admin) + AdjustLeaveBalance (admin upsert carry-over). Controller [Authorize] + admin Roles=Admin. Embed: GetLeaveRequestByIdHandler trả balance NGƯỜI TẠO (approver xem thấy đúng). FE: WorkflowAppDetailPage ×2 — block "Số dư phép" + cảnh báo vượt khi kind=leave (SHA256 identical). Tests (+11, 130→154 PASS): deduction single/multi-level/accumulate/negative-allowed/ reject-return-no-deduct + lazy-merge + adjust upsert + Create guard bogus→Conflict. Cũng repair 2 test S42 terminal FK-fail (template BuildLeave +seed LeaveType). Verify: build 0 error · 154 test · FE ×2 · reviewer Max PASS (deduction exactly-once + FK invariant fully closed, 2 minor concurrency/comment defer). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore;
|
||||
using SolutionErp.Application.Common.Exceptions;
|
||||
using SolutionErp.Application.Common.Interfaces;
|
||||
using SolutionErp.Domain.ApprovalWorkflowsV2;
|
||||
using SolutionErp.Domain.Hrm;
|
||||
using SolutionErp.Domain.Office;
|
||||
|
||||
namespace SolutionErp.Application.Office;
|
||||
@ -78,7 +79,12 @@ public record LeaveRequestDetailDto(
|
||||
int? CurrentApprovalLevelOrder,
|
||||
int? RejectedFromStatus,
|
||||
DateTime CreatedAt,
|
||||
List<LeaveRequestLevelOpinionDto> LevelOpinions);
|
||||
List<LeaveRequestLevelOpinionDto> LevelOpinions,
|
||||
// P11-B: số dư phép của NGƯỜI TẠO cho (LeaveType, năm của đơn) — embed để approver
|
||||
// cũng thấy (khác /my = balance người xem). null nếu loại phép không tồn tại.
|
||||
decimal? LeaveBalanceEntitled,
|
||||
decimal? LeaveBalanceUsed,
|
||||
decimal? LeaveBalanceRemaining);
|
||||
|
||||
public record GetLeaveRequestByIdQuery(Guid Id) : IRequest<LeaveRequestDetailDto?>;
|
||||
|
||||
@ -140,12 +146,36 @@ public class GetLeaveRequestByIdHandler(IApplicationDbContext db)
|
||||
.OrderBy(o => o.StepOrder).ThenBy(o => o.LevelOrder)
|
||||
.ToList();
|
||||
|
||||
// P11-B: số dư phép người tạo cho (LeaveType, năm của StartDate) — hiển thị + cảnh báo vượt.
|
||||
// Lazy: chưa có row → từ LeaveType.DaysPerYear (Used=0). Remaining = Entitled + Adjustment − Used.
|
||||
var balYear = p.StartDate.Year;
|
||||
var balRow = await db.LeaveBalances.AsNoTracking()
|
||||
.Where(b => b.UserId == p.RequesterUserId && b.LeaveTypeId == p.LeaveTypeId
|
||||
&& b.Year == balYear && !b.IsDeleted)
|
||||
.Select(b => new { b.EntitledDays, b.UsedDays, b.AdjustmentDays })
|
||||
.FirstOrDefaultAsync(ct);
|
||||
decimal? balEntitled, balUsed, balRemaining;
|
||||
if (balRow is not null)
|
||||
{
|
||||
balEntitled = balRow.EntitledDays + balRow.AdjustmentDays;
|
||||
balUsed = balRow.UsedDays;
|
||||
balRemaining = balRow.EntitledDays + balRow.AdjustmentDays - balRow.UsedDays;
|
||||
}
|
||||
else
|
||||
{
|
||||
var dpy = await db.LeaveTypes.AsNoTracking()
|
||||
.Where(t => t.Id == p.LeaveTypeId).Select(t => (decimal?)t.DaysPerYear).FirstOrDefaultAsync(ct);
|
||||
balEntitled = dpy;
|
||||
balUsed = dpy.HasValue ? 0m : (decimal?)null;
|
||||
balRemaining = dpy;
|
||||
}
|
||||
|
||||
return new LeaveRequestDetailDto(
|
||||
p.Id, p.MaDonTu, p.RequesterUserId, p.RequesterFullName, p.LeaveTypeId,
|
||||
p.StartDate, p.EndDate, p.NumDays, p.Reason, (int)p.Status,
|
||||
p.ApprovalWorkflowId, wfCode, wfName, p.CurrentApprovalLevelOrder,
|
||||
p.RejectedFromStatus.HasValue ? (int)p.RejectedFromStatus.Value : (int?)null,
|
||||
p.CreatedAt, opinions);
|
||||
p.CreatedAt, opinions, balEntitled, balUsed, balRemaining);
|
||||
}
|
||||
}
|
||||
|
||||
@ -195,6 +225,11 @@ public class UpdateLeaveRequestDraftHandler(IApplicationDbContext db, ICurrentUs
|
||||
throw new ConflictException("Quy trình duyệt không thuộc loại Đơn nghỉ phép.");
|
||||
}
|
||||
|
||||
// P11-B: enforce LeaveTypeId tồn tại nếu đổi (deduction FK→LeaveTypes Restrict).
|
||||
if (req.LeaveTypeId != p.LeaveTypeId
|
||||
&& !await db.LeaveTypes.AsNoTracking().AnyAsync(t => t.Id == req.LeaveTypeId, ct))
|
||||
throw new ConflictException("Loại phép không tồn tại.");
|
||||
|
||||
p.LeaveTypeId = req.LeaveTypeId;
|
||||
p.StartDate = req.StartDate;
|
||||
p.EndDate = req.EndDate;
|
||||
@ -319,6 +354,32 @@ public class ApproveLeaveRequestHandler(IApplicationDbContext db, ICurrentUser c
|
||||
{
|
||||
p.Status = WorkflowAppStatus.DaDuyet;
|
||||
p.CurrentApprovalLevelOrder = null;
|
||||
|
||||
// P11-B: trừ phép khi duyệt cuối — chạy đúng 1 lần (DaDuyet không approve lại,
|
||||
// early guard Status != DaGuiDuyet chặn re-approve). UPSERT LeaveBalance theo năm.
|
||||
var year = p.StartDate.Year;
|
||||
var bal = await db.LeaveBalances.FirstOrDefaultAsync(
|
||||
b => b.UserId == p.RequesterUserId && b.LeaveTypeId == p.LeaveTypeId && b.Year == year, ct);
|
||||
if (bal is null)
|
||||
{
|
||||
var daysPerYear = await db.LeaveTypes.AsNoTracking()
|
||||
.Where(t => t.Id == p.LeaveTypeId).Select(t => t.DaysPerYear).FirstOrDefaultAsync(ct);
|
||||
bal = new LeaveBalance
|
||||
{
|
||||
UserId = p.RequesterUserId,
|
||||
LeaveTypeId = p.LeaveTypeId,
|
||||
Year = year,
|
||||
EntitledDays = daysPerYear,
|
||||
UsedDays = 0,
|
||||
AdjustmentDays = 0,
|
||||
CreatedAt = clock.UtcNow,
|
||||
CreatedBy = cu.UserId,
|
||||
};
|
||||
db.LeaveBalances.Add(bal);
|
||||
}
|
||||
bal.UsedDays += p.NumDays;
|
||||
bal.UpdatedAt = clock.UtcNow;
|
||||
bal.UpdatedBy = cu.UserId;
|
||||
}
|
||||
p.UpdatedAt = clock.UtcNow;
|
||||
p.UpdatedBy = cu.UserId;
|
||||
|
||||
@ -41,6 +41,10 @@ public class CreateLeaveRequestHandler(IApplicationDbContext db, ICurrentUser cu
|
||||
public async Task<Guid> Handle(CreateLeaveRequestCommand req, CancellationToken ct)
|
||||
{
|
||||
if (cu.UserId is null) throw new UnauthorizedException();
|
||||
// P11-B: enforce LeaveTypeId tồn tại (deduction lúc duyệt cuối insert LeaveBalance
|
||||
// FK→LeaveTypes Restrict — bogus type → 500 kẹt đơn). Guard tại cửa Create.
|
||||
if (!await db.LeaveTypes.AsNoTracking().AnyAsync(t => t.Id == req.LeaveTypeId, ct))
|
||||
throw new ConflictException("Loại phép không tồn tại.");
|
||||
var e = new LeaveRequest
|
||||
{
|
||||
RequesterUserId = cu.UserId.Value,
|
||||
|
||||
Reference in New Issue
Block a user