Commit Graph

441 Commits

Author SHA1 Message Date
4678d192e2 [CLAUDE] App+Api: PurchaseEvaluation CQRS + Controller + WorkflowService
Application (4 file, ~900 lines):
 - IPurchaseEvaluationWorkflowService + PurchaseEvaluationDtos
 - PurchaseEvaluationFeatures: Create / UpdateDraft / Transition / List /
   Inbox / GetDetail (bundle Suppliers+Details+Quotes+Approvals+Workflow) /
   Delete / ListChangelogs. IDOR filter role-based phase eligibility.
 - PurchaseEvaluationSupplierFeatures: Add / Update / Remove supplier
   (N:M Phiếu × Supplier). Block remove nếu còn Quote FK reference.
 - PurchaseEvaluationDetailFeatures: Add/Update/Delete hạng mục +
   Upsert/Delete Quote + SelectWinner (set SelectedSupplierId).

Infrastructure:
 - PurchaseEvaluationWorkflowService: policy load pinned definition →
   guard role + transition rules. Emit Notification drafter khi
   state-change. Tạo PurchaseEvaluationApproval + Changelog row.

Api:
 - PurchaseEvaluationsController ~15 endpoint: CRUD phiếu, N:M supplier,
   hạng mục CRUD, Quote upsert, SelectWinner, Changelog list.
   Route /api/purchase-evaluations.

DI: đăng ký IPurchaseEvaluationWorkflowService scoped.

Skip MVP: Attachments upload, Admin PeWorkflows designer UI (sẽ phase sau
— framework versioned WF table đã sẵn, designer pattern copy từ HĐ).
2026-04-23 16:43:47 +07:00
2c6f0cabfb [CLAUDE] Domain+Infra: PurchaseEvaluation module — 10 bảng + 2 workflow seed (migration 12)
Module Duyệt NCC (tiền-HĐ): phiếu trình duyệt so sánh giá N NCC × M hạng
mục trước khi ký HĐ. 2 quy trình: A DuyetNcc (3-step: Purchasing→CCM→CEO),
B DuyetNccPhuongAn (5-step: Purchasing→DựÁn→CCM→CEO PA→CEO NCC).

Domain (7 core + 3 workflow admin):
 - PurchaseEvaluation (header, AuditableEntity, pin WorkflowDefinitionId,
   SelectedSupplierId, PaymentTerms JSON, ContractId? FK kế thừa)
 - PurchaseEvaluationSupplier (N:M Phiếu × Supplier + contact + payment term)
 - PurchaseEvaluationDetail (hạng mục + ngân sách, group A.I/A.II/...)
 - PurchaseEvaluationQuote (báo giá per NCC per hạng mục + IsSelected)
 - PurchaseEvaluationApproval (workflow history, reuse ApprovalDecision)
 - PurchaseEvaluationChangelog (audit log, reuse ChangelogAction)
 - PurchaseEvaluationAttachment (file upload — báo giá NCC + spec...)
 - PurchaseEvaluationWorkflowDefinition/Step/StepApprover (config y như HĐ,
   tách table riêng vì Phase là PurchaseEvaluationPhase enum riêng)

Policy:
 - PurchaseEvaluationPolicy record + PurchaseEvaluationPolicies.NccOnly/
   NccWithPlan (default hardcoded) + FromDefinition(def) build runtime policy
   từ DB admin-authored. Default SLA: soạn 3d, step 1-2d, CEO 1d.

EF: 10 configurations với index phase+isDeleted, SupplierId, ProjectId,
SlaDeadline, WorkflowDefinitionId, ContractId. UX index (PeId, SupplierId)
+ (DetailId, SupplierId). HasQueryFilter soft delete cho header.

Migration 12 AddPurchaseEvaluations tạo 10 bảng. Idempotent seed:
 - SeedMenuTreeAsync +13 menu item (Pe_* root + 2 group + 6 action leaf
   + PeWorkflows root + 2 admin leaf)
 - SeedPurchaseEvaluationWorkflowsAsync seed QT-DN-A-v01 + QT-DN-B-v01
2026-04-23 16:37:55 +07:00
a7ea6ad3d6 [CLAUDE] Docs: chốt session 2026-04-23 tối — UAT-ready 100%
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m48s
5 commit feature work session 2 (072ad6dbcdc007) — clear hết task
pending high-impact, sẵn sàng UAT.

## Session log mới

`docs/changelog/sessions/2026-04-23-2200-roles-demo-pending-cleanup.md`
~270 dòng — outcome A→G (RolesPage + 7 demo HĐ + User-kind guard +
Warning SLA + Edit detail + Master expand + Deps script), stats,
architectural notes, next priority.

## STATUS.md

- Last updated 2026-04-23 22:30 — UAT-ready 100%
- Header phase: "Pending tasks cleared — UAT-ready"
- 5 Recently Done row mới (RolesPage, demo HĐ, user-kind+SLA, edit
  detail+deps, master expand+backfill)
- Cumulative table thêm cột "+RolesPg+Demo+Pending":
  - LOC ~7800 → ~8800
  - Endpoints ~80 → ~93
  - FE pages ~22 → ~23 (RolesPage)
  - Scripts 4 → 5 (deps-audit.ps1)
  - Demo data 5+3 → 15+8+7+13+4 (NCC/Project/HĐ/User/Catalogs)
  - Commits ~47 → ~52
- Session log link mới
- Skills count = 14 file

## HANDOFF.md

- TL;DR cập nhật: UAT-ready 100%, demo data đầy đủ inventory
- Phase table thêm 6 row Done (RolesPage, demo HĐ, user-kind+SLA,
  edit detail, master expand, deps script)
- Git state 8 commit gần nhất

## migration-todos.md

- Section "Session 2026-04-23 (tối)" với 8 ticked checkbox + commit refs
- 3 Roles CRUD checkbox legacy → ticked với commit 072ad6d ref

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 16:07:20 +07:00
bcdc00706c [CLAUDE] Infra: Mở rộng seed master (15 NCC + 8 Project) + backfill demo HĐ
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m51s
User feedback: thêm master data NCC + Project + cập nhật HĐ đang thiếu/
trùng nhau.

## SeedDemoMasterDataAsync — per-code idempotent

Trước: skip toàn bộ nếu Suppliers + Projects table đã có row → không add
được seed mới khi expand list.

Sau: per-Code check — add từng item nếu Code chưa tồn tại, skip nếu có.
Cho phép expand seed list theo thời gian mà không clobber data admin
đã add manual.

## 15 demo suppliers (5 SupplierType × 3 entities)

- NhaCungCap (5): VLXD-ABC, Xi măng Hà Tiên, Thép Hòa Phát, Cadivi
  Điện, Tiền Phong Cấp thoát nước
- NhaThauPhu (4): Thăng Long XD, Cô Công Cơ khí, MEP Hà Nội, Next Stage
  Nội thất
- ToDoi (3): Hoàng Nam (cốp pha), Bắc Ninh (xây trát), Hà Trang (ốp lát)
- DonViDichVu (3): Clean Pro, Hồng Phát Vận chuyển, Long An Bảo vệ
- ChuDauTu (3): Vingroup, Sun Group, Masterise Homes

Đầy đủ TaxCode + Phone + Email + ContactPerson + Address.

## 8 demo projects (đa dạng quy mô + giai đoạn)

- FLOCK01 (sẵn) + SKYGARDEN (sẵn) + INDUSTRIAL (sẵn)
- VHOMES-OP (Vinhomes Ocean Park 3, 350B)
- ECOPARK-VL (Ecopark Văn Lâm, 180B)
- BWTOWER (Văn phòng BW Tower 25 tầng, 95B)
- WAREHOUSE-LB (Kho vận Long Biên, 32B)
- RESORT-PQ (Resort 5* Phú Quốc 250 phòng, 220B)

## Backfill demo HĐ supplier + project

Vấn đề trước: 7 demo HĐ tất cả dùng cùng 1 supplier (FirstOrDefault)
+ cùng 1 project → list nhìn không thực tế.

DemoSupplierByType + DemoProjectByType maps mới:
| ContractType | Supplier | Project |
|---|---|---|
| HopDongThauPhu | NTP-XD (thầu phụ) | FLOCK01 |
| HopDongGiaoKhoan | TD-NEHOANG (tổ đội) | FLOCK01 |
| HopDongNhaCungCap | NCC-XIMANG | VHOMES-OP |
| HopDongDichVu | DV-VANCHUYEN | RESORT-PQ |
| HopDongMuaBan | NCC-DIEN | BWTOWER |
| HopDongNguyenTacNCC | NCC-THEP | ECOPARK-VL |
| HopDongNguyenTacDichVu | DV-CLEAN | WAREHOUSE-LB |

SeedDemoContractsAsync 2 path:
1. Lần đầu (no [DEMO] HĐ): tạo mới với supplier+project diverse per type
2. Đã có [DEMO] HĐ: gọi BackfillDemoContractsSupplierProjectAsync —
   loop từng demo HĐ, update supplier_id + project_id nếu mismatch với
   map (idempotent, log count updated)

Match đúng business: HĐ thầu phụ → NTP, HĐ NCC → NCC supplier, HĐ DV →
DV supplier, HĐ chủ đầu tư (BypassCCM) → CDT supplier (admin tự gán).

## Build

dotnet build BE pass (0 error)

## Note deploy

Lần CI/CD deploy `e8XXXXX` lên prod sẽ:
- Add 10 supplier mới + 5 project mới (existing 5+3 giữ nguyên)
- Backfill 7 demo HĐ → switch sang đúng supplier + project per type
- Log: "Seeded 10 demo suppliers", "Seeded 5 demo projects",
  "Backfill [DEMO] contracts supplier+project: 6 updated."
  (6 vì FLOCK01 vẫn dùng cho ThauPhu/GiaoKhoan unchanged)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 15:54:39 +07:00
e53cd3a3b2 [CLAUDE] App+Api+FE+Scripts: Edit detail row inline + deps audit helper
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m45s
## Edit detail row inline (BE)

7 typed UpdateXxxDetailCommand handler trong ContractDetailsFeatures.cs
— pattern lặp giống Add commands, EnsureContractType guard + log
ChangelogAction.Update với summary "Sửa <hạng mục/SP/CV/...>".

7 PUT endpoints trong ContractsController:
- PUT /contracts/{id}/details/{thau-phu|giao-khoan|nha-cung-cap|dich-vu|
  mua-ban|nguyen-tac-ncc|nguyen-tac-dv}/{detailId}

## Edit detail row inline (FE)

ContractDetailsTab.tsx refactor:
- DeleteBtn → ActionBtns (Pencil + Trash) với onEdit + onDelete callbacks
- 7 XxxTable signatures + onEdit prop + pass row data via callback
- New EditRowDialog component:
  * useEffect populate form từ row data khi target thay đổi
  * Reuse FIELDS_BY_TYPE config + buildPayload (compute thanhTien)
  * Date field convert ISO → yyyy-MM-dd cho input[type=date]
  * PUT /contracts/{id}/details/{slug}/{detailId}
- Parent state editTarget — open dialog, close khi save thành công

Mirror fe-admin (file copy).

## Deps audit helper script

scripts/deps-audit.ps1 — chạy thủ công hoặc CI integration:
- dotnet list package --vulnerable --include-transitive (BE)
- npm audit --audit-level=moderate (fe-admin + fe-user)
- Color-coded output (green/red), summary cuối
- -FailOnHigh switch để CI gate

Skill ref .claude/skills/dependency-audit-erp/SKILL.md (đã có) cho
pin constraints + workflow fix.

## Build

- BE: dotnet build pass (0 error)
- fe-user: tsc + vite pass (11.52s)
- fe-admin: tsc + vite pass (577ms)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 15:18:53 +07:00
4edcd588d8 [CLAUDE] Domain+Infra: User-kind approver runtime guard + Warning 20% SLA
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m41s
## User-kind approver guard

Trước: WorkflowDefinition Designer cho admin pick User cụ thể vào step
approver, nhưng runtime guard bỏ qua (User-kind treat như DeptManager
fallback per skill doc).

Bây giờ: enable đầy đủ. WorkflowPolicy + UserTransitions parallel dict
(default null cho hardcoded Standard/SkipCcm, populated qua
FromDefinition khi WorkflowStepApprover Kind=User).

IsTransitionAllowed signature update: (from, to, actorRoles, actorUserId?)
- Check Role first (existing behavior)
- Fallback User-kind: actorUserId.ToString() có trong UserTransitions[(from,to)]?

ContractWorkflowService.TransitionAsync dùng IsTransitionAllowed thay
inline check. Error message thêm "{N} user explicit" nếu policy có
User-kind approvers cho transition đó.

FromDefinition cũng update: nếu step CHỈ có User-kind (không Role),
không fallback DeptManager nữa — guard sẽ check user-level. Chỉ
fallback DeptManager nếu step thiếu cả 2.

## Warning 20% SLA

SlaExpiryJob.ProcessWarningsAsync mới — chạy trước ProcessAsync
(auto-approve quá hạn):
- Pull Contracts WHERE !SlaWarningSent && SlaDeadline > now &&
  Phase NOT IN (DaPhatHanh, TuChoi, DangDongDau)
- Per phase, threshold = 20% × default SLA (vd Soạn thảo 7 ngày → 33.6h
  remaining trigger warning; In ký 1 ngày → 4.8h)
- Compute remaining = SlaDeadline - now; nếu remaining <= threshold
  + còn slot → notify Drafter via INotificationService
- Set SlaWarningSent = true để chỉ warning 1 lần per phase (reset trong
  TransitionAsync khi chuyển phase mới)
- NotificationType.SlaWarning (đã có trong enum) + title icon ⚠

## Build

dotnet build BE pass (0 error)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 15:11:34 +07:00
8bc9565127 [CLAUDE] Infra: SeedDemoContractsAsync — 7 HĐ varied phases để UAT-ready
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m39s
User feedback: làm hết task pending. Phase 1: seed sample HĐ data để admin
login thấy ngay E2E hoạt động full (không cần tự tạo từ đầu).

## Idempotent guard

Skip nếu đã có bất kỳ HĐ nào tên bắt đầu "[DEMO]" — admin có thể xóa
demo + create thật bình thường, restart không clobber.

## 7 demo HĐ — covering 7 ContractTypes + 4-5 phases khác nhau

| # | Type | Final Phase | Tên HĐ | Giá trị | Details |
|---|---|---|---|---|---|
| 1 | ThauPhu | DangSoanThao | Thi công móng + cột tầng 1 — FLOCK 01 | 850M | 3 hạng mục (đào, đổ BT, lắp thép) |
| 2 | GiaoKhoan | DangGopY | Khoán nhân công xây + trát + sơn | 320M | 3 công việc + 2 comments demo |
| 3 | NhaCungCap | DangInKy | Cung cấp xi măng + sắt thép Q2/2026 | 1.2B | 3 SP (xi măng, thép D14/D18) |
| 4 | DichVu | DangTrinhKy | Thuê cẩu tháp 6 tháng | 540M | 1 DV (cẩu tháp Liebherr) |
| 5 | MuaBan | DaPhatHanh | Mua máy phát điện 250kVA | 850M | 2 SP có VAT 10% |
| 6 | NguyenTacNCC | DangGopY | HĐ nguyên tắc cung cấp vật tư 2026 | 0 (framework) | 2 SP với khung giá min/max |
| 7 | NguyenTacDV | DangSoanThao | HĐ nguyên tắc bảo trì TB 2026 | 0 (framework) | 1 DV với SLA |

## Workflow simulation

Loop transition phases tới finalPhase, insert ContractApproval row mỗi
phase với ApproverUserId mapping đúng role:
- DangKiemTraCCM → ccm.tran (CostControl)
- DangTrinhKy + DangDongDau → bod.huynh (Director)
- DaPhatHanh → hra.dang (HrAdmin)
- Khác → qs.hoang (Drafter — soạn thảo + đàm phán + in ký)

SkipCcm policy (DichVu/MuaBan/NguyenTacNcc/NguyenTacDv) bỏ DangKiemTraCCM
khỏi flow.

Mã HĐ auto gen qua codeGen.GenerateAsync (RG-001 format đầy đủ).

## Demo data gồm

- 7 Contracts (Header)
- ~14 Details rows (3+3+3+1+2+2+1)
- ~30 ContractApprovals (workflow history per phase)
- 2 ContractComments (demo conversation CCM↔Drafter)

## Build

dotnet build BE pass (0 error)

## Login test sau deploy

Admin → /my-contracts hoặc /contracts → thấy 7 [DEMO] HĐ với mã RG-001
+ varied phases. Click bất kỳ HĐ → Panel 2 thấy Tổng quan + Chi tiết +
Lịch sử duyệt full content.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 15:06:34 +07:00
072ad6d014 [CLAUDE] App+Api+FE-Admin: RolesPage CRUD (/system/roles)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m58s
User feedback: /system/roles trỏ tới placeholder "chưa được build" — build
trang quản lý 12 role mặc định + custom role admin tự thêm.

## BE — PermissionFeatures.cs

3 command mới:
- CreateRoleCommand — Name regex `^[A-Za-z][A-Za-z0-9_]*$` (chỉ chữ/số/
  underscore, bắt đầu chữ), throw ConflictException nếu code đã tồn tại
- UpdateRoleCommand — CHỈ update ShortName + Description. KHÔNG đổi
  Name (Identity FK trong UserRoles + WorkflowStepApprover.AssignmentValue
  + [Authorize(Roles="...")] attr — đổi = data corruption widespread)
- DeleteRoleCommand — block 2 trường hợp:
  * Role thuộc AppRoles.All hardcoded (workflow guard reference)
  * Còn user assigned (UserManager.GetUsersInRoleAsync count > 0)

ValidationException reference fully-qualified để tránh ambiguous với
FluentValidation.ValidationException.

## BE — RolesController

3 endpoint mới (POST/PUT/DELETE) — Authorize Admin role.

## FE — RolesPage

Table list 12 + custom roles với 5 column (Mã code / Mã viết tắt / Tên
đầy đủ / Loại badge / Ngày tạo) + actions Edit/Delete:
- Edit dialog: chỉ ShortName + Description editable, Name disabled với
  hint "Không đổi được sau khi tạo"
- Delete: block với toast nếu role mặc định (HARDCODED_ROLES set check
  client-side trước khi gọi BE — UX faster, BE vẫn double-check)
- Create dialog: 3 field Name (regex pattern HTML5) + ShortName + Description
- Banner amber warning về Mã code FK constraint
- Loại badge: Mặc định (slate) vs Tùy chỉnh (brand)

## FE — App.tsx

+ import RolesPage + route /system/roles → RolesPage.

## Build

- BE: dotnet build pass (0 error)
- fe-admin: tsc + vite pass (13.88s)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 14:57:36 +07:00
ff5e35f279 [CLAUDE] Docs: chốt session 2026-04-23 chiều — toolkit + 4-bảng + master + roles VN
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m47s
11 commit feature work (b75448eae59cfe) → docs sync.

## STATUS.md

- Last updated 2026-04-23 16:00
- Phase header: Tier 3 + 4-bảng + master catalogs + roles VN
- 7 Recently Done row mới (3-panel layout, 4-bảng overhaul, Thao tác
  2-panel, Mã HĐ gen Create, master catalogs, roles VN demo users)
- Cumulative table thêm cột "+Toolkit/Catalogs/Roles" (DB 36, endpoints
  ~80, migrations 11, commits ~47)
- Session log link mới
- Skill list count = 13 file

## HANDOFF.md

- TL;DR cập nhật: 36 tables, 80 endpoints, 11 migrations
- Phase table thêm 5 row Done (3-panel, 4-bảng, mã HĐ, master, roles)
- Git state 18 commit gần nhất
- Credentials block thêm 13 demo user (User@123456) — warn rotate trước UAT

## migration-todos.md

Section "Session 2026-04-23 (chiều)" với 14 ticked checkbox + commit refs.

## schema-diagram.md

- Header: 24 → 36 bảng
- Migration table thêm row 9-11 (highlighted)
- Section 8bis mới: chi tiết 7 Details + ContractChangelogs + 4 Catalogs +
  Role.ShortName + User.DepartmentId/Position

## Session log mới

`docs/changelog/sessions/2026-04-23-1500-toolkit-data-roles.md` (~270
dòng) — outcome A→I, stats cumulative, 6 architectural decisions, next
session priority.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 14:39:48 +07:00
ae59cfeb5d [CLAUDE] FE-Admin: UsersPage dept/position field + RoleShortName tiếng Việt
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m27s
## types/users.ts

- User type + departmentId/departmentName/position
- CreateUserInput + departmentId/position
- RoleShortName map (Mã viết tắt VN per role): QTV/NV.PB/TPB/PM/PRO/CCM/
  FIN/ACT/EQU/BOD/NĐUQ/HRA
- RoleLabel map (Tên đầy đủ VN per role)
- roleDisplayName(role) → "BOD — Ban Giám đốc" combined helper

## types/menu.ts

Role type + shortName field (mirror BE RoleDto).

## UsersPage redesign

- Column "Phòng ban" (departmentName + position 2 dòng)
- Column "Vai trò" hiển thị badge ShortName ("BOD", "CCM", "PM"), tooltip
  hover full label
- Column actions thêm "Sửa thông tin" (Pencil icon) — dialog edit dept/
  position/active state
- Create dialog 2-col grid: Email | Họ tên / Phòng ban (dropdown) | Chức vụ /
  Password (col-span-2). Roles checkboxes hiển thị "ShortName — full label"
- Edit dialog mới — sửa fullName + dept + position + isActive
- Roles dialog title kèm dept name (context cho user reviewer)
- toggleActive mutation include departmentId/position để không reset

## PermissionsPage

Panel 1 role list:
- 2-line per row: ShortName (semibold) + Description (truncate small)
- Tooltip = description đầy đủ
- Active row vẫn ring-brand-200

Panel 2 header badge: ShortName thay name code English.

## Build

fe-admin: tsc + vite pass (12.17s lần 1, 671ms lần 2)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 14:28:32 +07:00
330d529c92 [CLAUDE] Domain+App+Infra: Role ShortName + User Department/Position + 13 demo users (migration 11)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m53s
User feedback: chi tiết hóa Users/Phòng ban + gán roles. Roles label
tiếng Việt có Mã (ShortName) + Tên đầy đủ (Description).

## Entity changes

### Role (Domain/Identity/Role.cs)
+ ShortName (max 50)  — Mã viết tắt VN: QTV/BOD/CCM/PRO/FIN/...
+ Description (đã có) — Tên đầy đủ VN
- Identity Name = code English giữ nguyên (FK + [Authorize] attr)

### User (Domain/Identity/User.cs)
+ DepartmentId Guid? FK Departments (Restrict — không xóa dept nếu user reference)
+ Position string? max 200 — chức vụ free text

## Migration 11: AddRoleShortNameAndUserDepartment

3-file rule. Apply LocalDB OK. DB total: 36 tables (không tăng — chỉ
thêm cột vào existing).

## Seed VN labels (12 roles)

| Code | ShortName | Description |
|---|---|---|
| Admin | QTV | Quản trị viên hệ thống |
| Drafter | NV.PB | Nhân viên phòng ban (soạn thảo HĐ) |
| DeptManager | TPB | Trưởng phòng ban |
| ProjectManager | PM | Giám đốc dự án |
| Procurement | PRO | Phòng Cung ứng |
| CostControl | CCM | Phòng Kiểm soát chi phí |
| Finance | FIN | Phòng Tài chính |
| Accounting | ACT | Phòng Kế toán |
| Equipment | EQU | Phòng Thiết bị |
| Director | BOD | Ban Giám đốc |
| AuthorizedSigner | NĐUQ | Người được Ủy quyền ký HĐ |
| HrAdmin | HRA | Phòng Nhân sự - Hành chính |

SeedRolesAsync idempotent + backfill (existing role thiếu ShortName/
Description → update).

## Seed 13 demo users

Default password: User@123456 (warn log để rotate prod). Coverage full
org chart:
- bod.huynh (Tổng GĐ — Director, BOD dept)
- bod.le (Phó GĐ NĐUQ — AuthorizedSigner, BOD dept)
- pm.nguyen (PM FLOCK 01 — ProjectManager, PM dept)
- ccm.tran (TPB CCM — CostControl + DeptManager, CCM dept)
- pro.pham (TPB PRO — Procurement + DeptManager, PRO dept)
- fin.do, act.vu, equ.bui, hra.dang (TPB respective dept)
- qs.hoang, qs.ngo (Drafter — QS dept)
- nv.cao, nv.dinh (Drafter — PRO/FIN dept)

Idempotent (skip nếu email đã tồn tại).

## DTOs + Commands updated

- RoleDto + ShortName field
- UserDto + DepartmentId/DepartmentName/Position
- CreateUserCommand + DepartmentId/Position params (defaults null)
- UpdateUserCommand + DepartmentId/Position
- ListUsersQueryHandler load dept names denormalize per page
- UpdateUserCommandHandler set UpdatedAt

## Note

FE updates (UsersPage dept dropdown + role label VN) ở commit kế tiếp.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 14:24:12 +07:00
39031ca33c [CLAUDE] FE: ContractDetailsPreview cho create mode — table headers + disabled add
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m36s
User feedback: thay vì placeholder dashed nhỏ "Chi tiết sẽ hiện sau khi
tạo Header", show structure thật của Chi tiết section ngay từ đầu nhưng
disabled. User thấy trước layout columns + button add → trải nghiệm
liên tục, không bất ngờ khi switch sang edit mode.

## Component mới: ContractDetailsPreview

- Section title "Chi tiết ({TypeLabel})" + amber pill "🔒 Cần tạo Header trước"
- Table opacity-60 với:
  - thead column headers per type (sync với HEADERS_BY_TYPE config)
  - tbody empty state: Lock icon + "Tạo Header xong sẽ thêm được hạng mục"
- Disabled "+ Thêm dòng" button (cursor-not-allowed, slate-400 text)

## HEADERS_BY_TYPE config

7 type × column headers — duplicate nhỏ với ContractDetailsTab.tsx renderers
(acceptable: chỉ là labels visual, không logic).

## Reactive theo type

User đổi dropdown "Loại HĐ" → preview headers update tương ứng (state-driven).

## Build

- fe-user: tsc + vite pass (586ms)
- fe-admin: tsc + vite pass (709ms)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 12:33:00 +07:00
16e24ed962 [CLAUDE] FE: Admin CatalogsPage CRUD + Details form datalist autocomplete
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m36s
## fe-admin

### CatalogsPage.tsx (mới)

1 page generic CRUD cho 4 master catalogs (units / materials / services /
work-items). Dispatch theo URL param :kind:
- /master/catalogs (redirect units)
- /master/catalogs/:kind (units|materials|services|work-items)

Sub-tabs ở top chuyển nhanh giữa 4 kind. Mỗi kind có FIELDS_BY_TYPE config
riêng (3-7 field). Form dialog nested với input/textarea/checkbox theo type.

### Layout.tsx + App.tsx

- resolvePath thêm 4 CatalogXxx → /master/catalogs/{kind}
- Route /master/catalogs/:kind → CatalogsPage

## fe-user + fe-admin (mirror)

### ContractDetailsTab.tsx

Datalist autocomplete cho Add row form:
- Fetch 4 catalogs via TanStack Query (cache shared key 'catalogs')
- Mỗi field config thêm optional `datalist` + `datalistField` ('code'|'name')
- HTML5 <datalist> render options theo type:
  - ThauPhu: hangMuc → work-items, donViTinh → units
  - GiaoKhoan: maCongViec/tenCongViec → work-items, donViTinh → units
  - NhaCungCap/MuaBan: maSP/tenSP → materials, donViTinh → units
  - DichVu: maDichVu/tenDichVu → services, donViTinh → units
  - NguyenTacNcc: tenSP → materials, donViTinh → units
  - NguyenTacDv: tenDichVu → services, donViTinh → units

Smart-fill (handleFieldChange):
- User pick value khớp catalog → autofill sibling fields cùng catalog:
  - Field name 'maXxx' → fill code; 'tenXxx'/'hangMuc' → fill name
  - donViTinh nếu chưa có giá trị → fill từ defaultUnit của catalog item

Vẫn cho user gõ tự do (free text) — datalist chỉ là suggestion.

## Build

- fe-user: tsc + vite pass (5.69s)
- fe-admin: tsc + vite pass (633ms + 15.84s lúc test CatalogsPage lần đầu)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 12:27:41 +07:00
e27c54702a [CLAUDE] Domain+App+Api: 4 master catalogs cho Details (migration 10)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m48s
User feedback: thêm Master Data cho phần Chi tiết (line items) — autocomplete
khi user nhập field thay vì gõ tay free text.

## 4 entities mới (Domain/Master/Catalogs/)

| Entity | Bảng | Dùng cho HĐ Detail |
|---|---|---|
| UnitOfMeasure | UnitsOfMeasure | Tất cả 7 type (DonViTinh) |
| MaterialItem | MaterialItems | NCC + Mua bán + Nguyên tắc NCC (MaSP/TenSP) |
| ServiceItem | ServiceItems | Dịch vụ + Nguyên tắc DV (MaDichVu/TenDichVu) |
| WorkItem | WorkItems | Thầu phụ + Giao khoán (HangMuc/MaCongViec) |

Common pattern: Code unique (filter IsDeleted=0) + Name + Category +
DefaultUnit + AuditableEntity (soft delete) + IsActive flag.

## Migration 10: AddMasterCatalogs

3-file rule (gotcha #17). Total DB: 32 → 36 tables. Apply LocalDB OK.

## Seed defaults (idempotent — skip per-table nếu có row)

- 20 UnitsOfMeasure: m2, m3, kg, tấn, lít, ngc (ngày công), giờ, gói, ...
- 15 MaterialItems demo: xi măng PCB40, cát vàng, đá 1x2, thép D10, gạch
  4 lỗ, sơn lót, ống PVC...
- 10 ServiceItems demo: vận chuyển, bảo trì, tư vấn, kiểm định, vệ sinh...
- 15 WorkItems demo: đào móng, đổ bê tông, xây tường, trát, lát gạch,
  sơn nước, lắp điện, lắp nước, thấm chống...

## CQRS (Application/Master/Catalogs/CatalogsFeatures.cs ~290 dòng)

Mỗi catalog 5 handlers (List filter q+category, Create với unique code
guard, Update, Delete soft). FluentValidation max length per spec EF.

## Controller (Api/Controllers/CatalogsController.cs)

13 endpoints:
- GET  /api/catalogs/{units|materials|services|work-items}
- POST /api/catalogs/{kind}                  (Admin role)
- PUT  /api/catalogs/{kind}/{id}             (Admin role)
- DELETE /api/catalogs/{kind}/{id}           (Admin role)

Read open cho mọi role (FE Details add form autocomplete cần list).

## Menu (5 mới)

- Catalogs (group, Master parent, order 24, "Library" icon)
  - CatalogUnits "Đơn vị tính" (Ruler)
  - CatalogMaterials "Vật tư / SP" (Package)
  - CatalogServices "Dịch vụ" (Wrench)
  - CatalogWorkItems "Hạng mục công việc" (ListChecks)

Admin auto-grant tất cả CRUD action (qua SeedAdminPermissionsAsync
loop MenuKeys.All).

## Build

dotnet build BE pass (0 error)

## Note

FE admin page CatalogsPage + datalist autocomplete trong Details form
sẽ ở commit kế tiếp.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 12:21:39 +07:00
51449d6b9d [CLAUDE] App+Infra: Mã HĐ gen ngay tại CreateContract + backfill HĐ legacy
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m45s
User feedback: HĐ phải có mã ngay khi tạo (không đợi đến DangDongDau như
cũ). HĐ đã tạo trước đây nhưng chưa có mã → backfill tự động.

## Thay đổi

### CreateContractCommandHandler (App)

- Inject IContractCodeGenerator
- Load supplier + project FULL (cần Code, không chỉ check tồn tại như trước)
- Call codeGenerator.GenerateAsync TRƯỚC khi db.Contracts.Add — entity
  chưa tracked nên GenerateAsync internal SaveChangesAsync chỉ save SEQ
  (không kèm contract chưa tracked)
- Set entity.MaHopDong = result trước khi Add → INSERT contract đã có mã
- Changelog summary include mã: "Tạo HĐ {mã} — {tên}"

### Trade-off documented

- Mã gen sớm → HĐ TuChoi sẽ "wasted" 1 mã (gap trong sequence)
- Acceptable vì user cần mã reference vào tài liệu/giấy tờ ngay từ đầu

### ContractWorkflowService.TransitionAsync (Infra)

- Giữ logic cũ `if MaHopDong is null → gen` ở DangDongDau
- Update comment: nominal flow skip vì mã đã có; defensive cho HĐ legacy
  hoặc HĐ tạo bằng path khác (seed/import)

### DbInitializer.BackfillContractCodesAsync (Infra)

- Chạy 1 lần trước WarnDefaultAdminPasswordAsync
- Idempotent: count Contracts WHERE MaHopDong IS NULL → skip nếu 0
- Loop từng HĐ: load supplier+project → GenerateAsync → SaveChangesAsync
- Skip + log warning nếu missing supplier/project (legacy data corruption)
- Try-catch per HĐ, log success/failed count cuối cùng

## Build

dotnet build BE pass (0 error, 2 pre-existing DocxRenderer warning)

## Note

Khi deploy lên prod, DbInitializer chạy startup → backfill HĐ cũ tự động.
Log line "Backfill mã HĐ: X HĐ thiếu mã, đang gen..." sẽ xuất hiện ở
Logs/log-{date}.txt để verify.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 11:36:59 +07:00
7f26ff9d66 [CLAUDE] FE-User+FE-Admin: 2 button luôn hiện, mờ + disabled khi != DangSoanThao
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m45s
User feedback: hiển thị Edit + Xóa cho mọi row (kể cả Phase khác), nhưng
mờ và disabled khi không thao tác được — để user biết button TỒN TẠI mà
không bị bất ngờ phải hover row đúng phase mới thấy.

## Thay đổi

- Bỏ conditional render `{phase === DangSoanThao && ...}`
- Thêm canMutate = c.phase === DangSoanThao biến + className conditional:
  - canMutate=true: text-slate-500 + hover brand/red + clickable
  - canMutate=false: text-slate-300 + cursor-not-allowed + disabled
- Default opacity-60 (luôn visible nhẹ), group-hover:opacity-100 (rõ
  khi hover)
- title tooltip thay đổi theo state — hint user lý do disable
- onClick guard early return nếu !canMutate (defense in depth)

Build: tsc + vite pass cả 2 app

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 11:25:22 +07:00
501b4de418 [CLAUDE] FE-User+FE-Admin: Edit + Xóa, chỉ hiện khi DangSoanThao
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m45s
User feedback: 2 button trên row Panel 1 phải là Edit + Xóa, và CHỈ
hoạt động trong trạng thái nhập liệu/điều chỉnh (Phase = DangSoanThao).

## Thay đổi

- ✏ Pencil icon thay ExternalLink — hành động Edit (select Panel 2 form)
- 🗑 Trash2 — Xóa (giữ nguyên)
- Cả 2 button bọc trong `c.phase === DangSoanThao` conditional → Phase
  khác (DangGopY, DangDamPhan, ...) → ẩn cả 2
- Lý do: BE chỉ cho update + delete khi Phase=DangSoanThao
  (UpdateContractDraftCommand + DeleteContractCommand throw Conflict-
  Exception nếu khác)

## UX

- Phase=DangSoanThao: hover row → 2 button fade in
- Phase khác: chỉ row click select Panel 2 (form sẽ render read-only +
  banner amber "HĐ đã chuyển khỏi Đang soạn thảo")

Build: tsc + vite pass cả 2 app

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 11:06:29 +07:00
ec0c983e8e [CLAUDE] FE-User+FE-Admin: action buttons (Mở chi tiết + Xóa) trên row Panel 1 Thao tác
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m35s
User feedback: thêm nút edit/action ở mỗi row trong list Panel 1 trang
Thao tác. Hiện absolute positioned ở góc phải-trên row, opacity-0 → 100
khi hover (group-hover). Sibling không nested để click không trigger
row select propagation.

## 2 button per row

- ⤴ ExternalLink → navigate /contracts/{id} (fullpage detail với
  Workflow + History, khác Panel 2 chỉ có Edit form)
- 🗑 Trash2 → confirm() + DELETE /contracts/{id} (soft delete,
  blocked sau DangInKy ở BE). Nếu xóa HĐ đang select → clear ?id=

## Implementation details

- pr-16 cho row button để chừa khoảng cho action group
- group-hover:opacity-100 transition (smooth fade in)
- Mutation invalidate ['my-contracts'] sau xóa thành công
- Toast success + getErrorMessage cho fail case (vd xóa HĐ đã qua DangInKy)

Build: tsc + vite pass cả 2 app (fe-user 515ms, fe-admin 937ms)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 10:54:54 +07:00
8c4b4da951 [CLAUDE] FE-User+FE-Admin: 2-panel layout cho Thao tác (Ct_*_Create)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m36s
Trang /contracts/new?type=X (menu "Thao tác") redesign từ single form
→ 2-panel: Panel 1 list HĐ theo type | Panel 2 Header form + Chi tiết.

## Layout

Panel 1 (320px) — flex column 3 vùng:
- Top: Search box (filter mã/tên/NCC client-side)
- Middle: List HĐ theo type (scroll, click row chọn)
- Bottom: + Thêm mới button (sticky, ring-brand khi active mode=new)

Panel 2 (flex) — 3 trạng thái theo URL:
- Empty state — chưa chọn HĐ và chưa bấm + Thêm mới
- ContractHeaderForm (mode=new) — form trống, sau Tạo HĐ draft
  → URL update ?id=newId chuyển edit mode
- ContractEditForm (id=abc) — form populated từ /contracts/{id}, +
  section Chi tiết bên dưới (ContractDetailsTab reuse)

## URL state

- ?type=X            → empty
- ?type=X&mode=new   → form trống
- ?type=X&id=abc     → edit form + Chi tiết
- ?type=X&q=keyword  → search filter Panel 1

## Edit constraints

ContractEditForm respect UpdateContractDraftCommand limits:
- Editable khi Phase=DangSoanThao: Tên HĐ, Giá trị, Template, Nội dung
- Read-only luôn: Loại HĐ, NCC, Dự án, Bypass CCM (không đổi sau create
  qua BE command hiện tại)
- Khi Phase != DangSoanThao: warning amber + tất cả input disabled,
  nhưng Chi tiết section vẫn render để user xem (ContractDetailsTab tự
  disable add/delete khi không phải draft)

## Components

ContractCreatePage.tsx (rewrite) — page entry
ContractHeaderForm — create mode (full fields editable)
ContractEditForm — edit mode (limited fields + Chi tiết section)
FormFields helper — shared form layout cho create

## Build verify

- fe-user: tsc + vite pass (374ms)
- fe-admin: tsc + vite pass (987ms)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 10:48:29 +07:00
ad0652d590 [CLAUDE] FE-User+FE-Admin: bỏ tabs, Chi tiết + Lịch sử 7/3 grid dưới Overview
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m44s
User feedback: thay vì click tab để switch, hiển thị Chi tiết + Lịch sử
LUÔN ngay dưới Tổng quan content. Tỷ lệ cột 7 (Chi tiết) - 3 (Lịch sử
điều chỉnh).

## Thay đổi (apply 2 app)

ContractDetailContent.tsx:
- Bỏ TabsNav + tab state + TabButton helper
- Bỏ conditional render theo tab
- Tổng quan content (Info / Comments / Attachments) render flat đầu tiên
- Thêm grid lg:grid-cols-10 dưới cùng:
  - lg:col-span-7 → ContractDetailsTab (line items)
  - lg:col-span-3 → ContractChangelogsTab (timeline)
- Mobile (<lg): stack vertical 1 cột, Chi tiết trên, Lịch sử dưới

## Build verify

- fe-user: tsc + vite pass (17.23s)
- fe-admin: tsc + vite pass (8.12s)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 10:39:07 +07:00
b3762afbc3 [CLAUDE] FE-User+FE-Admin: Panel 2 tabs (Tổng quan / Chi tiết / Lịch sử)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m39s
Phần 2.6 — UI cho 4-bảng data model overhaul. Panel 2 trong 3-panel
layout giờ tabbed thay flat, expose 7 Details + Changelog cho user.

## Files mới (4 per app — cố ý duplicate theo project convention)

### types/contract-details.ts
7 typed interfaces (ThauPhuDetail, GiaoKhoanDetail, NhaCungCapDetail,
DichVuDetail, MuaBanDetail, NguyenTacNccDetail, NguyenTacDvDetail) +
ContractDetailsBundle wrapper (chỉ 1 list có data theo Type) +
ContractChangelog + 4 enum const-objects với Vietnamese label.

### components/contracts/ContractDetailsTab.tsx (~400 dòng)
- Auto-pick render component theo bundle.type (7 table renderers)
- Mỗi table: header per type + columns thanhTien total + delete row btn
- AddRowForm sử dụng FIELDS_BY_TYPE config (5-7 field per type)
- buildPayload auto compute thanhTien (SL × DonGia × (1+VAT/100) cho MuaBan)
- canEdit chỉ khi Phase = DangSoanThao (sau khi nộp HĐ → khóa edit details)
- Banner amber cảnh báo khi không edit được

### components/contracts/ContractChangelogsTab.tsx (~150 dòng)
- Render unified changelog list desc CreatedAt
- Icon + tone color theo EntityType (5 loại: Contract/Detail/Workflow/
  Comment/Attachment)
- Expandable detail row hiển thị FieldChangesJson (parse JSON, render
  table Field|Cũ|Mới với strike-through old + emerald new)
- Show contextNote khi có

## Files sửa (2 per app)

### components/contracts/ContractDetailContent.tsx
- Thêm useState<Tab>('overview')
- Tabs nav (TabButton helper, border-b underline active brand-700)
- 3 tab: Tổng quan (Info + Comments + Attachments) | Chi tiết (Details
  table + add form) | Lịch sử (changelog timeline)
- Wrap Tổng quan content trong fragment, conditionally render

## Build verify

- fe-user: tsc + vite pass (521ms, 1888 modules)
- fe-admin: tsc + vite pass (997ms, 1903 modules)

## Test flow desktop

1. /my-contracts → click HĐ → Panel 2 mở tab "Tổng quan" (default)
2. Click tab "Chi tiết (HĐ Mua bán)" → table line items + add row form
3. Add row "Xi măng / kg / 1000 / 50000" → POST /contracts/{id}/details/mua-ban
   → table refresh + changelog tự log "Thêm SP: Xi măng"
4. Click tab "Lịch sử" → thấy entries: Tạo HĐ, Thêm SP Xi măng, ...
5. Tab giữ state khi switch HĐ khác (per-component state)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 10:24:00 +07:00
e6844553a4 [CLAUDE] App+Api: 7 Details CRUD endpoints + Changelogs query
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m37s
## DTOs (Application/Contracts/Dtos/ContractDetailDtos.cs)

- 7 typed DTOs (ThauPhuDetailDto, GiaoKhoanDetailDto, NhaCungCapDetailDto,
  DichVuDetailDto, MuaBanDetailDto, NguyenTacNccDetailDto,
  NguyenTacDvDetailDto) — schema 1-1 với Domain entities
- ContractDetailsBundleDto — wrapper trả về theo Type, chỉ 1 list có data
  (FE đọc field tương ứng, tránh polymorphic deserialize phức tạp)
- ContractChangelogDto — full audit entry

## CQRS (Application/Contracts/ContractDetailsFeatures.cs)

- GetContractDetailsQuery — load bundle, switch theo Contract.Type chỉ
  query bảng tương ứng (avoid 7 query waste)
- 7 AddXxxDetailCommand handlers — typed payload + EnsureContractType
  guard (throw ConflictException nếu Contract.Type sai)
- DeleteContractDetailCommand generic — dispatch xóa theo Type, log change
- Tất cả handler call IChangelogService.LogDetailChangeAsync với summary
  human-readable (vd "Thêm hạng mục: Đào móng")

## CQRS (Application/Contracts/ContractChangelogFeatures.cs)

- ListContractChangelogsQuery (read-only) — desc CreatedAt, default top 200

## Controller (Api/Controllers/ContractsController.cs)

8 endpoints mới:
- GET /api/contracts/{id}/details → bundle theo Type
- POST /api/contracts/{id}/details/{thau-phu|giao-khoan|nha-cung-cap|
  dich-vu|mua-ban|nguyen-tac-ncc|nguyen-tac-dv} → 7 typed POST
- DELETE /api/contracts/{id}/details/{detailId} → generic delete
- GET /api/contracts/{id}/changelogs → list audit entries

Build: dotnet pass (0 error)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 10:16:18 +07:00
71c035d31e [CLAUDE] App+Infra: IChangelogService + log Workflow/Contract/Comment/Attachment
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m26s
User decision B (log cả 3): mọi thay đổi liên quan HĐ ghi vào unified
ContractChangelogs để render tab Lịch sử FE.

## IChangelogService (Application/Common/Interfaces/)

5 methods:
- LogContractChangeAsync — Header insert/update
- LogDetailChangeAsync — line item insert/update/delete
- LogWorkflowTransitionAsync — phase change (parallel với ContractApprovals)
- LogCommentAddedAsync — góp ý mới
- LogAttachmentAsync — upload/delete file

KHÔNG SaveChanges trong service — caller chịu trách nhiệm save atomic
cùng business changes (pattern giống INotificationService).

## ChangelogService impl

- Resolve actor qua ICurrentUser → UserManager.FindByIdAsync
- Denormalize UserName (FullName ?? Email) cho log readable
- null UserId = system action (vd SLA auto-approve)
- DI: AddScoped trong DependencyInjection.cs

## Wiring vào handlers hiện tại

- ContractWorkflowService.TransitionAsync — LogWorkflowTransitionAsync
  sau khi insert ContractApproval
- CreateContractCommandHandler — LogContractChangeAsync(Insert)
- UpdateContractDraftCommandHandler — diff GiaTri/TenHopDong/NoiDung/
  TemplateId trước update, log update với fieldChangesJson nếu có thay đổi
- AddCommentCommandHandler — LogCommentAddedAsync
- UploadContractAttachmentCommandHandler — LogAttachmentAsync(Insert)
- DeleteContractAttachmentCommandHandler — LogAttachmentAsync(Delete)

Build: dotnet build BE pass (0 error, 2 pre-existing warning trong
DocxRenderer.cs)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 10:12:51 +07:00
70810e1b34 [CLAUDE] Domain+Infra: 7 ContractType-specific Details + ContractChangelog (migration 9)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m37s
User decision: Option B — bảng riêng cho mỗi loại HĐ (chuẩn nhất, schema
chuyên biệt). Plus: ContractChangelog audit log thống nhất Header /
Detail / Workflow / Comment / Attachment.

## 8 entities mới

### Details (7) — Domain/Contracts/Details/

| Bảng | Loại HĐ | Field đặc trưng |
|---|---|---|
| ThauPhuDetails | 1 (Thầu phụ) | HangMuc, KhoiLuong, DonGia, ThoiGianHoanThanh |
| GiaoKhoanDetails | 2 (Giao khoán) | MaCongViec, KhoiLuong, YeuCauKyThuat |
| NhaCungCapDetails | 3 (NCC) | MaSP, ThongSoKyThuat, SoLuong, ThoiGianGiao, XuatXu |
| DichVuDetails | 4 (Dịch vụ) | MaDichVu, ThoiGian, TuNgay/DenNgay |
| MuaBanDetails | 5 (Mua bán) | MaSP, SoLuong, DonGia, ThueVAT (%), XuatXu |
| NguyenTacNccDetails | 6 (Nguyên tắc NCC) | NhomSP, DonGiaToiThieu/ToiDa, DieuKienGiaoHang |
| NguyenTacDvDetails | 7 (Nguyên tắc DV) | LoaiDichVu, DonGiaToiThieu/ToiDa, PhamViDichVu, SLA |

Common base `ContractDetailBase`: ContractId FK + Order + ThanhTien
decimal(18,2) + GhiChu nvarchar(1000) + audit (BaseEntity).

### ContractChangelog (1) — Domain/Contracts/

Unified audit log. Khác ContractApprovals (workflow-only, dùng cho guard
logic) — Changelog là VIEW LAYER cho user đọc lịch sử thao tác:
- EntityType enum: Contract | Detail | Workflow | Comment | Attachment
- Action enum: Insert | Update | Delete | Transition
- PhaseAtChange snapshot
- UserId + UserName denormalize (log readable)
- Summary human-readable + FieldChangesJson [{Field, Old, New}]
- ContextNote (comment kèm theo)

## EF Configurations

ContractDetailsConfiguration.cs (1 file gộp 7 IEntityTypeConfiguration):
- ToTable + HasMaxLength + HasPrecision per type
- HasOne(Contract).WithMany(<TypeDetails>) cascade delete
- IX (ContractId, Order) cho load timeline

ContractChangelogConfiguration.cs:
- Cascade delete khi Contract xóa
- IX (ContractId, CreatedAt) timeline + IX (ContractId, EntityType) filter

## DbContext + IApplicationDbContext

+ 8 DbSet mới (7 Details + ContractChangelogs).

## Migration 9: AddContractDetailsAndChangelog

3-file rule (gotcha #17): .cs + .Designer.cs + ApplicationDbContextModel
Snapshot.cs đầy đủ. Applied LocalDB SolutionErp_Dev OK — 24 + 8 = 32 bảng
total.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 10:08:42 +07:00
d326e80082 [CLAUDE] FE-User: tách Tổng quan thành /dashboard riêng (fix bug trùng /inbox)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m47s
Bug: Layout resolvePath map "Dashboard" key → "/inbox" cũ (coi inbox là
home), khiến menu "Tổng quan" và "Hộp thư" cùng navigate về /inbox →
user thấy interface giống nhau, không phân biệt được.

Fix:
- Tạo UserDashboardPage.tsx — overview cá nhân:
  * Greeting với fullName
  * 5-card "Của tôi" row (HĐ đang soạn / Chờ tôi duyệt / Sắp quá hạn /
    Đã quá hạn / Tổng giá trị nháp) — dùng /api/reports/my-dashboard có sẵn
  * Card click navigate vào page tương ứng (/my-contracts hoặc /inbox)
  * Section HĐ gần đây — list 5 row với click → /my-contracts?id=X
- App.tsx: thêm route /dashboard + redirect "/" sang /dashboard
- Layout.tsx: Dashboard → /dashboard, logo link cũng chuyển về /dashboard

Build: tsc + vite pass (439ms)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 10:01:54 +07:00
7ea3957acc [CLAUDE] FE-User: sidebar accordion cho menu loại HĐ — chỉ 1 group expand cùng lúc
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m46s
User feedback: 7 group Ct_<Code> (HĐ Thầu phụ / Giao khoán / NCC / Dịch vụ
/ Mua bán / Nguyên tắc NCC / Nguyên tắc DV) trước đây expand tự do →
sidebar dài lê thê khi user mở nhiều. Mỗi group nên độc lập (accordion):
chỉ 1 group expand cùng lúc.

## Cách làm

### AccordionContext lifted to Layout

- Layout maintain `expandedCtCode: string | null` state
- React Context expose getter + setter cho MenuGroup
- MenuGroup detect key `Ct_<Code>` qua regex `/^Ct_([^_]+)$/`:
  - Match → controlled mode: open = (expandedCtCode === code)
  - Toggle = setExpandedCtCode(open ? null : code)
- Group khác (Hợp đồng top-level, Quy trình admin, ...) giữ behavior cũ
  (independent local useState)

### Auto-expand theo URL ?type=

useEffect watch location.search:
- `/my-contracts?type=5` → INT_TO_TYPE_CODE[5] = "MuaBan" → expand HĐ Mua bán
- `/contracts/new?type=2` → expand HĐ Giao khoán
- `/inbox?type=3` → expand HĐ Nhà cung cấp
- URL không có ?type= → KHÔNG reset (giữ user-selected context)

### Visual: highlight active group

Ct_ group đang accordion-open: `bg-slate-50 text-slate-900` (subtle tint
để user biết group nào đang active trong 7 type).

## Build

fe-user: tsc -b + vite build pass (1888 modules, 1.08MB JS, 380ms)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 09:33:56 +07:00
89c7e88e2d [CLAUDE] FE-User: 3-panel layout cho InboxPage (Hộp thư)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m46s
Apply cùng pattern Danh sách (commit b75448e) cho Hộp thư để consistent
trải nghiệm — Ct_*_List và Ct_*_Pending menu cùng UX 3-panel.

## Thay đổi InboxPage

- Bỏ DataTable + StatCard 4-card grid lớn → header compact với StatPill
  inline (Cần xử lý / Sắp quá hạn / Quá hạn / Giá trị) → Panel 1 max chỗ
- Vai trò user banner amber 1 dòng (transparent về scope filtering)
- 3-panel grid lg:grid-cols-[320px_1fr_360px] h-[calc(100vh-4rem)]:
  Panel 1: search + list pending compact, overdue highlight border-l-red,
           click update ?id= active highlight ring-brand
  Panel 2: ContractDetailContent embedded (sticky header + Yêu cầu sửa /
           Duyệt → tiếp buttons sẵn để duyệt từ inbox)
  Panel 3: WorkflowHistoryPanel (timeline + lịch sử duyệt full)
- Mobile (<lg): chỉ Panel 1 visible, click row → fullpage /contracts/:id
- URL state: ?type=X (sidebar menu Ct_*_Pending) + ?id (selected) + ?q
  (search) — bookmarkable

## Reuse components (đã tạo commit b75448e)

- ContractDetailContent.tsx — không cần thay đổi
- WorkflowHistoryPanel.tsx — không cần thay đổi

## Build verified

fe-user: tsc -b + vite build pass (1888 modules, 1.08MB JS, 686ms)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 09:17:45 +07:00
b75448e711 [CLAUDE] FE-User+FE-Admin: 3-panel layout cho danh sách HĐ
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m50s
Redesign trang Danh sách HĐ (Ct_*_List menu fe-user + /contracts admin)
thành 3-panel: List | Detail content | Workflow + lịch sử duyệt. Selected
HĐ giữ qua URL ?id= (bookmarkable + back/forward navigation work).

## Components mới (reuse cho cả 3-panel embedded + fullpage detail)

### fe-user/src/components/contracts/
- ContractDetailContent.tsx — Panel 2 body: header sticky (title + phase
  + actions Yêu cầu sửa/Duyệt) + Info section + Comments thread + form
  thêm góp ý + Attachments. Transition Dialog inline. Prop optional
  onBack — render arrow back button (fullpage) hoặc skip (embedded).
- WorkflowHistoryPanel.tsx — Panel 3: WorkflowSummaryCard (timeline
  policy current+next) + Lịch sử duyệt (approvals: phase from→to + actor
  + timestamp + comment).

### fe-admin/src/components/contracts/
- ContractDetailContent.tsx — variant admin có thêm Phòng ban + Bypass
  CCM trong Info section. Invalidate ['contracts'] khi transition.
- WorkflowHistoryPanel.tsx — identical fe-user.

## Trang refactored

### fe-user
- MyContractsPage.tsx — bỏ DataTable, dùng 3-panel grid
  lg:grid-cols-[320px_1fr_360px] h-[calc(100vh-4rem)]:
    Panel 1: search box + list compact (mã/tên/NCC/phase/SLA/giá), click
             update ?id= active highlight ring-brand
    Panel 2: detail content embedded
    Panel 3: workflow + history
  Mobile (<lg): chỉ Panel 1 visible, click row navigate fullpage
  /contracts/:id (UX khả dụng, không nhồi 3 panel màn hình hẹp).
  URL state: ?type=X (filter loại) + ?id= (selected) + ?q= (search).
- ContractDetailPage.tsx — slim version dùng ContractDetailContent +
  WorkflowHistoryPanel, giữ deep link /contracts/:id work.

### fe-admin
- ContractsListPage.tsx — 3-panel + filter phase + pagination compact
  trong Panel 1 footer. URL state: ?type, ?pendingMe, ?id, ?q, ?phase,
  ?page (full bookmarkable). Title hiển thị loại HĐ + count badge.
- ContractDetailPage.tsx — slim version giống fe-user.

## Build verified

- fe-user: tsc -b + vite build pass (1888 modules, 1.08MB JS)
- fe-admin: tsc -b + vite build pass (1903 modules, 1.15MB JS)

Note: npm install resolved @microsoft/signalr 8.0.7 → 8.0.17 (within
^8.0.7 caret), reverted package.json + lock changes do bump không phải
scope task này. Dev tiếp theo run npm install sẽ tự re-resolve.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 09:04:46 +07:00
d43d2c0024 [CLAUDE] Docs: chốt session 2026-04-23 — skill governance + cron audit
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m46s
- Session log 2026-04-23-0900-skill-governance.md (A→E):
  khảo sát alirezarezvani/claude-skills + quyết định không bulk-clone,
  3 skill ops mới (dependency-audit-erp, ef-core-migration,
  iis-deploy-runbook), rules §9 + audit cadence cron 1/tháng,
  touch-points 6 file index
- STATUS: Recently Done 2 row mới (b904a25 governance + 661f859
  3 skill), header phase = "Tier 3 + skill governance",
  session log count → 12 file, link skills README.md
- HANDOFF: Last updated → 2026-04-23 09:30, TL;DR mention skill
  governance setup, table phase tier thêm row Skill governance ,
  Skills callout "PHẢI dùng khi task khớp" + audit cron next 2026-05-01,
  git state cập nhật 3 commit gần nhất

Cron task verified live qua list_scheduled_tasks: nextRunAt =
2026-05-01T02:05:48.000Z (jitter 348s).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 00:30:37 +07:00
b904a25dc1 [CLAUDE] Skill: governance + audit định kỳ hàng tháng
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m48s
- rules.md §9 mới: liệt kê 6 skill (3 domain + 3 ops) với trigger,
  nguyên tắc tạo skill project-specific (không clone generic),
  format SKILL.md bắt buộc, audit workflow §9.4 chi tiết 7 bước,
  4 anti-patterns
- CLAUDE.md (root): block "🛠️ Skills" callout 6 skill + audit cadence
  + commit scope thêm `Skill`
- HANDOFF.md: section A1 — định kỳ audit, lần kế tiếp 2026-05-01
- migration-todos: section "Skill governance (recurring)" với checkbox
  audit hàng tháng

Cron task tạo qua scheduled-tasks (ID: solution-erp-skill-audit-
monthly): chạy 9:00 AM ngày 1 mỗi tháng. Self-contained prompt cold-
start để session tự audit + log vào docs/changelog/skill-audit-
{YYYY-MM}.md. Auto-refresh stale skill nhỏ, đề xuất add/archive cho
human approve.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 00:12:54 +07:00
661f8595f8 [CLAUDE] Skill: thêm 3 skill ops project-specific
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m47s
Khảo sát alirezarezvani/claude-skills repo — phần lớn skill đã có ở
user-level (code-reviewer, sql-database-assistant, focused-fix,
senior-frontend, mcp-builder...). Bulk import sẽ trùng + nhiều skill
là doc-dump generic không có YAML when-to-use.

Thay vào đó: viết 3 skill PROJECT-SPECIFIC encode kiến thức
SOLUTION_ERP-only mà generic không thể biết:

- dependency-audit-erp: dotnet list --vulnerable + npm audit cho
  fe-admin/fe-user, respect pin constraint MediatR 12.4.1 +
  Swashbuckle 6.9.0 + Node 20.x, dẫn chiếu gotchas, output template
  + CI integration TODO Phase 5.1

- ef-core-migration: 8 migration history + 3-file rule + Design
  TimeDbContextFactory + 6 pitfalls cụ thể (bao gồm cascade vs
  restrict cho WorkflowDefinitionId), workflow add entity mới end-
  to-end, prod apply via idempotent script

- iis-deploy-runbook: 3 IIS site topology + win-acme cert + NSSM
  gitea-runner shared VIETREPORT + LibreOffice 25.8.6 headless,
  debug playbook 500/502/SignalR/login, deploy steps + manual
  emergency, rotate creds + backup commands, dẫn chiếu gotcha #25/26/28/29

Skills README cập nhật: 6 skill (3 domain + 3 ops). CLAUDE.md
+ docs/CLAUDE.md sync count.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 23:44:24 +07:00
fbca83264c [CLAUDE] Docs: chốt session Tier 3 feature-complete + versioned workflow
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m33s
- Session log 2026-04-22-0300 (A→K): attachment, SignalR, form builder,
  PDF, dynamic + versioned workflow, nested menu, 3-panel permissions,
  seed master, brand identity, content polish, Gitea fix
- STATUS: Tier 3 feature-complete snapshot + cumulative stats (24 tables,
  ~50 endpoints, 8 migrations); next-up = UAT + Email SMTP (blocked) +
  rotate creds + SQL backup schedule
- HANDOFF: rewrite brief cho session mới — phase 5 prod done, Tier 3
  đóng gói, quick sanity-check 2 app, versioned workflow quick ref,
  file active hiện trạng, git state
- migration-todos: tick Tier 3 items (attachment/realtime/form builder/
  PDF/dynamic+versioned workflow/nested menu) + thêm iter-3 versioned
  workflow section + post-launch list
- schema-diagram: +5 table (Notifications, WorkflowTypeAssignments,
  WorkflowDefinitions, WorkflowSteps, WorkflowStepApprovers); indexes
  mới, cardinality FK restrict cho pinned policy, truy vấn tiêu biểu
- workflow-contract: +section 7bis resolution order, 7ter admin
  designer flow, updated data model + code pointers Tier 3
- PROJECT-MAP: module map post-Tier-3 (3 box mới Notification/
  Attachment/Branding + Infra/DevOps box), API namespace đầy đủ,
  architectural wins 5 điểm
- contract-workflow skill: versioned workflow section, policy
  resolution code snippet, admin designer flow, code pointers Tier 3,
  tier 4+ backlog
- gotchas +7 bẫy mới (#26-32): SignalR WebSocket headers, interceptor
  2-phase pattern, LibreOffice mirror 404, PS 5.1 UTF-16 GITHUB_PATH,
  PS 5.1 diacritics parse, Dialog size TS, NavLink end query-params

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 10:25:02 +07:00
91b2da147f [CLAUDE] FE-Admin: PermissionsPage 3-panel layout
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m33s
Redesign theo yêu cầu user: 3 panel vertical đồng thời trên cùng 1
màn hình (không modal/dialog popup).

Layout grid lg:grid-cols-[280px_1fr_300px]:

Panel 1 — Vai trò (trái, 280px):
  Danh sách roles click-to-select với active highlight (brand-50 bg +
  ring-brand-200 + check icon). Đếm số roles ở header.

Panel 2 — Quyền theo menu (giữa, flex):
  Tìm menu inline header + sticky thead. Click vai trò → lọc menu
  instant. Column toggle header (tick toàn cột) + per-cell checkbox.
  Hover brand-tinted. Menu key hiện mono nhỏ dưới label.

Panel 3 — Tổng quan (phải, 300px):
  Vai trò đang chọn + số quyền (progress bar brand) + chi tiết từng
  CRUD (Xem/Tạo/Sửa/Xóa) với badge color-coded (slate/emerald/amber/
  red) + count "X / Y menus" + tip helper cuối.

Bỏ dialog select + 3-col grid filter ở đầu (thay bằng 3 panel), giữ
logic mutation/toggle/column nguyên.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 10:02:25 +07:00
f216169039 [CLAUDE] FE-Admin+Domain+Infra+App: Workflows tab → sidebar menu items
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m37s
User request: 7 tab trong /system/workflows thành menu items riêng.

Domain:
- MenuKeys.WorkflowTypeLeaf(code) helper — `Wf_<TypeCode>` pattern

Infrastructure (DbInitializer):
- Seed 7 leaves dưới Workflows group (order 95..101), label matches
  ContractType (HĐ Thầu phụ / Giao khoán / NCC / Dịch vụ / Mua bán /
  Nguyên tắc NCC / Nguyên tắc Dịch vụ). Idempotent.

Application (GetMyMenuTreeQuery):
- Generalized inherit-perm logic: descendants of Contracts AND Workflows
  inherit parent CanRead flag. Single Workflows.Read grant → all 7
  Wf_* leaves visible; no per-leaf permission rows needed.

FE Layout (admin):
- resolvePath: Wf_<Code> → /system/workflows/<code>. Ct_* still hidden
  on admin side.

FE App.tsx:
- New route /system/workflows/:typeCode?

FE WorkflowsPage:
- Removed horizontal tab bar; type selection now comes từ URL param.
- Landing view (no param): 3-col grid card per type với active version
  badge — so admin có visual overview khi click top-level Workflows
  group without selecting a type.
- TYPE_CODE_TO_INT map drives URL→int conversion.

Result: click `Quy trình HĐ > HĐ Mua bán` trong sidebar → opens
/system/workflows/MuaBan directly với designer scoped.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 09:49:42 +07:00
29dbac2051 [CLAUDE] Docs: STATUS update cho versioned workflow + nested menu user
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m38s
2026-04-22 09:37:53 +07:00
355bbe3a61 [CLAUDE] FE-Admin: Dialog size xl → lg (fix TS2322 CI build)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m48s
2026-04-22 09:31:10 +07:00
e7e5f2d066 [CLAUDE] Domain+Infra+App+Api+FE-Admin: versioned workflow per ContractType
Some checks failed
Deploy SOLUTION_ERP / build-deploy (push) Failing after 1m32s
User yêu cầu: mỗi loại HĐ có quy trình riêng với admin add roles + users
vào từng bước. Khi tạo version mới → HĐ tương lai chạy theo, HĐ cũ giữ
version cũ.

Domain:
- WorkflowDefinition (Code + Version + ContractType + IsActive + Steps)
- WorkflowStep (Order + Phase + Name + SlaDays + Approvers)
- WorkflowStepApprover (Kind: Role/User + AssignmentValue)
- Contract.WorkflowDefinitionId — pinned at creation
- WorkflowPolicyRegistry.FromDefinition() — build runtime policy từ DB

Infrastructure:
- EF config + migration AddVersionedWorkflows (3 table mới)
- DbInitializer.SeedWorkflowDefinitionsAsync: v01 per 7 ContractType,
  steps sinh từ hardcoded WorkflowPolicies (Role approvers).
- ContractWorkflowService.TransitionAsync: load pinned WorkflowDefinition
  → FromDefinition(), fallback cho HĐ cũ không có pin.

Application:
- CreateContractCommand pin WorkflowDefinitionId = active version cho type
- ContractFeatures.Get(id): load pinned def cho workflow summary
- WorkflowAdminFeatures: GetWorkflowAdminOverviewQuery (7 types + active
  + history + ContractsUsingCount), CreateWorkflowDefinitionCommand
  (validate payload, auto-increment version, deactivate old).

Api:
- GET /api/workflows trả overview
- POST /api/workflows tạo version mới (deactivate old)

FE /system/workflows:
- Tabs per 7 ContractType, mỗi tab hiện active version + lịch sử
- DefinitionCard: steps với badge role/user + SLA + archived indicator
  hiện "N HĐ còn chạy" cho version cũ
- WorkflowDesigner modal: form code/name/desc + danh sách steps
  (phase/name/SLA) + approvers (+ Role hoặc + User). Drop step ok.
  Clone từ version hiện tại để tạo v02 có điểm start sensible.
- Amber banner: HĐ cũ không bị ảnh hưởng khi tạo version mới

Invariants được giữ:
- Unique (Code, Version) index
- Chỉ 1 version IsActive per ContractType tại 1 thời điểm
- Set default sẽ auto xóa override → respect legacy override table
- Role-kind approvers drive transition guards; User-kind fallback
  DeptManager role cho v1 (user-level targeting = iteration 2)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 22:57:41 +07:00
5e0f3801a1 [CLAUDE] Move nested-type menu → fe-user; Admin workflow config page
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m41s
User clarified: menu loại HĐ 3-level (Danh sách/Thao tác/Duyệt) thuộc
fe-user. Admin có page riêng để config quy trình per loại HĐ.

fe-admin Layout:
- filterForAdmin() drops Ct_* entries (hide nested type menu).
- Admin sidebar giờ về lại đơn giản: Dashboard / Master / Hợp đồng
  (leaf) / Forms / Reports / System.

fe-user Layout:
- Dynamic menu tree từ /menus/me (thay fixed USER_MENU hardcoded).
- Recursive MenuNodeRenderer (top-level expanded, nested collapsed).
- resolvePath user-specific: Ct_*_List → /my-contracts?type=X,
  Ct_*_Create → /contracts/new?type=X, Ct_*_Pending → /inbox?type=X.
- filterForUser drops admin-only entries (Master/System/Forms/Reports).
- Static USER_FIXED_TOP prepends "Hộp thư" leaf → /inbox.
- MyContractsPage + InboxPage đọc ?type=X param, filter client-side.

Workflow config (Admin side):
- Domain: WorkflowTypeAssignment entity (ContractType → PolicyName
  override). Registry.ForContractWithOverrides() prefer DB override
  else default.
- Infrastructure: EF config + migration AddWorkflowTypeAssignments,
  unique index trên ContractType. ContractWorkflowService load
  overrides dict mỗi transition. ContractFeatures load overrides khi
  build WorkflowSummaryDto.
- Application: GetWorkflowAdminOverviewQuery returns 7 types × current
  policy + available policies. SetWorkflowAssignmentCommand validate
  policy name tồn tại; nếu = default thì delete override (no stale row).
- Api: GET /api/workflows + PUT /api/workflows/{contractType}
  với policy "Workflows.Read" + "Workflows.Update".
- Menu: new key `Workflows` dưới System, label "Quy trình HĐ".
- FE /system/workflows: 7 card per type, dropdown Standard/SkipCcm +
  'Đã override' badge khi khác default, phase sequence timeline,
  explanation banner ở top. Iteration 2 note: admin-authored custom
  policies.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 22:41:05 +07:00
48e91fe7ca [CLAUDE] Domain+Infra+App+FE-Admin: per-ContractType nested sidebar menu
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m48s
User request: mỗi loại HĐ có menu riêng với 3 action Danh sách /
Thao tác / Duyệt.

Sidebar giờ 3-level under "Hợp đồng":
  Hợp đồng (group, expandable)
  ├── HĐ Thầu phụ (sub-group)
  │   ├── Danh sách → /contracts?type=1
  │   ├── Thao tác  → /contracts/new?type=1
  │   └── Duyệt      → /contracts?type=1&pendingMe=1
  ├── HĐ Giao khoán (sub-group)
  ├── HĐ NCC / Dịch vụ / Mua bán / Nguyên tắc NCC / Nguyên tắc DV
  └── ... (7 types × 4 = 28 new menu items)

BE:
- MenuKeys.cs: ContractTypeCodes array + helpers ContractTypeGroup/
  List/Create/Pending → key format Ct_<TypeCode>[_<Action>]
- DbInitializer.SeedMenuTreeAsync: loop seeds 28 entries under Contracts
- GetMyMenuTreeQuery.BuildChildren: descendants of `Contracts` inherit
  parent permission (avoid adding 28 rows to Permissions table per role)

FE:
- Layout.tsx recursive: MenuNodeRenderer dispatches group vs leaf by
  depth; nested groups collapsed by default (top-level expanded).
  Deeper levels get smaller padding/text + left border guide.
- Pattern-based resolvePath: Ct_<Type>_<Action> → URL with query.
- Contract type code → int map (matches Domain ContractType enum).
- ContractsListPage reads ?type + ?pendingMe, filters client-side.
  Header title + description reflect active filter. "← Tất cả loại"
  quick-reset button.
- ContractCreatePage new cho admin (copy từ fe-user), pre-select type
  từ ?type URL param.
- App.tsx route /contracts/new → ContractCreatePage.

Pure navigation UX; no new permissions needed. Admin + any role with
Contracts.Read see full menu; leaves click-through to filtered views.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 22:25:00 +07:00
fb3a410a1b [CLAUDE] Docs: STATUS update cho seed master data + MyDashboard
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m46s
2026-04-21 22:12:08 +07:00
6197c841bb [CLAUDE] App+Infra+FE-Admin: seed master data + MyDashboard widgets
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m48s
Task 1 — Seed master data unblock UAT/demo:
- DbInitializer.SeedDepartmentsAsync: 9 departments từ QT-TP-NCC.docx
  (PM/QS/CCM/PRO/FIN/ACT/EQU/HRA/BOD) — reference data không phải demo.
- DbInitializer.SeedDemoMasterDataAsync: 5 demo suppliers (NCC VLXD, NTP
  Xây dựng, TĐ Hoàng Nam, DV Clean, CĐT Vingroup — covers cả 5
  SupplierType) + 3 demo projects (FLOCK01, SkyGarden, Industrial).
  Chỉ seed nếu tables empty — respect admin's real data khi họ add.

Task 2 — Roles CRUD đã có sẵn trong UsersPage (Shield icon button mở
dialog gán 12 roles từ AppRoles.cs). Skip.

Task 3 — MyDashboard role-specific widgets:
- GetMyDashboardQuery (Reports): returns DraftsInProgress (tôi là
  Drafter + phase soạn thảo), PendingMyApproval (phase eligible role
  tôi + không phải tôi drafter), DueSoon 24h, Overdue, DraftsTotalValue.
- Endpoint GET /api/reports/my-dashboard.
- FE MyDashboardRow ở đầu DashboardPage: 4 card hover → navigate.
  Admin ẩn row nếu tất cả = 0 (ERP noise reduction).
  'Đang soạn thảo' + 'Chờ tôi duyệt' clickable → /contracts?filter=...
  (filter param để wire lần sau; row hiện chưa implement).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 22:06:28 +07:00
4690cc3a81 [CLAUDE] Docs: STATUS update — PDF + workflow policy + form builder iter2 E2E verified
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m38s
2026-04-21 21:54:21 +07:00
cae4d84830 [CLAUDE] Domain+Infra+App+FE: dynamic workflow policy per ContractType
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m42s
Đọc QT-TP-NCC.docx: quy trình 9 bước chỉ áp dụng cho Thầu phụ/NCC/Tổ đội.
Dịch vụ/Mua bán/Nguyên tắc bypass CCM. Thay hardcoded dict bằng policy
registry.

Domain — WorkflowPolicy.cs:
- Record WorkflowPolicy { Name, Description, Transitions, PhaseSla,
  ActivePhases } — pure data, testable.
- WorkflowPolicies.Standard: 9-phase full (Thầu phụ/Giao khoán/NCC)
- WorkflowPolicies.SkipCcm: 7-phase (Dịch vụ/Mua bán/Nguyên tắc)
- WorkflowPolicyRegistry.For(type) map ContractType → policy
- WorkflowPolicyRegistry.ForContract(c) override nếu BypassProcurement
  AndCCM=true (instance-level escape hatch)

Infrastructure — ContractWorkflowService:
- Xóa hardcoded Transitions/PhaseSla dicts → load từ policy.ForContract
- TransitionAsync: validate qua policy.Transitions thay vì dict local
- Error message include policy.Name để debug dễ hơn
- GetPhaseSla trả SLA từ Standard policy (fallback — SLA hiện tại giống
  nhau giữa 2 policy)

Application — ContractDetailDto:
- Field mới `Workflow: WorkflowSummaryDto { PolicyName, Description,
  ActivePhases, NextPhases }` — FE dùng để render nút chuyển phase
  dynamic + timeline card.
- BuildWorkflowSummary helper trong ContractFeatures.

FE (both apps):
- Type WorkflowSummary + ContractDetail.workflow
- ContractDetailPage xóa hardcoded NEXT_PHASES — dùng
  c.workflow.nextPhases từ BE (single source of truth)
- WorkflowSummaryCard: timeline của ActivePhases với check/current/
  future states + policy name/description ở header
- Card hiển thị trong sidebar, phía trên "Lịch sử duyệt"

Docs:
- gotchas.md #21 marked RESOLVED (NEXT_PHASES sync không còn cần)

Foundation: sau này admin có thể edit policy qua UI khi chuyển sang DB-
backed policy — nhưng API contract (WorkflowSummaryDto) đã stable.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 21:46:31 +07:00
e45909712b [CLAUDE] App+Infra+FE-Admin: DynamicForm + .doc/.xls auto-convert on upload
Some checks failed
Deploy SOLUTION_ERP / build-deploy (push) Failing after 1m17s
Tier 3 iter2 — form builder UI dùng FieldSpec thay raw JSON textarea.

FE:
- DynamicForm component — parse FieldSpec JSON (record of FieldDef với
  label/type/required/placeholder/hint/options) và render inputs
  dynamic theo type: text/textarea/number/date/currency/select.
- FormsPage render dialog thêm toggle Form ↔ JSON (segmented control).
  Mặc định Form mode khi template có FieldSpec, JSON mode khi không.
  Khi mở dialog cho row khác, reset formValues + chọn đúng default mode.
- parseFieldSpec helper trả { spec, error } — UI báo lỗi nếu JSON
  không parse được, fallback JSON textarea.

BE — generalize converter thành IDocumentConverter:
- IPdfConverter → IDocumentConverter (ConvertAsync(bytes, src, tgt, ct))
  — đủ gánh cả pdf, docx, xlsx targets.
- LibreOfficeDocumentConverter — 1 shell-out pattern cho mọi conversion
  (docx→pdf, doc→docx, xls→xlsx, xlsx→pdf), target arg truyền vào
  --convert-to.
- ExportTemplatePdfCommand update dùng "pdf" target.

Auto-convert .doc/.xls trên upload:
- Validator accept thêm .doc/.xls (thêm note "sẽ tự convert").
- UploadContractTemplateCommandHandler: nếu ext là doc/xls → read stream
  → converter.ConvertAsync → lưu file .docx/.xlsx thay vì format gốc.
  File rendering pipeline (DocxRenderer/XlsxRenderer) chỉ support docx/
  xlsx — convert đảm bảo consistent.
- Display FileName preserve original name nhưng đổi extension.

Unblock 3 file .doc legacy template — admin giờ upload .doc bình thường,
system tự convert.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 21:35:05 +07:00
6bbd894d96 [CLAUDE] App+Infra+Api+FE-Admin: PDF export (LibreOffice headless)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m33s
Pipeline: template.docx → FormRenderer fill placeholders → LibreOffice
soffice --headless --convert-to pdf → PDF byte[] → File() stream to
browser.

Clean-arch split:
- Application: IPdfConverter abstraction (swap to QuestPDF/Aspose later
  without touching caller).
- Infrastructure: LibreOfficePdfConverter — shells out to soffice.exe
  path from config (Pdf:SofficePath, default
  `C:\Program Files\LibreOffice\program\soffice.exe` on Windows).
  Per-request temp workDir để tránh filename collision + -env:
  UserInstallation isolate mỗi conversion (chống "soffice already
  running" khi concurrent). Timeout 60s (configurable). Best-effort
  cleanup. Kill entire process tree nếu timeout.
- Application: ExportTemplatePdfCommand — reuses existing FormRenderer
  + pipes bytes through IPdfConverter. Same data dict signature as
  Render để UI code share.
- Api: POST /api/forms/templates/{id}/export-pdf (same JSON body as
  /render, returns PDF stream).

FE:
- useExport hook chung cho 2 endpoints (DRY render + export-pdf mutations)
- Render dialog thêm nút "Tải PDF" (outline variant) cạnh "Tải file gốc".
  Disabled khi mutation khác đang chạy.
- Hướng dẫn dialog nâng cấp: "file gốc để edit Word/Excel, PDF để
  in/gửi không chỉnh sửa được".

Ops: scripts/install-libreoffice.ps1 — silent MSI install 25.8.6 cho
VPS (đã chạy trên prod).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 21:28:31 +07:00
acc134a2fd [CLAUDE] Docs: STATUS update cho Form template builder + Gitea 500 fix
Some checks failed
Deploy SOLUTION_ERP / build-deploy (push) Failing after 2m23s
2026-04-21 21:21:46 +07:00
166d26c1d8 [CLAUDE] App+Api+FE-Admin: Form template builder (upload + edit + delete)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m44s
Admin giờ có thể quản lý template HĐ hoàn toàn qua UI — không cần dev
đụng vào file system hay seed data.

BE (FormFeatures.cs + FormsController.cs):
- UploadContractTemplateCommand (multipart): validate FormCode
  (regex [A-Za-z0-9._-]+, unique), file <= 10MB, ext .docx/.xlsx,
  FieldSpec phải là JSON hợp lệ hoặc null. Ghi file vào
  wwwroot/templates/{formCode}_{guid:N}.{ext} để tránh collision
  + path traversal.
- UpdateContractTemplateCommand: sửa metadata + FieldSpec + IsActive
  (không đụng file — chỉ DB).
- DeleteContractTemplateCommand: soft delete qua IsActive=false
  (historical contracts ref template này vẫn resolve).
- Endpoints: POST /api/forms/templates (multipart),
  PUT /api/forms/templates/{id}, DELETE /api/forms/templates/{id}.
  RequestSizeLimit 12MB (validator caps 10MB).

FE (FormsPage.tsx admin):
- PageHeader action button "Upload template" mở dialog mới
- Row actions: Download (render existing), Pencil (edit), Trash (xóa
  confirm) thay vì chỉ có 1 nút Render — row hover reveals clearly
- Upload dialog: file picker với file: pseudo-element brand styled,
  FormCode (required, font-mono), Tên, Loại HĐ select, Mô tả,
  FieldSpec JSON textarea với placeholder example
- Edit dialog: same fields minus file (FormCode disabled, edit chỉ
  cập nhật metadata), có checkbox Kích hoạt
- Shared form submit handler — same dialog cho upload (__new) + edit

Foundation sẵn cho form builder thật (render UI từ FieldSpec JSON
đang là text field — iteration sau sẽ parse + render form dynamic).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 21:15:35 +07:00
c52186bed0 [CLAUDE] Docs: gotcha #25 — Install-WindowsFeature Web-WebSockets locks webSocket section in applicationHost
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m24s
2026-04-21 21:10:43 +07:00
93e107208c [CLAUDE] Docs: STATUS update cho SignalR realtime deploy
Some checks failed
Deploy SOLUTION_ERP / build-deploy (push) Has been cancelled
2026-04-21 21:03:33 +07:00
ea9ab5e352 [CLAUDE] App+Infra+Api+FE: SignalR realtime notifications E2E
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m43s
Clean-arch split:
- Application: IRealtimeNotifier (PushToUserAsync, abstraction)
- Api: NotificationHub (/hubs/notifications, [Authorize]) +
  SignalRNotifier impl với IHubContext<NotificationHub>, uses
  Clients.User(userId) (default provider resolves NameIdentifier="sub")
- Infrastructure: NotificationPushInterceptor — SaveChangesInterceptor
  capture Notification entities state=Added trong SavingChanges,
  push qua IRealtimeNotifier trong SavedChanges sau khi commit thành
  công. Zero caller changes — handlers chỉ cần db.Add(Notification).
  Attached vào ApplicationDbContext cùng với AuditingInterceptor.

Auth:
- JWT config thêm OnMessageReceived event: read ?access_token= từ
  query string khi path = /hubs/* (WebSockets không set headers).
- SignalRNotifier singleton (stateless, chỉ delegate IHubContext).

FE (both apps):
- @microsoft/signalr 8.0.7 vào package.json.
- lib/realtime.ts: singleton connection với lazy start + automatic
  reconnect [0,2s,5s,10s,15s] + accessTokenFactory lấy từ localStorage.
- NotificationBell: useEffect subscribe 'notification-created' khi
  isAuthenticated. On push: invalidate query + toast.message. Fallback
  polling giảm từ 30s → 60s (realtime cover gap).
- AuthContext.logout: dynamic import stopConnection() — avoid leaking
  auth'd socket across users.

Result: ERP-grade feel. Contract transition → Drafter nhận toast ngay
trong vòng 100-300ms (same-origin WebSocket), không cần F5 hay polling.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 20:56:37 +07:00