Commit Graph

19 Commits

Author SHA1 Message Date
7b7b28f2cd [CLAUDE] Scripts Docs: Chunk T5+T6 — Final DELETE + verify NO re-seed loop (Plan T proven active)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 3m15s
Post-Plan T deploy Run #207 sha=0b97840 PASS — DemoSeed:Disabled flag
applied prod via appsettings.json (commit qua git, override
appsettings.Production.json gitignored).

T5 — Final DELETE sau flag deploy:
- scripts/plan-t5-final-cleanup.sql upload qua scp + sqlcmd -i
- 3 TRANSACTION DELETE: 4 PE + 1 V2 + 2 V1 = 7 rows direct + cascade child
- Post-state: PE=0 + V2=0 + V1=0 + Steps cascade=0 + Levels cascade=0

T6 — Verify NO re-seed loop (FORCE IIS recycle test):
- Restart-WebAppPool SolutionErp-Api → app pool Started
- Wait BE healthy (curl auth login 200)
- sqlcmd verify post-recycle DB state:
  * PE=0  NO re-seed
  * V2 workflows=0  NO re-seed
  * V1 workflows=0  NO re-seed
  * Users=33  preserved (SeedDemoUsers KEEP)
  * Suppliers=19  preserved (SeedDemoMasterData KEEP)
  * Projects=9  preserved (SeedDemoMasterData KEEP)
  * Contracts=7  preserved (bro chưa request xóa)

→ DemoSeed:Disabled flag PROVEN active end-to-end. DbInitializer skip 5
method seed, KHÔNG còn re-seed contaminate sau mỗi deploy.

Cumulative Plan R + S + T cleanup:
- R: 35 PE + 17 V2 + 4 V1 + ~600 cascade (52 + 600 = 652 rows)
- S: 4 workflow + cascade (4 + ~20 = 24 rows)
- T5: 7 rows direct + cascade child (~7 + ~30 = 37 rows)
- T flag: DbInitializer permanent disable demo seed
- TOTAL: ~713 rows wiped + flag persist active

Stats final S23 t10:
- 31 mig · 59 tables · ~145 endpoints · 34 FE pages
- 111 test unchanged · 47 gotcha · 20 memory · 6 skills
- 4 sub-agents · backup rollback ready
- **0 PE + 0 workflow + flag disable seed** UAT permanent clean slate

Bro Designer setup workflow mới from scratch khi UAT continue — KHÔNG còn
auto re-seed contaminate. Plan B Contract V2 wire next HIGH priority.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 15:14:39 +07:00
c4d5704269 [CLAUDE] Scripts Docs: Chunk S — Wipe ALL workflows (UAT clean slate hoàn toàn)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 3m22s
Bro chốt sau Plan R: "các cái demo quy trình cũ -> xóa hết luôn đi nhé"

State post-Plan R: 4 workflows còn lại đều seed demo cumulative:
- V2 `QT-DN-PA-V2-001 v2` "Quy trình duyệt NCC và Giải pháp (mẫu UAT)"
- V2 `QT-DN-V2-001 v16` "QT Duyệt So Sánh Giá NCC-TP" (sample seed default)
- V1 `QT-DN-A v3` "Quy trình Duyệt NCC (v01) (clone)(clone)"
- V1 `QT-DN-B v1` "Quy trình Duyệt NCC và Giải pháp (v01)" (sample seed)

Bro AskUserQuestion chốt Option A (Recommended): wipe ALL 4 workflows
→ UAT clean slate hoàn toàn. Em main solo execute (Investigator audit Plan
R đã cover scope precedent + backup rollback Plan R còn dùng được).

Backup rollback ready: C:\Backup\SolutionErp_pre_cleanup_2026-05-15.bak
(Plan R, 18.5MB) — capture full state pre-cleanup, reuse cho Plan S rollback.

Execute via scp scripts/plan-s-wipe-all-workflows.sql + sqlcmd -i:
- DELETE ALL ApprovalWorkflows (2 rows cascade Steps+Levels)
- DELETE ALL PurchaseEvaluationWorkflowDefinitions (2 rows cascade
  Steps+Approvers)

Post-state cumulative Plan R + S:
- PE: 35 → 0
- V2 workflows: 17 → 2 → 0
- V1 workflows: 4 → 2 → 0
- Cascade Steps + Levels + Approvers: 0 (all entities wiped)

BE smoke verify 5/5 endpoints 200 post-cleanup:
- /api/auth/login → OK (admin token len 468)
- /api/purchase-evaluations → 200 (empty list)
- /api/approval-workflows-v2 → 200 (empty list)
- /api/pe-workflows → 200 (empty list)
- /api/users + /api/menus → 200

→ KHÔNG crash startup (Plan F precedent avoid: no Contract pin to V1, PE
đã wipe Plan R, nên drop workflow safe).

Hậu quả expected:
- User KHÔNG tạo được phiếu mới qua Workspace (Select workflow empty)
- Admin Designer phải seed workflow mới from scratch để UAT continue
- Total cleanup cumulative ~670 rows wiped (35 PE + 17 V2 + 4 V1 + ~600
  cascade child)

Stats final S23 t9:
- 31 mig · 59 tables · ~145 endpoints · 34 FE pages · 111 test unchanged
- 47 gotcha · 20 memory · 6 skills · 4 sub-agents
- **0 PE + 0 workflow** — database UAT clean slate hoàn toàn

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 14:52:55 +07:00
5cbf516a78 [CLAUDE] Scripts Docs: Chunk R — Cleanup destructive prod database (52 rows + ~600 cascade child)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 3m27s
Bro UAT confirm Plan P+Q wire OK + chỉ thị cleanup test data:
> "OK Tao thấy tạm ổn rồi đấy, mày xóa hết các phiếu test cũ đi nhé,
> các quy trình cũ ko ghim cũng xóa hết đi. Cho gọn đẹp."

Investigator pre-flight audit prod DB ~64K spawn confirm scope:
- 35 PE rows total (28 active + 7 soft-deleted)
- 17 ApprovalWorkflowsV2 (15 IsUserSelectable=false + 2 ghim+active)
- 4 PurchaseEvaluationWorkflowDefinitions V1 (2 IsActive=false + 2 active)

Critical gotchas:
1. PE.ApprovalWorkflowId FK Restrict → soft-delete KHÔNG release FK,
   hard-DELETE PE first
2. ApprovalWorkflow extend BaseEntity (NO soft-delete) → hard DELETE only
3. Filtered indexes Mig 29+ require SET QUOTED_IDENTIFIER ON
4. SQL Express constraints: NO BACKUP COMPRESSION + RESTORE VERIFYONLY
   require sysadmin (vrapp KHÔNG có)

Execute via scripts/plan-r-*.sql upload scp + sqlcmd -i workflow:

Step 1+2 — BACKUP DATABASE:
- C:\Backup\SolutionErp_pre_cleanup_2026-05-15.bak (18.5MB, 2249 pages)
- Verified via Get-Item file size

Step 3-5 — 3 separate transactions DELETE:
- 28 PE active + 7 soft-deleted → cascade 446 child rows
  (42 Details + 49 Suppliers + 64 Approvals + 238 Changelogs +
   10 Attachments + 43 LevelOpinions)
- 15 V2 workflows unghim → cascade ~140 Steps+Levels
- 2 V1 workflows inactive → cascade ~37 Steps+Approvers

Total: 52 rows direct + ~600 cascade child = ~650+ rows wiped.

Step 6 — Verify post-cleanup state:
- PE total: 35 → 0 ✓
- V2 workflows: 17 → 2 (QT-DN-V2-001 v16 + QT-DN-PA-V2-001 v2 ghim+active)
- V1 workflows: 4 → 2 (QT-DN-A v3 + QT-DN-B v1 active, PE pin protected)

Step 7 — BE smoke verify alive post-cleanup:
- /api/auth/login → 200
- /api/purchase-evaluations → 200
- /api/approval-workflows-v2 → 200
- /api/pe-workflows → 200
→ KHÔNG crash startup (Plan F precedent avoid được)

Multi-agent ROI: Investigator save em main hard-delete blind without
backup + catch SQL Express constraint + catch FK Restrict gotcha.

Pattern reinforced:
- Destructive operation prod BẮT BUỘC pre-flight audit + backup + verify
- scp + sqlcmd -i workflow cho complex SQL trên prod (avoid shell escape
  hell qua SSH PowerShell)
- Plan F precedent: KHÔNG drop active workflow (PE pin → BE crash)

Stats final S23 t8:
- 31 mig · 59 tables · ~145 endpoints · 34 FE pages · 111 test unchanged
- 47 gotcha · 20 memory · 6 skills · 4 sub-agents
- **0 PE phiếu test + 4 workflow ghim/active** — UAT clean slate
- Backup rollback ready: vietreport-vps:C:\Backup\SolutionErp_pre_cleanup_2026-05-15.bak

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 14:11:56 +07:00
0e707891ff [CLAUDE] Scripts: rename 20 test user sang role-based naming (S22+3)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 3m6s
Bro feedback: "đổi tên thành roles luôn đi cho dễ test, để user ít nhầm lẫn"

20 user S22+2 đã rename:

Email pattern: {dept}.{level}@solutions.com.vn
  - act.nv / act.pp / act.tp
  - bod.1 / bod.2 (no hierarchy)
  - equ.nv / equ.pp / equ.tp
  - fin.nv / fin.pp / fin.tp
  - hra.nv / hra.pp / hra.tp
  - pm.nv / pm.pp / pm.tp
  - qs.nv / qs.pp / qs.tp

FullName pattern: "{DEPT} {LEVEL} - {Roles} [Flags]"
  - [Bypass] = CanBypassReview=true (act.tp, hra.tp)
  - [SkipFinal] = AllowDrafterSkipToFinal=true (fin.pp, pm.nv)

Identity rename pattern per gotcha #38 — 4 fields atomic UPDATE:
  Email + NormalizedEmail + UserName + NormalizedUserName + FullName.

Implementation:
- Build single SQL transaction 20 UPDATE
- SET QUOTED_IDENTIFIER ON (required filtered indexes Users)
- SCP file → SSH sqlcmd execute (avoid shell quote escape hell)

Verify:
- 20 rows UPDATE affected (1 mỗi user)
- Login test act.nv / TestUser@2026 → ACT NV - Drafter+Accounting OK
- NormalizedEmail + NormalizedUserName uppercase match Identity convention

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 22:09:10 +07:00
8185070109 [CLAUDE] Scripts: seed 20 test user prod cho UAT (S22+2)
Some checks failed
Deploy SOLUTION_ERP / build-deploy (push) Has been cancelled
Bro request: tạo mỗi phòng 2-3 user + phân quyền để test scenarios.

Script `scripts/seed-test-users-prod.ps1` ASCII-only (gotcha #30 PS 5.1 diacritics)
gọi API admin token, idempotent (skip 409 conflict). Tạo 20 user mới:

| Phòng | Trước | Sau | Pattern |
|---|---:|---:|---|
| ACT | 0 | 3 | NV (Drafter+Accounting) / PP / TP (DeptManager, CanBypassReview=true) |
| BOD | 1 | 3 | +2 Director (no PositionLevel) |
| CCM | 7 | 7 | SKIP existing đủ |
| EQU | 0 | 3 | NV / PP / TP (DeptManager+Equipment) |
| FIN | 0 | 3 | NV / PP (AllowDrafterSkipToFinal=true) / TP |
| HRA | 0 | 3 | NV / PP / TP (CanBypassReview=true) |
| PM | 0 | 3 | NV (AllowDrafterSkipToFinal=true, ProjectManager) / PP / TP |
| PRO | 5 | 5 | SKIP existing đủ |
| QS | 0 | 3 | NV / PP / TP (Drafter-only, no role chuyên) |

Total active prod: 13 → 33 users.

UAT scenarios covered:
- N-stage workflow inner step (Mig 18): NV/PP/TP per phòng test sequential + bypass
- 2-stage dept approval (Mig 16): 2 user CanBypassReview=true (ACT.tp + HRA.tp)
- F2 per-Drafter skip (Mig 29): 2 user AllowDrafterSkipToFinal=true (FIN.pp + PM.nv)
- Plan E strict V2 scope: 33 user × 9 dept × various roles (test diverse approver match)

Password tất cả: TestUser@2026 (>=12 chars per Identity policy).

Discoveries:
- Identity password policy: >=12 chars (HANDOFF "User@123456" 11 chars FAIL 400)
- API auth response: field `accessToken` không phải `token`
- Rate limit awareness: Start-Sleep 500ms giữa requests

Verify: sqlcmd Prod 9 phòng × 2-7 user, 33 total active.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 22:05:46 +07:00
ac41d5e0d8 [CLAUDE] Scripts: SQL clean transactional UAT (Session 17 V2 testing)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 3m12s
User UAT V2 schema cần clean phiếu cũ trên prod để đỡ rối mắt + giữ
master data (Users / Suppliers / Projects / Departments / Workflows).

scripts/sql/clean-transactional-uat.sql:
- DELETE theo FK order (child → parent):
  1. PE child rows (DeptApprovals/Opinions/Attachments/Changelogs/
     Approvals/Quotes/Details/Suppliers)
  2. PE main (giải phóng FK PE.ContractId/BudgetId)
  3. Contract per-type Details (7 bảng) + Contract child rows
  4. Contract main
  5. Budget child rows + main
  6. CodeSequences (PE + Contract reset)
  7. Notifications (dangling refs sau khi xóa phiếu)
- Wrap BEGIN/COMMIT TRANSACTION
- Verify queries cuối in count master KEEP + transactional after-clean

KEEP master: Users, Roles, MenuItems, Permissions, Suppliers, Projects,
Departments, UnitsOfMeasure, MaterialItems, ServiceItems, WorkItems,
ContractTemplates, ContractClauses, WorkflowTypeAssignments,
WorkflowDefinitions (V1 legacy), PurchaseEvaluationWorkflowDefinitions,
ApprovalWorkflows + Steps + Levels (V2 Mig 22).

Required SET QUOTED_IDENTIFIER ON; ANSI_NULLS ON; cho filtered indexes
Mig 19/20 (sqlcmd default off → DELETE fail).

Verify local Dev: chạy OK, 1 Contract + 0 PE + 0 Budget cleaned, master
giữ (Users=2 admin seed, Suppliers=3, Projects=1, Departments=9, V1
WfDef=7).
2026-05-08 15:28:40 +07:00
b93dacff44 [CLAUDE] Scripts: fix migrate-domains.ps1 ASCII-only (gotcha #30 PS 5.1)
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m46s
2026-04-24 09:55:57 +07:00
66c1a5c170 [CLAUDE] Rebrand: 3 domain huypham.vn → solutions.com.vn + migrate script
All checks were successful
Deploy SOLUTION_ERP / build-deploy (push) Successful in 2m52s
User request: anh trỏ 3 subdomain mới về VPS IP 103.124.94.38:
  - api.huypham.vn        → api.solutions.com.vn
  - admin.huypham.vn      → admin.solutions.com.vn
  - user.huypham.vn       → eoffice.solutions.com.vn

Verified DNS: cả 3 resolve 103.124.94.38 ✓

Update 17 file repo:
FE (4): fe-admin/.env.production + fe-user/.env.production
        (VITE_API_BASE_URL → https://api.solutions.com.vn)
        fe-admin/src/lib/{api,realtime}.ts + fe-user equivalents (comment)
BE (1): appsettings.Production.json.example — CORS AllowedOrigins
CI/CD (1): .gitea/workflows/deploy.yml — smoke test URL
Scripts (3): setup-iis-sites (DomainApi/Admin/User), setup-ssl (3 host),
             deploy-all (verify curls)
Docs (5): STATUS, HANDOFF, PROJECT-MAP, vps-setup, gotchas
Skill (1): iis-deploy-runbook — 3 site table + description
Email admin@huypham.vn giữ nguyên (Let's Encrypt contact — không phải
domain serve).

Thêm scripts/migrate-domains.ps1 — 1-shot VPS migration:
  1. Pre-flight: resolve DNS 3 domain → verify IP VPS khớp
  2. Add HTTP binding mới cho 3 IIS site (giữ binding cũ làm fallback)
  3. Run win-acme xin 3 cert Let's Encrypt qua HTTP-01 challenge
     (auto add HTTPS binding + http→https redirect)
  4. Verify /health/live + /health/ready + 2 FE endpoint
  5. (Optional -RemoveOld) xóa binding huypham.vn sau verify OK
Rollback: nếu fail, binding cũ vẫn active → site serve qua huypham.vn.

Anh chạy trên VPS:
  cd C:\solution-erp\scripts  ;  .\migrate-domains.ps1
  # Sau 1-2 ngày verify stable:
  .\migrate-domains.ps1 -RemoveOld -SkipCert
2026-04-24 09:43:05 +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
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
397eb367e5 [CLAUDE] Scripts: SPA web.config thêm HTTP→HTTPS redirect (fix admin login Network Error)
Some checks failed
Deploy SOLUTION_ERP / build-deploy (push) Has been cancelled
2026-04-21 15:33:01 +07:00
45452765e3 [CLAUDE] Scripts: fix setup-ssl.ps1 --installationsiteid flag
Some checks failed
Deploy SOLUTION_ERP / build-backend (push) Failing after 8s
Deploy SOLUTION_ERP / build-fe-admin (push) Has been cancelled
Deploy SOLUTION_ERP / build-fe-user (push) Has been cancelled
Deploy SOLUTION_ERP / deploy-iis (push) Has been cancelled
win-acme 2.2.9 with --target manual + --installation iis requires
--installationsiteid (not --siteid). --siteid only applies to the
iis target plugin, not the iis installation plugin.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 14:19:26 +07:00
169e268b28 [CLAUDE] Scripts: rewrite 4 deploy PS1 ASCII-only for PS 5.1 compat
Some checks failed
Deploy SOLUTION_ERP / build-backend (push) Failing after 9s
Deploy SOLUTION_ERP / build-fe-admin (push) Has been cancelled
Deploy SOLUTION_ERP / build-fe-user (push) Has been cancelled
Deploy SOLUTION_ERP / deploy-iis (push) Has been cancelled
PowerShell 5.1 reads .ps1 files as locale codepage (not UTF-8 no BOM),
which corrupts multi-byte Vietnamese chars and breaks parsing. Rewrote
setup-iis-sites.ps1, setup-ssl.ps1, setup-gitea-runner.ps1, deploy-all.ps1
as ASCII-only. Also renamed $Host param to $HostName in Ensure-Site to
avoid collision with PowerShell built-in $Host automatic variable.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 14:17:36 +07:00
85acf750b3 [CLAUDE] Scripts: update cho SQLEXPRESS instance + Invoke-Sqlcmd (no sqlcmd.exe binary needed)
Some checks failed
Deploy SOLUTION_ERP / build-backend (push) Failing after 9s
Deploy SOLUTION_ERP / build-fe-admin (push) Has been cancelled
Deploy SOLUTION_ERP / build-fe-user (push) Has been cancelled
Deploy SOLUTION_ERP / deploy-iis (push) Has been cancelled
- setup-sql-db.ps1: Server=.\SQLEXPRESS default, dung Invoke-Sqlcmd (SqlServer PS module) voi credential + TrustServerCertificate
- appsettings.Production.json.example: Server=.\SQLEXPRESS (voi escaped backslash JSON)
- DB_CONNECTION Gitea secret da update (qua API)

VPS Windows Server 2022 minimal, co VIETREPORT da chay 4 site, SQL instance SQLEXPRESS.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 14:10:08 +07:00
1b7d8872ab [CLAUDE] Scripts: deploy-all.ps1 one-command gop 4 step
Some checks failed
Deploy SOLUTION_ERP / build-backend (push) Failing after 9s
Deploy SOLUTION_ERP / build-fe-admin (push) Has been cancelled
Deploy SOLUTION_ERP / build-fe-user (push) Has been cancelled
Deploy SOLUTION_ERP / deploy-iis (push) Has been cancelled
- Pre-check prerequisites (admin, sqlcmd, WebAdministration, .NET 10)
- Chay theo thu tu SQL → IIS → appsettings.Production.json (auto write tu template + ACL restrict) → SSL (voi confirm) → Runner
- Idempotent: chay lai khong pha
- -SkipSsl / -SkipRunner flag cho debug
- Summary voi next steps

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 13:49:55 +07:00
b1a4571c86 [CLAUDE] VPS setup scripts + SSL + runner + FE prod config + master runbook
Some checks failed
Deploy SOLUTION_ERP / build-backend (push) Failing after 9s
Deploy SOLUTION_ERP / build-fe-admin (push) Has been cancelled
Deploy SOLUTION_ERP / build-fe-user (push) Has been cancelled
Deploy SOLUTION_ERP / deploy-iis (push) Has been cancelled
Scripts moi (PowerShell admin trên VPS Windows Server):
- setup-sql-db.ps1: tao DB SolutionErp + grant db_owner cho vrapp (user shared voi VIETREPORT). Idempotent.
- setup-iis-sites.ps1: app pool SolutionErp-Api (NoManagedCode + AlwaysRunning + no idle) + 3 site (SolutionErp-Api/Admin/User) voi host header, C:\inetpub\solution-erp\{api,fe-admin,fe-user,logs,uploads}. Placeholder index.html + SPA web.config voi URL rewrite fallback + security headers. Firewall rule. ACL grant AppPool identity Modify. Naming prefix SolutionErp-* tranh conflict VIETREPORT.
- setup-ssl.ps1: download win-acme v2.2.9 → issue cert Let's Encrypt 3 domain (api/admin/user.huypham.vn) qua HTTP-01 challenge + auto install IIS binding + HTTP→HTTPS redirect + scheduled task 90d renew.
- setup-gitea-runner.ps1: download act_runner.exe → register voi Gitea git.baocaogiaoduc.vn, install Windows service, labels windows-latest,self-hosted,windows,x64 (cho phep share voi VIETREPORT).

FE production config:
- fe-admin/.env.production + fe-user/.env.production: VITE_API_BASE_URL=https://api.huypham.vn
- fe-admin/src/lib/api.ts + fe-user/src/lib/api.ts: BASE_URL = (import.meta.env.VITE_API_BASE_URL ?? '') + '/api'
  - Dev: empty prefix → /api qua Vite proxy :5443
  - Prod: https://api.huypham.vn/api (cross-origin CORS da config AllowedOrigins)

Docs:
- docs/guides/vps-setup.md MOI (master runbook): prereq, 4 script chay theo thu tu, set 5 Gitea secrets, first deploy, appsettings.Production.json pattern (file hoac user-secrets), smoke test 3 curl, post go-live checklist (doi admin password, rotate secrets chat-exposed, backup schedule, disable Swagger prod, monitor logs), table co-existence VIETREPORT
- CLAUDE.md root: add vps-setup.md reference

Gitea repo da setup (extern):
- https://git.baocaogiaoduc.vn/vietreport-admin/solution-erp (private)
- Secrets set via API: IIS_HOST=103.124.94.38, IIS_USER=Administrator, DB_CONNECTION (voi vrapp password), JWT_SECRET placeholder
- CON THIEU: IIS_PASSWORD (Windows admin — user cung cap), JWT_SECRET real value (64-char tu vps-jwt-key.txt — user update qua Gitea UI)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 13:37:34 +07:00
f3fb3fd565 [CLAUDE] Phase5 prep: production infra + deploy scripts + 4 guides + FE refresh token
Backend production infra:
- Packages: Serilog.Sinks.File, HealthChecks.EntityFrameworkCore (RateLimiting built-in .NET 10)
- appsettings.Production.json MOI: placeholder __SET_VIA_SECRETS__, AllowedOrigins, Serilog File sink rolling daily retention 30d, RateLimit config
- appsettings.json + Development.json: them Serilog WriteTo Console
- Program.cs REWRITE:
  - Serilog ReadFrom.Configuration (prod file / dev console)
  - Rate limiter: policy auth-login 5/min/IP (AuthController.Login) + GlobalLimiter 300/min/IP
  - Health checks: /health/live liveness (empty predicate) + /health/ready DB probe (AddDbContextCheck)
  - HSTS production 1 year
  - CORS origins from config AllowedOrigins (default dev 2 localhost)
- AuthController.Login gắn [EnableRateLimiting("auth-login")]

Deploy scripts:
- scripts/deploy-iis.ps1: stop pool → backup current → clean+extract artifact → start pool → health check loop 30s timeout → rollback instruction if fail
- scripts/backup-sql.ps1: BACKUP DATABASE voi INIT+COMPRESSION+CHECKSUM + retention 30d auto cleanup
- .gitea/workflows/deploy.yml MOI: 4 job build BE (Windows) + build 2 FE (Ubuntu, pin .nvmrc 20) + deploy-iis qua WinRM PSSession (secrets IIS_HOST/USER/PASSWORD/JWT_SECRET/DB_CONNECTION)

Docs guides MOI (4 file):
- deployment-iis.md: prereqs (IIS features, Hosting Bundle, SQL, WinRM) + setup lan dau (app pool, 3 site, HTTPS win-acme, user-secrets) + deploy hang ngay (CI/CD + manual) + rollback + monitoring + troubleshooting + SPA web.config sample
- cicd.md: pipeline overview 4 job, secrets setup, runner Windows+Ubuntu, branch strategy, build optimizations, common CI/CD issues
- security-checklist.md: OWASP top 10 2021 mapping voi status + pre go-live checklist + incident response
- runbook.md: daily ops (health/logs), restart/rollback, DB backup/restore/migration revert, user management (reset password, unlock, disable), monitoring (CPU/disk/connection pool), deployment checklist, common gotcha

Frontend refresh token (ca 2 app fe-admin + fe-user):
- lib/api.ts REWRITE: them REFRESH_KEY, axios response interceptor 401 → POST /auth/refresh → retry request goc. Queue pattern cho nhieu request song song chi 1 refresh call chay. Skip retry /auth/login + /auth/refresh tranh infinite loop. _retry flag tren original config.
- contexts/AuthContext.tsx: luu+xoa REFRESH_KEY trong login/logout

E2E verified:
- GET /health/live → 200 Healthy
- GET /health/ready → 200 Healthy (DB probe)
- Rate limit flood 7 POST /auth/login → #1-5 HTTP 400 (cred sai) + #6-7 HTTP 429 Too Many Requests 
- TS check fe-admin + fe-user → pass
- dotnet build → 0 errors

Docs updates:
- docs/STATUS.md: Phase 5 prep done, next Phase 5 deploy production + Phase 5.1 security hardening, cumulative stats 8 commits
- docs/HANDOFF.md: phase table them Phase 5 prep row, file tree update voi guides + scripts + workflows, git state commit 8
- docs/changelog/migration-todos.md: tick Phase 5 prep items (12 items done) + Phase 5 deploy items remaining + Phase 5.1 security hardening list
- docs/changelog/sessions/2026-04-21-1530-phase5-prep.md: session log chi tiet

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 12:57:12 +07:00
5113e4c771 [CLAUDE] Phase2: Form Engine MVP + docs (gotchas, skill, handoff)
Backend Forms:
- Domain/Forms: ContractTemplate (FormCode, Name, ContractType, FileName, StoragePath, Format, FieldSpec JSON, IsActive) + ContractClause
- EF config voi unique FormCode + query filter IsDeleted
- DbSets + IApplicationDbContext update
- Migration AddForms (bang 14 total)
- Packages: DocumentFormat.OpenXml 3.x + ClosedXML 0.105+
- Application/Forms:
  - IFormRenderer interface + RenderResult record
  - FormFeatures.cs: List/Get/Render CQRS
  - IWebHostEnvironmentLocator (abstract IWebHostEnvironment)
- Infrastructure/Forms:
  - DocxRenderer: OpenXml-based placeholder {{field}} replace, handle split runs (gom text tat ca <w:t> trong paragraph, replace, gan lai text dau + clear rest)
  - XlsxRenderer: ClosedXML cell value replace
  - FormRenderer router theo format docx/xlsx
- Api:
  - FormsController: GET /templates (filter type, onlyActive), GET /templates/{id}, POST /templates/{id}/render (return file)
  - WebHostEnvironmentLocator impl
- DbInitializer SeedContractTemplatesAsync: seed 8 template metadata, IsActive=true chi khi file ton tai

Templates vat ly:
- Copy 5 .docx/.xlsx tu FORM/ sang wwwroot/templates/
- 3 .doc (FO-002.02/03/06) chua convert: IsActive=false (Word COM bi stuck luc test, can retry voi DisplayAlerts=0 hoac LibreOffice)
- scripts/convert-doc-to-docx.ps1 (Word COM automation)

Frontend fe-admin:
- types/forms.ts: ContractTemplate + ContractTypeLabel
- pages/forms/FormsPage.tsx: list templates + Render dialog (paste JSON data → download .docx/.xlsx)
- Route /forms them vao App.tsx

Bug fix:
- SpaceProcessingModeValues namespace: wrap EnumValue<> full path
- SaveAs2($path, 16) thay vi SaveAs([ref], [ref]) — PowerShell type issue
- Word COM stuck: kill process, skip .doc cho MVP

Docs (theo yeu cau user):
- docs/gotchas.md MOI: 17 pitfalls nhom theo tech stack / EF Core / OpenXml / JSON / dev workflow
- .claude/skills/form-engine/SKILL.md: placeholder → full spec (algorithm + code pointers + API + limitations)
- .claude/skills/permission-matrix/SKILL.md: placeholder → full spec (BE policy + FE guard + seed + pitfalls)
- docs/HANDOFF.md MOI: brief 5 phut cho session sau (run quickstart + where we are + next steps + file tree + gotchas ref)
- docs/STATUS.md: update cumulative stats + next up Phase 3
- docs/changelog/migration-todos.md: tick Phase 2 iteration 1 items + add iteration 2 list
- docs/changelog/sessions/2026-04-21-1200-phase2-form-engine.md: session log
- CLAUDE.md root: them reference den gotchas + HANDOFF

E2E verified:
- GET /api/forms/templates (onlyActive=false) → 8 templates
- POST /api/forms/templates/{FO-002.05}/render voi data dict → HTTP 200 + file .docx 482KB (Microsoft Word 2007+ OK)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 12:01:11 +07:00
25dad7f36f [CLAUDE] Scaffold: khoi tao SOLUTION_ERP Phase 0
- .NET 10 Clean Architecture: Domain/Application/Infrastructure/Api (4 project)
- 2 React + Vite + TS app: fe-admin (:8082), fe-user (:8080) voi proxy /api
- Node engines >=20, .nvmrc = 20 cho CI (bai hoc NamGroup)
- SQL Server 2022 qua docker-compose (dev)
- Parse 8 FORM -> docs/forms-spec.md (catalog + ma HD format RG-001)
- Parse QUY_TRINH -> docs/workflow-contract.md (9 phase state machine + role matrix)
- docs: CLAUDE.md, STATUS.md, PROJECT-MAP.md, migration-todos.md (roadmap 5 phase)
- .claude/skills: 3 placeholder (contract-workflow, form-engine, permission-matrix)

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