Commit Graph

16 Commits

Author SHA1 Message Date
61e9ce5b3b [CLAUDE] Domain+App+Api+Tests+FE-Admin+FE-User: S34 Plan 3 Phase 1.5 batch 4 item
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 3m48s
Phase 1.5 backlog G-H1 EmployeeProfile hardening batch (Items 6+2+1+4 of 6).

Item 6 — menuKeys FE drift sync × 2 app:
- fe-admin add: Catalogs + 4 Catalog leaves + Workflows + Budgets + Bg_List/Create/Pending (10 key)
- fe-user add: Budgets + Bg_List/Create/Pending + ApprovalWorkflowsV2 + 2 AwV2 leaf + MenuVisibility + Workflows (8 key)
- Cả 2 file giờ identical mirror BE MenuKeys.cs (28 key cumulative)

Item 2 — UpdateEmployeeProfileCommand bool→bool? safe partial update:
- 3 field IsCommunistParty/IsYouthUnion/IsTradeUnion → bool?
- Handler: HasValue check, null = giữ giá trị cũ (Reviewer minor #(b) S33 fixed)
- FE không bắt buộc gửi 3 field every PUT — tránh accidental reset

Item 1 — EmployeesController per-action policy (gotcha #44 mitigation):
- Class-level [Authorize(Policy = "Hrm_HoSo.Read")] — non-admin thiếu Read → 403
- POST [Authorize(Policy = "Hrm_HoSo.Create")]
- PUT  [Authorize(Policy = "Hrm_HoSo.Update")]
- DELETE [Authorize(Policy = "Hrm_HoSo.Delete")]

Item 4 — Test bundle Phase 1.5 (+10 [Fact], baseline 120 → 130/130 PASS):
- EmployeeCodeGeneratorTests (3 [Fact]) — atomic SERIALIZABLE NV/YYYY/NNNN
  + first call + sequential increment + year boundary preserve old year
- CreateEmployeeProfileCommandTests (4 [Fact]) — Create handler edge case
  + first profile + duplicate UserId Conflict + soft-deleted Conflict-restore
  + UserNotFound NotFoundException
- ListEmployeesQueryTests (3 [Fact]) — filter + paging logic
  + status filter + departmentId filter + search by EmployeeCode partial

Implementer Case 3 test gen caught spec mismatch (allow new after soft-delete
vs throws Conflict-restore) — chose CODE source of truth + renamed test
documenting discriminator message branch. Em main verify behavior correct
(admin UX khôi phục thay vì tạo mới — explicit flow defer Phase 1.5+).

Verify:
- dotnet build PASS (2 warn DocxRenderer baseline, 0 error)
- dotnet test 130/130 PASS (58 Domain + 72 Infra = +10)
- 4 endpoint /api/employees policy wired (gotcha #44 active mitigation)
- 4 MEMORY agent updated post-spawn (CICD Run #238 + Implementer test bundle)

Deferred Phase 1.5 next batch:
- Item 3 Satellite CRUD endpoints (WorkHistory/Education/FamilyRelation/Skill/
  Document) + FE inline edit forms — heavy ~2-3h
- Item 5 UAT smoke non-admin role verify silent 403 catch — defer post-deploy

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 13:57:08 +07:00
0605f19f57 [CLAUDE] Tests: Plan C B-Wrap BW1-BW7 Contract V2 test bundle +9 tests (111→120)
Plan C B-Wrap (spec D-Bis migration-todos.md lines 563-619) — Contract V2
ApproveV2Async ~227 LOC NO test cover after S29 Plan B deploy prod. Risk
gotcha #48 high. Anh main S32 chốt defer dedicated session ~2h post-Phase 9
stabilize. S33 kick off cùng Plan B G-H1.

7 BW spec deterministic → 9 [Fact] method (BW6 split 3 for clean isolation):

BW1 — ApproveV2 happy path Cấp 1→Cấp 2 cùng Bước advance pointer + Approval
      row + LevelOpinion UPSERT + LogTransition "Hoàn tất Cấp 1, sang Cấp 2"
BW2 — Terminal Cấp cuối Bước cuối → DaPhatHanh + gen mã HĐ format
      "FLOCK01/HĐTP/SOL&BTBM/01" + clear pointers
BW3 — skipToFinal F2 admin opt-in AllowApproverSkipToFinal=true Cấp 1 Bước 1
      → advance lastStepIdx/lastLevelMaxOrder + prefix [Duyệt vượt cấp]
BW4 — Outsider (không trong pendingLevelGroup.ApproverUserId) → ForbiddenException
BW5 — CreateContractCommand pin workflow ApplicableType=DuyetNcc → exception
      "Workflow phải ApplicableType=Contract" (Reviewer S29 MAJOR catch)
BW6a — ContractLevelOpinion duplicate composite (ContractId, LevelId)
       → DbUpdateException (UNIQUE Mig 33)
BW6b — UPSERT pattern fetch+update → 1 row only Comment updated
BW6c — Delete Contract → FK Cascade auto-delete ContractLevelOpinions
BW7 — V1 fallback skipToFinal non-admin → ConflictException
      "skipToFinal chỉ hỗ trợ HĐ V2"

Test infra dependencies:
-  TestApplicationDbContext SQLite reuse (Common/SqliteDbFixture.cs)
-  IdentityFixture reuse (UserManager + CreateUserAsync helper)
-  FixedDateTime reuse (deterministic clock)
-  NoOpNotificationService reuse
- 🆕 TestCurrentUser stub ICurrentUser (configurable per-test scope) — 31 LOC
-  REAL ChangelogService inject TestCurrentUser
-  REAL ContractCodeGenerator inline (no mock needed, SqliteDbFixture
     enough for atomic sequence test)

Verify:
- dotnet build: 0 err 0 warn (2.49s)
- dotnet test: **120/120 PASS** (was 111 baseline + 9 new)
  - Domain: 58/58 PASS
  - Infrastructure: 62/62 PASS (was 53 → +9 BW)

Reviewer S33 verdict: **PASS** — 0 critical/major issues, 3 minor cosmetic
defer-OK (CreateService helper dead code unused, TestCurrentUser null
defensive C# warning shadow, BW1-4+7 vs BW6 using pattern style). 9/9 indep
verify PASS in 4.7s. Spec strings exact match service source (BW1 ContextNote
+ BW2 Mã HĐ + BW3 ContextNote + BW4-7 exception messages).

Smart Friend independence lần thứ 5 cumulative:
1. S22 #44 silent 403 — Reviewer catch
2. S25 #48 SQLite tie-break — Reviewer catch
3. S29 Plan CA password ≥12 — Reviewer catch
4. S29 Plan B ApplicableType — Reviewer catch
5. S33 Plan C BW — clean, em main+Implementer quality genuine NOT lowered

Patterns applied:
- Implementer Pattern 12-bis cross-module entity cookie-cutter mirror PE
  → Contract (proven 3× S29 + S33)
- Test deterministic seeded helper SeedApproverF2WorkflowAsync mirror
  PurchaseEvaluationWorkflowServiceReturnModeTests.cs structure

Files (4 new tests + 1 stub):
- A tests/SolutionErp.Infrastructure.Tests/Common/TestCurrentUser.cs (31 LOC)
- A tests/SolutionErp.Infrastructure.Tests/Services/ContractWorkflowServiceApproveV2Tests.cs
- A tests/SolutionErp.Infrastructure.Tests/Application/CreateContractCommandApplicableTypeTests.cs
- A tests/SolutionErp.Infrastructure.Tests/Common/ContractV2SchemaPersistenceTests.cs

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 18:17:59 +07:00
8c05947176 [CLAUDE] Tests: Plan AB Chunk A2 — fix Plan M tests filter LogTransition entry post Plan AB
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 3m16s
Plan AB Chunk A thêm Changelog entry mới (EntityType=Workflow + Summary
"Trả lại (...)" + ContextNote=null) trong ApplyReturnModeAsync end-of-function.
Plan M edge case tests (OneLevel_AtStep1Level1 + OneStep_AtStep1) assert
ContextNote.Contains("không lùi được") qua OrderByDescending(CreatedAt) — SQLite
frozen test clock cùng CreatedAt 2 entry → tie-break non-deterministic → pick
Plan AB entry (ContextNote=null) → FAIL.

Fix: Test query filter by Summary.Contains("Chuyển phase") để pick đúng
LogTransitionAsync entry (chứa "không lùi được" trong ContextNote).

Verify:
- dotnet test SolutionErp.slnx — 111/111 PASS (58 Domain + 53 Infra)
- KHÔNG đụng code Plan AB Chunk A — code stays clean, tests get more specific
- Pattern saved: multi-Changelog.Add() per transaction → tests filter by EntityType/Summary discriminator

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 10:21:34 +07:00
ae01ca56f2 [CLAUDE] PurchaseEvaluation Tests: Chunk O1-O5 — HOTFIX 4 lookup sites cùng pattern per-NV (Plan N point 9 cascade)
Bro UAT 2026-05-15 sau Plan N deploy phát hiện 2 bug mới:
1. Actor NV Test trong OR-of-N slot click "Trả lại Người chỉ định" → toast
   "Không phải lượt bạn — chỉ NV Cấp duyệt hiện tại mới được Trả lại / Từ
   chối phiếu" mặc dù NV Test đúng trong slot.
2. F2 Duyệt thẳng Cấp cuối → trỏ đến Phan Văn Chương Bước 2 Cấp 2 thay vì
   Nguyễn Văn Trường Bước 3 Cấp 1 (BOD) — defer follow-up vì F2 logic line
   483-524 đã đúng (lastStepIdx + lastLevelMaxOrder), cần verify workflow
   v14 DB structure.

Audit em main: Plan N chỉ fix 1/5 lookup sites — còn 4 sites cùng bug pattern:
  1. Service.cs:201 EnsureCanRejectV2Async — bug bro UAT 1 ROOT CAUSE
  2. Service.cs:248 ApplyReturnModeAsync — read Allow flag từ row đầu
  3. DetailFeatures.cs:72 F3 EnsureEditableForDetailsAsync — cùng bug
  4. Features.cs:311 F4 AdjustBudgetCommand — cùng bug

4 fix surgical (~30 LOC BE total):

**Site 1** (`PurchaseEvaluationWorkflowService.cs:201`):
```diff
- var currentLevel = step.Levels.FirstOrDefault(l => l.Order == curLvl);
- if (currentLevel?.ApproverUserId != actorId)
+ var currentLevel = step.Levels.FirstOrDefault(l =>
+     l.Order == curLvl && l.ApproverUserId == actorId);
+ if (currentLevel is null)
    throw new ForbiddenException("Không phải lượt bạn — ...");
```

**Site 2** (`PurchaseEvaluationWorkflowService.cs:248`): ApplyReturnModeAsync
+`Guid? actorUserId` param 4th + caller TransitionAsync:94 update. Filter
`l.ApproverUserId == actorUserId` trong FirstOrDefault. Non-admin actor
KHÔNG match slot → currentLevel=null → validation skip (mode logic switch
KHÔNG dùng currentLevel object — chỉ dùng curStepIdx + curLevel int values).
Admin bypass validation existing line 252.

**Site 3** (`PurchaseEvaluationDetailFeatures.cs:72`):
```diff
- var level = step?.Levels.FirstOrDefault(lv => lv.Order == levelOrder);
- if (level is null) throw ConflictException("schema lỗi");
- if (!level.AllowApproverEditDetails) throw ConflictException(...);
- if (level.ApproverUserId != actorUserId) throw ForbiddenException(...);
+ var level = step?.Levels.FirstOrDefault(lv =>
+     lv.Order == levelOrder && lv.ApproverUserId == actorUserId);
+ if (level is null) throw ForbiddenException(...);
+ if (!level.AllowApproverEditDetails) throw ConflictException(...);
```

**Site 4** (`PurchaseEvaluationFeatures.cs:311`):
```diff
- var level = step.Levels.FirstOrDefault(l => l.Order == curLvl);
- if (level is null) throw ConflictException("schema lỗi");
- if (!level.AllowApproverEditBudget) throw ConflictException(...);
- if (level.ApproverUserId != actorId) throw ForbiddenException(...);
+ var level = step.Levels.FirstOrDefault(l =>
+     l.Order == curLvl && l.ApproverUserId == actorId);
+ if (level is null) throw ForbiddenException(...);
+ if (!level.AllowApproverEditBudget) throw ConflictException(...);
```

**Regression test** (`PurchaseEvaluationPerNvLookupRegressionTests.cs` 3 test):
1. `TransitionReject_ActorD_LastInSlot_AllowsRejectViaDrafterMode` —
   Actor D (non-first-row trong OR-of-N) trả lại Drafter mode → no throw.
   Pre-fix: throw "Không phải lượt bạn" vì handler check row đầu A.
2. `TransitionReject_Outsider_NotInSlot_ThrowsForbidden` — Outsider không
   trong slot → throw đúng intent (verify fix KHÔNG over-permissive).
3. `TransitionRejectOneLevel_ActorC_HasFlagWhileOthersDont_AllowsMode` —
   Actor C only tick AllowReturnOneLevel, 3 NV khác KHÔNG. Actor C click
   "Trả lại 1 Cấp" → mode allowed. Pre-fix: read flag từ row A (false) →
   throw ConflictException "không bật mode OneLevel".

Pattern reinforced: per-NV admin opt-in flag wire **5 lookup sites** đều
phải discriminate ApproverUserId. Plan N chỉ catch 1/5. Plan O catch 4/5
còn lại. Memory user-level cần update danh sách 5 sites cho future audit.

Verify:
- dotnet build SolutionErp.slnx clean (0 err, 2 warn pre-existing DocxRenderer)
- dotnet test SolutionErp.slnx **111/111 PASS** (+3 từ 108 baseline Plan N)

Pending Chunk O7: docs + memory update commit + push.
Pending Chunk O8: CICD Monitor post-deploy verify.
Pending follow-up Bug 2 F2 đến Phan Văn Chương: verify workflow v14 DB.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 13:05:02 +07:00
4dd6f9c013 [CLAUDE] Tests: Chunk M2 — Add F1 OneLevel/OneStep edge case tests Bước 1 reset ChoDuyet
Hai test mới cover edge case Plan M S23 t3 (em main M1 edit
PurchaseEvaluationWorkflowService.cs line 287-333):

- ApplyReturnMode_OneLevel_AtStep1Level1_ResetsToBuoc1Cap1_KeepsChoDuyet
  PE init Step 0 Cấp 1 + actor=a1 + slot Cấp 1 tick AllowReturnOneLevel.
  Trước fallback Drafter Phase=TraLai → sau reset (0, 1) giữ Phase=ChoDuyet,
  SLA reset 7d, audit log ContextNote chứa "không lùi được".

- ApplyReturnMode_OneStep_AtStep1_ResetsToBuoc1Cap1_KeepsChoDuyet
  PE init Step 0 Cấp 2 + actor=a2 + slot Cấp 2 tick AllowReturnOneStep.
  Service check curStepIdx > 0 → fallback ngay. Assert Phase=ChoDuyet,
  pointer (0, 1), SLA reset, audit log "không lùi được".

Extend helper SeedWorkflowAsync +2 params optional (allowReturnOneLevelL1
+ allowReturnOneStepL2) — default false, không phá compat 4 test ReturnMode
existing. Pattern 3 audit-reuse (extend helper KHÔNG clone).

Audit log assertion dùng ContextNote thay vì Summary: LogTransitionAsync set
Summary cố định "Chuyển phase {from} → {to}", summary từ ApplyReturnModeAsync
chèn vào comment qua line 96-99 service → ContextNote = comment.

K7 cascade NO regression: 3 ApproveV2_SkipToFinal_* tests still green (M1
edit chỉ F1 path, KHÔNG đụng F2 ApproveV2Async).

Verify:
- Build pass (0 error, 2 pre-existing DocxRenderer warning)
- 106/106 test pass (58 Domain + 48 Infra: +2 từ 46 baseline Plan L)
- 10 ReturnMode-class tests pass (4 ReturnMode + 3 ApproveV2_SkipToFinal
  + 1 Reject_NonApprover + 2 edge case mới)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 11:15:47 +07:00
da30e270c8 [CLAUDE] Tests: Chunk L4 — Update K7 Approver F2 tests cho L1 semantic refactor (advance pointer NOT terminate)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 3m7s
Run #196 CI FAIL: K7 tests assume Phase=DaDuyet (Plan K K2 original semantic).
L1 (`f3db9e6`) refactor Service ApproveV2Async F2 branch sang advance pointer
tới NV cuối (Phase giữ ChoDuyet) — bro UAT correction.

Em main quên update K7 tests cùng L1 commit → test_infra FAIL → CI block deploy.
L2 (`10ddc87`) + L3 (`f212f04`) inherit failure → bundle hash unchanged prod
(admin/user vẫn CRsX6cFo/X7qb4Zl4 K11 baseline) → L1+L2+L3 KHÔNG deploy.

Fix 2 test assertions match new L1 semantic:
1. ApproveV2_SkipToFinal_AdminTickFlag_AdvancesToLastSlot (rename từ _SetsPhaseDaDuyet):
   - Phase.Should().Be(ChoDuyet) — giữ ChoDuyet KHÔNG terminal
   - CurrentWorkflowStepIndex.Should().Be(1) — lastStepIdx (Bước cuối)
   - CurrentApprovalLevelOrder.Should().Be(2) — lastLevelMaxOrder (Cấp cuối)
   - SlaDeadline.Should().NotBeNull — SLA reset 7d cho NV cuối
   - Changelog assertion: "Approver skip thẳng" (text mới)

2. ApproveV2_SkipToFinal_FlagOff_Admin_BypassesFlagCheck:
   - Phase.Should().Be(ChoDuyet)
   - Pointer advance tới (1, 2)
   - Changelog "Approver skip thẳng"

3. ApproveV2_SkipToFinal_FlagOff_NonAdmin_ThrowsConflictException — UNCHANGED
   (ConflictException semantic giống L1 — flag check trước advance).

Verify:
- dotnet test SolutionErp.slnx 104/104 PASS (58 Domain + 46 Infra)
- 3 Approver F2 tests all green

Pattern lesson saved: Service refactor → update test cùng commit (test-before §7
rule). Em main vi phạm UAT mode skip dotnet test mỗi chunk → CI catch retroactive.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 01:47:17 +07:00
6b1e2d9220 [CLAUDE] Tests: Chunk F — K7 Mig 31 Approver F2 service regression + delete deprecated Drafter F2 tests
Sub-task 1: Fix broken references
- Tests reading removed User.AllowDrafterSkipToFinal prop -> delete entire test methods (semantic deprecated, no value)
- 3 deleted: SkipToFinal_DrafterAllowed_SetsPointerToFinalLevel + SkipToFinal_DrafterDenied_NonAdmin_Throws + SkipToFinal_AdminBypass_Succeeds

Sub-task 2: Add 3 Approver F2 service tests (PurchaseEvaluationWorkflowServiceReturnModeTests)
- ApproveV2_SkipToFinal_AdminTickFlag_SetsPhaseDaDuyet (happy path)
- ApproveV2_SkipToFinal_FlagOff_NonAdmin_ThrowsConflictException (denied)
- ApproveV2_SkipToFinal_FlagOff_Admin_BypassesFlagCheck (admin bypass)

Pattern reusable: SeedApproverF2WorkflowAsync 2 Step x 2 Level cookie-cutter
(Implementer memory Pattern 11 S22 SeedWorkflowAsync). PE init Phase=ChoDuyet
+ pointer Step 0 Cap 1. TestApplicationDbContext SQLite. Add EntityFrameworkCore
using for ToListAsync queries on PEL/PEA/Changelog audit assertions.

Verify:
- dotnet build SolutionErp.slnx 0 err 2 pre-existing DocxRenderer warn
- dotnet test SolutionErp.slnx 104 PASS (58 Domain + 46 Infra, 3 deleted + 3 added cancel out, baseline preserved)
- 3 Approver F2 tests verified individually PASS

Plan K Chunk F test-after carry per Phase 9 UAT mode bro confirm.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 23:41:26 +07:00
40f64c6b32 [CLAUDE] PE-Workflow: UAT S22+1 — disable cả 3 button khi không quyền + BE guard
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 3m29s
User UAT feedback: "Nếu đã không được quyền thao tác thì ko được quyền thao tác
hết tất cả các hành động" — trước đây chỉ "Duyệt" disabled, "Trả lại" + "Từ chối"
vẫn enabled (design intent S17 cũ).

FE 2 app mirror (PeWorkflowPanel.tsx):
- `isDisabled = blockedByV2Level` (drop `isForwardApprove &&` qualifier)
- Tooltip update "mới thao tác được (Duyệt / Trả lại / Từ chối)"
- Comment refresh ghi UAT S22+1 spec + cross-ref BE EnsureCanRejectV2Async

BE defense-in-depth (PurchaseEvaluationWorkflowService.cs):
- Helper mới `EnsureCanRejectV2Async` mirror FE actorInV2Level logic:
  Skip silent khi admin/V1/non-ChoDuyet/no actor/no pointer. Throw
  ForbiddenException khi V2 + ChoDuyet + actor != currentLevel.ApproverUserId.
- Invoke ở top Reject branch (cover cả TuChoi + Trả lại sub-branches).
- Chặn request forge: non-approver gọi PATCH /transitions direct sẽ 403.

Test (test-before §7 — security guard critical algorithm):
- ReturnMode tests existing 7/7 vẫn PASS (a2.Id = currentLevel approver, guard accept)
- +1 NEW test `Reject_NonApprover_V2_Throws_ForbiddenException` — outsider
  Drafter role gọi Reject phiếu V2 → throw + Phase không mutate

Verify:
- dotnet test SolutionErp.slnx — 104/104 PASS (+1 guard regression)
  Δ: 103 → 104
- npm run build × 2 app — pass (482ms + 583ms)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 21:46:51 +07:00
215b1e036a [CLAUDE] Tests: Plan C task 1-3 — Service per-NV Allow* test catch-up (S21 t4-t5 Mig 28-29)
14 test cover 3 helper sửa lớn S21 t4-t5 (test-after UAT backlog):

Task 1+2 — PurchaseEvaluationWorkflowServiceReturnModeTests.cs (7 test):
- ApplyReturnModeAsync Drafter allowed/denied/admin bypass (3 test mode flag)
- OneLevel happy path (peer review chain in same Step)
- OneLevel admin bypass (override disabled flag)
- skipToFinal Drafter allowed/denied/admin bypass (3 test per-user F2)

Task 3 — PurchaseEvaluationDraftGuardTests.cs (7 test):
- Drafter scope: DangSoanThao + TraLai → return (2 test)
- F3 Approver scope: ChoDuyet + flag on + actor match → return
- F3 Approver scope: ChoDuyet + flag off → ConflictException
- F3 Approver scope: ChoDuyet + flag on + actor mismatch → ForbiddenException
- Admin bypass ChoDuyet + flag off → return
- DaDuyet any caller → ConflictException (terminal phase)

InternalsVisibleTo: expose PurchaseEvaluationDraftGuard internal helper cho test.

Finding: skipToFinal Service mutate Phase=ChoDuyet TRƯỚC validate user flag.
Throw chặn SaveChanges nên DB không persist nhưng in-memory dirty. Note trong
test — không refactor scope catch-up (defer S22+).

Verify:
- dotnet test SolutionErp.slnx — 103/103 PASS (58 Domain + 45 Infra)
  Δ: 89 → 103 (+14: ReturnMode 7 + Guard 7)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 21:14:03 +07:00
de0088742f [CLAUDE] PurchaseEvaluation: Chunk A — BE guard target TraLai/TuChoi BẮT BUỘC decision=Reject + 3 regression test
Defense-in-depth chặn FE inconsistency (gotcha #45 — Session 21 turn 3).
Bug pattern: button "← Trả lại" trong PeWorkflowPanel.tsx gửi decision=Approve
khi target=TraLai do `isReject` local var thiếu nhánh TraLai → BE skip Reject
branch → enter APPROVE STEP → ApproveV2Async UPSERT opinion = "đã duyệt" +
advance Cấp. User UAT thấy: "Trả về nhưng hệ thống vẫn duyệt".

BE guard:
- Service `TransitionAsync` thêm early check sau set isAdmin/isSystem
- targetPhase ∈ {TraLai, TuChoi} && decision != Reject → throw ConflictException
- Boundary protection cho mọi caller tương lai (API client / mobile / cron)

Tests (Infra suite +3):
- TransitionAsync_TargetTraLai_WithApproveDecision_Throws_AndDoesNotMutateState
- TransitionAsync_TargetTuChoi_WithApproveDecision_Throws_AndDoesNotMutateState
- TransitionAsync_TargetTraLai_WithRejectDecision_SetsPhaseTraLai (happy path)
+ NoOpNotificationService stub reusable cho future PE service tests

Verify:
- dotnet test SolutionErp.slnx → 84 PASS (58 Domain + 26 Infra = +3 from 81 baseline)
- Build pass (0 err, 2 warn CS8602 pre-existing DocxRenderer)

Pending Chunk B: FE fix PeWorkflowPanel.tsx isReject + dialog isSendBack
mirror 2 app (fe-admin + fe-user) — sync với BE guard rule.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 09:41:14 +07:00
dbb0089e28 [CLAUDE] Drastic refactor: flat workflow Phòng × Cấp + Migration 21 (Chunk A)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 3m18s
User chốt drastic refactor — bỏ phase enum hoàn toàn, dùng ChoDuyet=10
đơn nhất + currentStepIndex tracking. Workflow flat list (Phòng × Cấp ×
Approvers). Mỗi PE/HĐ pin WorkflowDefinitionId chạy hết quy trình đó.

Schema (Migration 21 `RefactorWorkflowToFlatModel`):
- Phase enum +ChoDuyet=10 (PE + Contract). Legacy 2-9 + 98 deprecated.
- WorkflowStep + DepartmentId Guid? (FK Restrict) + PositionLevel int?
  (PE + Contract — mirror).
- PE/Contract + CurrentWorkflowStepIndex int? + RejectedAtStepIndex int?
- DROP table PurchaseEvaluationWorkflowStepInnerSteps (Mig 18)
- DROP table WorkflowStepInnerSteps (Mig 20)
- DROP column ContractDeptApproval.InnerStepId (Mig 20)
- DROP column PEDeptApproval.InnerStepId (Mig 18)
- DROP filtered indexes (Mig 19/20) + restore simple unique
  (TargetId, Phase, Dept, Stage) non-filtered

Service rewrite (PE + Contract WorkflowService.TransitionAsync):
- Phase transitions: DangSoanThao → ChoDuyet (Drafter trình, init idx=0)
- ChoDuyet → ChoDuyet (advance idx per approve)
- ChoDuyet → DaDuyet/DaPhatHanh (idx >= steps.Count → terminal)
- ChoDuyet → DangSoanThao (Trả lại — save RejectedAtStepIndex)
- ChoDuyet → TuChoi (Từ chối — khoá vĩnh viễn)
- DangSoanThao + RejectedAtStepIndex → ChoDuyet jump-back to saved idx
- Approver match: actor.Dept == step.Dept AND actor.PositionLevel >=
  step.PositionLevel (OR-of-many cùng cấp/dept = pass) OR
  Approvers.Any(Kind=User AND id match) OR
  Approvers.Any(Kind=Role AND actorRoles contains)
- Admin role bypass policy. Last step done → gen mã HĐ (Contract only)

App CQRS:
- WorkflowStepDto + WorkflowStepInput drop InnerStep, add DepartmentId
  + PositionLevel fields. PE + Contract mirror.

Tests rewrite:
- DROP PeNStageApprovalTests.cs (6 test) + ContractNStageApprovalTests.cs
  (6 test) + PeTwoStageApprovalTests.cs (7 test) — legacy N-stage/2-stage
  no longer applicable
- UPDATE PeWorkflowAdminTests signature to new flat input
- 96 → 77 test pass (drop 19 legacy)

Reference Domain entities removed:
- WorkflowStepInnerStep (Contract)
- PurchaseEvaluationWorkflowStepInnerStep (PE)
- DTOs WorkflowStepInnerStepDto / CreateWorkflowStepInnerStepInput per module

Memory `feedback_drastic_refactor_scope.md` validated: drastic refactor
done in dedicated session với context fresh, scope ~5h actual (planned ~8-10h
with 2x buffer).

Verify:
- dotnet build SolutionErp.slnx 0 error
- dotnet ef database update Mig 21 LocalDB applied OK
- dotnet test 77 pass (54 Domain + 23 Infra)
- 3-file rule: Migration .cs + Designer.cs + Snapshot updated

Pending Chunk B: FE Designer flat UI (PeWorkflowsPage + WorkflowsPage).
Pending Chunk C: FE PeWorkflowPanel + workflow timeline display.
Pending Chunk D: Docs + Skill + Memory + session log.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 12:04:51 +07:00
0d776987e4 [CLAUDE] PE workflow 3-button Duyệt/Trả lại/Từ chối (Task 4)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 3m6s
User chỉ thị thay 2-button hiện tại bằng 3 hành động rõ ràng:
- Duyệt = forward phase tiếp theo
- Trả lại = về DangSoanThao + Drafter sửa → workflow tự jump tới phase
  đã reject (smart reject Mig 16 pattern + clear N-stage rows)
- Từ chối = phiếu khoá hoàn toàn (Phase=TuChoi → 17 handler Mig 16 lock
  edit). Drafter phải tạo phiếu mới.

Domain (PurchaseEvaluationPolicy.cs):
- NccOnly + NccWithPlan: thêm (X → TuChoi) transition cho mọi phase
  trung gian (ChoPurchasing/ChoCCM/ChoCEODuyetNCC/ChoDuAn/ChoCEODuyetPA)
  với roles của phase đó. Trước đây chỉ DangSoanThao → TuChoi (Drafter).
- FromDefinition expand: mỗi step (trừ DangSoanThao) thêm
  (step.Phase → TuChoi) với roles của step.

Service (PurchaseEvaluationWorkflowService.cs):
- Reject branch tách 2 case:
  * target=TuChoi → giữ nguyên (KHÔNG override + KHÔNG set
    RejectedFromPhase + KHÔNG clear N-stage rows). Phiếu khoá vĩnh viễn.
  * target khác (thường DangSoanThao) → smart reject (set
    RejectedFromPhase + force DangSoanThao + clear N-stage rows).

FE (PeWorkflowPanel.tsx, fe-admin + fe-user mirror):
- next.phases render 3 button rõ ràng:
  * "✓ Duyệt → <label>" brand (forward)
  * "← Trả lại (về Drafter sửa)" red (target=DangSoanThao + isSendBack)
  * "✗ Hủy / Từ chối" red (target=TuChoi)
- Decision logic: target=TuChoi || isSendBack → Reject (2), else Approve (1)
- Dialog confirm:
  * Title rõ theo loại hành động
  * Cancel case: warning red "Phiếu sẽ bị khoá hoàn toàn"
  * SendBack case: hint amber "Phiếu sẽ về Đang soạn thảo, Drafter sửa
    rồi trình lại — workflow tự jump tới phase này"

Tests update + add 1 test mới:
- Reject_Sets_RejectedFromPhase_And_Forces_DangSoanThao →
  Reject_To_DangSoanThao_Sets_RejectedFromPhase_TraLai (rename + change
  target từ TuChoi → DangSoanThao để test Trả lại pattern)
- + Reject_To_TuChoi_Locks_Permanently_No_RejectedFromPhase (NEW test
  Từ chối — phase=TuChoi + RejectedFromPhase null)
- NStage_Reject_Clears_InnerStep_Rows_At_Phase: target TuChoi →
  DangSoanThao (test Trả lại + clear N-stage rows pattern)

Verify:
- dotnet build 0 error
- dotnet test 95 → **96 pass** (+1 test mới Từ chối)
- npm build fe-admin + fe-user pass

Pending Task 2: Sample data seed N-stage.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 19:25:44 +07:00
7c0772acca [CLAUDE] Tests: Contract N-stage approval 6 test mirror PE (Chunk D)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 3m1s
ContractNStageApprovalTests.cs (NEW, 6 test) cover N-stage logic Mig 20
mirror PeNStageApprovalTests pattern:

1. NStage_FirstInner_NV_Approve_Blocks_Phase_Transition
   NV cấp 1 → 1 row InnerStepId set, phase chưa đổi.

2. NStage_All_3_Levels_Sequential_Pass_Allow_Phase_Transition
   NV → PP → TP duyệt lần lượt → 3 rows + phase chuyển.

3. NStage_TP_Bypass_Skips_Lower_Levels_Same_Dept
   TP có CanBypassReview → 1 transition tạo 3 rows (NV+PP IsBypassed,
   TP exact match).

4. NStage_Wrong_Department_Throws_Forbidden
   Actor dept khác inner step's dept → ForbiddenException.

5. NStage_Reject_Clears_InnerStep_Rows_At_Phase
   NV approve → 1 row. Admin reject → DangSoanThao + RejectedFromPhase
   set + N-stage rows cleared.

6. LegacyFallback_NoInnerSteps_Uses_2Stage_Logic
   Contract không pin WorkflowDefinitionId → fallback hardcoded Standard
   policy → no inner steps → legacy 2-stage Stage=Review row.
   Phase pair DangKiemTraCCM → DangTrinhKy + role CostControl khớp
   Standard.Transitions (DangGopY → DangDamPhan trong test ban đầu fail
   vì policy chỉ cho [Drafter, DeptManager]; switched to phase pair work).

Helper SeedWorkflowDefinitionAsync 2 step adjacent (DangGopY + DangDamPhan)
+ SeedContractAsync với Project + Supplier seed cho FK.

FakeChangelogService + FakeContractCodeGenerator stubs (no-op cho tests
không cần verify changelog/codegen path).

Verify: 89 → **95 test pass** (54 Domain + 41 Infra: 17 codegen + 6 PE WF
versioning + 6 PE 2-stage + 6 PE N-stage + 6 Contract N-stage).

Pending Chunk E: API check (Workflows controller likely auto-bind via DTO,
skip nếu OK).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 19:07:32 +07:00
3d76c6bc0c [CLAUDE] Tests: PE N-stage workflow approval (6 test) + IdentityFixture extend (Chunk D)
Some checks failed
Deploy SOLUTION_ERP / build-deploy (push) Has been cancelled
PeNStageApprovalTests.cs (NEW, 6 test) cover N-stage logic Mig 18:

1. NStage_FirstInner_NV_Approve_Blocks_Phase_Transition
   NV.PRO duyệt cấp 1 → 1 row InnerStepId set, phase chưa đổi (còn 2 cấp).

2. NStage_All_3_Levels_Sequential_Pass_Allow_Phase_Transition
   NV → PP → TP duyệt lần lượt → 3 rows + phase chuyển. Order asc enforce.

3. NStage_TP_Bypass_Skips_Lower_Levels_Same_Dept
   TP có CanBypassReview → 1 transition tạo 3 rows (NV+PP IsBypassed=true,
   TP exact match). Audit chuẩn.

4. NStage_Wrong_Department_Throws_Forbidden
   Actor dept khác inner step's dept → ForbiddenException.

5. NStage_Reject_Clears_InnerStep_Rows_At_Phase
   NV approve → 1 row. Reject → DangSoanThao + RejectedFromPhase set +
   N-stage rows cleared (resume sẽ approve lại).

6. LegacyFallback_NoInnerSteps_Uses_2Stage_Logic
   PE không pin WorkflowDefinitionId → service fallback hardcoded policy →
   no inner steps → legacy 2-stage Stage=Review/Confirm logic kick in.

IdentityFixture.CreateUserAsync extend +PositionLevel? param (default null
cho admin/system user).

Helper SeedWorkflowDefinitionAsync: tạo definition với 2 steps adjacent
(ChoPurchasing có inner steps + ChoCCM next) — đủ cho FromDefinition build
transition policy guard pass actor role Procurement.

Verify: 83 → **89 test pass** (54 Domain + 35 Infra: 17 codegen + 6 PE WF
versioning + 6 PE 2-stage + 6 PE N-stage). 0 fail.

Pending Chunk E: API endpoints (PATCH /users/{id}/position-level + DTO
extend in PeWorkflowsController bind tự động).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 18:23:59 +07:00
8353fe87c0 [CLAUDE] Tests: Chunk E6 — 6 test 2-stage approval (PE) + IdentityFixture helper
Đóng "Tests Phase 3 mini cần UserManager DI helper" defer từ session 8.

IdentityFixture (Common/IdentityFixture.cs):
- Setup ServiceProvider với Identity stack đầy đủ:
  - DbContext SQLite shared connection
  - AddIdentityCore<User> + AddRoles<Role> + AddEntityFrameworkStores
- Single shared scope cho fixture lifetime → DbContext + UserManager đồng instance
- Helper CreateUserAsync(email, name, deptId, roles, canBypassReview)
- Note: dùng Role custom (không phải IdentityRole<Guid>) để match
  ApplicationDbContext : IdentityDbContext<User, Role, Guid>

6 test PE 2-stage logic (Services/PeTwoStageApprovalTests.cs):
- NV_Review_Blocks_Phase_Transition (đóng bug anh Kiệt — chính xác)
- TPB_Confirm_After_NV_Review_Allows_Transition (happy path 2-stage)
- NV_With_BypassReview_Allows_Transition_With_IsBypassed_True (bypass NV)
- Admin_Skips_TwoStage_Logic_Entirely (admin bypass)
- Reject_Sets_RejectedFromPhase_And_Forces_DangSoanThao (smart reject)
- Resume_After_Reject_Jumps_Back_To_RejectedPhase (jump-back logic)

Stub FakeNotificationService — best effort path không cần verify.

Note: tests cho Contract + Budget 2-stage skip — logic identical PE, ROI thấp.
Pattern PeTwoStageApprovalTests reusable nếu cần test riêng tương lai.

Total: 54 Domain + 29 Infra (17 codegen + 6 PE WF Application + 6 PE 2-stage)
= **83 test pass** (+6 mới).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 13:52:43 +07:00
df5988b7a9 [CLAUDE] Tests Phase 2: Code generator format + sequence tests (SQLite in-memory)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 3m16s
Phase 2 — chống regression code generator. 17 test mới integration với
DB thật (SQLite in-memory) tổng cộng 71 test pass < 3 giây.

Test project:
- tests/SolutionErp.Infrastructure.Tests/ (xUnit + FluentAssertions + EF SQLite 10)
- ProjectReference SolutionErp.Infrastructure (transitively get Application + Domain)
- Added vào SolutionErp.slnx

Test fixtures:
- Common/SqliteDbFixture.cs:
  - SQLite ":memory:" + shared connection + EnsureCreated() từ DbContext model
  - TestApplicationDbContext subclass — override OnModelCreating replace
    'nvarchar(max)' → 'TEXT' (SQLite không support max keyword)
  - FixedDateTime stub IDateTime cho deterministic year boundary test

Test files:
- Services/ContractCodeGeneratorTests.cs (10 test):
  - Format per ContractType (5 type × Project scope) — RG-001 spec
  - Framework HĐ (NguyenTacNCC + NguyenTacDV) → year scope thay vì project
  - Sequence increment per prefix (3 calls → /01, /02, /03)
  - Different prefixes (project / supplier) → independent sequences
  - Year change (2026 → 2027) → reset sequence vì prefix khác
  - PersistsSequenceRow LastSeq verification
- Services/PurchaseEvaluationCodeGeneratorTests.cs (7 test):
  - Format A/B (DuyetNcc → 'A', DuyetNccPhuongAn → 'B')
  - Seq là 3-digit padded (001..012)
  - Type A và B sequence độc lập trong cùng năm
  - Year boundary reset cả A và B

CI gate update (.gitea/workflows/deploy.yml):
- Step "Run integration tests (Infrastructure)" thêm sau Domain tests
- TRX log saved riêng (infra-tests.trx)
- Cả 2 step đều exit non-zero → no deploy

Verify local:
- dotnet test SolutionErp.slnx → Total tests: 71 (54 Domain + 17 Infra) / Passed: 71 / 2.1s
- dotnet build SolutionErp.slnx → 0 error

Phase 3+ pending:
- Application handler tests (CQRS) với EF InMemory hoặc SQLite (~1 ngày)
- API smoke tests qua WebApplicationFactory (~0.5 ngày)
- FE Vitest cho lib utility (~0.5 ngày)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 13:29:06 +07:00