[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7F41VCHW50EVHGZZFX6WQVB":3,"skill-same:01M7F41VCHW50EVHGZZFX6WQVB":57},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7F41VCHW50EVHGZZFX6WQVB","handling-fe-auth-and-i18n",null,"Auth signals (branchActiveId, authBusinessProfile — D15: KHÔNG còn companyActiveId), tenant scope FE, permission check, TimezoneService, i18n key taxonomy và i18n:find. Dùng skill này KHI làm feature đụng permission\u002Fquyền, branch scope, thông tin thương hiệu, timezone\u002FDatePicker, hoặc trước khi thêm bất kỳ i18n key mới nào.","cluvix\u002Fcluvix-crm","cluvix","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F324537109?v=4","01M7F40XX639HYM8HRW4JW1TA5","Cluvix Solutions","01M7F40XYG6YMX0CD0QZNV61K4",21,"AGPL-3.0","https:\u002F\u002Fgithub.com\u002Fcluvix\u002Fcluvix-crm\u002Fblob\u002Fmain\u002Ffrontend\u002Fskill\u002Fskills\u002Fhandling-fe-auth-and-i18n\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: handling-fe-auth-and-i18n\ndescription: >-\n  Auth signals (branchActiveId, authBusinessProfile — D15: KHÔNG còn companyActiveId),\n  tenant scope FE, permission check, TimezoneService, i18n key taxonomy và i18n:find.\n  Dùng skill này KHI làm feature đụng permission\u002Fquyền, branch scope, thông tin thương\n  hiệu, timezone\u002FDatePicker, hoặc trước khi thêm bất kỳ i18n key mới nào.\n---\n\n# Handling FE auth and i18n\n\n> Timezone chi tiết (DatePicker → unix timestamp, dateHmsToUnix, toTz\u002FtoUnix): `reference\u002Ffe-timezone.md`\n> Auth gotchas (restoreAuthUser async, IDB missing case, permission gate): `reference\u002Ffe-patterns-gotchas-auth.md`\n\n\n\nTài liệu cho AI agents hiểu auth signals, tenant scope FE, và cách dùng đúng.\nĐọc file này trước khi làm việc với branch selection, permissions, hoặc print.\n\n> **(đã bỏ, D15\u002FCRM standalone)**: hệ thống là 1 thương hiệu\u002FDB — KHÔNG còn `companyActiveId`,\n> `companyListId`, hay khái niệm \"chọn công ty\". Thông tin thương hiệu (tên, logo, timezone, tiền\n> tệ, 2FA, IP allowlist) đọc qua signal `authBusinessProfile` (`src\u002Fapp\u002Fcore\u002Fservices\u002Fauth\u002Fauth.state.ts`),\n> nguồn BE là `pkg\u002Fbrand`\u002Fbảng `business_profile` (D22, story-62\u002F63). Trục scope duy nhất còn lại là\n> `branchActiveId`\u002F`branchListId`.\n\n---\n\n## 1. Auth signals — import từ `@\u002Fcore\u002Fservices\u002Fauth`\n\n**File:** `src\u002Fapp\u002Fcore\u002Fservices\u002Fauth\u002Fauth.selectors.ts`\n\n```typescript\nimport {\n    branchActiveId,    \u002F\u002F computed: userProfile()?.branchActive_id\n    branchListId,      \u002F\u002F computed: authUser()?.branchId ?? []    — mảng tất cả branch\n    userId,            \u002F\u002F computed: authUser()?.id\n    userFullname,      \u002F\u002F computed: userProfile()?.fullname\n    isLoggedIn,        \u002F\u002F computed: !!authUser()\n    isSuperUser,       \u002F\u002F computed: role in SUPER_ROLES whitelist\n    isDevelop,         \u002F\u002F computed: role === 'develop'\n    isAdmin,           \u002F\u002F computed: role === 'admin'\n    hasPermission,     \u002F\u002F fn(name): boolean — check permission string\n    hasAnyPermission,  \u002F\u002F fn(...names): boolean\n    hasAllPermissions, \u002F\u002F fn(...names): boolean\n} from '@\u002Fcore\u002Fservices\u002Fauth';\n```\n\n**State signals (low-level, ít dùng trực tiếp):**\n```typescript\nimport { authUser, authBusinessProfile, userPermissions } from '@\u002Fcore\u002Fservices\u002Fauth';\n```\n\n---\n\n## 2. `authBusinessProfile` — hồ sơ thương hiệu (thay `companyActiveId`\u002F`companyListId` cũ)\n\n| Signal | Trả về | Ý nghĩa |\n|---|---|---|\n| `authBusinessProfile()` | `BusinessProfileModel \\| null` | Hồ sơ thương hiệu duy nhất của DB (tên, logo, timezone, tiền tệ...) |\n| `branchActiveId()` | `number \\| undefined` | Branch user đang chọn (active context) — có thể chưa chọn |\n| `branchListId()` | `number[]` | Tất cả branch user có quyền — mảng rỗng nếu chưa login |\n\n### Dùng đúng\n\n```typescript\n\u002F\u002F ✅ Scope SELECT theo active context\ntenant.ScopedDBNullBranch(c, h.DB, \"table\")  \u002F\u002F BE lo (đọc từ context, AuthResponseHeaders set từ user_profile)\n\n\u002F\u002F ✅ FE: pre-fill form mặc định\nthis.initialValue = {\n    branch_id: branchActiveId(),\n};\n\n\u002F\u002F ❌ NEVER — dùng để auto-fill khi INSERT (xem B.1.1 CLAUDE.md)\n\u002F\u002F branch_id của record phải từ FE picker, không tự derive từ active context\n```\n\n---\n\n## 3. Tenant scope trong component FE\n\n### Pre-fill form — OK\n\nFE pre-fill `branch_id` từ active context để tiện UX. User vẫn có thể đổi qua picker.\n\n```typescript\n\u002F\u002F ✅ OK — pre-fill mặc định, user đổi được\nthis.initialValue = {\n    ...this.initialValue,\n    branch_id: branchActiveId(),\n};\n```\n\n### (đã bỏ, D15\u002FCRM standalone) Company picker trong form — toàn bộ pattern đã xoá\n\nTrước D15, mục này còn 3 pattern lớn cho `company_id` trong form: \"Root entity không picker, seed theo\nthương hiệu active\" (`BaseSignalForm.seedCompanyId`, `CompanyFormControl`, gate BE `company_active_required`),\n\"Record con derive company từ record cha\" (`FormAppointment` seed `company_id` từ `customer.company_id`),\nvà \"IndexedDB cache key theo `companyActiveId()-branchActiveId()`\". Verify 2026-09-28: `seedCompanyId`,\n`CompanyFormControl`, và field `company_id` trong các form trên **không còn tồn tại** trong\n`frontend\u002Fsrc\u002Fapp\u002F` — company đã xoá hoàn toàn khỏi FE (`tenantKey` kiểu `companyActiveId()-branchActiveId()`\ncũng không còn xuất hiện trong code — verify trước khi viết lại pattern IndexedDB key mới, đừng suy\ntừ đoạn lịch sử này). Giữ đoạn trên làm lịch sử\u002Ftham khảo nếu cần đọc code cũ, KHÔNG áp dụng cho code mới.\n\n---\n\n## 4. RBAC \u002F Permissions\n\n**KHÔNG dùng `ngx-permissions`\u002F`NgxPermissionsService`\u002F`NgxPermissionsModule`** — đã gỡ khỏi package.json (2026-07-05).\nCơ chế permission DUY NHẤT là signal-based (`userPermissions()` + `isSuperUser()`), lộ ra qua `hasPerm` directive \u002F `hasPermission()` fn.\n`BaseApp.permissionsService` vẫn còn (nhiều component cũ gọi `this.permissionsService.getPermission(x)`) nhưng giờ là `PermissionsService` (`share\u002Fservices\u002Fpermissions.service.ts`) — shim mỏng gọi `hasPermission()`, KHÔNG phải ngx-permissions.\n\n**Permission tính năng (`viewX`\u002F`createX`...) CHỈ enforce ở FE** — BE (`pkg\u002Fdefine\u002Frbac.go`) chỉ chặn super-role + tenant scope, KHÔNG có middleware kiểm quyền per-endpoint. ⇒ guard FE bypass được qua gọi API trực tiếp; kiểm soát dữ liệu thật vẫn ở BE (`ScopedDBNullBranch`).\n\nQuyền MỚI tạo: **gán cho role TRƯỚC, thêm `*hasPerm`\u002F`requirePerm` SAU**. Gate FE là chặn thật, mà quyền mới chỉ super role tự có ⇒ thêm gate trước khi gán = khoá tính năng với 100% user thường.\n\n```typescript\n\u002F\u002F Template — directive tên `hasPerm` (KHÔNG phải `hasPermission`)\n\u003Cbutton *hasPerm=\"permission.permissionCreateCustomer\">Tạo KH\u003C\u002Fbutton>\n\n\u002F\u002F TS — check trước khi action\nif (!hasPermission('deleteCustomer')) {\n    this.noti.warnMsg('Bạn không có quyền xóa');\n    return;\n}\n\n\u002F\u002F Super user bypass tất cả\nif (isSuperUser()) { \u002F* admin toàn quyền *\u002F }\n```\n\n**Format permission name:** camelCase phẳng theo `PERMISSION_SELECT` (`@\u002Fdefine`) — vd `viewCheckUp`, `createCheckUp`, `deleteCustomer`. KHÔNG phải dạng `module.resource.action`.\n\n**Tên hằng ≠ raw value** (vd `permissionViewLabo` = `'viewLaboOrder'`). Mọi chỗ ghi quyền dạng chuỗi (`route_perm_map.json`, migration SQL, mobile `kPerm*`, Dev Notes story) lấy raw value từ `permission.define.ts`, KHÔNG suy từ tên hằng. `TestRoutePermMapPermsInCatalog` chỉ bắt key không tồn tại, không bắt nhầm sang key có thật.\n\n`PERMISSION_MATRIX` (catalog cho màn phân quyền role) là const top-level, evaluate 1 LẦN lúc module import — KHÔNG thể gate theo signal runtime (`branchActiveId()`...) vì sẽ đóng băng ở giá trị lúc app khởi động (thường null\u002F0, trước khi auth xong). Cần ẩn\u002Fhiện theo runtime → đổi thành function gọi lại mỗi lần dùng, hoặc bỏ gate (luôn hiện đủ catalog).\n\n`PERMISSION_SELECT` = tập quyền ĐẦY ĐỦ dùng gating; `PERMISSION_MATRIX` là **subset** hiển thị ở màn gán role + sync xuống `rbac_auth_item` (BE catalog). Sync\u002Fseed catalog phải lấy nguồn từ **SELECT**, KHÔNG chỉ MATRIX — nếu không sẽ prune\u002Fthiếu quyền defined-nhưng-không-ở-matrix (vd `viewTool`, `configDevelop`).\n\n**CRITICAL — `*hasPerm` constant: verify qua `route_perm_map.json`, đừng copy sibling module.** Nhiều module `config-emr\u002F*` từng gate nút bằng `permissionCreateBroker`\u002F`UpdateBroker` (copy-paste từ 1 scaffold không liên quan) trong khi BE khai đúng (nay là `manageConfig` cho mọi route module Cấu hình) (`backend\u002Finternal\u002Fmodules\u002Fwebapp\u002Fauth\u002Frbac\u002Fseed\u002Froute_perm_map.json`). Trước khi wire `*hasPerm`, grep route đích trong file đó lấy đúng field `perm` — không suy ra từ module cùng cây thư mục.\n\n**Route `canActivate: [requirePerm(...)]` khi di dời UI giữa section (vd CRM → Config) phải dùng đúng permission family của resource, KHÔNG dùng permission chung của section chứa nó.** Di dời `psych-quiz` từ CRM sang Config từng gán nhầm guard `permissionViewConfigClinic` (quyền chung Config-Clinic) thay vì `permissionViewPsychQuiz` (quyền thật của resource). ⚠ Cập nhật 2026-09-02: riêng `psych-quiz` **dưới `\u002Fconfig`** nay CỐ Ý dùng `manageConfig` vì BE `\u002Fapi\u002Fconfig\u002Fpsych-quiz*` đã gộp về key đó — `*PsychQuiz` chỉ còn cho `\u002Fapi\u002Fcrm\u002Fpsych-session*`. Nguyên tắc không đổi: lấy permission từ `route_perm_map.json` của **endpoint màn đó gọi**, không suy từ section chứa nó — user có quyền Clinic nhưng không có quyền PsychQuiz vẫn vào được trang vì list bên trong không tự chặn theo permission riêng khi load (chỉ `*hasPerm` ẩn nút CRUD).\n\n**`CustomerDetail` — CHỦ ĐÍCH chỉ gate `viewCustomer` ở route cha, KHÔNG gate view theo tab (user chốt 2026-08-14).** `\u002Fcrm\u002Fcustomer\u002Fdetail\u002F:id` chỉ có `requirePerm(permissionViewCustomer)` trên path `customer` (`crm.routes.ts:27`); route `detail\u002F:id` (`customer.routes.ts`) không guard riêng, thừa hưởng cha. Vào được trang = xem hết 13 tab + data. **KHÔNG thêm `*hasPerm` view cho tab, KHÔNG thêm permission check vào GET API con** — quyết định nghiệp vụ, không phải nợ kỹ thuật; đừng \"dọn cho đồng nhất\". Quyền CUD trong tab (`createPayment`, `deletePayment`, `createTreatmentCourse`...) giữ nguyên: `viewCustomer` chỉ quy định quyền XEM. **2 ngoại lệ cố ý giữ**: tab 7 \"Hình ảnh\" gate `permissionViewImage` ở CẢ template LẪN `visibleTabValues()` (`customer-detail.ts:284` — sửa 1 chỗ thôi thì vào bằng `?tab=7` vẫn lọt, đây là pattern chung cho mọi tab gate bằng quyền); nút xem chi tiết phiên trắc nghiệm tab 13 gate `permissionViewPsychQuiz` (gate điều hướng sang trang khác, không phải gate list). Tab 3\u002F9\u002F12\u002F13 ẩn\u002Fhiện theo **chuyên khoa** (`isDental`\u002F`isCheckUpGeneralVisible`\u002F`isPsychiatryVisible`), KHÔNG phải permission — đừng nhầm. Bối cảnh đầy đủ + các trang detail khác vẫn ở trạng thái gap: repo cha `..\u002Fskill\u002Fskills\u002Fbackend-hard-rules\u002Freference\u002Fsecurity-patterns.md` (mục \"Field lock \u002F permission\").\n\n---\n\n## 5. Token storage — rules\n\n```typescript\n\u002F\u002F ✅ access_token: AES-GCM encrypted trong localStorage (SecureStorageService)\n\u002F\u002F ✅ refresh_token: HttpOnly Secure SameSite=Lax cookie — FE không đọc trực tiếp\n\n\u002F\u002F ❌ NEVER\ntokenService.getRefreshToken()  \u002F\u002F method đã xóa\nconsole.log(token)              \u002F\u002F NEVER log token\nurl + '?token=' + token        \u002F\u002F NEVER attach vào URL\n\n\u002F\u002F Kiểm tra refresh session còn hạn\ntokenService.isRefreshTokenExpired()  \u002F\u002F dùng cái này\n```\n\n**Device fingerprint** (`core\u002Fservices\u002Fauth\u002Ffingerprint.ts`): `getDeviceFingerprint()` — SHA-256 base64url các thuộc tính browser ổn định (KHÔNG gồm screen\u002FdevicePixelRatio → tránh sai khi cắm màn ngoài), cache in-memory. Gửi ở login (`login.ts`) + refresh (`token.service.doRefresh`) cho device binding BE. Quản lý thiết bị: dialog `UserDevices` trong menu profile (`GET\u002FPOST \u002Fauth\u002Fdevices`).\n\n---\n\n## 6. `authGuard` — protect routes\n\n```typescript\n\u002F\u002F app.routes.ts\n{\n    path: 'crm',\n    component: AppLayout,\n    canActivate: [authGuard],\n    loadChildren: () => import('@\u002Fmodules\u002Fcrm\u002Fcrm.routes'),\n}\n\n\u002F\u002F Print routes cũng có authGuard\n{\n    path: 'print',\n    component: PrintLayout,\n    canActivate: [authGuard],\n    loadChildren: () => import('@\u002Fprints\u002Fprints.routes'),\n}\n```\n\n`authGuard`: check token valid → nếu không → navigate `\u002Flogin?reason=...`  \n`loginGuard`: nếu đã login → redirect về `\u002F`\n\nRoute trung gian sau login (như `\u002Fsyncing`) PHẢI loại khỏi `redirect` query param trong `toLogin()` — giống `isLoginRoute` đã làm cho `\u002Flogin`. Thiếu → nếu token hết hạn đúng lúc user ở route trung gian, redirect-back tạo bounce loop qua chính route đó trước khi tới đích thật. Pattern: `isSyncingRoute()` trong `authGuard.ts`.\n\n---\n\n## 7. `AuthService` — methods chính\n\n```typescript\nconst authService = inject(AuthService);\n\nauthService.login(params)                \u002F\u002F → set authUser signal + save IndexedDB + auth_user_id localStorage\nauthService.logout()                     \u002F\u002F → clear tokens + authUser + IndexedDB\nauthService.restoreAuthUser()            \u002F\u002F → async, await trong APP_INITIALIZER — restore từ IndexedDB (fallback localStorage)\nauthService.fetchAndSyncMe()             \u002F\u002F → gọi \u002Fapi\u002Fauth\u002Fme, set signals, fire-and-forget safe\nauthService._cachedAuthVersion           \u002F\u002F → in-memory authVersion — dùng trong effect, KHÔNG đọc IDB async\n```\n\n---\n\n## 8. Auth state lifecycle\n\n```\nApp bootstrap (APP_INITIALIZER — chạy SONG SONG, KHÔNG sequential):\n    initializeAuth:      tokenService.initialize() → restoreAuthUser() → authInitialized.set(true)\n    initializeTranslations: load i18n\n    preloadIndexedDb:    ensureSyncedIfEmpty() → refreshCompanyActive() + refreshCallCenterActive()\n    router (internal):   withEnabledBlockingInitialNavigation() — navigation bắt đầu NGAY khi bootstrap\n                         → authGuard đợi authInitialized trước khi pass\n\nLogin flow\n    → POST \u002Fauth\u002Flogin → tokens + user + permissions\n    → userAuthSession.save(IDB)\n    → storageService.saveStorage('auth_user_id', userId)\n    → navigate('\u002F')\n\nLogout flow\n    → clearAllAuthData() — clear IDB + localStorage\n    → window.location.href = '\u002Flogin'\n\nTab sync (StorageEvent 'auth_user_id')\n    → other tab login (oldValue null → newValue) → reload\n    → other tab logout (oldValue → newValue null) → reload\n\nToken revoke → 401 → silent refresh → fetchAndSyncMe() → authUser signal update\nX-User-Auth-Version lệch → fetchAndSyncMe() → authUser signal update\n```\n\n**CRITICAL — APP_INITIALIZER chạy song song:** `preloadIndexedDb` bắt đầu cùng lúc với `initializeAuth`. `restoreAuthUser()` phải `await` — → Xem `frontend\u002Fskill\u002Fskills\u002Fhandling-fe-auth-and-i18n\u002Freference\u002Ffe-patterns-gotchas-auth.md`. `preloadIndexedDb` dùng `hasValidRefreshSession()` (đọc localStorage) thay vì `hasValidToken` vì `initialize()` chưa chạy xong khi check.\n\n**CRITICAL — withEnabledBlockingInitialNavigation race:** Router navigation chạy song song với APP_INITIALIZER. `requirePerm` guard có thể chạy trước khi `userPermissions` được populate. `authGuard` đợi `authInitialized` signal để chặn race này. Xem `skills\u002Fhandling-auth-and-workspace\u002FSKILL.md §authInitialized`.\n\n---\n\n## 9. Signals trong component — pattern chuẩn\n\n```typescript\n\u002F\u002F ✅ Đọc signal trong template\n{{ branchActiveId() }}\n@if (isLoggedIn()) { ... }\n\n\u002F\u002F ✅ Đọc signal trong TS (không cần async)\nconst bid = branchActiveId();\nif (!bid) return;\n\n\u002F\u002F ✅ Reactive với effect\neffect(() => {\n    const bid = branchActiveId();\n    if (bid) this.loadDataForBranch(bid);\n});\n\n\u002F\u002F ✅ Computed từ auth signal\nreadonly canDelete = computed(() =>\n    hasPermission('crm.customer.delete') || isSuperUser()\n);\n```\n\n---\n\n## 10. Menu component reactive với permission changes\n\nTất cả `*menu.ts` extend `BaseApp`. Pattern chuẩn để sidebar tự rebuild khi admin đổi role:\n\n```typescript\nimport { effect } from '@angular\u002Fcore';\nimport { userPermissions } from '@\u002Fcore\u002Fservices\u002Fauth\u002Fauth.state';\n\nexport class XxxMenu extends BaseApp {\n  model: any[] = [];\n\n  constructor() {\n    super();\n    effect(() => this.buildMenu()); \u002F\u002F re-run mỗi khi userPermissions signal thay đổi\n  }\n\n  \u002F\u002F KHÔNG dùng ngOnInit() + implements OnInit\n\n  private buildMenu(): void {\n    const per = Array.from(userPermissions()); \u002F\u002F ✅ SIGNAL\n    this.model = filterMenuByPermission([...], per);\n  }\n}\n```\n\nNếu menu cần đợi thêm signal khác (vd translations):\n\n```typescript\nconstructor() {\n  super();\n  effect(() => {\n    if (!this.translationsReady()) return; \u002F\u002F guard signal trước\n    this.buildMenu();\n  });\n}\n\u002F\u002F ngOnInit chỉ set translationsReady.set(true), không gọi buildMenu()\n```\n\n\n## Define files\n\n```typescript\n\u002F\u002F ❌ NEVER (legacy)\n{ value: 1, label: 'Chưa xử lý' }\n\n\u002F\u002F ✅ Giữ `label` để backwards-compat, ADD `labelKey` cho code mới\n{ value: 1, label: 'Chưa xử lý', labelKey: 'define.customer_status.pending' }\n```\n\n## Gotcha: `_MAP` reduce ẩn `labelKey`\n\n`*_MAP = *_OPTIONS.reduce(..., {} as Record\u003Cnumber, {value,label}>)` — nếu type annotation thiếu `labelKey?: string`,\nTS chặn truy cập dù object runtime (từ OPTIONS) có sẵn field này → dễ bị hardcode label tiếng Việt thay vì fix type.\nGặp ở `appointment\u002Fpartner\u002Fpayment\u002Freminder\u002Fcustomer-care.define.ts`. Fix: thêm `labelKey?: string` vào type annotation của reduce.\n\n## PrimeNG p-select — dùng `translateOptions()`\n\n```typescript\nimport { translateOptions } from '@\u002Fshare\u002Futils\u002Ftranslate-options.util';\nimport { CUSTOMER_STATUS_OPTIONS } from '@\u002Fdefine';\n\nprotected readonly customerStatusOptions = translateOptions(CUSTOMER_STATUS_OPTIONS);\n```\n\n```html\n\u003Cp-select [options]=\"customerStatusOptions()\" optionLabel=\"label\" optionValue=\"value\"\u002F>\n```\n\n`translateOptions()` trả `Signal\u003CT[]>`. Lang change → signal re-emits → re-render. Fallback: nếu chưa có `labelKey`, giữ nguyên `label`.\n\n## Direct template rendering\n\n```html\n\u003C!-- ✅ CHUẨN — smart fallback -->\n\u003Cspan>{{ (item.labelKey || item.label) | translate }}\u003C\u002Fspan>\n\u003Cspan>{{ (model.nameKey || model.name) | translate }}\u003C\u002Fspan>\n\n\u003C!-- Constant key -->\n\u003Cspan>{{ 'define.permission.action.list' | translate }}\u003C\u002Fspan>\n\n\u003C!-- ❌ DEPRECATED -->\n\u003Cspan>{{ item.labelKey ? (item.labelKey | translate) : item.label }}\u003C\u002Fspan>\n```\n\nTS code: `this.translate.instant(item.labelKey || item.label)`.\n\n`translate.instant(key)` thiếu bản dịch ⇒ trả NGUYÊN chuỗi key (không `''`\u002F`undefined`) ⇒ `instant(k) || fallback`\nKHÔNG BAO GIỜ fallback. Cần fallback: `const t = instant(k); return t === k ? fallback : t`.\n\n`TranslatePipe` có trong `ListShareImports` — không cần wire thêm.\n\n- KHÔNG ghép i18n key từ giá trị dữ liệu runtime (`'prefix.' + code`) — dùng key do BE khai sẵn trong payload, fallback về chính giá trị đó khi bảng tra chưa tải xong. Ghép chuỗi vỡ **câm** ngay khi quy ước 2 bên lệch nhau một ký tự (`-` vs `_`).\n\n## displayCols \u002F data structures\n\n```typescript\n\u002F\u002F ❌ DEPRECATED\n{ label: 'Họ tên', value: 'fullname' }\n\n\u002F\u002F ❌ AVOID\n{ label: 'CUSTOMER_CODE', value: 'code' }\n\n\u002F\u002F ✅ CHUẨN\n{ label: 'Họ tên', labelKey: 'common.label.fullname', value: 'fullname' }\n```\n\n## Layout menu \u002F dialog header\n\n```typescript\n\u002F\u002F ❌ NEVER\n{ label: 'Khách hàng', icon: 'pi pi-users', routerLink: ['\u002Fcrm\u002Fcustomer'] }\nthis.dialog.open(Form, { header: 'Cập nhật khách hàng' });\n\n\u002F\u002F ✅ ALWAYS\n{ label: 'Khách hàng', labelKey: 'layout.menu.customer', icon: 'pi pi-users', routerLink: ['\u002Fcrm\u002Fcustomer'] }\nthis.dialog.open(Form, { header: this.translate.instant('crm.customer.update_dialog_title') });\n```\n\n## ⛔ Tạo key dịch mới — BẮT BUỘC check value trước (chống trùng)\n\n**Quy trình bắt buộc TRƯỚC khi thêm bất kỳ key dịch nào:**\n\n1. **Tra value đã tồn tại chưa:**\n   ```bash\n   npm run i18n:find -- \"Thanh toán\"          # khớp chính xác\n   npm run i18n:find -- --contains \"thanh\"     # khớp chứa\n   ```\n2. **Nếu CÓ key trùng value (exit 3):**\n   - Cùng nghĩa → **DÙNG LẠI key đó**, KHÔNG tạo mới.\n   - Tool nhóm theo nghĩa EN: nếu có nhiều nghĩa (vd Payment vs Billing) → chọn key ĐÚNG ngữ cảnh.\n3. **Nếu CHƯA có (exit 0)** → tạo key mới theo taxonomy:\n   - Dùng chung ≥2 module → `common.\u003Clabel|action|status|message|tooltip|placeholder|validation>.\u003Cslug>` (vd `common.action.save`, `common.label.customer`, `common.status.paid`)\n   - Riêng 1 module → `{module}.{feature}.\u003Cslug>` (vd `crm.customer.fullname`)\n   - Menu items → `layout.menu.*`\n   - Add ĐỦ 4 locale cùng path: `vi-VN` + `en-US` + `ja-JP` + `fil-PH`.\n\n**1 nghĩa = 1 key**: VI trùng nhưng khác nghĩa EN (vd \"Thanh toán\" = Payment vs Billing) → key RIÊNG theo nghĩa, KHÔNG gộp.\n\n**KHÔNG được:** tạo key mới khi value đã tồn tại · đặt key trùng nghĩa ở module khác nhau · hardcode string trong template\u002FTS.\n\n### Tooling\n- `npm run i18n:find -- \"\u003Cvalue>\"` → tra ngược theo value TRƯỚC khi tạo key (exit 3 = đã có, reuse)\n- `node scripts\u002Fi18n-dedup.mjs` → `i18n-dedup\u002Freport.json` (group trùng + usage)\n- `node scripts\u002Fi18n-build-mapping.mjs` → `i18n-dedup\u002Fmapping.json` (oldKey→canonical)\n- `node scripts\u002Fi18n-apply.mjs \u003Csafe|risky|all> [--step=add|rewrite|prune|all]` — áp dụng\n- Protected dynamic prefix (codemod KHÔNG được đụng): `define.emr.record_type.*`\n\n## i18n key audit gate\n\nPre-commit hook (`.husky\u002Fpre-commit`) chạy 2 gate:\n1. `npm run i18n:check -- --fail-on-missing` — **BLOCK** nếu thiếu key.\n2. `npm run i18n:dup` — **CẢNH BÁO** khi commit thêm key MỚI trùng value cùng nghĩa (so staged vs HEAD; đồng âm khác nghĩa EN được bỏ qua). Mặc định không chặn; `I18N_DUP_STRICT=1` để chặn cứng.\n\n```bash\nnpm run i18n:check          # human-readable summary\nnpm run i18n:check:verbose  # full lists\nnpm run i18n:check:json     # JSON cho CI\n```\n\nKhi PR fail i18n gate:\n1. Xem MISSING keys (file path + key name)\n2. Trước khi add key mới hàng loạt: nếu số lượng MISSING gần bằng số ORPHAN cùng module → nghi ngờ đây là rename sót (prefix đổi ở JSON nhưng code chưa cập nhật, hoặc ngược lại). So sánh suffix-set (bỏ prefix) giữa 2 danh sách — khớp 1:1 → sửa code dùng đúng prefix JSON hiện có, KHÔNG tạo key trùng mới.\n3. Add đủ 4 locale cùng nested path (gate chỉ check `vi-VN`\u002F`en-US`)\n4. Re-run `npm run i18n:check` → confirm 0 missing\n\nKey trả về GIÁN TIẾP qua hàm thuần (vd `resolveXxxKey()` return string key, không phải literal `'key' | translate` trong template) → `i18n:check` báo ORPHAN SAI (false-positive) vì tool chỉ static-scan literal — đừng xoá key chỉ vì nằm trong danh sách ORPHAN, grep thử usage gián tiếp trước.\n\n`git commit --no-verify` chỉ dùng emergency — fix keys luôn là đúng.\n\n## Nguồn file\n\n- **Key i18n mới HOẶC sửa value key có sẵn: ghi CẢ 2 nơi × 4 locale** — `frontend\u002Fsrc\u002Fassets\u002Fi18n\u002F*.json` (nguồn `ng build`, repo `frontend\u002F` riêng, gitignored khỏi repo chính) VÀ `public\u002Fassets\u002Fi18n\u002F*.json` (artifact đang serve, được git track ở repo chính). Chỉ sửa `src` → runtime thiếu key tới lần build kế; chỉ sửa `public` → key MẤT khi `ng build` regenerate. hr-completion + hr-2026-compliance đều dính lệch 2 dir (mỗi key chỉ nằm 1 nơi) — verify bằng grep key ở CẢ 2 dir. ⚠ Hai gốc là `frontend\u002Fsrc\u002Fassets\u002Fi18n\u002F` và `public\u002Fassets\u002Fi18n\u002F` ở **repo GỐC** — `frontend\u002Fpublic\u002Fassets\u002Fi18n\u002F` **KHÔNG tồn tại**; grep nhầm ở đó trả rỗng rồi kết luận \"chỉ có 1 nơi\" (đã xảy ra 2026-08-31, dẫn tới một đính chính SAI ghi vào sổ nợ). Đối chứng: grep từ gốc repo với CẢ 2 đường dẫn + một key đã biết chắc có.\n- **Sửa bằng script: KHÔNG `json.load()` rồi `json.dump()` lại** — dump không giữ thứ tự key gốc, diff nhảy lên hàng nghìn dòng (re-sort toàn file thay vì chỉ thêm key mới). Chèn text-based: regex tìm dòng key láng giềng đã biết, insert ngay sau, giữ nguyên phần còn lại của file.\n\n## Loader\n- Prod: `StaticTranslateLoader` (vi-VN inline main.js, en-US lazy chunk)\n- Dev: `CachedTranslateLoader` — stale-while-revalidate qua localStorage (`i18n_\u003Clang>`), sửa JSON KHÔNG hiện ngay lập tức. Cần reload 2 lần (lần 1 kích hoạt fetch nền update cache, lần 2 mới đọc cache mới) hoặc `localStorage.removeItem('i18n_\u003Clang>')`. `LS_VERSION` (auto-invalidate cache) chỉ đổi khi `npm run build` (hook `prebuild`), KHÔNG đổi khi `ng serve`\u002Fhot-reload.\n- `fallbackLang: 'vi-VN'` → missing en key fallback VN thay vì raw key\n","# Handling FE auth and i18n\n\n> Timezone chi tiết (DatePicker → unix timestamp, dateHmsToUnix, toTz\u002FtoUnix): `reference\u002Ffe-timezone.md`\n> Auth gotchas (restoreAuthUser async, IDB missing case, permission gate): `reference\u002Ffe-patterns-gotchas-auth.md`\n\n\n\nTài liệu cho AI agents hiểu auth signals, tenant scope FE, và cách dùng đúng.\nĐọc file này trước khi làm việc với branch selection, permissions, hoặc print.\n\n> **(đã bỏ, D15\u002FCRM standalone)**: hệ thống là 1 thương hiệu\u002FDB — KHÔNG còn `companyActiveId`,\n> `companyListId`, hay khái niệm \"chọn công ty\". Thông tin thương hiệu (tên, logo, timezone, tiền\n> tệ, 2FA, IP allowlist) đọc qua signal `authBusinessProfile` (`src\u002Fapp\u002Fcore\u002Fservices\u002Fauth\u002Fauth.state.ts`),\n> nguồn BE là `pkg\u002Fbrand`\u002Fbảng `business_profile` (D22, story-62\u002F63). Trục scope duy nhất còn lại là\n> `branchActiveId`\u002F`branchListId`.\n\n---\n\n## 1. Auth signals — import từ `@\u002Fcore\u002Fservices\u002Fauth`\n\n**File:** `src\u002Fapp\u002Fcore\u002Fservices\u002Fauth\u002Fauth.selectors.ts`\n\n```typescript\nimport {\n    branchActiveId,    \u002F\u002F computed: userProfile()?.branchActive_id\n    branchListId,      \u002F\u002F computed: authUser()?.branchId ?? []    — mảng tất cả branch\n    userId,            \u002F\u002F computed: authUser()?.id\n    userFullname,      \u002F\u002F computed: userProfile()?.fullname\n    isLoggedIn,        \u002F\u002F computed: !!authUser()\n    isSuperUser,       \u002F\u002F computed: role in SUPER_ROLES whitelist\n    isDevelop,         \u002F\u002F computed: role === 'develop'\n    isAdmin,           \u002F\u002F computed: role === 'admin'\n    hasPermission,     \u002F\u002F fn(name): boolean — check permission string\n    hasAnyPermission,  \u002F\u002F fn(...names): boolean\n    hasAllPermissions, \u002F\u002F fn(...names): boolean\n} from '@\u002Fcore\u002Fservices\u002Fauth';\n```\n\n**State signals (low-level, ít dùng trực tiếp):**\n```typescript\nimport { authUser, authBusinessProfile, userPermissions } from '@\u002Fcore\u002Fservices\u002Fauth';\n```\n\n---\n\n## 2. `authBusinessProfile` — hồ sơ thương hiệu (thay `companyActiveId`\u002F`companyListId` cũ)\n\n| Signal | Trả về | Ý nghĩa |\n|---|---|---|\n| `authBusinessProfile()` | `BusinessProfileModel \\| null` | Hồ sơ thương hiệu duy nhất của DB (tên, logo, timezone, tiền tệ...) |\n| `branchActiveId()` | `number \\| undefined` | Branch user đang chọn (active context) — có thể chưa chọn |\n| `branchListId()` | `number[]` | Tất cả branch user có quyền — mảng rỗng nếu chưa login |\n\n### Dùng đúng\n\n```typescript\n\u002F\u002F ✅ Scope SELECT theo active context\ntenant.ScopedDBNullBranch(c, h.DB, \"table\")  \u002F\u002F BE lo (đọc từ context, AuthResponseHeaders set từ user_profile)\n\n\u002F\u002F ✅ FE: pre-fill form mặc định\nthis.initialValue = {\n    branch_id: branchActiveId(),\n};\n\n\u002F\u002F ❌ NEVER — dùng để auto-fill khi INSERT (xem B.1.1 CLAUDE.md)\n\u002F\u002F branch_id của record phải từ FE picker, không tự derive từ active context\n```\n\n---\n\n## 3. Tenant scope trong component FE\n\n### Pre-fill form — OK\n\nFE pre-fill `branch_id` từ active context để tiện UX. User vẫn có thể đổi qua picker.\n\n```typescript\n\u002F\u002F ✅ OK — pre-fill mặc định, user đổi được\nthis.initialValue = {\n    ...this.initialValue,\n    branch_id: branchActiveId(),\n};\n```\n\n### (đã bỏ, D15\u002FCRM standalone) Company picker trong form — toàn bộ pattern đã xoá\n\nTrước D15, mục này còn 3 pattern lớn cho `company_id` trong form: \"Root entity không picker, seed theo\nthương hiệu active\" (`BaseSignalForm.seedCompanyId`, `CompanyFormControl`, gate BE `company_active_required`),\n\"Record con derive company từ record cha\" (`FormAppointment` seed `company_id` từ `customer.company_id`),\nvà \"IndexedDB cache key theo `companyActiveId()-branchActiveId()`\". Verify 2026-09-28: `seedCompanyId`,\n`CompanyFormControl`, và field `company_id` trong các form trên **không còn tồn tại** trong\n`frontend\u002Fsrc\u002Fapp\u002F` — company đã xoá hoàn toàn khỏi FE (`tenantKey` kiểu `companyActiveId()-branchActiveId()`\ncũng không còn xuất hiện trong code — verify trước khi viết lại pattern IndexedDB key mới, đừng suy\ntừ đoạn lịch sử này). Giữ đoạn trên làm lịch sử\u002Ftham khảo nếu cần đọc code cũ, KHÔNG áp dụng cho code mới.\n\n---\n\n## 4. RBAC \u002F Permissions\n\n**KHÔNG dùng `ngx-permissions`\u002F`NgxPermissionsService`\u002F`NgxPermissionsModule`** — đã gỡ khỏi package.json (2026-07-05).\nCơ chế permission DUY NHẤT là signal-based (`userPermissions()` + `isSuperUser()`), lộ ra qua `hasPerm` directive \u002F `hasPermission()` fn.\n`BaseApp.permissionsService` vẫn còn (nhiều component cũ gọi `this.permissionsService.getPermission(x)`) nhưng giờ là `PermissionsService` (`share\u002Fservices\u002Fpermissions.service.ts`) — shim mỏng gọi `hasPermission()`, KHÔNG phải ngx-permissions.\n\n**Permission tính năng (`viewX`\u002F`createX`...) CHỈ enforce ở FE** — BE (`pkg\u002Fdefine\u002Frbac.go`) chỉ chặn super-role + tenant scope, KHÔNG có middleware kiểm quyền per-endpoint. ⇒ guard FE bypass được qua gọi API trực tiếp; kiểm soát dữ liệu thật vẫn ở BE (`ScopedDBNullBranch`).\n\nQuyền MỚI tạo: **gán cho role TRƯỚC, thêm `*hasPerm`\u002F`requirePerm` SAU**. Gate FE là chặn thật, mà quyền mới chỉ super role tự có ⇒ thêm gate trước khi gán = khoá tính năng với 100% user thường.\n\n```typescript\n\u002F\u002F Template — directive tên `hasPerm` (KHÔNG phải `hasPermission`)\n\u003Cbutton *hasPerm=\"permission.permissionCreateCustomer\">Tạo KH\u003C\u002Fbutton>\n\n\u002F\u002F TS — check trước khi action\nif (!hasPermission('deleteCustomer')) {\n    this.noti.warnMsg('Bạn không có quyền xóa');\n    return;\n}\n\n\u002F\u002F Super user bypass tất cả\nif (isSuperUser()) { \u002F* admin toàn quyền *\u002F }\n```\n\n**Format permission name:** camelCase phẳng theo `PERMISSION_SELECT` (`@\u002Fdefine`) — vd `viewCheckUp`, `createCheckUp`, `deleteCustomer`. KHÔNG phải dạng `module.resource.action`.\n\n**Tên hằng ≠ raw value** (vd `permissionViewLabo` = `'viewLaboOrder'`). Mọi chỗ ghi quyền dạng chuỗi (`route_perm_map.json`, migration SQL, mobile `kPerm*`, Dev Notes story) lấy raw value từ `permission.define.ts`, KHÔNG suy từ tên hằng. `TestRoutePermMapPermsInCatalog` chỉ bắt key không tồn tại, không bắt nhầm sang key có thật.\n\n`PERMISSION_MATRIX` (catalog cho màn phân quyền role) là const top-level, evaluate 1 LẦN lúc module import — KHÔNG thể gate theo signal runtime (`branchActiveId()`...) vì sẽ đóng băng ở giá trị lúc app khởi động (thường null\u002F0, trước khi auth xong). Cần ẩn\u002Fhiện theo runtime → đổi thành function gọi lại mỗi lần dùng, hoặc bỏ gate (luôn hiện đủ catalog).\n\n`PERMISSION_SELECT` = tập quyền ĐẦY ĐỦ dùng gating; `PERMISSION_MATRIX` là **subset** hiển thị ở màn gán role + sync xuống `rbac_auth_item` (BE catalog). Sync\u002Fseed catalog phải lấy nguồn từ **SELECT**, KHÔNG chỉ MATRIX — nếu không sẽ prune\u002Fthiếu quyền defined-nhưng-không-ở-matrix (vd `viewTool`, `configDevelop`).\n\n**CRITICAL — `*hasPerm` constant: verify qua `route_perm_map.json`, đừng copy sibling module.** Nhiều module `config-emr\u002F*` từng gate nút bằng `permissionCreateBroker`\u002F`UpdateBroker` (copy-paste từ 1 scaffold không liên quan) trong khi BE khai đúng (nay là `manageConfig` cho mọi route module Cấu hình) (`backend\u002Finternal\u002Fmodules\u002Fwebapp\u002Fauth\u002Frbac\u002Fseed\u002Froute_perm_map.json`). Trước khi wire `*hasPerm`, grep route đích trong file đó lấy đúng field `perm` — không suy ra từ module cùng cây thư mục.\n\n**Route `canActivate: [requirePerm(...)]` khi di dời UI giữa section (vd CRM → Config) phải dùng đúng permission family của resource, KHÔNG dùng permission chung của section chứa nó.** Di dời `psych-quiz` từ CRM sang Config từng gán nhầm guard `permissionViewConfigClinic` (quyền chung Config-Clinic) thay vì `permissionViewPsychQuiz` (quyền thật của resource). ⚠ Cập nhật 2026-09-02: riêng `psych-quiz` **dưới `\u002Fconfig`** nay CỐ Ý dùng `manageConfig` vì BE `\u002Fapi\u002Fconfig\u002Fpsych-quiz*` đã gộp về key đó — `*PsychQuiz` chỉ còn cho `\u002Fapi\u002Fcrm\u002Fpsych-session*`. Nguyên tắc không đổi: lấy permission từ `route_perm_map.json` của **endpoint màn đó gọi**, không suy từ section chứa nó — user có quyền Clinic nhưng không có quyền PsychQuiz vẫn vào được trang vì list bên trong không tự chặn theo permission riêng khi load (chỉ `*hasPerm` ẩn nút CRUD).\n\n**`CustomerDetail` — CHỦ ĐÍCH chỉ gate `viewCustomer` ở route cha, KHÔNG gate view theo tab (user chốt 2026-08-14).** `\u002Fcrm\u002Fcustomer\u002Fdetail\u002F:id` chỉ có `requirePerm(permissionViewCustomer)` trên path `customer` (`crm.routes.ts:27`); route `detail\u002F:id` (`customer.routes.ts`) không guard riêng, thừa hưởng cha. Vào được trang = xem hết 13 tab + data. **KHÔNG thêm `*hasPerm` view cho tab, KHÔNG thêm permission check vào GET API con** — quyết định nghiệp vụ, không phải nợ kỹ thuật; đừng \"dọn cho đồng nhất\". Quyền CUD trong tab (`createPayment`, `deletePayment`, `createTreatmentCourse`...) giữ nguyên: `viewCustomer` chỉ quy định quyền XEM. **2 ngoại lệ cố ý giữ**: tab 7 \"Hình ảnh\" gate `permissionViewImage` ở CẢ template LẪN `visibleTabValues()` (`customer-detail.ts:284` — sửa 1 chỗ thôi thì vào bằng `?tab=7` vẫn lọt, đây là pattern chung cho mọi tab gate bằng quyền); nút xem chi tiết phiên trắc nghiệm tab 13 gate `permissionViewPsychQuiz` (gate điều hướng sang trang khác, không phải gate list). Tab 3\u002F9\u002F12\u002F13 ẩn\u002Fhiện theo **chuyên khoa** (`isDental`\u002F`isCheckUpGeneralVisible`\u002F`isPsychiatryVisible`), KHÔNG phải permission — đừng nhầm. Bối cảnh đầy đủ + các trang detail khác vẫn ở trạng thái gap: repo cha `..\u002Fskill\u002Fskills\u002Fbackend-hard-rules\u002Freference\u002Fsecurity-patterns.md` (mục \"Field lock \u002F permission\").\n\n---\n\n## 5. Token storage — rules\n\n```typescript\n\u002F\u002F ✅ access_token: AES-GCM encrypted trong localStorage (SecureStorageService)\n\u002F\u002F ✅ refresh_token: HttpOnly Secure SameSite=Lax cookie — FE không đọc trực tiếp\n\n\u002F\u002F ❌ NEVER\ntokenService.getRefreshToken()  \u002F\u002F method đã xóa\nconsole.log(token)              \u002F\u002F NEVER log token\nurl + '?token=' + token        \u002F\u002F NEVER attach vào URL\n\n\u002F\u002F Kiểm tra refresh session còn hạn\ntokenService.isRefreshTokenExpired()  \u002F\u002F dùng cái này\n```\n\n**Device fingerprint** (`core\u002Fservices\u002Fauth\u002Ffingerprint.ts`): `getDeviceFingerprint()` — SHA-256 base64url các thuộc tính browser ổn định (KHÔNG gồm screen\u002FdevicePixelRatio → tránh sai khi cắm màn ngoài), cache in-memory. Gửi ở login (`login.ts`) + refresh (`token.service.doRefresh`) cho device binding BE. Quản lý thiết bị: dialog `UserDevices` trong menu profile (`GET\u002FPOST \u002Fauth\u002Fdevices`).\n\n---\n\n## 6. `authGuard` — protect routes\n\n```typescript\n\u002F\u002F app.routes.ts\n{\n    path: 'crm',\n    component: AppLayout,\n    canActivate: [authGuard],\n    loadChildren: () => import('@\u002Fmodules\u002Fcrm\u002Fcrm.routes'),\n}\n\n\u002F\u002F Print routes cũng có authGuard\n{\n    path: 'print',\n    component: PrintLayout,\n    canActivate: [authGuard],\n    loadChildren: () => import('@\u002Fprints\u002Fprints.routes'),\n}\n```\n\n`authGuard`: check token valid → nếu không → navigate `\u002Flogin?reason=...`  \n`loginGuard`: nếu đã login → redirect về `\u002F`\n\nRoute trung gian sau login (như `\u002Fsyncing`) PHẢI loại khỏi `redirect` query param trong `toLogin()` — giống `isLoginRoute` đã làm cho `\u002Flogin`. Thiếu → nếu token hết hạn đúng lúc user ở route trung gian, redirect-back tạo bounce loop qua chính route đó trước khi tới đích thật. Pattern: `isSyncingRoute()` trong `authGuard.ts`.\n\n---\n\n## 7. `AuthService` — methods chính\n\n```typescript\nconst authService = inject(AuthService);\n\nauthService.login(params)                \u002F\u002F → set authUser signal + save IndexedDB + auth_user_id localStorage\nauthService.logout()                     \u002F\u002F → clear tokens + authUser + IndexedDB\nauthService.restoreAuthUser()            \u002F\u002F → async, await trong APP_INITIALIZER — restore từ IndexedDB (fallback localStorage)\nauthService.fetchAndSyncMe()             \u002F\u002F → gọi \u002Fapi\u002Fauth\u002Fme, set signals, fire-and-forget safe\nauthService._cachedAuthVersion           \u002F\u002F → in-memory authVersion — dùng trong effect, KHÔNG đọc IDB async\n```\n\n---\n\n## 8. Auth state lifecycle\n\n```\nApp bootstrap (APP_INITIALIZER — chạy SONG SONG, KHÔNG sequential):\n    initializeAuth:      tokenService.initialize() → restoreAuthUser() → authInitialized.set(true)\n    initializeTranslations: load i18n\n    preloadIndexedDb:    ensureSyncedIfEmpty() → refreshCompanyActive() + refreshCallCenterActive()\n    router (internal):   withEnabledBlockingInitialNavigation() — navigation bắt đầu NGAY khi bootstrap\n                         → authGuard đợi authInitialized trước khi pass\n\nLogin flow\n    → POST \u002Fauth\u002Flogin → tokens + user + permissions\n    → userAuthSession.save(IDB)\n    → storageService.saveStorage('auth_user_id', userId)\n    → navigate('\u002F')\n\nLogout flow\n    → clearAllAuthData() — clear IDB + localStorage\n    → window.location.href = '\u002Flogin'\n\nTab sync (StorageEvent 'auth_user_id')\n    → other tab login (oldValue null → newValue) → reload\n    → other tab logout (oldValue → newValue null) → reload\n\nToken revoke → 401 → silent refresh → fetchAndSyncMe() → authUser signal update\nX-User-Auth-Version lệch → fetchAndSyncMe() → authUser signal update\n```\n\n**CRITICAL — APP_INITIALIZER chạy song song:** `preloadIndexedDb` bắt đầu cùng lúc với `initializeAuth`. `restoreAuthUser()` phải `await` — → Xem `frontend\u002Fskill\u002Fskills\u002Fhandling-fe-auth-and-i18n\u002Freference\u002Ffe-patterns-gotchas-auth.md`. `preloadIndexedDb` dùng `hasValidRefreshSession()` (đọc localStorage) thay vì `hasValidToken` vì `initialize()` chưa chạy xong khi check.\n\n**CRITICAL — withEnabledBlockingInitialNavigation race:** Router navigation chạy song song với APP_INITIALIZER. `requirePerm` guard có thể chạy trước khi `userPermissions` được populate. `authGuard` đợi `authInitialized` signal để chặn race này. Xem `skills\u002Fhandling-auth-and-workspace\u002FSKILL.md §authInitialized`.\n\n---\n\n## 9. Signals trong component — pattern chuẩn\n\n```typescript\n\u002F\u002F ✅ Đọc signal trong template\n{{ branchActiveId() }}\n@if (isLoggedIn()) { ... }\n\n\u002F\u002F ✅ Đọc signal trong TS (không cần async)\nconst bid = branchActiveId();\nif (!bid) return;\n\n\u002F\u002F ✅ Reactive với effect\neffect(() => {\n    const bid = branchActiveId();\n    if (bid) this.loadDataForBranch(bid);\n});\n\n\u002F\u002F ✅ Computed từ auth signal\nreadonly canDelete = computed(() =>\n    hasPermission('crm.customer.delete') || isSuperUser()\n);\n```\n\n---\n\n## 10. Menu component reactive với permission changes\n\nTất cả `*menu.ts` extend `BaseApp`. Pattern chuẩn để sidebar tự rebuild khi admin đổi role:\n\n```typescript\nimport { effect } from '@angular\u002Fcore';\nimport { userPermissions } from '@\u002Fcore\u002Fservices\u002Fauth\u002Fauth.state';\n\nexport class XxxMenu extends BaseApp {\n  model: any[] = [];\n\n  constructor() {\n    super();\n    effect(() => this.buildMenu()); \u002F\u002F re-run mỗi khi userPermissions signal thay đổi\n  }\n\n  \u002F\u002F KHÔNG dùng ngOnInit() + implements OnInit\n\n  private buildMenu(): void {\n    const per = Array.from(userPermissions()); \u002F\u002F ✅ SIGNAL\n    this.model = filterMenuByPermission([...], per);\n  }\n}\n```\n\nNếu menu cần đợi thêm signal khác (vd translations):\n\n```typescript\nconstructor() {\n  super();\n  effect(() => {\n    if (!this.translationsReady()) return; \u002F\u002F guard signal trước\n    this.buildMenu();\n  });\n}\n\u002F\u002F ngOnInit chỉ set translationsReady.set(true), không gọi buildMenu()\n```\n\n\n## Define files\n\n```typescript\n\u002F\u002F ❌ NEVER (legacy)\n{ value: 1, label: 'Chưa xử lý' }\n\n\u002F\u002F ✅ Giữ `label` để backwards-compat, ADD `labelKey` cho code mới\n{ value: 1, label: 'Chưa xử lý', labelKey: 'define.customer_status.pending' }\n```\n\n## Gotcha: `_MAP` reduce ẩn `labelKey`\n\n`*_MAP = *_OPTIONS.reduce(..., {} as Record\u003Cnumber, {value,label}>)` — nếu type annotation thiếu `labelKey?: string`,\nTS chặn truy cập dù object runtime (từ OPTIONS) có sẵn field này → dễ bị hardcode label tiếng Việt thay vì fix type.\nGặp ở `appointment\u002Fpartner\u002Fpayment\u002Freminder\u002Fcustomer-care.define.ts`. Fix: thêm `labelKey?: string` vào type annotation của reduce.\n\n## PrimeNG p-select — dùng `translateOptions()`\n\n```typescript\nimport { translateOptions } from '@\u002Fshare\u002Futils\u002Ftranslate-options.util';\nimport { CUSTOMER_STATUS_OPTIONS } from '@\u002Fdefine';\n\nprotected readonly customerStatusOptions = translateOptions(CUSTOMER_STATUS_OPTIONS);\n```\n\n```html\n\u003Cp-select [options]=\"customerStatusOptions()\" optionLabel=\"label\" optionValue=\"value\"\u002F>\n```\n\n`translateOptions()` trả `Signal\u003CT[]>`. Lang change → signal re-emits → re-render. Fallback: nếu chưa có `labelKey`, giữ nguyên `label`.\n\n## Direct template rendering\n\n```html\n\u003C!-- ✅ CHUẨN — smart fallback -->\n\u003Cspan>{{ (item.labelKey || item.label) | translate }}\u003C\u002Fspan>\n\u003Cspan>{{ (model.nameKey || model.name) | translate }}\u003C\u002Fspan>\n\n\u003C!-- Constant key -->\n\u003Cspan>{{ 'define.permission.action.list' | translate }}\u003C\u002Fspan>\n\n\u003C!-- ❌ DEPRECATED -->\n\u003Cspan>{{ item.labelKey ? (item.labelKey | translate) : item.label }}\u003C\u002Fspan>\n```\n\nTS code: `this.translate.instant(item.labelKey || item.label)`.\n\n`translate.instant(key)` thiếu bản dịch ⇒ trả NGUYÊN chuỗi key (không `''`\u002F`undefined`) ⇒ `instant(k) || fallback`\nKHÔNG BAO GIỜ fallback. Cần fallback: `const t = instant(k); return t === k ? fallback : t`.\n\n`TranslatePipe` có trong `ListShareImports` — không cần wire thêm.\n\n- KHÔNG ghép i18n key từ giá trị dữ liệu runtime (`'prefix.' + code`) — dùng key do BE khai sẵn trong payload, fallback về chính giá trị đó khi bảng tra chưa tải xong. Ghép chuỗi vỡ **câm** ngay khi quy ước 2 bên lệch nhau một ký tự (`-` vs `_`).\n\n## displayCols \u002F data structures\n\n```typescript\n\u002F\u002F ❌ DEPRECATED\n{ label: 'Họ tên', value: 'fullname' }\n\n\u002F\u002F ❌ AVOID\n{ label: 'CUSTOMER_CODE', value: 'code' }\n\n\u002F\u002F ✅ CHUẨN\n{ label: 'Họ tên', labelKey: 'common.label.fullname', value: 'fullname' }\n```\n\n## Layout menu \u002F dialog header\n\n```typescript\n\u002F\u002F ❌ NEVER\n{ label: 'Khách hàng', icon: 'pi pi-users', routerLink: ['\u002Fcrm\u002Fcustomer'] }\nthis.dialog.open(Form, { header: 'Cập nhật khách hàng' });\n\n\u002F\u002F ✅ ALWAYS\n{ label: 'Khách hàng', labelKey: 'layout.menu.customer', icon: 'pi pi-users', routerLink: ['\u002Fcrm\u002Fcustomer'] }\nthis.dialog.open(Form, { header: this.translate.instant('crm.customer.update_dialog_title') });\n```\n\n## ⛔ Tạo key dịch mới — BẮT BUỘC check value trước (chống trùng)\n\n**Quy trình bắt buộc TRƯỚC khi thêm bất kỳ key dịch nào:**\n\n1. **Tra value đã tồn tại chưa:**\n   ```bash\n   npm run i18n:find -- \"Thanh toán\"          # khớp chính xác\n   npm run i18n:find -- --contains \"thanh\"     # khớp chứa\n   ```\n2. **Nếu CÓ key trùng value (exit 3):**\n   - Cùng nghĩa → **DÙNG LẠI key đó**, KHÔNG tạo mới.\n   - Tool nhóm theo nghĩa EN: nếu có nhiều nghĩa (vd Payment vs Billing) → chọn key ĐÚNG ngữ cảnh.\n3. **Nếu CHƯA có (exit 0)** → tạo key mới theo taxonomy:\n   - Dùng chung ≥2 module → `common.\u003Clabel|action|status|message|tooltip|placeholder|validation>.\u003Cslug>` (vd `common.action.save`, `common.label.customer`, `common.status.paid`)\n   - Riêng 1 module → `{module}.{feature}.\u003Cslug>` (vd `crm.customer.fullname`)\n   - Menu items → `layout.menu.*`\n   - Add ĐỦ 4 locale cùng path: `vi-VN` + `en-US` + `ja-JP` + `fil-PH`.\n\n**1 nghĩa = 1 key**: VI trùng nhưng khác nghĩa EN (vd \"Thanh toán\" = Payment vs Billing) → key RIÊNG theo nghĩa, KHÔNG gộp.\n\n**KHÔNG được:** tạo key mới khi value đã tồn tại · đặt key trùng nghĩa ở module khác nhau · hardcode string trong template\u002FTS.\n\n### Tooling\n- `npm run i18n:find -- \"\u003Cvalue>\"` → tra ngược theo value TRƯỚC khi tạo key (exit 3 = đã có, reuse)\n- `node scripts\u002Fi18n-dedup.mjs` → `i18n-dedup\u002Freport.json` (group trùng + usage)\n- `node scripts\u002Fi18n-build-mapping.mjs` → `i18n-dedup\u002Fmapping.json` (oldKey→canonical)\n- `node scripts\u002Fi18n-apply.mjs \u003Csafe|risky|all> [--step=add|rewrite|prune|all]` — áp dụng\n- Protected dynamic prefix (codemod KHÔNG được đụng): `define.emr.record_type.*`\n\n## i18n key audit gate\n\nPre-commit hook (`.husky\u002Fpre-commit`) chạy 2 gate:\n1. `npm run i18n:check -- --fail-on-missing` — **BLOCK** nếu thiếu key.\n2. `npm run i18n:dup` — **CẢNH BÁO** khi commit thêm key MỚI trùng value cùng nghĩa (so staged vs HEAD; đồng âm khác nghĩa EN được bỏ qua). Mặc định không chặn; `I18N_DUP_STRICT=1` để chặn cứng.\n\n```bash\nnpm run i18n:check          # human-readable summary\nnpm run i18n:check:verbose  # full lists\nnpm run i18n:check:json     # JSON cho CI\n```\n\nKhi PR fail i18n gate:\n1. Xem MISSING keys (file path + key name)\n2. Trước khi add key mới hàng loạt: nếu số lượng MISSING gần bằng số ORPHAN cùng module → nghi ngờ đây là rename sót (prefix đổi ở JSON nhưng code chưa cập nhật, hoặc ngược lại). So sánh suffix-set (bỏ prefix) giữa 2 danh sách — khớp 1:1 → sửa code dùng đúng prefix JSON hiện có, KHÔNG tạo key trùng mới.\n3. Add đủ 4 locale cùng nested path (gate chỉ check `vi-VN`\u002F`en-US`)\n4. Re-run `npm run i18n:check` → confirm 0 missing\n\nKey trả về GIÁN TIẾP qua hàm thuần (vd `resolveXxxKey()` return string key, không phải literal `'key' | translate` trong template) → `i18n:check` báo ORPHAN SAI (false-positive) vì tool chỉ static-scan literal — đừng xoá key chỉ vì nằm trong danh sách ORPHAN, grep thử usage gián tiếp trước.\n\n`git commit --no-verify` chỉ dùng emergency — fix keys luôn là đúng.\n\n## Nguồn file\n\n- **Key i18n mới HOẶC sửa value key có sẵn: ghi CẢ 2 nơi × 4 locale** — `frontend\u002Fsrc\u002Fassets\u002Fi18n\u002F*.json` (nguồn `ng build`, repo `frontend\u002F` riêng, gitignored khỏi repo chính) VÀ `public\u002Fassets\u002Fi18n\u002F*.json` (artifact đang serve, được git track ở repo chính). Chỉ sửa `src` → runtime thiếu key tới lần build kế; chỉ sửa `public` → key MẤT khi `ng build` regenerate. hr-completion + hr-2026-compliance đều dính lệch 2 dir (mỗi key chỉ nằm 1 nơi) — verify bằng grep key ở CẢ 2 dir. ⚠ Hai gốc là `frontend\u002Fsrc\u002Fassets\u002Fi18n\u002F` và `public\u002Fassets\u002Fi18n\u002F` ở **repo GỐC** — `frontend\u002Fpublic\u002Fassets\u002Fi18n\u002F` **KHÔNG tồn tại**; grep nhầm ở đó trả rỗng rồi kết luận \"chỉ có 1 nơi\" (đã xảy ra 2026-08-31, dẫn tới một đính chính SAI ghi vào sổ nợ). Đối chứng: grep từ gốc repo với CẢ 2 đường dẫn + một key đã biết chắc có.\n- **Sửa bằng script: KHÔNG `json.load()` rồi `json.dump()` lại** — dump không giữ thứ tự key gốc, diff nhảy lên hàng nghìn dòng (re-sort toàn file thay vì chỉ thêm key mới). Chèn text-based: regex tìm dòng key láng giềng đã biết, insert ngay sau, giữ nguyên phần còn lại của file.\n\n## Loader\n- Prod: `StaticTranslateLoader` (vi-VN inline main.js, en-US lazy chunk)\n- Dev: `CachedTranslateLoader` — stale-while-revalidate qua localStorage (`i18n_\u003Clang>`), sửa JSON KHÔNG hiện ngay lập tức. Cần reload 2 lần (lần 1 kích hoạt fetch nền update cache, lần 2 mới đọc cache mới) hoặc `localStorage.removeItem('i18n_\u003Clang>')`. `LS_VERSION` (auto-invalidate cache) chỉ đổi khi `npm run build` (hook `prebuild`), KHÔNG đổi khi `ng serve`\u002Fhot-reload.\n- `fallbackLang: 'vi-VN'` → missing en key fallback VN thay vì raw key\n",{"name":5,"description":7},"main","ea9f5ed9bd4eaf32e9489bcbe9603955c1462a63","frontend\u002Fskill\u002Fskills\u002Fhandling-fe-auth-and-i18n",20,"https:\u002F\u002Fgithub.com\u002Fcluvix\u002Fcluvix-crm","https:\u002F\u002Fgithub.com\u002Fcluvix","cluvixsolutions.com","Cluvix Solutions is a technology outsourcing company specializing in custom software development for growing businesses. We build end-to-end enterprise solution","2026-11-02 19:55:39",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add cluvix\u002Fcluvix-crm --skill handling-fe-auth-and-i18n",{"tool":39,"command":40},"bunx","bunx skills add cluvix\u002Fcluvix-crm --skill handling-fe-auth-and-i18n",{"tool":42,"command":43},"pnpm","pnpm dlx skills add cluvix\u002Fcluvix-crm --skill handling-fe-auth-and-i18n","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fcluvix\u002Fcluvix-crm\u002Fblob\u002Fmain\u002Ffrontend\u002Fskill\u002Fskills\u002Fhandling-fe-auth-and-i18n\u002FSKILL.md",true,[47,53],{"path":48,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":51,"sourceHtmlUrl":52},"reference\u002Ffe-patterns-gotchas-auth.md","REFERENCE","参考文档",15015,"https:\u002F\u002Fgithub.com\u002Fcluvix\u002Fcluvix-crm\u002Fblob\u002Fmain\u002Ffrontend\u002Fskill\u002Fskills\u002Fhandling-fe-auth-and-i18n\u002Freference\u002Ffe-patterns-gotchas-auth.md",{"path":54,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":55,"sourceHtmlUrl":56},"reference\u002Ffe-timezone.md",12135,"https:\u002F\u002Fgithub.com\u002Fcluvix\u002Fcluvix-crm\u002Fblob\u002Fmain\u002Ffrontend\u002Fskill\u002Fskills\u002Fhandling-fe-auth-and-i18n\u002Freference\u002Ffe-timezone.md",[58,65,72,79,86,93],{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":19},"01M7F47FCP2MP548SWCP0BJ6B1","writing-mysql-migrations","Viết migration MySQL cho Cluvix (golang-migrate, Go + GORM): quy ước timestamp, idempotent ADD\u002FDROP COLUMN, FK constraint thật, decimal tiền, MySQL 9.7 LTS syntax mới\u002Fcũ, và luật CẤM tuyệt đối test\u002Fmigrate chạm DB dev\u002Fprod thật. Dùng skill này TRƯỚC KHI tạo file migration mới, sửa schema, thêm cột\u002FFK, backfill dữ liệu, hoặc trước khi chạy `cmd\u002Fmigrate`\u002Fintegration test đụng tới database — kể cả migration chỉ 1-2 dòng.","https:\u002F\u002Fgithub.com\u002Fcluvix\u002Fcluvix-crm\u002Fblob\u002Fmain\u002Fskill\u002Fskills\u002Fwriting-mysql-migrations\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":19},"01M7F475VEPATD0D8KP8V2HHYV","writing-backend-resources","Hướng dẫn quy trình 6 bước TẠO MỚI resource backend Go (entity, dao, repository, service, handler, router, DTO, module layout) cho ERP Cluvix. Dùng skill này TRƯỚC KHI tạo resource CRUD mới hoặc module mới trong internal\u002Fmodules\u002F, khi cần biết Handler DI\u002FRouter\u002FRepository Reader\u002FDTO pattern chuẩn, hoặc trước khi đụng module service (status filter 2 tầng, cascade, optimistic lock). KHÔNG dùng skill này để debug\u002Fsửa query đang sai — xem debugging-backend-queries cho việc đó.","https:\u002F\u002Fgithub.com\u002Fcluvix\u002Fcluvix-crm\u002Fblob\u002Fmain\u002Fskill\u002Fskills\u002Fwriting-backend-resources\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":19},"01M7F46Z6MMBQ0AP2ZA5HW5R4X","working-on-ops","Hướng dẫn nghiệp vụ dashboard CRM, export, và import dữ liệu trong module ops của backend Cluvix. Dùng skill này KHI đụng report\u002Fdashboard CRM, thêm cột export (`?columns=`), hoặc import khách hàng (migration onboard SAAS client) — đọc trước khi đổi bất kỳ hành vi nào trong các luồng này.","https:\u002F\u002Fgithub.com\u002Fcluvix\u002Fcluvix-crm\u002Fblob\u002Fmain\u002Fskill\u002Fskills\u002Fworking-on-ops\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":19},"01M7F46PPNCK976F4SYWVHXAHC","working-on-hr","Quy tắc và pattern nghiệp vụ HR Cluvix trong CRM standalone: user nội bộ, role\u002FRBAC, đổi\u002Fđặt lại mật khẩu, import user. Dùng skill này KHI làm feature\u002Fsửa bug đụng module hr (chỉ còn `hr\u002Fuser`) — trước khi đọc code.","https:\u002F\u002Fgithub.com\u002Fcluvix\u002Fcluvix-crm\u002Fblob\u002Fmain\u002Fskill\u002Fskills\u002Fworking-on-hr\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M7F468VEARVSRRYBJ8VHJSJ3","working-on-crm","Quy tắc và pattern nghiệp vụ CRM Cluvix: khách hàng, lịch hẹn, liệu trình, đơn hàng, thanh toán. Dùng skill này KHI làm feature\u002Fsửa bug đụng module crm (customer, appointment, order, treatment, payment) — trước khi đọc code, để tránh phá vỡ business rule đã có (tái khai thác, customer status IN(...)).","https:\u002F\u002Fgithub.com\u002Fcluvix\u002Fcluvix-crm\u002Fblob\u002Fmain\u002Fskill\u002Fskills\u002Fworking-on-crm\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M7F45Y15Q0CBEP06CFF2AAEY","working-on-config","Quy tắc và pattern nghiệp vụ Config Cluvix còn sống trong CRM standalone: mẫu in (print_template), control field trong bảng (control_field_in_table), IndexedDB sync của config. Dùng skill này KHI làm feature\u002Fsửa bug đụng các module đó — trước khi đọc code. Tổng đài\u002Fchữ ký số\u002FAI config đã bỏ (chỉ còn mô tả lịch sử trong skill, KHÔNG áp dụng).","https:\u002F\u002Fgithub.com\u002Fcluvix\u002Fcluvix-crm\u002Fblob\u002Fmain\u002Fskill\u002Fskills\u002Fworking-on-config\u002FSKILL.md",[],[]]