Skip to content

Ops role system - #4

Merged
clyang82 merged 1 commit into
suanova:mainfrom
skeeey:ops-role-system
Aug 12, 2026
Merged

clyang82 merged 1 commit into
suanova:mainfrom
skeeey:ops-role-system

Conversation

@skeeey

@skeeey skeeey commented Aug 11, 2026 •

Copy link
Copy Markdown
Collaborator

⚠️ 提交说明 / PR Notice

Important

  • 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。

porting ops role system

📝 变更描述 / Description

(简述:做了什么?为什么这样改能生效?请基于你对代码逻辑的理解来写,避免粘贴未经整理的内容)

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix) - 请关联对应 Issue,避免将设计取舍、理解偏差或预期不一致直接归类为 bug
  • ✨ 新功能 (New feature) - 重大特性建议先通过 Issue 沟通
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

  • Closes # (如有)

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

(请在此粘贴截图、关键日志或测试报告,以证明变更生效)

Summary by CodeRabbit

  • New Features
    • Added the Ops role with role-based navigation and access controls.
    • Added read-only Campaigns and Invite History pages with search, pagination, details, statistics, participants, and rewards.
    • Added invitee CSV export, selectable columns, and masked phone numbers.
    • Added admin and root actions to promote or demote Ops users.
  • Bug Fixes
    • Improved table filter initialization when no filters are provided.
    • Restricted campaign and invitee data to authorized Ops access.
  • Documentation
    • Added Ops role guides, design specifications, and changelog entries.
  • Localization
    • Added English, Simplified Chinese, and Traditional Chinese translations for Ops features and messages.

@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 96f76c74-5c93-4a36-9eef-71de657305ec

📥 Commits

Reviewing files that changed from the base of the PR and between 2ccabd3 and b754403.

📒 Files selected for processing (3)
  • controller/user_ops_test.go
  • model/user.go
  • model/user_ops_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • controller/user_ops_test.go
  • model/user.go
  • model/user_ops_test.go

📝 Walkthrough

Walkthrough

Adds the Ops role and role management. Adds authenticated, invitee-scoped campaign and invitee APIs. Adds frontend routes, tables, exports, navigation guards, localization, documentation, and tests.

Changes

Ops role system

Layer / File(s) Summary
Role, authorization, and management
common/*, middleware/*, controller/user.go, i18n/*
Adds role value 5, OpsAuth, phone masking, localized validation messages, and promote_ops and demote_ops actions.
Scoped backend APIs
model/*, controller/campaign_ops.go, controller/user_ops.go, controller/ops_user_columns.go, router/api-router.go
Adds inviter- and invitee-scoped queries, read-only handlers, pagination, CSV export, metadata, and campaign participant and reward responses.
Backend validation
*_test.go
Adds coverage for masking, authorization, exact scope matching, exports, pagination, and localized errors.

Frontend Ops features

Layer / File(s) Summary
Roles, navigation, and routes
web/src/lib/*, web/src/hooks/*, web/src/routes/_authenticated/ops/*, web/src/routeTree.gen.ts
Adds Ops role guards, role-filtered navigation, protected routes, and generated route wiring.
Campaign interface
web/src/features/ops-campaigns/*
Adds campaign listing and search, typed API calls, and a detail drawer with statistics, participants, and rewards.
Invitee interface and role actions
web/src/features/ops-users/*, web/src/features/users/*
Adds invitee listing, search, dynamic columns, CSV downloads, and Ops promotion and demotion actions.

Documentation and localization

Layer / File(s) Summary
Ops documentation and UI text
docs/*, i18n/*, web/src/i18n/locales/*
Documents the Ops role system and adds English, Simplified Chinese, and Traditional Chinese messages.
Frontend tooling support
web/package.json, web/tsconfig.app.json, web/src/components/data-table/hooks/use-data-table.ts
Adds Bun type support and controllable table column-filter state.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant OpsUser
  participant WebApp
  participant OpsAPI
  participant ScopedModels
  OpsUser->>WebApp: open Ops campaign or invite-history route
  WebApp->>OpsAPI: request scoped data
  OpsAPI->>ScopedModels: query by invitee or inviter
  ScopedModels-->>OpsAPI: return filtered records
  OpsAPI-->>WebApp: return typed response or CSV blob
  WebApp-->>OpsUser: render table, drawer, or download
Loading

Possibly related PRs

  • suanova/new-api#3 — Provides the campaign functionality reused by the invitee-scoped campaign APIs and frontend views.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.53% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main change: adding the Ops role system.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

🟡 Minor comments (19)
web/src/features/ops-users/index.tsx-96-101 (1)

96-101: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Attach the anchor and revoke the object URL after the download starts.

Two problems affect the CSV download. The anchor is never appended to the document, and Firefox ignores click() on a disconnected anchor. URL.revokeObjectURL(url) also runs in the same tick as click(), which can cancel the download before the browser reads the blob.

🐛 Proposed fix
       const url = URL.createObjectURL(blob)
       const link = document.createElement('a')
       link.href = url
       link.download = filename || 'invitees.csv'
+      document.body.appendChild(link)
       link.click()
-      URL.revokeObjectURL(url)
+      link.remove()
+      setTimeout(() => URL.revokeObjectURL(url), 0)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/features/ops-users/index.tsx` around lines 96 - 101, Update the CSV
download flow around the temporary anchor to append the link to document.body
before triggering click, then revoke the object URL only after the download has
started, using the appropriate deferred cleanup timing; remove the temporary
anchor afterward.
web/src/features/ops-users/index.tsx-84-93 (1)

84-93: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

An active search overrides the row selection during export.

When trimmed is non-empty, the payload uses only the keyword and drops selectedIds. A user who searches, selects three rows, and clicks Export receives every matching invitee instead of the three selected rows. The selection checkboxes stay visible, so the result contradicts the UI.

Give the explicit selection precedence over the keyword, or disable the selection checkboxes while a search is active.

🐛 Proposed fix
       const trimmed = debouncedKeyword.trim()
       let payload: { ids?: number[]; keyword?: string }
-      if (trimmed) {
+      if (selectedIds.length > 0) {
+        payload = { ids: selectedIds }
+      } else if (trimmed) {
         payload = { keyword: trimmed }
-      } else if (selectedIds.length > 0) {
-        payload = { ids: selectedIds }
       } else {
         // An empty keyword means "all invitees" on the backend.
         payload = { keyword: '' }
       }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/features/ops-users/index.tsx` around lines 84 - 93, Update the
payload selection logic in the export flow so non-empty selectedIds take
precedence over debouncedKeyword.trim(), ensuring exports contain only
explicitly selected rows even during an active search. Preserve keyword-based
export when no rows are selected and the existing empty-keyword fallback when
neither selection nor search is provided.
web/src/features/ops-users/components/ops-users-table.tsx-330-340 (1)

330-340: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guard aff_count against a missing value.

The cell casts the value to number and calls .toLocaleString() directly. If the backend omits aff_count or sends null, this throws and the table row crashes. The created_at cell at Line 347 already guards its value.

🛡️ Proposed fix
         cell: ({ row }) => (
           <span className='text-sm'>
-            {(row.getValue('aff_count') as number).toLocaleString()}
+            {(row.getValue('aff_count') as number | undefined)?.toLocaleString() ??
+              '-'}
           </span>
         ),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/features/ops-users/components/ops-users-table.tsx` around lines 330 -
340, Update the `aff_count` cell in the column definition to safely handle
missing or null values before formatting, matching the guard pattern used by the
nearby `created_at` cell. Preserve localized number formatting for valid numeric
values and render the established fallback when no count is available.
web/src/features/ops-campaigns/components/ops-campaigns-detail-drawer.tsx-374-387 (1)

374-387: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Make the truncated email error reachable by keyboard.

The tooltip trigger renders a plain <span>. A <span> is not focusable, so keyboard and screen reader users cannot read the full email_error. The visible text is truncated, so the tooltip holds the only complete value.

Add tabIndex={0} and an accessible role, or render the trigger as a Button with variant='ghost'.

♿ Proposed fix
                                   <TooltipTrigger
                                     render={
-                                      <span className='text-muted-foreground block max-w-[160px] truncate text-xs'>
+                                      <span
+                                        tabIndex={0}
+                                        className='text-muted-foreground block max-w-[160px] truncate text-xs'
+                                      >
                                         {reward.email_error}
                                       </span>
                                     }
                                   />
As per coding guidelines: "界面必须支持键盘操作和合理焦点顺序".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/features/ops-campaigns/components/ops-campaigns-detail-drawer.tsx`
around lines 374 - 387, Update the TooltipTrigger in the reward email error
rendering to make the truncated value keyboard-accessible by adding tabIndex={0}
and an appropriate accessible role to the trigger span, or replace it with the
existing ghost Button pattern. Preserve the current truncation and full error
text in TooltipContent.

Source: Coding guidelines

web/src/features/ops-users/api.ts-62-72 (1)

62-72: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Handle HTTP 200 JSON errors before returning the export blob.

ExportOpsInvitees returns { success: false, message } with HTTP 200 for validation errors. Because this request uses responseType: 'blob', the interceptor does not detect the envelope, and the caller saves it as invitees.csv. Check for application/json, parse the message, and throw before returning the blob.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/features/ops-users/api.ts` around lines 62 - 72, Update the export
request flow in ExportOpsInvitees to inspect successful blob responses for an
application/json content type, parse the blob as JSON, and throw using its
message when the response indicates success: false. Perform this check before
extracting the filename or returning the blob, while preserving normal CSV blob
handling.
docs/superpowers/specs/2026-08-10-ops-role-system-design.md-4-4 (1)

4-4: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Remove the workstation-specific source path.

/home/skeeey/workspace/searouter-isuanova exposes a developer-local filesystem path in committed documentation. Replace it with a repository-relative path or a public source reference.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/specs/2026-08-10-ops-role-system-design.md` at line 4,
Update the Source reference in the documentation header to remove the
workstation-specific absolute filesystem path, replacing it with a
repository-relative path or public source reference while preserving the
existing source attribution.
docs/superpowers/changelogs/2026-08-10-ops-role-system.md-49-51 (1)

49-51: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Keep the known-limitations sections consistent.

docs/ops-role-system.md lists LIKE-based search, phone omission, and Go-side campaign pagination as limitations, but this changelog says None. Replace None with a concise summary or link to the operator guide.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/changelogs/2026-08-10-ops-role-system.md` around lines 49 -
51, Update the “Known limitations” section in the changelog to replace “None”
with a concise summary of the LIKE-based search, phone omission, and Go-side
campaign pagination limitations documented in the operator guide, or link
directly to that guide.
docs/superpowers/specs/2026-08-10-ops-role-system-design.md-15-15 (1)

15-15: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Align the test-case numbering.

The scope lists backend cases 1–19 and frontend cases 20–21, but sections 5.1–5.8 enumerate backend cases 1–17 and frontend cases 18–20. There is no case 21 in the detailed plan. Use one numbering scheme so implementation and review can trace every required test.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/specs/2026-08-10-ops-role-system-design.md` at line 15,
Align the test-case numbering between the scope summary and detailed sections
5.1–5.8: ensure backend cases and frontend cases use one consistent sequence,
including defining the missing final case if required. Update the summary or
detailed plan as needed so every required test is uniquely numbered and
traceable, with no conflicting ranges or omitted case 21.
web/src/i18n/locales/zh-TW.json-3146-3147 (1)

3146-3147: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use one Traditional Chinese term for Ops.

"Ops" and "Ops Campaigns" use 營運, but "Promote to Ops" and "User promoted to ops successfully" use 運營. Use 營運 consistently for the role.

Proposed fix
-    "Promote to Ops": "提升為運營",
+    "Promote to Ops": "提升為營運",
-    "User promoted to ops successfully": "已成功提升為運營",
+    "User promoted to ops successfully": "已成功提升為營運",

Also applies to: 3528-3528, 4977-4977

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/i18n/locales/zh-TW.json` around lines 3146 - 3147, Update the
Traditional Chinese translations for “Promote to Ops” and “User promoted to ops
successfully” to use “營運” instead of “運營,” matching the existing “Ops” and “Ops
Campaigns” entries and preserving the intended role terminology across all
referenced occurrences.
web/src/i18n/locales/zh-TW.json-2357-2357 (1)

2357-2357: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use a consistent translation for invitees.

邀請用戶 can mean users who send invitations. It conflicts with "Invited Users": "受邀用戶" and "Invitee": "被邀請人". Use 受邀用戶 consistently for these labels and messages.

Also applies to: 5410-5412, 5414-5415

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/i18n/locales/zh-TW.json` at line 2357, Update the affected
invitee-related translations in zh-TW.json, including the Invitee entry and the
additionally referenced labels/messages, to use 受邀用戶 consistently. Replace
occurrences using 邀請用戶 while preserving unrelated invitation-sender translations
and the existing JSON structure.
web/src/i18n/locales/zh.json-5410-5412 (1)

5410-5412: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use “受邀用户” for invitee messages.

“邀请用户” is ambiguous. It can mean users who invite others. Existing translations use “受邀用户” for invited users. Change these values to “导出受邀用户失败”, “加载受邀用户失败”, “搜索受邀用户失败”, “未找到受邀用户”, and “搜索受邀用户”.

Also applies to: 5414-5415

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/i18n/locales/zh.json` around lines 5410 - 5412, Update the
invitee-related Chinese translations near the existing “Failed to export
invitees”, “Failed to load invitees”, and “Failed to search invitees” entries,
plus the adjacent invitee messages, to consistently use “受邀用户” instead of
“邀请用户”: “导出受邀用户失败”, “加载受邀用户失败”, “搜索受邀用户失败”, “未找到受邀用户”, and “搜索受邀用户”.
controller/user.go-1197-1218 (1)

1197-1218: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use an authorization error that describes the rejected operation.

MsgUserAdminCannotPromote states that an administrator cannot promote another user to administrator. It is inaccurate for an Ops caller and for demote_ops. Return a generic insufficient-privilege message, or add an Ops-management-specific message, then update the test expectation.

  • controller/user.go#L1197-L1218: replace i18n.MsgUserAdminCannotPromote in both insufficient-role branches.
  • controller/user_manage_test.go#L198-L210: assert the replacement authorization message for the rejected Ops caller.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/user.go` around lines 1197 - 1218, The promote_ops and demote_ops
insufficient-role branches in controller/user.go lines 1197-1218 must use a
generic insufficient-privilege or Ops-management-specific authorization message
instead of i18n.MsgUserAdminCannotPromote; update controller/user_manage_test.go
lines 198-210 to expect the replacement message for the rejected Ops caller.
common/mask.go-9-19 (1)

9-19: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Mask Unicode phone values by rune.

len(phone) and phone[index] operate on bytes. A multibyte phone value can split a UTF-8 code point and produce invalid output. Convert the value to []rune before applying length checks and slices.

Proposed fix
 func MaskPhone(phone string) string {
-	n := len(phone)
+	characters := []rune(phone)
+	n := len(characters)
 	if n == 0 {
 		return ""
 	}
 	if n <= 2 {
 		return strings.Repeat("*", n)
 	}
 	if n <= 7 {
-		return string(phone[0]) + strings.Repeat("*", n-2) + string(phone[n-1])
+		return string(characters[0]) + strings.Repeat("*", n-2) + string(characters[n-1])
 	}
-	return phone[:3] + strings.Repeat("*", 4) + phone[n-4:]
+	return string(characters[:3]) + strings.Repeat("*", 4) + string(characters[n-4:])
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@common/mask.go` around lines 9 - 19, Update the phone masking logic to
convert phone to []rune before calculating length or indexing, then apply all
length checks, masking, and slices to the rune collection so multibyte
characters remain valid.
controller/user_ops.go-20-24 (1)

20-24: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

The CSV headers and status labels are hard-coded Chinese.

opsUserExportHeaders and the status labels in formatOpsUserRow are fixed Chinese strings. An English or zh-TW operator receives a Chinese CSV. Resolve these strings through the backend i18n package with the request locale. The same root cause exists in controller/ops_user_columns.go.

Also applies to: 33-39

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/user_ops.go` around lines 20 - 24, Update opsUserExportHeaders and
formatOpsUserRow to obtain CSV headers and status labels from the backend i18n
package using the request locale instead of hard-coded Chinese strings. Apply
the same localization approach to the corresponding definitions in
ops_user_columns.go, preserving column order and existing row formatting.
controller/user_ops_test.go-153-153 (1)

153-153: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guard the BOM slice before indexing.

recorder.Body.Bytes()[3:] panics if the handler wrote a short error body. Assert the length first, as TestExportOpsInviteesWritesCsv does at line 126.

🛡️ Proposed fix
-	rows, err := csv.NewReader(strings.NewReader(string(recorder.Body.Bytes()[3:]))).ReadAll()
+	raw := recorder.Body.Bytes()
+	require.GreaterOrEqual(t, len(raw), 3)
+	rows, err := csv.NewReader(strings.NewReader(string(raw[3:]))).ReadAll()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/user_ops_test.go` at line 153, Update the CSV parsing in the
relevant test to verify recorder.Body.Bytes() is at least three bytes long
before slicing from index 3, matching the length assertion pattern used by
TestExportOpsInviteesWritesCsv; only then construct the reader and call ReadAll.
controller/campaign_ops.go-28-32 (1)

28-32: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Do not expose the raw lookup error for an unknown campaign id.

A missing campaign returns the database error through common.ApiError, and a foreign campaign returns the localized forbidden message. The two different responses let an ops user enumerate which campaign ids exist. Return forbiddenMsgKey for both cases.

🔒 Proposed fix
 	campaign, err := model.GetCampaignById(id)
-	if err != nil {
-		common.ApiError(c, err)
+	if err != nil || campaign == nil {
+		common.ApiErrorI18n(c, forbiddenMsgKey)
 		return nil, nil
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/campaign_ops.go` around lines 28 - 32, Update the campaign lookup
error handling around model.GetCampaignById in the controller to return
forbiddenMsgKey through common.ApiError for every lookup failure, including
missing and foreign campaign IDs, instead of exposing the raw database error.
controller/campaign_ops_test.go-147-149 (1)

147-149: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

The false-positive comment does not match the data.

opsA.Id is assigned by the database and is not 7. The campaign with invitee 77 is therefore not a LIKE false positive for opsA.Id, and the test does not cover the case the comment claims. Build the neighbour id from opsA.Id so the case is real.

💚 Proposed fix
 	insertOpsCampaign(t, db, "list-mine", opsA.Id)
-	insertOpsCampaign(t, db, "list-mine-77", 77) // LIKE false positive for userId 7 family
+	// LIKE false positive: the id string of opsA is a prefix of this id.
+	insertOpsCampaign(t, db, "list-mine-neighbour", opsA.Id*10+7)
 	insertOpsCampaign(t, db, "list-foreign", 999999)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/campaign_ops_test.go` around lines 147 - 149, Update the test data
in the setup around insertOpsCampaign so the invitee ID for “list-mine-77” is
derived from opsA.Id by constructing a neighbouring ID that could trigger the
LIKE false positive, rather than using the hard-coded 77. Keep the foreign
campaign fixture unchanged.
model/campaign.go-448-475 (1)

448-475: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Match config_json without assuming JSON whitespace.

common.Marshal currently produces compact JSON, but valid spaced or legacy config_json values do not match "invitee_user_id":%d. Broaden the pre-filter to match the key, then retain the Go-side exact comparison. Apply the same fix in SearchCampaignsByInviteeUserId.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@model/campaign.go` around lines 448 - 475, Update the SQL pre-filter in
GetCampaignsByInviteeUserId and SearchCampaignsByInviteeUserId to match the
invitee_user_id key without requiring a specific whitespace or colon format,
while retaining the Go-side ParseCampaignConfig exact user ID comparison. Keep
pagination and error behavior unchanged.
controller/user_ops_test.go-174-177 (1)

174-177: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the rendered localized message. When i18n.Init runs, body.Message is rendered as Unsupported export format: xlsx for the default language, not the message key. Initialize i18n in this test and assert the rendered value.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/user_ops_test.go` around lines 174 - 177, Update the test around
the response body assertions to initialize i18n before exercising the handler,
then assert that body.Message equals the rendered default-language text
“Unsupported export format: xlsx” rather than the message key
i18n.MsgOpsExportUnsupportedFormat.
🧹 Nitpick comments (19)
web/src/features/ops-users/components/ops-users-table.tsx (3)

116-116: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Memoize the column definitions.

buildOpsUserColumns runs on every render and returns a new array. TanStack Table rebuilds every column def from that new identity, and the guidelines ask you to avoid creating new arrays in the render path.

Wrap the call in useMemo keyed on t and columnMeta.

♻️ Proposed refactor
-  const columns = buildOpsUserColumns(t, columnMeta ?? DEFAULT_OPS_USER_COLUMNS)
+  const columns = useMemo(
+    () => buildOpsUserColumns(t, columnMeta ?? DEFAULT_OPS_USER_COLUMNS),
+    [t, columnMeta]
+  )

Add useMemo to the react import.

As per coding guidelines: "合理使用 `useMemo`、`useCallback` 和 `React.memo`,避免渲染路径中创建不必要的新对象或数组".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/features/ops-users/components/ops-users-table.tsx` at line 116,
Memoize the result of buildOpsUserColumns in the component using useMemo, with t
and columnMeta as dependencies, while preserving the columnMeta ??
DEFAULT_OPS_USER_COLUMNS fallback. Add useMemo to the React imports if needed.

Source: Coding guidelines


204-273: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Apply meta.required to every column, not only id and username.

enableHiding: !meta.required appears in the id and username cases only. If the server marks another column as required, OpsUsersColumnSelector disables its checkbox at Line 76, but the column stays hideable through the persisted columnVisibilityStorageKey state. The two sides then disagree.

Set enableHiding once from meta.required for all branches.

♻️ Proposed refactor
 function buildOpsUserColumn(
   meta: OpsUserColumnMeta,
   t: TFunction
 ): ColumnDef<OpsUser> {
   const columnId = meta.key
   const header = OPS_USER_COLUMN_LABEL_KEYS[columnId]
     ? t(OPS_USER_COLUMN_LABEL_KEYS[columnId])
     : meta.label
+  const base = { header, enableHiding: !meta.required } as const

Then spread ...base into each returned definition and drop the two per-case enableHiding lines.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/features/ops-users/components/ops-users-table.tsx` around lines 204 -
273, Update buildOpsUserColumn to derive a shared column definition containing
enableHiding: !meta.required, then spread it into every returned column
definition, including display_name, phone, and role. Remove the branch-specific
enableHiding properties so all columns consistently honor meta.required.

48-78: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Derive the fallback column list from the label map.

OPS_USER_COLUMN_LABEL_KEYS and DEFAULT_OPS_USER_COLUMNS repeat the same twelve keys and the same English labels. The two lists can drift when a column is added.

Build DEFAULT_OPS_USER_COLUMNS from OPS_USER_COLUMN_LABEL_KEYS entries and a small required key set.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/features/ops-users/components/ops-users-table.tsx` around lines 48 -
78, Derive DEFAULT_OPS_USER_COLUMNS from OPS_USER_COLUMN_LABEL_KEYS instead of
duplicating column keys and labels. Add a small required-key set for the
required id and username columns, then map the label-map entries into
OpsUserColumnMeta objects while preserving insertion order and required flags.
web/src/features/ops-users/components/ops-users-column-selector.tsx (1)

39-42: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Access props through props.xxx instead of destructuring.

The guidelines ask components to read props through props.xxx unless destructuring is necessary. The same pattern appears in web/src/features/ops-users/components/ops-users-table.tsx and web/src/features/ops-campaigns/components/ops-campaigns-detail-drawer.tsx. Align the new Ops components if the team applies this rule strictly.

As per coding guidelines: "组件 props 非必要不要解构,优先通过 props.xxx 访问".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/features/ops-users/components/ops-users-column-selector.tsx` around
lines 39 - 42, Update OpsUsersColumnSelector to accept a single props parameter
and access the table and columns values through props.table and props.columns
instead of destructuring. Keep the component behavior unchanged and follow the
same props-access pattern used by the related Ops components.

Source: Coding guidelines

web/src/features/ops-campaigns/components/ops-campaigns-detail-drawer.tsx (1)

234-424: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

Extract the paginated section; the file is 431 lines.

The participants block and the rewards block repeat the same structure: SideDrawerSection, a Table, and an identical pager with Previous/Next buttons and the Page {{page}} of {{totalPages}} label. Only the columns and the row renderer differ.

Extract a DrawerPagedSection component that takes title, page, totalPages, onPageChange, and children. Move each table into its own component file. This removes the duplication and brings the file under the size guidance.

As per coding guidelines: "单文件超过约 200 行时,应考虑拆分子组件或抽取自定义 Hook".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/features/ops-campaigns/components/ops-campaigns-detail-drawer.tsx`
around lines 234 - 424, Extract the repeated participants and rewards markup
from the main drawer component into separate table component files, and
introduce a reusable DrawerPagedSection component accepting title, page,
totalPages, onPageChange, and children. Move each table and its pager into the
corresponding component while preserving existing rendering, pagination
behavior, translations, and loading/empty states; update the drawer to compose
these components and reduce its size.

Source: Coding guidelines

web/src/lib/role-guards.test.ts (1)

19-19: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Both new unit test files use bun:test instead of Vitest. The frontend guidelines ask for Vitest for utility and pure-logic unit tests, and the shared root cause is the runner choice for these two new web/src/lib test files.

  • web/src/lib/role-guards.test.ts#L19-L19: switch the import to vitest, or confirm that CI runs bun test for this path.
  • web/src/lib/roles.test.ts#L19-L19: apply the same runner decision here so both files stay consistent.

As per coding guidelines: "工具函数和纯逻辑优先使用 Vitest 单元测试;测试文件使用 *.test.ts".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/lib/role-guards.test.ts` at line 19, Use Vitest consistently for both
web/src/lib/role-guards.test.ts lines 19-19 and web/src/lib/roles.test.ts lines
19-19 by replacing the bun:test imports with vitest; do not rely on Bun test
execution unless CI explicitly supports these files.

Source: Coding guidelines

web/src/components/layout/lib/__tests__/nav-role-filter.test.ts (1)

19-19: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Configure Vitest before migrating this test. web/package.json has no Vitest dependency or test script, and all existing web unit tests use bun:test. Add and configure Vitest before changing this import, then migrate the pure-logic tests together.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/layout/lib/__tests__/nav-role-filter.test.ts` at line 19,
Configure Vitest in the web project by adding its dependency and test script
before changing the nav-role-filter test. Then migrate the related pure-logic
tests together from bun:test imports to Vitest APIs, preserving their existing
behavior.

Source: Coding guidelines

web/src/routes/_authenticated/ops/invite-history/index.tsx (1)

26-30: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Align the search schema with its intended defaults and bounds.

optional().catch() returns undefined for absent keys, and z.number() accepts invalid pagination values. OpsUsers does not currently consume this search state. If these parameters are intended for route state, use integer-positive schemas with default() and catch(); otherwise remove the unused fields.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/routes/_authenticated/ops/invite-history/index.tsx` around lines 26 -
30, Update opsInviteHistorySearchSchema to either remove the unused page,
pageSize, and keyword fields or make them valid route state; for retained
pagination fields, use integer-positive Zod schemas with default values and
catch fallbacks so absent or invalid values resolve to page 1 and pageSize 10,
while preserving keyword’s empty-string fallback.
docs/superpowers/specs/2026-08-10-ops-role-system-design.md (4)

63-66: 🔒 Security & Privacy | 🔵 Trivial

Define privacy controls for export audit logs.

The design logs userId and username for every invitee CSV export. These are user identifiers associated with account data. Document audit-log retention and access controls, and ensure the event does not include export keywords or row contents.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/specs/2026-08-10-ops-role-system-design.md` around lines 63
- 66, Update the ExportOpsInvitees audit-log design to document retention and
access controls for logs containing userId and username. Specify that the event
records only the exporter identity and export count, excluding keyword filters,
IDs, and CSV row contents.

120-125: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use named branching for sidebar visibility.

The proposed group.id === 'admin' ? ... : group.id === 'ops' ? ... : true uses two nested ternary expressions. Replace it with a named predicate or early-return branches.

As per coding guidelines, web/**/*.{tsx,ts} forbids two or more nested ternary expressions and requires complex logic to use small, meaningfully named functions.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/specs/2026-08-10-ops-role-system-design.md` around lines 120
- 125, The sidebar group visibility logic in use-sidebar-view.ts must not use
nested ternary expressions. Replace the inline admin/ops/default condition with
a small meaningfully named predicate or early-return branching that uses isAdmin
for the admin group, isOps for the ops group, and preserves visibility for all
other groups.

Source: Coding guidelines


120-131: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse isOps in route guards.

The spec introduces web/src/lib/role-guards.ts so route guards and sidebar filtering share tested logic, but the route example compares auth.user.role < ROLE.OPS directly. Use isOps(auth.user?.role) in beforeLoad to keep the route and filterNavGroupsByRole on one role-threshold contract.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/specs/2026-08-10-ops-role-system-design.md` around lines 120
- 131, Update the beforeLoad guards for the Ops campaign and invite-history
routes to use isOps(auth.user?.role) from role-guards.ts instead of comparing
auth.user.role directly with ROLE.OPS. Preserve the existing redirect to /403
for unauthenticated or non-Ops users.

58-59: 🚀 Performance & Scalability | 🔵 Trivial

Bound invitee campaign queries before pagination.

The database only narrows candidates with LIKE; precise parsing and pagination happen in Go. A page request can therefore load and parse every candidate campaign. Add a normalized or indexed invitee_user_id predicate, or define an explicit bound and metrics for candidate count, memory, and latency.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/superpowers/specs/2026-08-10-ops-role-system-design.md` around lines 58
- 59, The campaign query design in GetCampaignsByInviteeUserId and
SearchCampaignsByInviteeUserId must bound candidate work before Go-side parsing
and pagination. Add a normalized or indexed invitee_user_id database predicate;
if that is not feasible, define an explicit candidate limit and metrics for
candidate count, memory, and latency, while preserving precise filtering and
paging semantics.
controller/ops_user_columns.go (1)

36-42: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use common.ApiSuccess for the response.

This handler builds the success envelope by hand. The other ops handlers use common.ApiSuccess. Use the shared helper here as well.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/ops_user_columns.go` around lines 36 - 42, Update
GetOpsUserColumns to return its successful response through the shared
common.ApiSuccess helper instead of constructing the gin.H envelope manually,
preserving the existing opsUserColumns payload and success response behavior.
controller/campaign_ops.go (1)

70-97: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use one response helper across this file.

GetOpsCampaigns, SearchOpsCampaigns, GetOpsCampaignParticipants, and GetOpsCampaignRewards call common.ApiSuccess. GetOpsCampaign and GetOpsCampaignStats build the same envelope with c.JSON. Use common.ApiSuccess in both handlers so the response shape stays defined in one place.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/campaign_ops.go` around lines 70 - 97, Update GetOpsCampaign and
GetOpsCampaignStats to use common.ApiSuccess instead of constructing success
envelopes with c.JSON. Pass each handler’s existing response data to the helper
and preserve the current error handling and success status behavior.
model/campaign.go (2)

451-453: 🚀 Performance & Scalability | 🔵 Trivial

Plan for growth of the campaign table.

config_json LIKE '%...%' cannot use an index, so each request scans the campaign table and loads every matching row into memory before pagination. This is acceptable for a small table. If invitation campaigns grow, add a dedicated indexed invitee_user_id column on campaigns and filter on it, and keep the JSON parse only as a fallback during migration.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@model/campaign.go` around lines 451 - 453, Update the campaign query in the
surrounding campaign retrieval function to use a dedicated indexed
campaigns.invitee_user_id column instead of filtering config_json with a
wildcard LIKE. Retain JSON parsing as a fallback for records without the new
column during migration, while preserving the existing ordering and pagination
behavior.

455-475: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the shared filter-and-paginate block.

Lines 455-475 and 492-512 are identical: parse each config, keep exact InviteeUserId matches, compute the total, then slice the page. Move this into one helper and call it from both functions.

♻️ Proposed helper
// filterCampaignsByInvitee keeps campaigns whose parsed config matches userId
// and returns the requested page plus the filtered total.
func filterCampaignsByInvitee(all []*Campaign, userId, startIdx, num int) ([]*Campaign, int64) {
	var filtered []*Campaign
	for _, c := range all {
		config, parseErr := c.ParseCampaignConfig()
		if parseErr != nil || config.InviteeUserId != userId {
			continue
		}
		filtered = append(filtered, c)
	}
	total := int64(len(filtered))
	if startIdx >= len(filtered) {
		return []*Campaign{}, total
	}
	end := startIdx + num
	if end > len(filtered) {
		end = len(filtered)
	}
	return filtered[startIdx:end], total
}

Also applies to: 492-512

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@model/campaign.go` around lines 455 - 475, Extract the duplicated filtering
and pagination logic from the functions around the visible campaign loops into a
shared filterCampaignsByInvitee helper. Have it parse configs, retain only exact
InviteeUserId matches, calculate the filtered total, and return the requested
page while preserving empty-page behavior; then replace both duplicate blocks
with calls to the helper and keep each caller’s existing error-return handling.
model/user.go (2)

1490-1507: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Consider reporting skipped batches to the caller.

A failed batch is logged and skipped. The function returns a partial list, and ExportOpsInvitees writes it as a complete CSV. The operator cannot detect missing rows. Return an error or a skipped-batch count so the controller can fail the request or add a warning.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@model/user.go` around lines 1490 - 1507, Update ExportOpsInviteesByIds to
expose batch query failures to its caller instead of logging and silently
skipping them; return an error or skipped-batch count alongside the users.
Propagate this result through ExportOpsInvitees so it can fail the request or
clearly warn that the generated CSV is incomplete.

1511-1531: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Bound the keyword export and drop the per-page COUNT.

The loop accumulates every matching invitee in memory before the caller writes any row. A large invitee set can exhaust memory. SearchOpsInvitees also runs a COUNT on every page, and the result is discarded, which doubles the query cost.

Add a maximum row cap, or stream each page to the CSV writer through a callback, and use a count-free query for the export path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@model/user.go` around lines 1511 - 1531, Update ExportOpsInviteesByKeyword to
avoid unbounded accumulation by enforcing a maximum export-row cap, and ensure
pagination stops at that cap while preserving existing batching and error
behavior. Replace the export path’s use of SearchOpsInvitees with a count-free
query variant or add one, since the returned total is unused; do not retain the
per-page COUNT operation.
controller/user_ops_test.go (1)

22-46: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated in-memory database setup in the two new ops test files. Both helpers save and restore model.DB, model.LOG_DB, common.RedisEnabled, and the database types, open the same shared-cache SQLite DSN, and register the same cleanup. Only the AutoMigrate argument list differs.

  • controller/user_ops_test.go#L22-L46: replace setupOpsUserTestDB with a single package-level helper that accepts the models to migrate.
  • controller/campaign_ops_test.go#L21-L45: delete setupOpsCampaignTestDB and call the shared helper with &model.User{}, &model.Campaign{}, &model.CampaignParticipant{}, and &model.CampaignReward{}.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/user_ops_test.go` around lines 22 - 46, In
controller/user_ops_test.go:22-46, convert setupOpsUserTestDB into the shared
package-level setupOpsTestDB helper that accepts migration models while
preserving its existing state setup and cleanup. In
controller/campaign_ops_test.go:21-45, delete setupOpsCampaignTestDB and update
its callers to use setupOpsTestDB with &model.User{}, &model.Campaign{},
&model.CampaignParticipant{}, and &model.CampaignReward{}; no direct change is
needed beyond replacing that helper and its call sites.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 945fb227-8bce-43fe-945c-e45bd8ce2cf4

📥 Commits

Reviewing files that changed from the base of the PR and between 2a7d887 and efd164e.

⛔ Files ignored due to path filters (1)
  • web/bun.lock is excluded by !**/*.lock
📒 Files selected for processing (56)
  • common/constants.go
  • common/mask.go
  • common/mask_test.go
  • controller/campaign_ops.go
  • controller/campaign_ops_test.go
  • controller/ops_user_columns.go
  • controller/user.go
  • controller/user_manage_test.go
  • controller/user_ops.go
  • controller/user_ops_test.go
  • docs/ops-role-system.md
  • docs/superpowers/changelogs/2026-08-10-ops-role-system.md
  • docs/superpowers/specs/2026-08-10-ops-role-system-design.md
  • i18n/keys.go
  • i18n/locales/en.yaml
  • i18n/locales/zh-CN.yaml
  • i18n/locales/zh-TW.yaml
  • i18n/ops_messages_test.go
  • middleware/auth.go
  • middleware/auth_test.go
  • model/campaign.go
  • model/campaign_test.go
  • model/user.go
  • model/user_ops_test.go
  • router/api-router.go
  • web/package.json
  • web/src/components/data-table/hooks/use-data-table.ts
  • web/src/components/layout/lib/__tests__/nav-role-filter.test.ts
  • web/src/components/layout/lib/nav-role-filter.ts
  • web/src/features/ops-campaigns/api.ts
  • web/src/features/ops-campaigns/components/ops-campaigns-detail-drawer.tsx
  • web/src/features/ops-campaigns/components/ops-campaigns-table.tsx
  • web/src/features/ops-campaigns/index.tsx
  • web/src/features/ops-campaigns/types.ts
  • web/src/features/ops-users/api.ts
  • web/src/features/ops-users/components/ops-users-column-selector.tsx
  • web/src/features/ops-users/components/ops-users-table.tsx
  • web/src/features/ops-users/index.tsx
  • web/src/features/ops-users/types.ts
  • web/src/features/users/components/data-table-row-actions.tsx
  • web/src/features/users/constants.ts
  • web/src/features/users/lib/user-actions.ts
  • web/src/features/users/types.ts
  • web/src/hooks/use-sidebar-data.ts
  • web/src/hooks/use-sidebar-view.ts
  • web/src/i18n/locales/en.json
  • web/src/i18n/locales/zh-TW.json
  • web/src/i18n/locales/zh.json
  • web/src/lib/role-guards.test.ts
  • web/src/lib/role-guards.ts
  • web/src/lib/roles.test.ts
  • web/src/lib/roles.ts
  • web/src/routeTree.gen.ts
  • web/src/routes/_authenticated/ops/campaign/index.tsx
  • web/src/routes/_authenticated/ops/invite-history/index.tsx
  • web/tsconfig.app.json

Comment thread controller/campaign_ops.go Resolved
Comment thread controller/ops_user_columns.go Resolved
Comment thread router/api-router.go Resolved
skeeey pushed a commit to skeeey/cuberouter that referenced this pull request Aug 11, 2026
- controller: batch user lookups in ops campaign participants/rewards
  (GetUsersByIds, kills per-row N+1 queries)
- i18n: ops column metadata returns stable English keys translated by the
  frontend; CSV export headers and user status labels resolve per request
  locale (new ops.export_header.* and ops.status.* keys in en/zh-CN/zh-TW)
- export: failed batches now return an error instead of being logged and
  skipped, and all batches are fetched before the CSV header is written;
  regression test closes the DB to prove no partial CSV is emitted
- router: rate-limit ops search routes (SearchRateLimit) and ops export
  (CriticalRateLimit)
- useDataTable: columnFilters now go through useControllableTableState so
  uncontrolled filter updates are retained (fixes toolbar state) and the
  default no longer pins state to []
- ops-campaigns: failed API envelopes route through handleServerError and
  fail the query instead of returning a successful empty result
- ops-users table: stable getRowId so row selection survives page changes
- admin users page: promote_ops/demote_ops require a confirmation dialog

Co-Authored-By: Claude <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
controller/user_ops.go (1)

41-67: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Prevent CSV formula injection.

Username, DisplayName, Group, and AffCode are written as user-controlled cells. csv.Writer quotes fields, but it does not prevent spreadsheet formula evaluation. A value beginning with =, +, -, @, tab, or carriage return can execute as a formula when an ops user opens the export. Neutralize formula-leading text before returning CSV cells.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@controller/user_ops.go` around lines 41 - 67, Update formatOpsUserRow to
neutralize spreadsheet formula-leading text in the user-controlled Username,
DisplayName, Group, and AffCode fields before returning the row. Reuse or add a
focused helper that prefixes a safe character when a value begins with =, +, -,
@, tab, or carriage return, while leaving other values unchanged; apply it only
to those CSV cells.
model/user.go (1)

1509-1524: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Bound Ops export size before materializing rows.

Both export paths collect every matching invitee in memory before the controller writes the CSV response. A large invitee set can cause unbounded database work and memory allocation in one request.

  • model/user.go#L1509-L1524: enforce a maximum selected-ID export size before accumulating batches.
  • model/user.go#L1529-L1547: enforce a maximum keyword-export row count, or move large exports to a bounded asynchronous job.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@model/user.go` around lines 1509 - 1524, Bound both export paths in
model/user.go: ExportOpsInviteesByIds (lines 1509-1524) must reject or otherwise
enforce a maximum selected-ID count before batching and accumulating users,
while the keyword-export function at lines 1529-1547 must enforce a maximum
exported row count or use a bounded asynchronous job; preserve existing
filtering and error behavior within the allowed limits.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@controller/user_ops.go`:
- Around line 41-67: Update formatOpsUserRow to neutralize spreadsheet
formula-leading text in the user-controlled Username, DisplayName, Group, and
AffCode fields before returning the row. Reuse or add a focused helper that
prefixes a safe character when a value begins with =, +, -, @, tab, or carriage
return, while leaving other values unchanged; apply it only to those CSV cells.

In `@model/user.go`:
- Around line 1509-1524: Bound both export paths in model/user.go:
ExportOpsInviteesByIds (lines 1509-1524) must reject or otherwise enforce a
maximum selected-ID count before batching and accumulating users, while the
keyword-export function at lines 1529-1547 must enforce a maximum exported row
count or use a bounded asynchronous job; preserve existing filtering and error
behavior within the allowed limits.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: c484bc18-dce4-4bd5-b11e-e81b40f9f2a3

📥 Commits

Reviewing files that changed from the base of the PR and between efd164e and 8f4e69d.

📒 Files selected for processing (19)
  • controller/campaign_ops.go
  • controller/ops_user_columns.go
  • controller/user_ops.go
  • controller/user_ops_test.go
  • i18n/keys.go
  • i18n/locales/en.yaml
  • i18n/locales/zh-CN.yaml
  • i18n/locales/zh-TW.yaml
  • i18n/ops_messages_test.go
  • model/user.go
  • model/user_ops_test.go
  • router/api-router.go
  • web/src/components/data-table/hooks/use-data-table.ts
  • web/src/features/ops-campaigns/index.tsx
  • web/src/features/ops-users/components/ops-users-table.tsx
  • web/src/features/users/components/data-table-row-actions.tsx
  • web/src/i18n/locales/en.json
  • web/src/i18n/locales/zh-TW.json
  • web/src/i18n/locales/zh.json
🚧 Files skipped from review as they are similar to previous changes (14)
  • i18n/locales/zh-TW.yaml
  • controller/ops_user_columns.go
  • router/api-router.go
  • i18n/locales/zh-CN.yaml
  • web/src/i18n/locales/zh-TW.json
  • i18n/keys.go
  • web/src/features/users/components/data-table-row-actions.tsx
  • web/src/features/ops-campaigns/index.tsx
  • web/src/features/ops-users/components/ops-users-table.tsx
  • web/src/i18n/locales/zh.json
  • controller/campaign_ops.go
  • controller/user_ops_test.go
  • model/user_ops_test.go
  • web/src/i18n/locales/en.json

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@model/user_ops_test.go`:
- Around line 49-60: Update TestGetOpsInviteesPagination to retain the users
created in the setup loop, then assert that the Page 2 result contains the exact
expected user IDs for the second page. Keep the existing total-count,
result-length, and no-error assertions.

In `@model/user.go`:
- Around line 1457-1462: Update the invitee queries in model/user.go:1457-1462
and model/user.go:1496-1498 to omit both password and access_token, preserving
the existing pagination and search behavior. Extend
controller/user_ops_test.go:65-78 and controller/user_ops_test.go:94-107 by
creating invitees with non-empty access tokens and asserting the list and search
responses do not contain those tokens.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 47b24cc2-2565-4b2a-8ecb-9e866c250af4

📥 Commits

Reviewing files that changed from the base of the PR and between 8f4e69d and 2ccabd3.

📒 Files selected for processing (4)
  • controller/user_ops.go
  • controller/user_ops_test.go
  • model/user.go
  • model/user_ops_test.go

Comment thread model/user_ops_test.go Resolved
Comment thread model/user.go Resolved
A read-only ops (运营) role between common users and admins, scoped to
the ops user's own invitees and invitation campaigns.

Backend:
- RoleOpsUser (5) role constant, OpsAuth middleware, MaskPhone helper
- inviter-scoped invitee queries (list/search/export, phone masked)
- invitee-scoped campaign queries (list/search/detail/stats/participants/rewards)
- promote_ops/demote_ops ManageUser actions, /api/ops/* routes, i18n keys
  (en/zh-CN/zh-TW), CSV export with ASCII filename

Frontend:
- ops sidebar section with role-based filtering, ops campaigns and
  invite history pages (columns from server metadata, masked phone)
- promote/demote ops actions in the admin users page
- fix: default table columnFilters to [] so DataTableToolbar does not
  crash for tables without explicit column filters

Docs: design spec, changelog, operator guide.

Co-Authored-By: Claude <[email protected]>
@clyang82
clyang82 merged commit 4caafd8 into suanova:main Aug 12, 2026
@skeeey
skeeey deleted the ops-role-system branch August 18, 2026 10:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants