[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

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:
pqhuy1987
2026-05-30 11:10:44 +07:00
parent 0db5e1fdc9
commit 82d7fcff4d
21 changed files with 7356 additions and 10 deletions

View File

@ -139,5 +139,8 @@ public interface IApplicationDbContext
// Phase 10.4 G-P1 (Mig 40 — S38) — Chấm công web GPS.
DbSet<Attendance> Attendances { get; }
// Phase 11 P11-B Wave 1 (Mig 42) — Số dư phép theo năm (NV × LoạiPhép × Năm).
DbSet<LeaveBalance> LeaveBalances { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}

View File

@ -0,0 +1,150 @@
using FluentValidation;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SolutionErp.Application.Common.Exceptions;
using SolutionErp.Application.Common.Interfaces;
using SolutionErp.Domain.Hrm;
namespace SolutionErp.Application.Hrm;
// Phase 11 P11-B Wave 1 (Mig 42 — S43 2026-05-30) — Số dư phép theo năm.
// Query lazy: list mọi LeaveType IsActive LEFT JOIN LeaveBalance — chưa có row thì
// synthesize default (Entitled=DaysPerYear, Used=0, Adjustment=0). Admin upsert qua
// AdjustLeaveBalanceCommand. Trừ phép tự động ở ApproveLeaveRequestHandler (terminal).
//
// RemainingDays = EntitledDays + AdjustmentDays UsedDays (COMPUTED, KHÔNG store).
// HRM entities KHÔNG có global HasQueryFilter → query phải Where(!IsDeleted) thủ công.
// ===== DTO =====
public record LeaveBalanceDto(
Guid LeaveTypeId,
string Code,
string Name,
int Year,
decimal EntitledDays,
decimal UsedDays,
decimal AdjustmentDays,
decimal RemainingDays,
decimal DaysPerYear,
bool IsPaid);
// ===== Shared builder: merge active LeaveTypes + balances cho 1 user/năm =====
internal static class LeaveBalanceProjection
{
public static async Task<List<LeaveBalanceDto>> BuildAsync(
IApplicationDbContext db, Guid userId, int year, CancellationToken ct)
{
var types = await db.LeaveTypes.AsNoTracking()
.Where(t => !t.IsDeleted && t.IsActive)
.OrderBy(t => t.Code)
.Select(t => new { t.Id, t.Code, t.Name, t.DaysPerYear, t.IsPaid })
.ToListAsync(ct);
var balances = await db.LeaveBalances.AsNoTracking()
.Where(b => !b.IsDeleted && b.UserId == userId && b.Year == year)
.Select(b => new { b.LeaveTypeId, b.EntitledDays, b.UsedDays, b.AdjustmentDays })
.ToListAsync(ct);
var byType = balances.ToDictionary(b => b.LeaveTypeId);
return types.Select(t =>
{
byType.TryGetValue(t.Id, out var b);
var entitled = b?.EntitledDays ?? t.DaysPerYear;
var used = b?.UsedDays ?? 0m;
var adjustment = b?.AdjustmentDays ?? 0m;
return new LeaveBalanceDto(
t.Id, t.Code, t.Name, year,
entitled, used, adjustment,
entitled + adjustment - used,
t.DaysPerYear, t.IsPaid);
}).ToList();
}
}
// ===== Query: số dư phép của chính mình =====
public record GetMyLeaveBalancesQuery(int Year) : IRequest<List<LeaveBalanceDto>>;
public class GetMyLeaveBalancesHandler(IApplicationDbContext db, ICurrentUser cu)
: IRequestHandler<GetMyLeaveBalancesQuery, List<LeaveBalanceDto>>
{
public async Task<List<LeaveBalanceDto>> Handle(GetMyLeaveBalancesQuery req, CancellationToken ct)
{
if (cu.UserId is null) throw new UnauthorizedException();
return await LeaveBalanceProjection.BuildAsync(db, cu.UserId.Value, req.Year, ct);
}
}
// ===== Query: số dư phép của 1 user (admin) =====
public record GetUserLeaveBalancesQuery(Guid UserId, int Year) : IRequest<List<LeaveBalanceDto>>;
public class GetUserLeaveBalancesHandler(IApplicationDbContext db)
: IRequestHandler<GetUserLeaveBalancesQuery, List<LeaveBalanceDto>>
{
public async Task<List<LeaveBalanceDto>> Handle(GetUserLeaveBalancesQuery req, CancellationToken ct)
=> await LeaveBalanceProjection.BuildAsync(db, req.UserId, req.Year, ct);
}
// ===== Command: admin upsert (carry-over / điều chỉnh) =====
public record AdjustLeaveBalanceCommand(
Guid UserId,
Guid LeaveTypeId,
int Year,
decimal? EntitledDays,
decimal? AdjustmentDays) : IRequest;
public class AdjustLeaveBalanceValidator : AbstractValidator<AdjustLeaveBalanceCommand>
{
public AdjustLeaveBalanceValidator()
{
RuleFor(x => x.UserId).NotEmpty();
RuleFor(x => x.LeaveTypeId).NotEmpty();
RuleFor(x => x.Year).InclusiveBetween(2000, 2100);
RuleFor(x => x.EntitledDays).GreaterThanOrEqualTo(0).When(x => x.EntitledDays.HasValue);
}
}
public class AdjustLeaveBalanceHandler(IApplicationDbContext db, ICurrentUser cu, IDateTime clock)
: IRequestHandler<AdjustLeaveBalanceCommand>
{
public async Task Handle(AdjustLeaveBalanceCommand req, CancellationToken ct)
{
var typeExists = await db.LeaveTypes.AsNoTracking()
.AnyAsync(t => t.Id == req.LeaveTypeId && !t.IsDeleted, ct);
if (!typeExists) throw new NotFoundException("LeaveType", req.LeaveTypeId);
var bal = await db.LeaveBalances
.FirstOrDefaultAsync(b => b.UserId == req.UserId && b.LeaveTypeId == req.LeaveTypeId
&& b.Year == req.Year && !b.IsDeleted, ct);
if (bal is null)
{
var daysPerYear = await db.LeaveTypes.AsNoTracking()
.Where(t => t.Id == req.LeaveTypeId).Select(t => t.DaysPerYear).FirstOrDefaultAsync(ct);
bal = new LeaveBalance
{
UserId = req.UserId,
LeaveTypeId = req.LeaveTypeId,
Year = req.Year,
EntitledDays = req.EntitledDays ?? daysPerYear,
UsedDays = 0,
AdjustmentDays = req.AdjustmentDays ?? 0,
CreatedAt = clock.UtcNow,
CreatedBy = cu.UserId,
};
db.LeaveBalances.Add(bal);
}
else
{
if (req.EntitledDays.HasValue) bal.EntitledDays = req.EntitledDays.Value;
if (req.AdjustmentDays.HasValue) bal.AdjustmentDays = req.AdjustmentDays.Value;
bal.UpdatedAt = clock.UtcNow;
bal.UpdatedBy = cu.UserId;
}
await db.SaveChangesAsync(ct);
}
}

View File

@ -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;

View File

@ -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,