MSO Cloud · Documentation

API Reference — tRPC

Source: docs/architecture/reference/api-reference.md Updated 2026-09-21
On this page

File sinh tự động từ apps/web/src/server/routers/ bằng scripts/docs/generate-api-reference.ts — không sửa tay. Tái sinh: pnpm tsx scripts/docs/generate-api-reference.ts && pnpm tsx scripts/docs-to-html.ts --only=docs/api-reference.md.

Toàn bộ API ứng dụng đi qua tRPC v11 (superjson + Zod) tại /api/trpc/[trpc], tổ chức thành các router theo nhóm chức năng bên dưới. Mô tả từng procedure lấy từ comment trong source — source là chuẩn, doc chỉ là chỉ mục.

Transport & REST routes#

Ngoài tRPC, một số flow cần HTTP route thuần (NextAuth, WebAuthn JSON, streaming chat, webhook, OAuth callback, export). Route mutating luôn qua rate limit và route org-scoped luôn set RLS context trước khi chạm dữ liệu. Bảng dưới chỉ liệt kê route dành cho bên tích hợp — bề mặt vận hành nội bộ không public.

Route Methods
/api/auth/[...nextauth] GET, POST
/api/auth/magic-link POST
/api/auth/passkey/auth/begin POST
/api/auth/passkey/register/begin POST
/api/auth/passkey/register/finish POST
/api/auth/switch-brand POST
/api/auth/switch-org POST
/api/chat/deck POST
/api/chat POST
/api/compliance/dsar GET, POST
/api/connectors/oauth/[platform]/callback GET
/api/exports/page-pdf POST
/api/health GET
/api/ingest/webhook/[connectorType]/[connectorId] POST
/api/marketing-systems/summary POST
/api/org-data/[id]/download GET
/api/trpc/[trpc] GET, POST

Tổng quan router theo nhóm chức năng#

Nhóm Router Tenancy bases File
Auth & workspace health, me (root) publicProcedure, orgProcedure apps/web/src/server/routers/root.ts
orgs authedProcedure, orgProcedure, rateLimitedOrgProcedure apps/web/src/server/routers/orgs.ts
users authedProcedure, orgProcedure, rateLimitedOrgProcedure apps/web/src/server/routers/users.ts
brands orgProcedure, rateLimitedOrgProcedure apps/web/src/server/routers/brands.ts
passkeys authedProcedure apps/web/src/server/routers/passkeys.ts
orgAuthLdap orgProcedure, rateLimitedOrgProcedure, authedProcedure apps/web/src/server/routers/org-auth-ldap.ts
Commerce data (first-party validation) dashboards brandProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/dashboards.ts
dashboardTemplates brandProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/dashboard-templates.ts
insights brandProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/insights.ts
orders authedProcedure, brandProcedure apps/web/src/server/routers/orders.ts
creators brandProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/creators.ts
inventory brandProcedure apps/web/src/server/routers/inventory.ts
products brandProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/products.ts
alerts orgProcedure, rateLimitedOrgProcedure, authedProcedure apps/web/src/server/routers/alerts.ts
briefing brandProcedure, orgProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/briefing.ts
subscription authedProcedure apps/web/src/server/routers/subscription.ts
actions orgProcedure, authedProcedure apps/web/src/server/routers/actions.ts
attribution rateLimitedBrandProcedure, brandProcedure apps/web/src/server/routers/attribution.ts
audiences orgProcedure, rateLimitedOrgProcedure apps/web/src/server/routers/audiences.ts
cases orgProcedure, rateLimitedOrgProcedure apps/web/src/server/routers/cases.ts
memos orgProcedure, rateLimitedOrgProcedure apps/web/src/server/routers/memos.ts
activation orgProcedure, rateLimitedOrgProcedure, authedProcedure apps/web/src/server/routers/activation.ts
campaigns brandProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/campaigns.ts
playbooks orgProcedure, rateLimitedOrgProcedure, authedProcedure apps/web/src/server/routers/playbooks.ts
reports brandProcedure, orgProcedure, authedProcedure apps/web/src/server/routers/reports.ts
marketplace brandProcedure apps/web/src/server/routers/marketplace.ts
explore brandProcedure, authedProcedure apps/web/src/server/routers/explore.ts
brandCompare orgProcedure apps/web/src/server/routers/brand-compare.ts
Marketing performance (first-party) marketing brandProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/marketing.ts
leadsDiagnostic orgProcedure, brandProcedure apps/web/src/server/routers/leads-diagnostic.ts
marketingWeb brandProcedure apps/web/src/server/routers/marketing-web.ts
marketingLeads brandProcedure apps/web/src/server/routers/marketing-leads.ts
marketingSocial brandProcedure apps/web/src/server/routers/marketing-social.ts
marketingCampaigns brandProcedure apps/web/src/server/routers/marketing-campaigns.ts
planBindings brandProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/plan-bindings.ts
Content intelligence contentInsights brandProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/content-insights.ts
contentTaxonomy brandProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/content-taxonomy.ts
contentDecks rateLimitedBrandProcedure, brandProcedure apps/web/src/server/routers/content-decks.ts
Data ingest & connectors connectors brandProcedure, rateLimitedBrandProcedure, authedProcedure apps/web/src/server/routers/connectors.ts
orgCredentials brandProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/org-credentials.ts
connectorBackfill rateLimitedOrgProcedure, orgProcedure apps/web/src/server/routers/connector-backfill.ts
pipeline authedProcedure, brandProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/pipeline.ts
manualUploads brandProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/manual-uploads.ts
validation brandProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/validation.ts
categories orgProcedure, rateLimitedOrgProcedure apps/web/src/server/routers/categories.ts
shopAliases orgProcedure, rateLimitedOrgProcedure apps/web/src/server/routers/shop-aliases.ts
importTemplates brandProcedure, rateLimitedBrandProcedure, rateLimitedOrgProcedure apps/web/src/server/routers/import-templates.ts
Market intelligence (third-party estimates) marketIntel brandProcedure, authedProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/market-intel.ts
socialListening orgProcedure apps/web/src/server/routers/social-listening.ts
socialTrends orgProcedure apps/web/src/server/routers/social-trends.ts
Decisions & learning loop offtake orgProcedure, rateLimitedOrgProcedure apps/web/src/server/routers/offtake.ts
msoPlaybooks orgProcedure, rateLimitedOrgProcedure, authedProcedure apps/web/src/server/routers/mso-playbooks.ts
AI & chat aiConfigs orgProcedure, rateLimitedOrgProcedure, authedProcedure apps/web/src/server/routers/ai-configs.ts
platformAiConfigs superAdminProcedure apps/web/src/server/routers/ai-configs.ts
aiPrompts orgProcedure, rateLimitedOrgProcedure, authedProcedure apps/web/src/server/routers/ai-prompts.ts
chat chatProcedure, rateLimitedChatProcedure apps/web/src/server/routers/chat.ts
chatAssistant orgProcedure, rateLimitedOrgProcedure apps/web/src/server/routers/chat-assistant.ts
Platform admin apiTokens orgProcedure, rateLimitedOrgProcedure apps/web/src/server/routers/api-tokens.ts
admin superAdminProcedure apps/web/src/server/routers/admin.ts
notificationSettings superAdminProcedure apps/web/src/server/routers/notification-settings.ts
siteIdentity publicProcedure, superAdminProcedure apps/web/src/server/routers/site-identity.ts
appearance superAdminProcedure, orgProcedure, rateLimitedOrgProcedure apps/web/src/server/routers/appearance.ts
orgData superAdminProcedure, orgProcedure, rateLimitedOrgProcedure, authedProcedure apps/web/src/server/routers/org-data.ts
orgBackupConfig superAdminProcedure, orgProcedure, rateLimitedOrgProcedure apps/web/src/server/routers/org-backup-config.ts
orgMenu orgProcedure, rateLimitedOrgProcedure apps/web/src/server/routers/org-menu.ts
orgBlueprints superAdminProcedure apps/web/src/server/routers/org-blueprints.ts
Chia sẻ & public shares brandProcedure, rateLimitedBrandProcedure apps/web/src/server/routers/shares.ts
publicShare publicProcedure apps/web/src/server/routers/public-share.ts

Tenancy & RBAC#

Sáu base procedure trong apps/web/src/server/trpc.ts — chọn base là chọn tầng cách ly dữ liệu:

Base Điều kiện RLS context
publicProcedure không không — chỉ dùng cho bề mặt public (health, share link, wordmark)
authedProcedure đã đăng nhập không set org GUC — chỉ dùng cho dữ liệu thuộc user (passkeys, danh sách org của tôi)
superAdminProcedure isSuperAdmin cross-org có chủ đích — mọi procedure trong admin.*
orgProcedure activeOrgId trong session chạy TOÀN BỘ resolver trong runWithRlsContext(orgId, null, …) — một transaction mang SET LOCAL app.current_org_id, Postgres RLS thực sự evaluate theo org (bare setOrgContext trước resolver KHÔNG đủ — autocommit làm bay GUC)
brandProcedure như orgProcedure thêm app.current_brand_id (null = rollup toàn org); brand authz ở tầng app qua org_memberships.viewable_brand_ids, RLS là lưới an toàn
chatProcedure như brandProcedure thêm 2 gate: plugin chat-with-data bật cho org (qua isPluginEnabledForOrg) VÀ caller có role trong CHAT_ALLOWED_ROLES (admin, owner)

RBAC trên mutation — hai helper trong apps/web/src/server/access.ts:

  • requireOwnerOrOrgAdmin({ userId, orgId, isSuperAdmin }) — gate role cứng (owner / admin / super-admin). Áp dụng cho mọi mutation của vòng học (offtake.approve, offtake.reject, offtake.markExecuted, offtake.cancel, offtake.confirmOutcome, offtake.approveLesson, offtake.updateSettings), thư viện playbook (msoPlaybooks.upsert/remove/seedDefaults), mapping admin (categories, shopAliases), cấu hình chat (chatAssistant.updateSettings) và ingest market intelligence (marketIntel.ingestExport). Cột RBAC trong các bảng dưới được detect trực tiếp từ resolver.
  • requireOrgCapability({ capability }) — gate theo capability per-org (role-policy động qua hasDynamicOrgCapability), dùng rộng khắp cho mutation cấu hình/vận hành (manage_connectors, manage_members, …). Cột RBAC hiển thị dạng cap:<capability>.

Mutation org-scoped đồng thời qua rateLimitOrgMutation(orgId, key); hành động quản trị ghi writeAuditLog với action dạng ${module}.${entity}.${verb}. Entitlement plugin (market intelligence, decision engine, chat…) enforce ở tầng page (requirePlugin) + nav, KHÔNG ở tầng tRPC — ngoại lệ duy nhất là chatProcedure, router riêng của chat nên gate được ngay tại procedure.

Decision engine surface#

Bề mặt API của vòng học off-take. Toán học chỉ nằm trong packages/metrics/src/offtake.ts (pure); ghi offtake_models/decisions/decision_outcomes chỉ từ packages/metrics/src/offtake-loop.ts — router đọc và cập nhật trạng thái lifecycle, không tự tính.

Ràng buộc của vòng học: human-in-the-loop (requireOwnerOrOrgAdmin trên mọi mutation duyệt/ghi nhận), abstain khi tín hiệu yếu, và mọi quyết định truy vết được về rule version + signal values + model version.

offtake.*

Procedure Loại Base RBAC Mô tả
offtake.signals query orgProcedure Social conversation (SocialHeat, 3rd-party) — all-brands weekly conversation per lever, the INPUT the off-take loop learns from.
offtake.decisions query orgProcedure Decision Memory (historical) + Inbox (proposed) + outcomes, all brands.
offtake.trackRecord query orgProcedure Track record (calibration): hit-rate by confidence bucket.
offtake.experimentsList query orgProcedure L3 incrementality experiments (experiments.readout, read-only list).
offtake.episodes query orgProcedure The DECISION LEDGER timeline — read-only.
offtake.playbookStats query orgProcedure Tier-1 track record per playbook × segment — the REBUILDABLE cache over the ledger, read-only here (the worker owns the rebuild).
offtake.confirmOutcome mutation rateLimitedOrgProcedure owner/org-admin Owner-confirm a measured verdict (hit/partial/miss).
offtake.approveLesson mutation rateLimitedOrgProcedure owner/org-admin Owner BLESSES the lesson from a measured decision — the lesson "enters the system" (becomes knowledge the loop carries forward) ONLY through this action, separate from the verdict.
offtake.approve mutation rateLimitedOrgProcedure owner/org-admin Govern gate → approve a proposed decision (1-click) + emit action_commands.
offtake.reject mutation rateLimitedOrgProcedure owner/org-admin Owner SKIPS a proposed decision ("Bỏ qua") — it never runs, so it gets no outcome, but it stays in the ledger as a real "đã từ chối" record (so the track-record honestly shows what was offered vs…
offtake.markExecuted mutation rateLimitedOrgProcedure owner/org-admin Owner marks an APPROVED decision as EXECUTED on a real start date: status → 'activated', anchor the review window to executionStartDate + horizon (ICT).
offtake.cancel mutation rateLimitedOrgProcedure owner/org-admin Owner/admin UN-RUNs an approved/activated decision — returns it to the Decision Inbox ('proposed') so it can be re-decided or skipped.
offtake.settings query orgProcedure The decision-loop measurement standards for THIS org: verdict tolerance (TRÚNG/LỆCH VỪA/TRƯỢT), diagnostic-scan severity (vàng/đỏ), and the off-take cold-start gate.
offtake.updateSettings mutation rateLimitedOrgProcedure owner/org-admin
offtake.policyRecommend query orgProcedure Recommend the next lever per brand (spec policy.recommend).
offtake.governanceStatus query orgProcedure L5 governance — System-Health read (L5 DoD).

msoPlaybooks.*

Procedure Loại Base RBAC Mô tả
msoPlaybooks.list query orgProcedure The org's playbook library (DB rows; falls back to code defaults when empty).
msoPlaybooks.upsert mutation rateLimitedOrgProcedure owner/org-admin Create or edit a playbook (by org+slug).
msoPlaybooks.remove mutation rateLimitedOrgProcedure owner/org-admin Retire a playbook.
msoPlaybooks.suggestRule mutation authedProcedure owner/org-admin Ask the model to structure an expert's prose into a rule SHAPE (thresholds blank).
msoPlaybooks.saveRuleDraft mutation rateLimitedOrgProcedure owner/org-admin Store a human-completed candidate as status:'draft' — reviewable, NOT live.
msoPlaybooks.activateRule mutation rateLimitedOrgProcedure owner/org-admin The ONLY path that makes an authored rule LIVE.
msoPlaybooks.rulePreview query orgProcedure owner/org-admin Dry-run a candidate against the org's OWN recorded signal panels, so the author sees what WOULD have matched before activating.
msoPlaybooks.simulateDraft query orgProcedure owner/org-admin Chạy thử NGAY một luật CHƯA LƯU trên dữ liệu thật — the loop-closer for authoring: AI drafts → human sets thresholds → simulate on real ad data → activate.
msoPlaybooks.simulate query orgProcedure owner/org-admin Chạy thử — replay ONE playbook's rule over an operator-chosen ICT window, against the org's own recorded ad data, and return the machine receipt for every entity the rule was eligible on.
msoPlaybooks.scanAndPropose mutation rateLimitedOrgProcedure owner/org-admin Quét & tạo đề xuất — turn marketing-audit findings into MEASURABLE proposed decisions in the inbox (the revised D4).
msoPlaybooks.seedDefaults mutation rateLimitedOrgProcedure owner/org-admin One-click: materialise the code defaults into editable DB rows for this org.

Root procedures#

Định nghĩa inline trong apps/web/src/server/routers/root.ts.

Procedure Loại Base RBAC Mô tả
health query publicProcedure Liveness check { ok, ts } — không cần đăng nhập.
me query orgProcedure Context phiên hiện tại: userId, orgId, isSuperAdmin.

Auth & workspace#

Phiên đăng nhập, thành viên, org/brand, passkey, đăng nhập doanh nghiệp.

orgsapps/web/src/server/routers/orgs.ts

Procedure Loại Base RBAC Mô tả
orgs.myMemberships query authedProcedure
orgs.current query orgProcedure
orgs.availableThemes query orgProcedure Skins THIS org may pick as its override: the built-ins, the platform's custom skins, and the org's OWN skins (two-tier).
orgs.updateTheme mutation rateLimitedOrgProcedure owner/org-admin Org skin override (two-tier).
orgs.updateSettings mutation rateLimitedOrgProcedure cap:manage_org_settings

usersapps/web/src/server/routers/users.ts

Procedure Loại Base RBAC Mô tả
users.me query authedProcedure
users.updateProfile mutation authedProcedure
users.updateNotificationPrefs mutation authedProcedure
users.changePassword mutation authedProcedure
users.setPassphrase mutation authedProcedure
users.disablePassphrase mutation authedProcedure
users.beginTwoFactorSetup mutation authedProcedure
users.confirmTwoFactorSetup mutation authedProcedure
users.disableTwoFactor mutation authedProcedure
users.regenerateRecoveryCodes mutation authedProcedure Regenerate recovery codes WITHOUT re-doing the TOTP setup.
users.twoFactorStatus query authedProcedure Read-only: how many unused recovery codes the user has left.
users.listOrgMembers query orgProcedure The org's OWN member list, gated by requireMemberAdmin (owner / admin, or a per-org manage_members grant).
users.addOrgMember mutation authedProcedure Add a member to THIS org.
users.updateMemberRole mutation rateLimitedOrgProcedure
users.updateMemberBrandAccess mutation rateLimitedOrgProcedure Assign a member to specific brands (or back to every brand).
users.removeOrgMember mutation rateLimitedOrgProcedure

brandsapps/web/src/server/routers/brands.ts

Procedure Loại Base RBAC Mô tả
brands.myAccess query orgProcedure Brands the signed-in user can SEE inside the active org.
brands.ingestContext query orgProcedure The brand an INGEST action would land in right now — the upload/connector surfaces render this as the receiving-brand chip and send it back as the echo.
brands.list query orgProcedure cap:manage_org_settings
brands.create mutation rateLimitedOrgProcedure cap:manage_org_settings
brands.update mutation rateLimitedOrgProcedure cap:manage_org_settings Edit an existing brand.
brands.themeOverrides query orgProcedure owner/org-admin Every brand in an Audience-CI org is a different CLIENT, so its deck must carry that client's colours.
brands.updateTheme mutation rateLimitedOrgProcedure owner/org-admin
brands.updateThemeOverrides mutation rateLimitedOrgProcedure owner/org-admin The BRAND OVERRIDE LAYER — a partial, per-mode set of token groups merged over the brand's resolved base skin.
brands.brandAlias query orgProcedure owner/org-admin THE BRAND'S ALIAS PAIRS — read.
brands.updateBrandAlias mutation rateLimitedOrgProcedure owner/org-admin THE BRAND'S ALIAS PAIRS — write.
brands.archive mutation rateLimitedOrgProcedure cap:manage_org_settings

passkeysapps/web/src/server/routers/passkeys.ts

User-facing passkey management.

Procedure Loại Base RBAC Mô tả
passkeys.list query authedProcedure
passkeys.rename mutation authedProcedure
passkeys.remove mutation authedProcedure

orgAuthLdapapps/web/src/server/routers/org-auth-ldap.ts

Per-org enterprise LDAP / AD login — CONFIG MANAGEMENT layer.

Procedure Loại Base RBAC Mô tả
orgAuthLdap.get query orgProcedure cap:manage_org_settings Read the org's config WITHOUT the encrypted bind password.
orgAuthLdap.upsert mutation rateLimitedOrgProcedure cap:manage_org_settings Create or update the org's LDAP config.
orgAuthLdap.testConnection mutation authedProcedure cap:manage_org_settings Directory reachability check for the org-admin config UI.

Commerce data (first-party validation)#

Dữ liệu bán hàng, creator, tồn kho, báo cáo và dashboard trên dữ liệu của chính org.

dashboardsapps/web/src/server/routers/dashboards.ts

Procedure Loại Base RBAC Mô tả
dashboards.list query brandProcedure
dashboards.getOrCreateHome query brandProcedure Lazily create the org's home dashboard on first access.
dashboards.bySlug query brandProcedure
dashboards.deckChat query brandProcedure "Chat with Dashboard" — is this deck chattable, and what should the panel offer?
dashboards.deckChatThreads query brandProcedure THE READER'S OWN HISTORY ON THIS DECK.
dashboards.deckChatMessages query brandProcedure One thread's messages, oldest first — what the panel rehydrates on open.
dashboards.deckChatDeleteThread mutation rateLimitedBrandProcedure Retire one of the caller's own deck threads.
dashboards.deckDimensions query brandProcedure The DIMENSIONS the layout editor's "Nhóm dữ liệu" dropdown offers for one deck — this corpus's own catalog rows (a client's vocabulary is DATA, so the list can only ever come from…
dashboards.create mutation rateLimitedBrandProcedure cap:edit_dashboard
dashboards.createFromExplore mutation rateLimitedBrandProcedure cap:edit_dashboard
dashboards.updateLayout mutation rateLimitedBrandProcedure cap:edit_dashboard
dashboards.renameDashboard mutation rateLimitedBrandProcedure cap:edit_dashboard
dashboards.deleteDashboard mutation rateLimitedBrandProcedure cap:edit_dashboard
dashboards.duplicate mutation rateLimitedBrandProcedure cap:edit_dashboard Deep-copy a dashboard: the dashboard row + its dashboard_tabs rows + every widget (type, title, config, position, sortOrder, tab_id) + a remapped layout.
dashboards.addWidget mutation rateLimitedBrandProcedure cap:edit_dashboard
dashboards.updateWidget mutation rateLimitedBrandProcedure cap:edit_dashboard
dashboards.deleteWidget mutation rateLimitedBrandProcedure cap:edit_dashboard
dashboards.createTab mutation rateLimitedBrandProcedure cap:edit_dashboard Org-editable tabs.
dashboards.renameTab mutation rateLimitedBrandProcedure cap:edit_dashboard
dashboards.moveTab mutation rateLimitedBrandProcedure cap:edit_dashboard Re-order and/or re-parent one tab.
dashboards.deleteTab mutation rateLimitedBrandProcedure cap:edit_dashboard Deleting a tab NEVER orphans a widget: the composite FK is ON DELETE SET NULL ("tab_id"), so its widgets fall back to NULL = the FIRST tab and stay on screen.
dashboards.assignWidgetTab mutation rateLimitedBrandProcedure cap:edit_dashboard Put one widget on one tab (or back on NULL = the first tab).
dashboards.saveDeckDraft mutation rateLimitedBrandProcedure cap:edit_dashboard THE DECK LAYOUT EDITOR'S ONE WRITE (Phase 1 spec, 2026-08-17).

dashboardTemplatesapps/web/src/server/routers/dashboard-templates.ts

Procedure Loại Base RBAC Mô tả
dashboardTemplates.list query brandProcedure Gallery: every registry template + this org's installed-instance state.
dashboardTemplates.install mutation rateLimitedBrandProcedure cap:edit_dashboard
dashboardTemplates.updatePreview query brandProcedure cap:edit_dashboard What the client should DO about an available update (resolveTemplateUpdate, the single decision rule).
dashboardTemplates.applyUpdate mutation rateLimitedBrandProcedure cap:edit_dashboard
dashboardTemplates.resetToTemplate mutation rateLimitedBrandProcedure cap:edit_dashboard Reset an instance back to its template baseline ("Hoàn tác về mẫu", S3): restores template widgets + drops the org's custom edits.
dashboardTemplates.detach mutation rateLimitedBrandProcedure cap:edit_dashboard

insightsapps/web/src/server/routers/insights.ts

Procedure Loại Base RBAC Mô tả
insights.forWidgets query brandProcedure Fetch cached insights for a list of widget IDs.
insights.keySummary query brandProcedure Fetch the key summary for a dashboard.
insights.runDashboard mutation rateLimitedBrandProcedure owner/org-admin Enqueue a dashboard analysis run.

ordersapps/web/src/server/routers/orders.ts

Procedure Loại Base RBAC Mô tả
orders.summary query authedProcedure KPI cards on the landing dashboard.
orders.dailyGmv query authedProcedure Daily time-series for line charts.
orders.opsStatus query brandProcedure Ops Floor status: a single SQL fetch that returns three operationally useful breakdowns for the /workspaces/ops dashboard: 1. slaBreached — orders still in pending/confirmed past 24h since…
orders.list query brandProcedure List / cursor pagination — this is a row-level data grid, not a metric, so it stays on Drizzle's select.
orders.getDetail query brandProcedure Single-order detail — lazy-loaded by the orders drawer.

creatorsapps/web/src/server/routers/creators.ts

Procedure Loại Base RBAC Mô tả
creators.list query brandProcedure
creators.topByGmv query brandProcedure Top creators by GMV over a window — drives the creator directory + leaderboard.
creators.detail query brandProcedure Per-creator detail dashboard — drives /creators/[creatorId].
creators.leaderboard query brandProcedure
creators.importCostsCsv mutation rateLimitedBrandProcedure cap:manage_finance

inventoryapps/web/src/server/routers/inventory.ts

Procedure Loại Base RBAC Mô tả
inventory.currentLevels query brandProcedure Latest quantity-on-hand per product.
inventory.expiringSoon query brandProcedure Products with expiry in the next N days — surfaces the "sắp hết hạn" risk widget.
inventory.riskTable query brandProcedure

productsapps/web/src/server/routers/products.ts

Procedure Loại Base RBAC Mô tả
products.list query brandProcedure
products.categoryOptions query brandProcedure Canonical category labels for the Product Catalog dropdown.
products.updateCategory mutation rateLimitedBrandProcedure Update a product's category manually.
products.decodeSku query brandProcedure Decode a SKU per client Principle.

alertsapps/web/src/server/routers/alerts.ts

Procedure Loại Base RBAC Mô tả
alerts.list query orgProcedure
alerts.preferences query orgProcedure
alerts.briefRulePacks query orgProcedure cap:manage_org_settings The Morning Brief transparency + delivery surface for the org-admin settings page.
alerts.upsertPreference mutation rateLimitedOrgProcedure
alerts.runNow mutation authedProcedure owner/org-admin

briefingapps/web/src/server/routers/briefing.ts

Procedure Loại Base RBAC Mô tả
briefing.byUser query brandProcedure
briefing.cadence query orgProcedure Day / week / month legs for the morning brief's signal panel.
briefing.refresh mutation rateLimitedBrandProcedure

subscriptionapps/web/src/server/routers/subscription.ts

Procedure Loại Base RBAC Mô tả
subscription.events subscription authedProcedure SSE stream sự kiện realtime per org (order.created, order.status_changed, inventory.below_reorder_point, creator.hour_spike) từ Redis stream.

actionsapps/web/src/server/routers/actions.ts

Procedure Loại Base RBAC Mô tả
actions.queue query orgProcedure cap:manage_ai · cap:manage_actions
actions.propose mutation authedProcedure cap:manage_actions
actions.approve mutation authedProcedure cap:manage_actions
actions.reject mutation authedProcedure cap:manage_actions
actions.rollback mutation authedProcedure cap:manage_actions
actions.monthlyApprovalRate query orgProcedure
actions.experiments query orgProcedure

attributionapps/web/src/server/routers/attribution.ts

Procedure Loại Base RBAC Mô tả
attribution.refresh mutation rateLimitedBrandProcedure owner/org-admin
attribution.byOrder query brandProcedure
attribution.byCreator query brandProcedure
attribution.byCampaign query brandProcedure
attribution.shoppers query brandProcedure

audiencesapps/web/src/server/routers/audiences.ts

Procedure Loại Base RBAC Mô tả
audiences.list query orgProcedure
audiences.presets query orgProcedure
audiences.get query orgProcedure
audiences.previewCount mutation rateLimitedOrgProcedure cap:manage_audiences
audiences.upsert mutation rateLimitedOrgProcedure cap:manage_audiences
audiences.delete mutation rateLimitedOrgProcedure cap:manage_audiences
audiences.refreshNow mutation rateLimitedOrgProcedure cap:manage_audiences
audiences.members query orgProcedure Read the active members of an audience — used by the detail page and by the Phase F4 audience-sync pipeline.

casesapps/web/src/server/routers/cases.ts

Procedure Loại Base RBAC Mô tả
cases.list query orgProcedure
cases.get query orgProcedure
cases.acknowledge mutation rateLimitedOrgProcedure cap:manage_cases
cases.resolve mutation rateLimitedOrgProcedure cap:manage_cases
cases.escalate mutation rateLimitedOrgProcedure cap:manage_cases
cases.slaList query orgProcedure SLA definitions — read-only listing; the editor lives in /admin and is out-of-scope for F2's first drop.

memosapps/web/src/server/routers/memos.ts

Phase F §F3 — Weekly Action Memo router.

Procedure Loại Base RBAC Mô tả
memos.list query orgProcedure
memos.get query orgProcedure
memos.publish mutation rateLimitedOrgProcedure cap:manage_decisions
memos.archive mutation rateLimitedOrgProcedure cap:manage_decisions
memos.generate mutation rateLimitedOrgProcedure cap:manage_decisions Generate (or refresh) the memo for an explicit period.

activationapps/web/src/server/routers/activation.ts

Procedure Loại Base RBAC Mô tả
activation.destinationsList query orgProcedure
activation.upsertDestination mutation rateLimitedOrgProcedure cap:manage_activation
activation.runs query orgProcedure
activation.runSync mutation authedProcedure cap:manage_activation Run an audience-sync.

campaignsapps/web/src/server/routers/campaigns.ts

Procedure Loại Base RBAC Mô tả
campaigns.list query brandProcedure
campaigns.create mutation rateLimitedBrandProcedure
campaigns.end mutation rateLimitedBrandProcedure
campaigns.performance query brandProcedure
campaigns.elasticity query brandProcedure

playbooksapps/web/src/server/routers/playbooks.ts

Playbooks router — backing store for the React-Flow canvas at /automations.

Procedure Loại Base RBAC Mô tả
playbooks.list query orgProcedure
playbooks.get query orgProcedure
playbooks.create mutation rateLimitedOrgProcedure cap:manage_playbooks
playbooks.saveGraph mutation rateLimitedOrgProcedure cap:manage_playbooks Canvas save path.
playbooks.run mutation authedProcedure cap:manage_playbooks
playbooks.toggle mutation rateLimitedOrgProcedure cap:manage_playbooks
playbooks.nodeCatalog query orgProcedure Canvas palette.

reportsapps/web/src/server/routers/reports.ts

Procedure Loại Base RBAC Mô tả
reports.activePlatforms query brandProcedure Which marketplace sàn does the ACTIVE BRAND actually have?
reports.orgMenuLabels query orgProcedure Active org's per-nav menu_labels overrides (org-wide config → orgProcedure, runs inside runWithRlsContext, CLAUDE.md).
reports.commercePerformance query authedProcedure Parallel-phase pattern (see bloCreator): 15 independent aggregates cost their SUM inside one RLS transaction (~3.1s measured under the app runtime role) and their MAX as pooled phases.
reports.settlement query authedProcedure
reports.liveCommerce query authedProcedure
reports.holidayCalendar query brandProcedure
reports.aiCubeBriefing query authedProcedure
reports.cohortRfmKol query brandProcedure
reports.operations query brandProcedure Vận hành (Operations) — surfaces the rich raw_payload client's promoter already captures: warehouse, shipping provider, payment method, province, cancel reason.
reports.bloLatestOrderDate query brandProcedure Latest order date (ICT) for the active org/brand — used by the client report pages to anchor their DEFAULT window to real data instead of wall-clock "last 30 days" (which is all-zero when the…
reports.bloOverview query authedProcedure KPIs (GMV/NMV/Orders/AOV), GMV-by-day, GMV-by-platform, GMV-by-category, GMV-by-source (self-sale vs affiliate), top creators.
reports.bloSku query authedProcedure Groups by the canonical 8-char SKU code (products.canonical_sku_code, falling back to the raw platform_sku_id when unmapped) and carries the product name — so a row reads "13121161 · Hộp 60 Miếng…
reports.bloCreator query authedProcedure The client's "CREATOR PERFORMANCE" dashboard (affiliate / KOC angle): • Source of contribution — GMV split Video vs Livestream (affiliate feed) • Top Creator Contribution — table of creators by…
reports.bloLivestream query authedProcedure The client's "INTERNAL LIVESTREAM PERFORMANCE" dashboard: • Performance by Day — Time/Duration have NO source in any client export → '—' (CLAUDE.md); only GMV/NMV/AOV/Cancelation are real.
reports.creatorDirectory query authedProcedure A long-horizon per-creator ROSTER (not a leaderboard): one row per (platform, creator) with money + activity over the selected period.

marketplaceapps/web/src/server/routers/marketplace.ts

Procedure Loại Base RBAC Mô tả
marketplace.overview query brandProcedure

exploreapps/web/src/server/routers/explore.ts

Procedure Loại Base RBAC Mô tả
explore.catalog query brandProcedure The widget/report metric picker.
explore.query query authedProcedure
explore.datasetCatalog query brandProcedure The dataset catalog for the widget picker.
explore.dataset query brandProcedure Resolve a dataset for a widget.
explore.audienceRecords query brandProcedure The RECORDS behind one clicked bar / heatmap cell / donut slice of an audience tile (G-RD, the delivered decks' one interaction).

brandCompareapps/web/src/server/routers/brand-compare.ts

Procedure Loại Base RBAC Mô tả
brandCompare.monthly query orgProcedure

Marketing performance (first-party)#

Chi tiêu quảng cáo, web/analytics, kênh sở hữu, lead và kế hoạch marketing của chính org.

marketingapps/web/src/server/routers/marketing.ts

Procedure Loại Base RBAC Mô tả
marketing.overview query brandProcedure
marketing.ads query brandProcedure Quảng cáo — per-platform + per-campaign breakdown, spend/CPC trends.
marketing.audit query brandProcedure Kiểm tra hiệu quả quảng cáo — the marketing AUDIT scan.
marketing.webSearch query brandProcedure Website & Tìm kiếm — GA4 + GSC owned-channel health.
marketing.kpi query brandProcedure Ngân sách & KPI — annual targets vs YTD actuals + time pacing (for MQL via computeMqlSummary; mode-gated when no targets).
marketing.kpiTargets.list query brandProcedure owner/org-admin
marketing.kpiTargets.upsert mutation rateLimitedBrandProcedure owner/org-admin
marketing.kpiTargets.remove mutation rateLimitedBrandProcedure owner/org-admin
marketing.businessKpi.list query brandProcedure owner/org-admin

leadsDiagnosticapps/web/src/server/routers/leads-diagnostic.ts

Procedure Loại Base RBAC Mô tả
leadsDiagnostic.plane query orgProcedure Which conversion plane the org measures on, resolved via the RLS-pinned ctx.activeOrgId — NOT session.user.activeOrgId, which is null for a super-admin viewing a tenant host.
leadsDiagnostic.spine query brandProcedure

marketingWebapps/web/src/server/routers/marketing-web.ts

Procedure Loại Base RBAC Mô tả
marketingWeb.website query brandProcedure
marketingWeb.engagement query brandProcedure
marketingWeb.monthlyUsers query brandProcedure
marketingWeb.seoMonthly query brandProcedure
marketingWeb.searchConsole query brandProcedure

marketingLeadsapps/web/src/server/routers/marketing-leads.ts

Procedure Loại Base RBAC Mô tả
marketingLeads.leadCrm query brandProcedure Lead CRM — non-junk MQL.
marketingLeads.leadMarketing query brandProcedure Lead Marketing — campaign-attributed responses (junk included, W-A2).

marketingSocialapps/web/src/server/routers/marketing-social.ts

Procedure Loại Base RBAC Mô tả
marketingSocial.socialPages query brandProcedure
marketingSocial.emailCampaigns query brandProcedure
marketingSocial.transactionalEmails query brandProcedure

marketingCampaignsapps/web/src/server/routers/marketing-campaigns.ts

Procedure Loại Base RBAC Mô tả
marketingCampaigns.list query brandProcedure
marketingCampaigns.detail query brandProcedure

planBindingsapps/web/src/server/routers/plan-bindings.ts

Procedure Loại Base RBAC Mô tả
planBindings.bindableMetrics query brandProcedure Metrics an operator may pick from, with the dimensions each supports.
planBindings.review query brandProcedure The review queue: every budget line covering today, its current binding state, and — for lines already measured — the actual it produces.
planBindings.suggest mutation rateLimitedBrandProcedure owner/org-admin Generate proposals for lines that have no binding yet.
planBindings.decide mutation rateLimitedBrandProcedure owner/org-admin Record an operator's decision on one line.
planBindings.remove mutation rateLimitedBrandProcedure owner/org-admin Drop a binding entirely, returning the line to "chưa map".
planBindings.setManualActual mutation rateLimitedBrandProcedure owner/org-admin Enter a manual actual/progress for a line the system cannot measure — the operator-owned counterpart to a binding (plan_line_actuals).
planBindings.clearManualActual mutation rateLimitedBrandProcedure owner/org-admin Remove a manual actual, returning the line to unmeasured.

Content intelligence#

Corpus hội thoại theo mention của khách hàng: taxonomy, insight và deck trình bày.

contentInsightsapps/web/src/server/routers/content-insights.ts

Procedure Loại Base RBAC Mô tả
contentInsights.capabilities query brandProcedure owner/org-admin What the current viewer may do, plus the org's Tier-2 allowance as the OrgLimit union — { kind: 'unlimited' } when no super admin ever set a cap.
contentInsights.deckDirection query brandProcedure The deck's HOUSE DIRECTION — read-only, for the widget config panel.
contentInsights.queue query brandProcedure The approval queue for the active dataset.
contentInsights.blockState query brandProcedure ONE BLOCK's publication state, for the widget that IS that block.
contentInsights.adoption query brandProcedure D4's ADOPTION METRIC — the share of narrative blocks left GENERATED versus human-LOCKED, per dataset.
contentInsights.requestGeneration mutation rateLimitedBrandProcedure owner/org-admin Ask for a Tier-2 draft.
contentInsights.regenerate mutation rateLimitedBrandProcedure owner/org-admin RE-GENERATE — ask the worker for a NEW PARKED DRAFT (D4/D6, two-column 0166).
contentInsights.createManual mutation rateLimitedBrandProcedure owner/org-admin AUTHOR A BLOCK BY HAND (D4's other half).
contentInsights.requestApproval mutation rateLimitedBrandProcedure owner/org-admin draft → pending_approval.
contentInsights.approve mutation rateLimitedBrandProcedure owner/org-admin pending_approval → published.
contentInsights.discardDraft mutation rateLimitedBrandProcedure owner/org-admin "HUỶ NHÁP" (0166) — throw the parked draft away, keep the live body intact.
contentInsights.retract mutation rateLimitedBrandProcedure owner/org-admin published → retracted.
contentInsights.editAndLock mutation rateLimitedBrandProcedure owner/org-admin EDIT-AND-LOCK.
contentInsights.revealEvidence mutation rateLimitedBrandProcedure owner/org-admin EXPLICIT PII REVEAL for evidence bodies.
contentInsights.recordLabelQuality mutation rateLimitedBrandProcedure D7 / ruling F3 — record the LABEL-QUALITY artifact on the dataset receipt.
contentInsights.labelQuality query brandProcedure D7, READ side — which of this corpus's dimensions sit under their own bar.
contentInsights.reflagStale mutation rateLimitedBrandProcedure owner/org-admin Re-flag every published block whose stored fact_pack_hash is no longer the one the reader resolves.

contentTaxonomyapps/web/src/server/routers/content-taxonomy.ts

Procedure Loại Base RBAC Mô tả
contentTaxonomy.list query brandProcedure owner/org-admin The whole catalog for the active dataset: dimensions, their vocabulary and their aliases, assembled without N+1 (parents limited, children via inArray).
contentTaxonomy.activeCorpusSpan query brandProcedure The org+brand's real corpus PERIODS, and which one a period surface opens on.
contentTaxonomy.listDatasets query brandProcedure Every dataset the org+brand owns, for the Studio's dataset bar and the upload dataset_key picker.
contentTaxonomy.createDataset mutation rateLimitedBrandProcedure owner/org-admin Register a new dataset — the FIRST thing a fresh org does, moved out of the onboarding CLI (D3, dataset registration is the sanctioned Studio path).
contentTaxonomy.listCloneSources query brandProcedure The clone picker's options: every dataset the ORG owns, plus its brands.
contentTaxonomy.cloneDataset mutation rateLimitedBrandProcedure owner/org-admin "Nhân bản từ bộ dữ liệu có sẵn" — register a new dataset by COPYING a delivered one's vocabulary onto a new brand (D3: client #6 adds zero TypeScript, ever).
contentTaxonomy.suggestValueMatches query brandProcedure Match SUGGESTIONS for one raw surface form — the last-resort diacritic-fold tier (D3 / content-alias.ts).
contentTaxonomy.createDimension mutation rateLimitedBrandProcedure owner/org-admin Add a dimension.
contentTaxonomy.seedDimensions mutation rateLimitedBrandProcedure owner/org-admin SEED the catalog from an approved mapping draft — the other half of "upload the file and the vocabulary exists".
contentTaxonomy.updateDimensionPresentation mutation rateLimitedBrandProcedure owner/org-admin PRESENTATION only — how the dimension reads, never what it counts.
contentTaxonomy.semanticEditDimension mutation rateLimitedBrandProcedure owner/org-admin SEMANTIC — kind / role / min_base / sparse_fill_floor_bp change what the dimension counts or when it abstains, so this is version N+1 + archive in one transaction.
contentTaxonomy.declareCrossPair mutation rateLimitedBrandProcedure owner/org-admin Declare (or re-activate) a cross-tab.
contentTaxonomy.archiveCrossPair mutation rateLimitedBrandProcedure owner/org-admin Retire a declared cross-tab.
contentTaxonomy.updateValuePresentation mutation rateLimitedBrandProcedure owner/org-admin Edit a value's PRESENTATION in place — label, the client-facing definition (definition_vi IS the glossary, D3), its token colour and order.
contentTaxonomy.addValue mutation rateLimitedBrandProcedure owner/org-admin SEMANTIC — a new value changes the vocabulary a corpus is counted against.
contentTaxonomy.confirmValue mutation rateLimitedBrandProcedure owner/org-admin SEMANTIC — promote a pending value into the confirmed vocabulary.
contentTaxonomy.rejectValue mutation rateLimitedBrandProcedure owner/org-admin SEMANTIC — take a value out of the counted vocabulary (never a DELETE: the tagged corpus keeps its text keys and the decision stays auditable).
contentTaxonomy.mergeValue mutation rateLimitedBrandProcedure owner/org-admin SEMANTIC — fold one value onto another: the source is marked merged and POINTS at the target through rollup_parent_value_id, so the fold is a readable edge rather than a lost row.
contentTaxonomy.upsertAlias mutation rateLimitedBrandProcedure owner/org-admin Record a raw surface form as a PENDING alias.
contentTaxonomy.confirmAlias mutation rateLimitedBrandProcedure owner/org-admin SEMANTIC — bind a pending alias to a value.
contentTaxonomy.rejectAlias mutation rateLimitedBrandProcedure owner/org-admin SEMANTIC — refuse a surface form.
contentTaxonomy.proposals query brandProcedure The current draft proposal set, as diffs against the LIVE catalog.
contentTaxonomy.requestProposals mutation rateLimitedBrandProcedure owner/org-admin Ask for a proposal set.

contentDecksapps/web/src/server/routers/content-decks.ts

Procedure Loại Base RBAC Mô tả
contentDecks.generateDeck mutation rateLimitedBrandProcedure owner/org-admin Generate the dataset's deck.
contentDecks.getPresentation query brandProcedure owner/org-admin READ the corpus's presentation document.
contentDecks.updatePresentation mutation rateLimitedBrandProcedure owner/org-admin PATCH the corpus's presentation document — the end of "CLI-only".
contentDecks.exportDeckBundle query rateLimitedBrandProcedure owner/org-admin EXPORT the corpus's whole declaration as one portable document.
contentDecks.importDeckBundle mutation rateLimitedBrandProcedure owner/org-admin RESTORE a bundle onto a corpus — dry run first, by design.
contentDecks.requestLayoutDraft mutation rateLimitedBrandProcedure owner/org-admin Ask for a CANDIDATE presentation document drafted from a described requirement.
contentDecks.layoutDraftState query brandProcedure owner/org-admin POLL one layout draft.
contentDecks.listPresentationTemplates query brandProcedure owner/org-admin The org's OWN corpora that already carry a presentation document — the decks a new report can be shaped after.

Data ingest & connectors#

Kết nối nguồn dữ liệu, credential dùng chung, upload file, mapping template, backfill, đối soát.

connectorsapps/web/src/server/routers/connectors.ts

Procedure Loại Base RBAC Mô tả
connectors.list query brandProcedure cap:manage_connectors Reads are gated the same as writes: connector config/health (which platforms are wired, sync state, settlement/live rollups) is org-admin material.
connectors.demoMode query brandProcedure cap:manage_connectors Connector presentation/demo posture for this org.
connectors.topologyProfile query brandProcedure Cosmetic topology metadata: which analytics surface the 2nd right-side output slot in the connector topology diagram represents.
connectors.setDemoMode mutation rateLimitedBrandProcedure Super-admin toggle for connector presentation mode.
connectors.enabledTypes query brandProcedure Connector-type gating for the "add connection" picker.
connectors.oauthCallbackUrls query brandProcedure cap:manage_connectors
connectors.testDraft mutation authedProcedure cap:manage_connectors Test credentials BEFORE the connector is saved (create-wizard gate).
connectors.authorizeUrl mutation authedProcedure cap:manage_connectors Build the seller-consent (OAuth) URL for the "Authorize" button.
connectors.ingestSourceSummary query brandProcedure cap:manage_connectors How orders were ingested: live API sync vs CSV/XLSX upload.
connectors.fileSources query brandProcedure cap:manage_connectors File intake sources — the CSV/XLSX uploads that carry a platform's data but own NO connector_credentials row, so list above cannot see them.
connectors.liveSummary query brandProcedure cap:manage_connectors LIVE-session performance rollup (live-room GMV + session count).
connectors.settlementSummary query brandProcedure cap:manage_connectors Finance/settlement rollup — net payout vs revenue vs fees per platform.
connectors.create mutation rateLimitedBrandProcedure cap:manage_connectors
connectors.updateLabel mutation rateLimitedBrandProcedure cap:manage_connectors
connectors.updateConfig mutation rateLimitedBrandProcedure cap:manage_connectors Update non-secret connector config — the sync cadence (config.syncIntervalMinutes + config.syncEnabled) plus the non-secret target ids (property/customer/account/… ids).
connectors.rotateSecret mutation rateLimitedBrandProcedure cap:manage_connectors
connectors.test mutation authedProcedure cap:manage_connectors
connectors.sniffSheetRange mutation authedProcedure cap:manage_connectors D5 — read the first few rows of a google-sheets binding range so the operator can author/preview a mapping template against REAL cells.
connectors.recentSyncJobs query brandProcedure cap:manage_connectors Recent sync jobs for a connector — powers the per-stream accounting panel: promoted/rejected + PII-safe reject samples per target stream, the sheets mirror of manual_upload_jobs.rejectedReasons.
connectors.delete mutation rateLimitedBrandProcedure cap:manage_connectors
connectors.dataInRange query brandProcedure cap:manage_connectors How many orders are ALREADY stored for this connector's platform in the selected ICT day window — powers the "this period already has data, syncing again may OVERWRITE it" confirm before a manual…
connectors.backfill mutation rateLimitedBrandProcedure cap:manage_connectors Operator-facing manual sync (incremental OR explicit ICT date-range backfill).

orgCredentialsapps/web/src/server/routers/org-credentials.ts

Procedure Loại Base RBAC Mô tả
orgCredentials.list query brandProcedure cap:manage_connectors List saved identities with the number of connectors linked to each.
orgCredentials.create mutation rateLimitedBrandProcedure cap:manage_connectors
orgCredentials.rename mutation rateLimitedBrandProcedure cap:manage_connectors
orgCredentials.setActive mutation rateLimitedBrandProcedure cap:manage_connectors
orgCredentials.rotate mutation rateLimitedBrandProcedure cap:manage_connectors Re-encrypt a NEW payload onto the SAME row — every linked connector picks it up on next decrypt.
orgCredentials.remove mutation rateLimitedBrandProcedure cap:manage_connectors Blocked while any connector references the identity.

connectorBackfillapps/web/src/server/routers/connector-backfill.ts

Procedure Loại Base RBAC Mô tả
connectorBackfill.request mutation rateLimitedOrgProcedure cap:manage_connectors Request a bounded re-pull for a connector across one or more streams.
connectorBackfill.list query orgProcedure cap:manage_connectors A connector's most recent runs (newest first, capped at 50 — plan A1.5).
connectorBackfill.get query orgProcedure cap:manage_connectors A single run (for polling one run's live progress).
connectorBackfill.cancel mutation rateLimitedOrgProcedure cap:manage_connectors Cooperative cancel — flips cancel_requested; the worker skips the remaining slices.

pipelineapps/web/src/server/routers/pipeline.ts

Procedure Loại Base RBAC Mô tả
pipeline.overview query authedProcedure High-level topology + counts per stage.
pipeline.connectorsHealth query authedProcedure Connector-level health: watermark, last sync, throughput since.
pipeline.activity query brandProcedure Hourly activity by stream for the last N hours — for a small sparkline grid.
pipeline.recentSyncs query brandProcedure Recent sync runs — the ticker for the pipeline page.
pipeline.deadLetters query brandProcedure owner/org-admin Dead-letter queue page.
pipeline.pauseConnector mutation rateLimitedBrandProcedure cap:manage_connectors

manualUploadsapps/web/src/server/routers/manual-uploads.ts

Procedure Loại Base RBAC Mô tả
manualUploads.schemas query brandProcedure Schema metadata for every upload type — required and optional column aliases, plus a hint.
manualUploads.template query brandProcedure Returns a starter CSV containing just the header row + an empty placeholder, so users can fill it in their spreadsheet and re-upload.
manualUploads.list query brandProcedure Recent uploads for the table.
manualUploads.get query brandProcedure
manualUploads.download query brandProcedure cap:manage_data_pipeline Re-download the exact bytes an operator uploaded, when still in the system.
manualUploads.upload mutation rateLimitedBrandProcedure cap:manage_data_pipeline
manualUploads.uploadTemplated mutation rateLimitedBrandProcedure cap:manage_data_pipeline Wave 3 — templated upload.

validationapps/web/src/server/routers/validation.ts

Procedure Loại Base RBAC Mô tả
validation.datasets query brandProcedure Dataset catalog + per-dataset availability: a dataset is runnable only when the org has an active import mapping template for its source_kind (the same template real uploads use — that's what…
validation.peekRange mutation rateLimitedBrandProcedure cap:manage_reports Peek an uploaded file WITHOUT creating a run: auto-detect WHICH dataset it is (each platform/stream export has a distinct date-column header) and the file's own MIN/MAX placed_at (ICT), so the UI…
validation.createRun mutation rateLimitedBrandProcedure cap:manage_reports
validation.listRuns query brandProcedure
validation.getRun query brandProcedure
validation.dayDiffs query brandProcedure
validation.deleteRun mutation rateLimitedBrandProcedure cap:manage_reports Delete a run + all associated diffs.
validation.orderDiffs query brandProcedure

categoriesapps/web/src/server/routers/categories.ts

Procedure Loại Base RBAC Mô tả
categories.list query orgProcedure owner/org-admin Canonical categories + their platform mappings + SKU rules, assembled without N+1 (parents limited, children fetched via inArray).
categories.platforms query orgProcedure
categories.autoMap mutation rateLimitedOrgProcedure owner/org-admin One-click bootstrap: create the canonical categories + SKU-code rules from the client decoder defaults.
categories.create mutation rateLimitedOrgProcedure owner/org-admin
categories.update mutation rateLimitedOrgProcedure owner/org-admin
categories.remove mutation rateLimitedOrgProcedure owner/org-admin
categories.upsertMapping mutation rateLimitedOrgProcedure owner/org-admin
categories.removeMapping mutation rateLimitedOrgProcedure owner/org-admin
categories.upsertRule mutation rateLimitedOrgProcedure owner/org-admin SKU-code → category rule (the editable client decoder).
categories.removeRule mutation rateLimitedOrgProcedure owner/org-admin

shopAliasesapps/web/src/server/routers/shop-aliases.ts

Procedure Loại Base RBAC Mô tả
shopAliases.platforms query orgProcedure
shopAliases.list query orgProcedure owner/org-admin
shopAliases.distinctShops query orgProcedure owner/org-admin Distinct (platform, platform_shop_id) actually present in orders, with order counts — so the UI can offer the operator the real raw/canonical ids to map instead of free-typing them.
shopAliases.upsert mutation rateLimitedOrgProcedure owner/org-admin
shopAliases.remove mutation rateLimitedOrgProcedure owner/org-admin

importTemplatesapps/web/src/server/routers/import-templates.ts

Mapping templates router.

Procedure Loại Base RBAC Mô tả
importTemplates.list query brandProcedure List all templates the user can see.
importTemplates.catalog query brandProcedure Catalog of canonical streams + their target fields.
importTemplates.installStarterPack mutation rateLimitedBrandProcedure cap:manage_org_settings Install every mapping template this org can be given without authoring one — ONE affordance, two derivations: • the product's vendor pack, filtered to the connector families the org runs…
importTemplates.upsertVersion mutation rateLimitedBrandProcedure cap:manage_org_settings
importTemplates.cloneToBrand mutation rateLimitedOrgProcedure cap:manage_org_settings Clone one brand's ACTIVE content_mention mapping template onto ANOTHER brand of the same org — the mapping half of "onboard client #6 from client #3's template" (the taxonomy half is…
importTemplates.preview mutation rateLimitedBrandProcedure Preview parse — runs the spec against the first 50 rows of an uploaded sample, returning normalized rows so the wizard can show "this is what your CSV will look like in canonical form" before…
importTemplates.sniffHeaders mutation rateLimitedBrandProcedure Header sniff — accepts a sample upload, returns the parsed header columns so the wizard can render the source-side dropdowns.
importTemplates.stats query brandProcedure Stats: how many staging rows queued / promoted / rejected per template.
importTemplates.previewRows mutation rateLimitedBrandProcedure D5 — preview a template against REAL sheet cells (the authoring-time guard that catches sheet-locale vs template-separator mismatch).
importTemplates.sampleFile query brandProcedure D4 — generate the customer's file template: a CSV whose header row is the mapping template's expected source columns (the export→upload artifact, or the target shape for their Google Sheet).

Market intelligence (third-party estimates)#

Mặt phẳng ước lượng thị trường và mạng xã hội — tách khỏi cổng đối soát dữ liệu 1st-party và không cấp cho chat.

marketIntelapps/web/src/server/routers/market-intel.ts

Procedure Loại Base RBAC Mô tả
marketIntel.trendSeries query brandProcedure Market trajectory per estimate window + own GMV/NMV overlay (org basis).
marketIntel.creatorMomentum query brandProcedure Creator momentum across windows: leaders, risers, newcomers.
marketIntel.productOpportunities query brandProcedure Market product list joined to own catalog: whitespace + weekly momentum.
marketIntel.comboLeaderboard query brandProcedure Top combo RECIPES + listings in the category market, by revenue (3p_derived, to_validate).
marketIntel.priceBands query brandProcedure Revenue distribution across fixed VND price bands per window + own-median band marker — "cơ cấu bậc giá" (is the market trading up into premium?).
marketIntel.launchVelocity query brandProcedure Recently-launched market products accelerating by revenue slope — the earliest competitive signal.
marketIntel.freshness query brandProcedure Most-recent snapshot capture for the platform — the staleness badge input.
marketIntel.competitorTrends query brandProcedure Competitor ranking movement across windows: top series, movers, entrants.
marketIntel.watchlistCard query brandProcedure "Danh sách theo dõi" card: latest weekly value + delta per watched entity.
marketIntel.signals query authedProcedure Tier-ranked "what changed this week" signals (estimates).
marketIntel.ingestExport mutation rateLimitedBrandProcedure owner/org-admin Ingest one Creator Commerce XLSX export (base64).
marketIntel.ingestShopeeJson mutation rateLimitedBrandProcedure owner/org-admin Ingest the Creator Commerce SHOPEE product-ranking JSON bundle (base64).
marketIntel.deleteSnapshot mutation rateLimitedBrandProcedure owner/org-admin Remove one snapshot (children cascade).
marketIntel.creatorClassification query brandProcedure "Phân loại nhà sáng tạo" — the classification review queue.
marketIntel.setCreatorTypeOverride mutation rateLimitedBrandProcedure owner/org-admin Record the human classification for one or many creators (Layer 2).
marketIntel.clearCreatorTypeOverride mutation rateLimitedBrandProcedure owner/org-admin Drop the human classification and fall back to the machine's opinion.
marketIntel.snapshots query brandProcedure Ingested snapshots, newest first — the admin "what data do we have".
marketIntel.periods query brandProcedure Available estimate windows (for the period picker), newest first.
marketIntel.platforms query brandProcedure Which marketplaces have ingested market data (drives the platform tab).
marketIntel.livestream query brandProcedure LIVESTREAM surface: the category's live-selling landscape for the latest ingested window — top live sessions by GMV, the creators driving live GMV, SHORT-vs-LONG cadence, live GPM efficiency, and…
marketIntel.overview query brandProcedure The market view for one estimate window: K1 position + category drill, K2 competitors (leaders + same-segment peers), products, creators, and the own-affiliate reconciliation.
marketIntel.decomposition query brandProcedure The expert SPINE: GMV/NMV = Traffic × ConversionRate × AOV, window-over-window, attributed via LMDI.
marketIntel.diagnosticScan query brandProcedure Multi-domain diagnostic SCAN — Beat 1's hero.
marketIntel.demandShift query brandProcedure Demand-shift signal — "cầu dịch về ngách X, mix mày lệch".
marketIntel.bundleAnalysis query brandProcedure Bundle / combo analysis — own combo % MEASURED from real 1P sales + market best-seller combo share DERIVED from titles (3p_derived, to_validate — Kalodata has no order baskets, so NEVER "X% of…
marketIntel.platformContribution query brandProcedure Platform contribution (— multi-sàn "vì sao").
marketIntel.leverSweep query brandProcedure Commercial lever SWEEP (→ S1): after the spine localises the move, sweep ~10 e-commerce levers and flag ONLY the real culprit (s).
marketIntel.benchmarkTriad query brandProcedure Benchmark TRIAD (→ S2): nothing is read in isolation.
marketIntel.socialPanel query brandProcedure SOCIAL panel (4 / → S1, the "social last" step).
marketIntel.socialReport query brandProcedure SocialHeat REPORT plane (§F10 / D3) — the 3-question social panel of the diagnostic report.
marketIntel.socialBuzzComposition query brandProcedure Weekly buzz COMPOSITION — what the 3rd-party conversation is made of, split by the 5 component levers (post / object_mention / online_seller / owned_media / consulting), for a stacked-area "what…
marketIntel.competitors.list query brandProcedure Active watchlist for the brand + sàn.
marketIntel.competitors.suggestions query brandProcedure Ranked competitor SUGGESTIONS from the brand's category-scoped Kalodata shop history + 1P profile, excluding the own shop and any already-listed or dismissed shop.
marketIntel.competitors.searchShops query brandProcedure Search the category-scoped Kalodata shops by name (manual add).
marketIntel.competitors.add mutation rateLimitedBrandProcedure Add (or re-activate) a shop on the watchlist — accept a suggestion or a manual pick.
marketIntel.competitors.dismiss mutation rateLimitedBrandProcedure owner/org-admin Dismiss a suggestion — keep a row marked dismissed so it is never re-suggested.
marketIntel.competitors.remove mutation rateLimitedBrandProcedure owner/org-admin Remove a shop from the watchlist entirely (it may be suggested again).
marketIntel.watchedCreators.list query brandProcedure Active watched-creator list for the brand + sàn.
marketIntel.watchedCreators.search query brandProcedure Search the estimate-plane creators by handle or name (manual add).
marketIntel.watchedCreators.add mutation rateLimitedBrandProcedure Add (or re-activate) a creator on the watchlist — a manual pick or an accepted suggestion.
marketIntel.watchedCreators.remove mutation rateLimitedBrandProcedure Remove a creator from the watchlist entirely (it may be searched/added again).
marketIntel.settings query brandProcedure Org-level Market Intelligence comparison basis (GMV default | NMV).
marketIntel.updateDemoMask mutation rateLimitedBrandProcedure Toggle the org-level demo identity-masking posture — SUPER ADMIN ONLY.
marketIntel.updateComparisonBasis mutation rateLimitedBrandProcedure owner/org-admin Set the org-level comparison basis (owner / org-admin only).
marketIntel.enabledMarketDataConnectors query brandProcedure Market-data (market_intel family) connector plugins that are effectively enabled for this org — drives the "3rd-party data sources" surface on /connectors and the source picker in the MI data…
marketIntel.marketDataConnector query brandProcedure The 3rd-party market feed (Kalodata internally; "Creator Commerce" to users).
marketIntel.saveMarketDataConnector mutation rateLimitedBrandProcedure owner/org-admin
marketIntel.testMarketDataConnector mutation authedProcedure owner/org-admin Validate connectivity with one cheap category/rank call.
marketIntel.getInsightConfig query brandProcedure
marketIntel.updateInsightConfig mutation rateLimitedBrandProcedure owner/org-admin Save the org's AI-Insight configuration (owner / org-admin only).
marketIntel.insightStatus query brandProcedure Whether the AI insight is available for this org: an AI plugin (catalog category 'ai_decision') must be ENABLED for the org AND an AI provider must be configured.
marketIntel.insight query brandProcedure Cached AI narrative for a window, or null while (re)generating.
marketIntel.requestInsight mutation rateLimitedBrandProcedure Generate the AI market narrative: the prompt carries ONLY numbers the overview already computed (the model narrates, never invents —).

socialListeningapps/web/src/server/routers/social-listening.ts

Procedure Loại Base RBAC Mô tả
socialListening.report query orgProcedure

socialTrendsapps/web/src/server/routers/social-trends.ts

Procedure Loại Base RBAC Mô tả
socialTrends.latestRanking query orgProcedure Most recent snapshot, ordered by rank, with rank movement vs the previous snapshot computed from two bounded reads (no cartesian join).
socialTrends.rankingHistory query orgProcedure Buzz + best rank over the last days ICT ranking days for one topic.
socialTrends.topicPosts query orgProcedure Top posts for a topic, ranked by engagement (nulls last).: buyer PII is not present here — these are public social posts stored verbatim.
socialTrends.dailyTopTopics query orgProcedure Per ICT ranking day, the day's #1 (best-rank) topic + its buzz over the [from,to] window — the summary that backs the period picker.

Decisions & learning loop#

Vòng học off-take: đề xuất → duyệt → thực thi → đo lường → bài học.

offtakeapps/web/src/server/routers/offtake.ts

Procedure Loại Base RBAC Mô tả
offtake.signals query orgProcedure Social conversation (SocialHeat, 3rd-party) — all-brands weekly conversation per lever, the INPUT the off-take loop learns from.
offtake.decisions query orgProcedure Decision Memory (historical) + Inbox (proposed) + outcomes, all brands.
offtake.trackRecord query orgProcedure Track record (calibration): hit-rate by confidence bucket.
offtake.experimentsList query orgProcedure L3 incrementality experiments (experiments.readout, read-only list).
offtake.episodes query orgProcedure The DECISION LEDGER timeline — read-only.
offtake.playbookStats query orgProcedure Tier-1 track record per playbook × segment — the REBUILDABLE cache over the ledger, read-only here (the worker owns the rebuild).
offtake.confirmOutcome mutation rateLimitedOrgProcedure owner/org-admin Owner-confirm a measured verdict (hit/partial/miss).
offtake.approveLesson mutation rateLimitedOrgProcedure owner/org-admin Owner BLESSES the lesson from a measured decision — the lesson "enters the system" (becomes knowledge the loop carries forward) ONLY through this action, separate from the verdict.
offtake.approve mutation rateLimitedOrgProcedure owner/org-admin Govern gate → approve a proposed decision (1-click) + emit action_commands.
offtake.reject mutation rateLimitedOrgProcedure owner/org-admin Owner SKIPS a proposed decision ("Bỏ qua") — it never runs, so it gets no outcome, but it stays in the ledger as a real "đã từ chối" record (so the track-record honestly shows what was offered vs…
offtake.markExecuted mutation rateLimitedOrgProcedure owner/org-admin Owner marks an APPROVED decision as EXECUTED on a real start date: status → 'activated', anchor the review window to executionStartDate + horizon (ICT).
offtake.cancel mutation rateLimitedOrgProcedure owner/org-admin Owner/admin UN-RUNs an approved/activated decision — returns it to the Decision Inbox ('proposed') so it can be re-decided or skipped.
offtake.settings query orgProcedure The decision-loop measurement standards for THIS org: verdict tolerance (TRÚNG/LỆCH VỪA/TRƯỢT), diagnostic-scan severity (vàng/đỏ), and the off-take cold-start gate.
offtake.updateSettings mutation rateLimitedOrgProcedure owner/org-admin
offtake.policyRecommend query orgProcedure Recommend the next lever per brand (spec policy.recommend).
offtake.governanceStatus query orgProcedure L5 governance — System-Health read (L5 DoD).

msoPlaybooksapps/web/src/server/routers/mso-playbooks.ts

Procedure Loại Base RBAC Mô tả
msoPlaybooks.list query orgProcedure The org's playbook library (DB rows; falls back to code defaults when empty).
msoPlaybooks.upsert mutation rateLimitedOrgProcedure owner/org-admin Create or edit a playbook (by org+slug).
msoPlaybooks.remove mutation rateLimitedOrgProcedure owner/org-admin Retire a playbook.
msoPlaybooks.suggestRule mutation authedProcedure owner/org-admin Ask the model to structure an expert's prose into a rule SHAPE (thresholds blank).
msoPlaybooks.saveRuleDraft mutation rateLimitedOrgProcedure owner/org-admin Store a human-completed candidate as status:'draft' — reviewable, NOT live.
msoPlaybooks.activateRule mutation rateLimitedOrgProcedure owner/org-admin The ONLY path that makes an authored rule LIVE.
msoPlaybooks.rulePreview query orgProcedure owner/org-admin Dry-run a candidate against the org's OWN recorded signal panels, so the author sees what WOULD have matched before activating.
msoPlaybooks.simulateDraft query orgProcedure owner/org-admin Chạy thử NGAY một luật CHƯA LƯU trên dữ liệu thật — the loop-closer for authoring: AI drafts → human sets thresholds → simulate on real ad data → activate.
msoPlaybooks.simulate query orgProcedure owner/org-admin Chạy thử — replay ONE playbook's rule over an operator-chosen ICT window, against the org's own recorded ad data, and return the machine receipt for every entity the rule was eligible on.
msoPlaybooks.scanAndPropose mutation rateLimitedOrgProcedure owner/org-admin Quét & tạo đề xuất — turn marketing-audit findings into MEASURABLE proposed decisions in the inbox (the revised D4).
msoPlaybooks.seedDefaults mutation rateLimitedOrgProcedure owner/org-admin One-click: materialise the code defaults into editable DB rows for this org.

AI & chat#

Data Assistant, cấu hình AI per-org, prompt registry.

aiConfigsapps/web/src/server/routers/ai-configs.ts

Procedure Loại Base RBAC Mô tả
aiConfigs.listConnections query orgProcedure Ordered list of the org's AI connections (primary first).
aiConfigs.saveByokAndEnable mutation rateLimitedOrgProcedure cap:manage_ai Save a usable organisation chain and enable BYOK in the SAME transaction.
aiConfigs.getOrganizationSettings query orgProcedure cap:manage_ai Effective source plus safe platform metadata; encrypted material is never projected.
aiConfigs.useInherited mutation rateLimitedOrgProcedure cap:manage_ai Return to platform defaults without deleting the organisation's encrypted BYOK rows.
aiConfigs.testConnection mutation authedProcedure cap:manage_ai
aiConfigs.listModels mutation authedProcedure cap:manage_ai
aiConfigs.usageThisMonth query orgProcedure

platformAiConfigsapps/web/src/server/routers/ai-configs.ts

Global platform default chain.

Procedure Loại Base RBAC Mô tả
platformAiConfigs.listConnections query superAdminProcedure super-admin
platformAiConfigs.saveConnections mutation superAdminProcedure super-admin
platformAiConfigs.testConnection mutation superAdminProcedure super-admin
platformAiConfigs.listModels mutation superAdminProcedure super-admin

aiPromptsapps/web/src/server/routers/ai-prompts.ts

Procedure Loại Base RBAC Mô tả
aiPrompts.list query orgProcedure List all override rows for the active org.
aiPrompts.upsert mutation rateLimitedOrgProcedure cap:manage_ai Upsert a single (slot, industry) override.
aiPrompts.reset mutation rateLimitedOrgProcedure cap:manage_ai Delete a (slot, industry) override row, restoring the built-in default for that slot.
aiPrompts.preview query orgProcedure Render the full effective prompt (system + role) using the current overrides — no caching, no mutation.
aiPrompts.test mutation authedProcedure cap:manage_ai Send the rendered prompt to the org's configured model and return the model's response, latency, and token usage.
aiPrompts.defaults query orgProcedure Read-only: defaults bundle for the admin UI.

chatapps/web/src/server/routers/chat.ts

Procedure Loại Base RBAC Mô tả
chat.listConversations query chatProcedure plugin chat-with-data + org-admin List active conversations for the current brand + user, newest first.
chat.getConversation query chatProcedure plugin chat-with-data + org-admin Fetch one conversation with its full message history.
chat.createConversation mutation rateLimitedChatProcedure Create a new (empty) conversation; messages are appended by /api/chat.
chat.renameConversation mutation rateLimitedChatProcedure Rename a conversation.
chat.deleteConversation mutation rateLimitedChatProcedure Archive (soft-delete) a conversation.

chatAssistantapps/web/src/server/routers/chat-assistant.ts

Procedure Loại Base RBAC Mô tả
chatAssistant.getSettings query orgProcedure owner/admin Read the org's chat-assistant settings (owner / admin / super).
chatAssistant.updateSettings mutation rateLimitedOrgProcedure owner/admin Save the org's chat-assistant settings (owner / admin / super).

Platform admin#

Bề mặt super-admin cross-org, cấu hình nền tảng, giao diện, dữ liệu org và sao lưu.

apiTokensapps/web/src/server/routers/api-tokens.ts

Procedure Loại Base RBAC Mô tả
apiTokens.list query orgProcedure cap:manage_org_settings
apiTokens.create mutation rateLimitedOrgProcedure cap:manage_org_settings
apiTokens.revoke mutation rateLimitedOrgProcedure cap:manage_org_settings

adminapps/web/src/server/routers/admin.ts

Procedure Loại Base RBAC Mô tả
admin.overview query superAdminProcedure super-admin
admin.listOrganizations query superAdminProcedure super-admin
admin.organizationAiStatus query superAdminProcedure super-admin A cross-org ai_configs scan is denied by the real NOBYPASSRLS app role.
admin.createOrganization mutation superAdminProcedure super-admin
admin.applyBlueprint mutation superAdminProcedure super-admin Re-apply a provisioning blueprint to an EXISTING org (D1 / 0015 S3).
admin.updateOrganization mutation superAdminProcedure super-admin
admin.tenantConfig query superAdminProcedure super-admin The tenant base domain (msocloud.net in prod, localhost in dev) is read from the server env so the UI never hardcodes it — it drives the &lt;sub>.&lt;base> suffix + the CNAME target the customer…
admin.listOrgDomains query superAdminProcedure super-admin Every white-label domain row for an org (org-scoped RLS → withOrgContext).
admin.addOrgDomain mutation superAdminProcedure super-admin Register a customer-owned white-label domain.
admin.verifyOrgDomain mutation superAdminProcedure super-admin Run the two DNS checks (ownership TXT + reachability CNAME/A) and record the outcome.
admin.removeOrgDomain mutation superAdminProcedure super-admin
admin.listPlugins query superAdminProcedure super-admin MSO Cloud compiles a fixed plugin catalog into the build (@yng/plugin-host PLUGIN_REGISTRY).
admin.togglePlugin mutation superAdminProcedure super-admin
admin.toggleOrgLdap mutation superAdminProcedure super-admin LDAP is a per-org ENTITLEMENT, not a plugin: org_auth_ldap.enabled is set ONLY here.
admin.getOrgLdapStatus query superAdminProcedure super-admin Super-admin read of an org's LDAP entitlement + whether it is configured.
admin.mintMcpToken mutation superAdminProcedure super-admin MCP server (apps/mcp-server) uses these tokens to call /api/mcp/* on behalf of an org.
admin.listMcpTokens query superAdminProcedure super-admin
admin.revokeMcpToken mutation superAdminProcedure super-admin
admin.deleteOrganization mutation superAdminProcedure super-admin
admin.listUsers query superAdminProcedure super-admin
admin.listOrgBrands query superAdminProcedure super-admin Assignable brands of ONE org, for the membership brand-scope picker.
admin.listRolePolicies query superAdminProcedure super-admin
admin.rolePolicyCatalog query superAdminProcedure super-admin
admin.updateRolePolicy mutation superAdminProcedure super-admin
admin.setOrgMenuOrder mutation superAdminProcedure super-admin Bulk hide/show a menu item across EVERY role in an org with a single call.
admin.getOrgMenuOrder query superAdminProcedure super-admin Returns the current per-org sidebar order.
admin.setOrgMenuLabels mutation superAdminProcedure super-admin Per-org sidebar LABEL overrides — super-admin renames nav items whose default i18n label isn't friendly for a tenant.
admin.getOrgMenuLabels query superAdminProcedure super-admin Current per-org label overrides.
admin.setOrgMenuGroupOrder mutation superAdminProcedure super-admin Per-org sidebar GROUP order — super-admin reorders the section blocks in the sidebar.
admin.getOrgMenuGroupOrder query superAdminProcedure super-admin
admin.bulkSetMenuItemVisibility mutation superAdminProcedure super-admin
admin.upsertMembership mutation superAdminProcedure super-admin
admin.updateMembershipRole mutation superAdminProcedure super-admin
admin.removeMembership mutation superAdminProcedure super-admin
admin.updateUserAccount mutation superAdminProcedure super-admin
admin.setUserPassword mutation superAdminProcedure super-admin
admin.resendUserInvitation mutation superAdminProcedure super-admin
admin.deleteUserAccount mutation superAdminProcedure super-admin
admin.toggleSuperAdmin mutation superAdminProcedure super-admin
admin.orgSnapshot query superAdminProcedure super-admin
admin.connectorMedallion query superAdminProcedure super-admin Per-connector medallion (Bronze → Silver → Gold) status for an org.
admin.systemHealth query superAdminProcedure super-admin Deployment-wide infrastructure health for the /admin/health page.
admin.orgHealth query superAdminProcedure super-admin Per-org operational health: durable-job backlog, open dead-letters, and recent sync-job failures.
admin.triggerConnectorSync mutation superAdminProcedure super-admin Manually enqueue a one-shot sync for a connector.
admin.listAuditLogs query superAdminProcedure super-admin
admin.browseTable query superAdminProcedure super-admin
admin.orgDataScope query superAdminProcedure super-admin Which browse tables (and data planes) the DEFAULT view for orgId should lead with.
admin.sampleDataStatus query superAdminProcedure super-admin Lightweight probe used by the /admin/data sample-data panel to decide which buttons to render.
admin.seedSampleData mutation superAdminProcedure super-admin Sample-data lifecycle — surfaced as buttons on /admin/data so super-admins can re-seed for demos or wipe before a customer presentation without shelling into the host.
admin.removeSampleData mutation superAdminProcedure super-admin

notificationSettingsapps/web/src/server/routers/notification-settings.ts

Procedure Loại Base RBAC Mô tả
notificationSettings.list query superAdminProcedure super-admin Every notification type, with its effective policy and its defaults.
notificationSettings.upsert mutation superAdminProcedure super-admin
notificationSettings.reset mutation superAdminProcedure super-admin Drop the override and fall back to the shipped default for this rule.

siteIdentityapps/web/src/server/routers/site-identity.ts

Procedure Loại Base RBAC Mô tả
siteIdentity.get query publicProcedure Public read — chrome of every page depends on this.
siteIdentity.getForAdmin query superAdminProcedure super-admin Super-admin read includes the audit metadata.
siteIdentity.update mutation superAdminProcedure super-admin
siteIdentity.setTokenRefreshDisabled mutation superAdminProcedure super-admin Super-admin kill-switch for OAuth token refresh.

appearanceapps/web/src/server/routers/appearance.ts

Procedure Loại Base RBAC Mô tả
appearance.list query superAdminProcedure super-admin Built-ins + custom rows of ONE cohort + the active slug.
appearance.get query superAdminProcedure super-admin A single skin (built-in, or a custom row of the addressed cohort).
appearance.create mutation superAdminProcedure super-admin
appearance.update mutation superAdminProcedure super-admin
appearance.delete mutation superAdminProcedure super-admin
appearance.activate mutation superAdminProcedure super-admin
appearance.exportThemes mutation superAdminProcedure super-admin Export the selected skins (built-in or custom) as ONE versioned bundle.
appearance.importThemes mutation superAdminProcedure super-admin Import an untrusted bundle into the PLATFORM cohort, or (with orgId) into one org's own catalogue.
appearance.selfList query orgProcedure owner/org-admin This org's OWN skins.
appearance.selfCreateTheme mutation rateLimitedOrgProcedure owner/org-admin
appearance.selfUpdateTheme mutation rateLimitedOrgProcedure owner/org-admin
appearance.selfDeleteTheme mutation rateLimitedOrgProcedure owner/org-admin
appearance.selfExportThemes mutation rateLimitedOrgProcedure owner/org-admin Export this org's own skins (or any built-in) as the SAME yng-theme-bundle the platform console produces — the bundle schema is palette-only and knows nothing about ownership.
appearance.selfImportThemes mutation rateLimitedOrgProcedure owner/org-admin Import a bundle as THIS ORG'S OWN skins — same mechanics as the platform importer (importBundleIntoCohort), only the cohort differs.

orgDataapps/web/src/server/routers/org-data.ts

Procedure Loại Base RBAC Mô tả
orgData.planPreview query superAdminProcedure super-admin The backup SCOPE PREVIEW: which data groups this org has, how much is in each, and which of them belong to the planes this tenant actually runs.
orgData.backupRequest mutation superAdminProcedure super-admin Enqueue a category-scoped backup.
orgData.jobs query superAdminProcedure super-admin Recent backup/restore jobs, newest first (capped at 50 — plan B5).
orgData.restoreIdentityPreview query superAdminProcedure super-admin Does an into_same_org restore of this artifact need the operator to say how row identities are handled?
orgData.job query superAdminProcedure super-admin A single job (poll one job's live progress).
orgData.downloadUrl mutation superAdminProcedure super-admin Mint a short-lived (≤15m) presigned download URL for a completed backup artifact.
orgData.deleteArtifact mutation superAdminProcedure super-admin Delete only terminal, non-retrying states, and require the physical object cleanup to succeed.
orgData.restoreRequest mutation superAdminProcedure super-admin Enqueue a restore from a completed backup artifact (plan B4/B6, phase B-3).
orgData.cancel mutation superAdminProcedure super-admin Cancel a job before the worker has picked it up.
orgData.selfPlanPreview query orgProcedure owner/org-admin The org's OWN scope preview — the same three facts Admin CP resolves (groups, sizes, relevance), for the tenant the caller is in.
orgData.selfJobList query orgProcedure owner/org-admin
orgData.selfBackupRequest mutation rateLimitedOrgProcedure owner/org-admin
orgData.selfArtifactDownload mutation authedProcedure owner/org-admin Presigned download of the caller's OWN artifact — org-scoped twin of downloadUrl.
orgData.selfDeleteArtifact mutation authedProcedure owner/org-admin Delete one of the caller's own terminal jobs + its object (org-scoped twin of deleteArtifact, same restore-the-row-on-storage-failure contract).
orgData.selfRestoreRequest mutation rateLimitedOrgProcedure owner/org-admin DESTRUCTIVE, and deliberately the narrowest of the five: same-org only, own artifact only, never an imported one, slug typed back.

orgBackupConfigapps/web/src/server/routers/org-backup-config.ts

Procedure Loại Base RBAC Mô tả
orgBackupConfig.schedules query superAdminProcedure super-admin Super admin — names the org.
orgBackupConfig.scheduleUpsert mutation superAdminProcedure super-admin
orgBackupConfig.scheduleDelete mutation superAdminProcedure super-admin
orgBackupConfig.destinations query superAdminProcedure super-admin
orgBackupConfig.destinationCreate mutation superAdminProcedure super-admin
orgBackupConfig.destinationDelete mutation superAdminProcedure super-admin
orgBackupConfig.destinationTest mutation superAdminProcedure super-admin
orgBackupConfig.selfSchedules query orgProcedure owner/org-admin The org's own — cannot name another org.
orgBackupConfig.selfScheduleUpsert mutation rateLimitedOrgProcedure owner/org-admin
orgBackupConfig.selfScheduleDelete mutation rateLimitedOrgProcedure owner/org-admin
orgBackupConfig.selfDestinations query orgProcedure owner/org-admin
orgBackupConfig.selfDestinationCreate mutation rateLimitedOrgProcedure owner/org-admin
orgBackupConfig.selfDestinationDelete mutation rateLimitedOrgProcedure owner/org-admin
orgBackupConfig.selfDestinationTest mutation rateLimitedOrgProcedure owner/org-admin

orgMenuapps/web/src/server/routers/org-menu.ts

Procedure Loại Base RBAC Mô tả
orgMenu.get query orgProcedure One call for the menu editor: the org's current override blobs + the catalog it needs to render controls (renamable nav item ids with their effective default labels, and the sidebar group…
orgMenu.setLabels mutation rateLimitedOrgProcedure
orgMenu.setOrder mutation rateLimitedOrgProcedure
orgMenu.setGroupOrder mutation rateLimitedOrgProcedure
orgMenu.setHiddenItems mutation rateLimitedOrgProcedure
orgMenu.setPinnedDashboards mutation rateLimitedOrgProcedure Pin up to 8 saved dashboards into the sidebar.
orgMenu.setCustomNavItems mutation rateLimitedOrgProcedure Promote org-created dashboards to real menu items.

orgBlueprintsapps/web/src/server/routers/org-blueprints.ts

Read-only listing of the compiled workspace-blueprint registry for the /admin/orgs create-org form.

Procedure Loại Base RBAC Mô tả
orgBlueprints.list query superAdminProcedure super-admin

Chia sẻ & public#

Share link dashboard/báo cáo và bề mặt public không cần đăng nhập.

sharesapps/web/src/server/routers/shares.ts

Procedure Loại Base RBAC Mô tả
shares.listAll query brandProcedure All shares of a type the caller's org owns, newest first — drives the per-type management page.
shares.listForResource query brandProcedure Shares for a single resource — drives the per-resource share panel/dialog.
shares.create mutation rateLimitedBrandProcedure
shares.update mutation rateLimitedBrandProcedure Rename + reset expiry.
shares.setPassword mutation rateLimitedBrandProcedure
shares.recordExport mutation rateLimitedBrandProcedure Record that an operator exported a share link to PDF.
shares.repoint mutation rateLimitedBrandProcedure Move every LIVE link of one resource onto another — the regeneration path.
shares.revoke mutation rateLimitedBrandProcedure

publicShareapps/web/src/server/routers/public-share.ts

Procedure Loại Base RBAC Mô tả
publicShare.lookup query publicProcedure
publicShare.recordView mutation publicProcedure Record a real view: increment counter + audit.
publicShare.audienceRecords query publicProcedure The records behind ONE clicked bucket of a shared deck — see readPublicShareAudienceRecords.

Quy ước dữ liệu#

  • Tiền = VND integer — không numeric/float; format hiển thị qua @yng/charts/formatVnd.
  • Thời gian = Asia/Ho_Chi_Minh (ICT) end-to-end — bucket ngày ICT-anchored trong SQL, day edges/labels qua @yng/ui/ict-date, chart nhận ISO string verbatim.
  • is_sample trên mọi bảng dữ liệu — dữ liệu mẫu tách khỏi dữ liệu thật.
  • Serialization = superjson (Date/Map/BigInt qua wire nguyên vẹn); input validate bằng Zod — lỗi validate trả về zodError flatten trong error shape (trpc.ts errorFormatter).
  • PII hiển thị qua @yng/ui/mask — lưu verbatim, mask ở tầng render; response không bao giờ mang credential/secret.