Skip to content

feat(admin): 用户管理列表展示订阅信息并支持按订阅套餐筛选 - #4133

Closed
ImogeneOctaviap794 wants to merge 1 commit into
QuantumNous:mainfrom
ImogeneOctaviap794:dev
Closed

ImogeneOctaviap794 wants to merge 1 commit into
QuantumNous:mainfrom
ImogeneOctaviap794:dev

Conversation

@ImogeneOctaviap794

@ImogeneOctaviap794 ImogeneOctaviap794 commented Apr 7, 2026 •

Copy link
Copy Markdown
Contributor

📝 变更描述 / Description

管理员的用户管理页面新增「订阅信息」列,直观展示每个用户的活跃订阅状态,并支持按订阅套餐筛选用户。

痛点: 管理员此前无法在用户列表中快速了解用户的订阅状态,需要逐个点击进入订阅管理弹窗才能查看。

方案:

后端:

  • model/subscription.go:新增 GetActiveSubscriptionsByUserIds 批量查询方法,一次 SQL 返回多个用户的全部活跃订阅(map[userId][]UserSubscription),避免 N+1 查询
  • controller/subscription.go:新增 AdminBatchActiveSubscriptions 接口,接收 user_ids 数组(上限 100),返回批量订阅数据
  • router/api-router.go:注册 POST /api/subscription/admin/users/batch_active_subscriptions
  • model/user.go:SearchUsers 新增可选参数 planId,通过子查询筛选持有指定活跃订阅的用户
  • controller/user.go:SearchUsers 解析 plan_id query 参数并传入 model 层

前端:

  • useUsersData.jsx:
    • 新增 planOptions / userSubscriptions state
    • 页面加载时拉取订阅套餐列表(fetchPlans)
    • 用户列表加载后通过批量接口一次获取订阅数据(loadUserSubscriptions)
    • 使用 useRef 防止快速翻页时旧请求覆盖新数据(竞态保护)
    • 搜索支持 plan_id 参数
  • UsersFilters.jsx:新增「选择订阅」下拉筛选框
  • UsersColumnDefs.jsx:
    • 新增「订阅信息」列,渲染 Tag 标签
    • 支持多订阅展示,不同套餐自动分配不同颜色
    • Tooltip 显示到期时间和额度使用情况
    • 过期订阅显示为灰色
  • UsersTable.jsx / index.jsx:透传 planOptions 和 userSubscriptions 到列定义

i18n:

  • 7 个语言文件新增 5 个翻译 key:选择订阅、无订阅、到期、订阅中、订阅信息
  • 覆盖语言:zh-CN、zh-TW、en、fr、ja、ru、vi

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)
  • ✨ 新功能 (New feature)
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

N/A

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自撰写此描述,去除了 AI 原始输出的冗余。
  • 深度理解: 我已完全理解这些更改的工作原理及潜在影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过了测试或手动验证。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

Summary by CodeRabbit

Release Notes

  • New Features

    • Added ability to filter users by subscription plan in the users table.
    • Display subscription information including status, expiration date, and quota usage per subscription in the users table.
  • Localization

    • Added subscription-related translations across multiple languages: English, French, Japanese, Russian, Vietnamese, Simplified Chinese, and Traditional Chinese.

后端:
- 新增 GetActiveSubscriptionsByUserIds 批量查询活跃订阅
- 新增 POST /api/subscription/admin/users/batch_active_subscriptions 接口
- SearchUsers 支持 plan_id 参数筛选订阅用户

前端:
- 用户列表新增订阅信息列,支持多订阅 Tag 展示
- 不同套餐自动分配不同颜色,过期订阅灰色
- Tooltip 显示到期时间和额度使用量
- 新增选择订阅下拉筛选框
- 批量接口替代 N+1 请求,含竞态保护

i18n:
- 7 种语言新增 5 个翻译 key
@coderabbitai

coderabbitai Bot commented Apr 7, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

This PR adds batch subscription retrieval and plan-based user filtering across the backend and frontend. It introduces a new admin API endpoint to fetch active subscriptions by user IDs, enables filtering users by subscription plan, updates the users table to display subscription details, and adds internationalization support for subscription-related UI strings.

Changes

Cohort / File(s) Summary
Backend Subscription Batch API
controller/subscription.go, model/subscription.go, router/api-router.go
Added AdminBatchActiveSubscriptions endpoint and GetActiveSubscriptionsByUserIds() function to fetch active subscriptions in batches; registered new POST route /api/subscription/admin/users/batch_active_subscriptions.
User Search Plan Filtering
controller/user.go, model/user.go
Enhanced SearchUsers to accept optional planId parameter for filtering by active subscription plan; controller now parses plan_id query param and validates it.
Users Table Components
web/src/components/table/users/UsersColumnDefs.jsx, web/src/components/table/users/UsersFilters.jsx, web/src/components/table/users/UsersTable.jsx, web/src/components/table/users/index.jsx
Added subscription info column rendering with color-coded tags, plan-based filter dropdown, and data flow to pass subscription and plan options to column definitions.
Users Data Hook
web/src/hooks/users/useUsersData.jsx
Integrated subscription data enrichment via batch API calls, plan options fetching, search plan parameter handling, and request de-duplication using ref-based tracking.
Internationalization
web/src/i18n/locales/{en,fr,ja,ru,vi,zh-CN,zh-TW}.json
Added translation keys for subscription-related UI strings: "到期" (expiry), "无订阅" (no subscription), "订阅中" (subscribed), "订阅信息" (subscription info), and "选择订阅" (select subscription).

Sequence Diagrams

sequenceDiagram
    participant Client as Frontend Client
    participant API as Backend API
    participant DB as Database

    Client->>API: POST /api/subscription/admin/users/batch_active_subscriptions<br/>(user_ids: [1, 2, 3])
    API->>API: Validate user_ids (non-empty, max 100)
    API->>DB: SELECT * FROM user_subscription<br/>WHERE user_id IN (...)<br/>AND status='active' AND end_time > now<br/>ORDER BY end_time DESC
    DB-->>API: [subscription rows]
    API-->>Client: {userId: [subscription, ...]}<br/>mapped response
    Client->>Client: Store subscriptions in state
    Client->>Client: Render subscription tags per user
Loading
sequenceDiagram
    participant Client as Frontend Client
    participant API as Backend API
    participant DB as Database

    Client->>Client: User selects plan from filter
    Client->>API: GET /api/user/search?<br/>keyword=...&plan_id=5
    API->>DB: Find user_ids with active<br/>subscriptions for plan_id=5
    DB-->>API: [user_ids matching plan]
    API->>DB: SELECT users WHERE id IN (...)<br/>AND (keyword search conditions)
    DB-->>API: [filtered users]
    API-->>Client: [users + total count]
    Client->>Client: Update users table display
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • Calcium-Ion
  • seefs001
  • creamlike1024

Poem

🐰 A batch of subscriptions, fetched with delight,
Plans filter the users, colors shining bright,
Tags wrapped in tooltips, dates on display,
Translations bloom worldwide, in every way! 🌍✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main feature: displaying subscription information in the user management list and supporting filtering by subscription plan.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Nitpick comments (2)
model/subscription.go (1)

671-688: Harden batch input normalization in the model layer.

The query works, but as a public model API it should defensively filter non-positive IDs and deduplicate IDs before hitting DB.

♻️ Proposed refactor
 func GetActiveSubscriptionsByUserIds(userIds []int) (map[int][]UserSubscription, error) {
-	if len(userIds) == 0 {
+	if len(userIds) == 0 {
 		return map[int][]UserSubscription{}, nil
 	}
+	normalized := make([]int, 0, len(userIds))
+	seen := make(map[int]struct{}, len(userIds))
+	for _, id := range userIds {
+		if id <= 0 {
+			continue
+		}
+		if _, ok := seen[id]; ok {
+			continue
+		}
+		seen[id] = struct{}{}
+		normalized = append(normalized, id)
+	}
+	if len(normalized) == 0 {
+		return map[int][]UserSubscription{}, nil
+	}
 	now := common.GetTimestamp()
 	var subs []UserSubscription
-	err := DB.Where("user_id IN ? AND status = ? AND end_time > ?", userIds, "active", now).
+	err := DB.Where("user_id IN ? AND status = ? AND end_time > ?", normalized, "active", now).
 		Order("end_time desc, id desc").
 		Find(&subs).Error
 	if err != nil {
 		return nil, err
 	}
-	result := make(map[int][]UserSubscription, len(userIds))
+	result := make(map[int][]UserSubscription, len(normalized))
 	for i := range subs {
 		result[subs[i].UserId] = append(result[subs[i].UserId], subs[i])
 	}
 	return result, nil
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@model/subscription.go` around lines 671 - 688,
GetActiveSubscriptionsByUserIds currently passes the raw userIds slice to the DB
query; harden it by normalizing the batch input: build a small set to
deduplicate and ignore non-positive IDs (<=0), produce a slice uniqueUserIds
from that set (skip early return only when no valid ids), then use uniqueUserIds
in the DB.Where call and size the result map using len(uniqueUserIds). Update
variable references in the function (userIds -> uniqueUserIds, result map
initialization, and DB query) so only valid, deduplicated IDs hit the database.
web/src/i18n/locales/vi.json (1)

2880-2880: Translation inconsistency with "信息" (information) pattern.

The Vietnamese translation "Đăng ký" (Subscription) for "订阅信息" (Subscription Information) omits the "information" part. Other similar terms in this file consistently follow the pattern "Thông tin XXX" for "XXX信息":

  • Line 63: "API信息": "Thông tin API"
  • Line 2218: "用户信息": "Thông tin người dùng"
  • Line 3286: "账户信息": "Thông tin tài khoản"

Consider changing to "Thông tin đăng ký" for consistency.

Suggested translation update
-    "订阅信息": "Đăng ký",
+    "订阅信息": "Thông tin đăng ký",

As per coding guidelines: Frontend i18n files must use flat JSON with Chinese keys and consistent translation patterns.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/i18n/locales/vi.json` at line 2880, The translation for the key
"订阅信息" is inconsistent with the project's "信息" -> "Thông tin ..." pattern:
update the value for the key "订阅信息" from "Đăng ký" to "Thông tin đăng ký" so it
matches other keys like "API信息" -> "Thông tin API" and "用户信息" -> "Thông tin
người dùng"; locate the JSON entry for the string "订阅信息" and replace its
Vietnamese value accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@controller/user.go`:
- Around line 255-258: The parse error for planId (planId, parseErr :=
strconv.Atoi(planIdStr) in controller/user.go) is leaking internal parser
details to clients; change the handler to return the same stable user-facing
"invalid ID" style error used elsewhere instead of common.ApiError(c, parseErr).
Keep the original parseErr for internal diagnostics by logging it (e.g., with
logger.Errorf or similar) but call the existing invalid-ID response helper (the
same helper used in the invalid-ID branch) so clients receive a consistent,
stable error message.

In `@web/src/components/table/users/UsersColumnDefs.jsx`:
- Around line 205-212: The tooltip currently converts sub.end_time to just a
date using toLocaleDateString(), losing time-of-day; update the endDate
computation used in tooltipContent (where endDate is defined from sub.end_time)
to include both date and time (e.g., use toLocaleString() or Intl.DateTimeFormat
with date and time options) so the tooltip displays the full expiry timestamp
instead of only the date.

In `@web/src/hooks/users/useUsersData.jsx`:
- Line 40: The current request token (latestSubscriptionRequestRef) only
protects batch subscription calls; you must apply the same token check in the
user-list request handlers so stale /api/user or /api/user/search responses
cannot overwrite state. Update the searchUsers function (and any other functions
that set users/userCount/activePage, e.g., the initial fetchUsers and pagination
handlers) to capture the request token at invocation, compare it to
latestSubscriptionRequestRef.current before performing any setState calls
(users, userCount, activePage), and bail out if they differ; keep using
latestSubscriptionRequestRef to increment for each new search/page action so
only the latest response updates state.
- Around line 99-105: The hook useUsersData is collapsing "loading/error" and
"no subscriptions" into the same value by setting setUserSubscriptions({}) on
fetch start/failure; instead preserve a distinct sentinel for "unknown" (e.g.,
null or undefined) during loading/errors and only set an empty object {} when
the request succeeded and returned an empty list. Change the logic around
userList handling (the conditional that calls setUserSubscriptions({}) at lines
referencing userList) to leave userSubscriptions as null/previous while fetching
or on batch errors, and only call setUserSubscriptions({}) when you have a
successful response that confirms there are no subscriptions; apply the same fix
to the similar block around lines 123-130.
- Around line 156-159: The URL is built by interpolating raw values (url,
searchKeyword, searchGroup, searchPlan, startIdx, pageSize) which breaks for
characters like & or +; replace the string interpolation with a
URLSearchParams-based builder: create a params = new URLSearchParams(), append
keyword, group, p, page_size, and conditionally append plan_id when searchPlan
is present, then set url = `/api/user/search?` + params.toString() so all query
values are correctly encoded.

In `@web/src/i18n/locales/vi.json`:
- Line 3422: The Vietnamese translation for the key "选择订阅" currently duplicates
the text used for "选择订阅套餐"; update the translation for "选择订阅" (the entry with
source key "选择订阅") to a differentiated form such as "Chọn đăng ký" to follow the
"选择XXX" → "Chọn XXX" pattern and avoid ambiguity with the existing "选择订阅套餐" →
"Chọn gói đăng ký" entry.

---

Nitpick comments:
In `@model/subscription.go`:
- Around line 671-688: GetActiveSubscriptionsByUserIds currently passes the raw
userIds slice to the DB query; harden it by normalizing the batch input: build a
small set to deduplicate and ignore non-positive IDs (<=0), produce a slice
uniqueUserIds from that set (skip early return only when no valid ids), then use
uniqueUserIds in the DB.Where call and size the result map using
len(uniqueUserIds). Update variable references in the function (userIds ->
uniqueUserIds, result map initialization, and DB query) so only valid,
deduplicated IDs hit the database.

In `@web/src/i18n/locales/vi.json`:
- Line 2880: The translation for the key "订阅信息" is inconsistent with the
project's "信息" -> "Thông tin ..." pattern: update the value for the key "订阅信息"
from "Đăng ký" to "Thông tin đăng ký" so it matches other keys like "API信息" ->
"Thông tin API" and "用户信息" -> "Thông tin người dùng"; locate the JSON entry for
the string "订阅信息" and replace its Vietnamese value accordingly.
🪄 Autofix (Beta)

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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 944bcd8c-c212-445d-8a09-2f64dd90d432

📥 Commits

Reviewing files that changed from the base of the PR and between 960bf9c and 107d4dd.

⛔ Files ignored due to path filters (1)
  • web/bun.lock is excluded by !**/*.lock
📒 Files selected for processing (17)
  • controller/subscription.go
  • controller/user.go
  • model/subscription.go
  • model/user.go
  • router/api-router.go
  • web/src/components/table/users/UsersColumnDefs.jsx
  • web/src/components/table/users/UsersFilters.jsx
  • web/src/components/table/users/UsersTable.jsx
  • web/src/components/table/users/index.jsx
  • web/src/hooks/users/useUsersData.jsx
  • web/src/i18n/locales/en.json
  • web/src/i18n/locales/fr.json
  • web/src/i18n/locales/ja.json
  • web/src/i18n/locales/ru.json
  • web/src/i18n/locales/vi.json
  • web/src/i18n/locales/zh-CN.json
  • web/src/i18n/locales/zh-TW.json

Comment thread controller/user.go
Comment on lines +255 to +258
planId, parseErr := strconv.Atoi(planIdStr)
if parseErr != nil {
common.ApiError(c, parseErr)
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Avoid returning raw parser errors to clients.

Line 257 returns internal parse details; prefer a stable user-facing error message like the invalid-ID branch for consistency and cleaner API contracts.

🔧 Suggested adjustment
 	if planIdStr != "" {
 		planId, parseErr := strconv.Atoi(planIdStr)
 		if parseErr != nil {
-			common.ApiError(c, parseErr)
+			common.ApiErrorMsg(c, "无效的订阅套餐ID")
 			return
 		}
 		if planId <= 0 {
 			common.ApiErrorMsg(c, "无效的订阅套餐ID")
 			return
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
planId, parseErr := strconv.Atoi(planIdStr)
if parseErr != nil {
common.ApiError(c, parseErr)
return
planId, parseErr := strconv.Atoi(planIdStr)
if parseErr != nil {
common.ApiErrorMsg(c, "无效的订阅套餐ID")
return
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@controller/user.go` around lines 255 - 258, The parse error for planId
(planId, parseErr := strconv.Atoi(planIdStr) in controller/user.go) is leaking
internal parser details to clients; change the handler to return the same stable
user-facing "invalid ID" style error used elsewhere instead of
common.ApiError(c, parseErr). Keep the original parseErr for internal
diagnostics by logging it (e.g., with logger.Errorf or similar) but call the
existing invalid-ID response helper (the same helper used in the invalid-ID
branch) so clients receive a consistent, stable error message.

Comment on lines +205 to +212
const endDate = sub.end_time
? new Date(sub.end_time * 1000).toLocaleDateString()
: '-';

const tooltipContent = (
<div className='text-xs'>
<div>
{t('到期')}: {endDate}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Show the expiry time, not just the date.

The tooltip currently uses toLocaleDateString(), so admins lose the time-of-day even though this feature is supposed to show expiry time. That can be misleading for subscriptions that expire mid-day.

💡 Suggested change
-        const endDate = sub.end_time
-          ? new Date(sub.end_time * 1000).toLocaleDateString()
-          : '-';
+        const endDate = sub.end_time
+          ? new Date(sub.end_time * 1000).toLocaleString()
+          : '-';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const endDate = sub.end_time
? new Date(sub.end_time * 1000).toLocaleDateString()
: '-';
const tooltipContent = (
<div className='text-xs'>
<div>
{t('到期')}: {endDate}
const endDate = sub.end_time
? new Date(sub.end_time * 1000).toLocaleString()
: '-';
const tooltipContent = (
<div className='text-xs'>
<div>
{t('到期')}: {endDate}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/components/table/users/UsersColumnDefs.jsx` around lines 205 - 212,
The tooltip currently converts sub.end_time to just a date using
toLocaleDateString(), losing time-of-day; update the endDate computation used in
tooltipContent (where endDate is defined from sub.end_time) to include both date
and time (e.g., use toLocaleString() or Intl.DateTimeFormat with date and time
options) so the tooltip displays the full expiry timestamp instead of only the
date.

const [planOptions, setPlanOptions] = useState([]);
const [userCount, setUserCount] = useState(0);
const [userSubscriptions, setUserSubscriptions] = useState({});
const latestSubscriptionRequestRef = useRef(0);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Guard the user-list requests too.

latestSubscriptionRequestRef only serializes the batch subscription call. Older /api/user or /api/user/search responses can still arrive last and overwrite users, userCount, and activePage, so fast paging/filter changes still show stale rows.

💡 Suggested direction
+  const latestUsersRequestRef = useRef(0);
+
   const loadUsers = async (startIdx, pageSize) => {
+    const requestId = ++latestUsersRequestRef.current;
     setLoading(true);
     const res = await API.get(`/api/user/?p=${startIdx}&page_size=${pageSize}`);
+    if (requestId !== latestUsersRequestRef.current) return;
     const { success, message, data } = res.data;
     if (success) {
       const newPageData = data.items;
       setActivePage(data.page);
       setUserCount(data.total);
       setUserFormat(newPageData);
       loadUserSubscriptions(newPageData);
     } else {
       showError(message);
     }
     setLoading(false);
   };

Apply the same request token check in searchUsers before any state updates.

Also applies to: 78-88, 135-167

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/hooks/users/useUsersData.jsx` at line 40, The current request token
(latestSubscriptionRequestRef) only protects batch subscription calls; you must
apply the same token check in the user-list request handlers so stale /api/user
or /api/user/search responses cannot overwrite state. Update the searchUsers
function (and any other functions that set users/userCount/activePage, e.g., the
initial fetchUsers and pagination handlers) to capture the request token at
invocation, compare it to latestSubscriptionRequestRef.current before performing
any setState calls (users, userCount, activePage), and bail out if they differ;
keep using latestSubscriptionRequestRef to increment for each new search/page
action so only the latest response updates state.

Comment on lines +99 to +105
if (!userList || userList.length === 0) {
setUserSubscriptions({});
return;
}

setUserSubscriptions({});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Don't collapse loading/error into “no subscription”.

Right now {} means “still fetching”, “batch request failed”, and “this user really has no subscriptions”. The new column will therefore render 无订阅 for every row during refreshes and after any batch endpoint failure, which is incorrect admin data.

Also applies to: 123-130

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/hooks/users/useUsersData.jsx` around lines 99 - 105, The hook
useUsersData is collapsing "loading/error" and "no subscriptions" into the same
value by setting setUserSubscriptions({}) on fetch start/failure; instead
preserve a distinct sentinel for "unknown" (e.g., null or undefined) during
loading/errors and only set an empty object {} when the request succeeded and
returned an empty list. Change the logic around userList handling (the
conditional that calls setUserSubscriptions({}) at lines referencing userList)
to leave userSubscriptions as null/previous while fetching or on batch errors,
and only call setUserSubscriptions({}) when you have a successful response that
confirms there are no subscriptions; apply the same fix to the similar block
around lines 123-130.

Comment on lines +156 to +159
let url = `/api/user/search?keyword=${searchKeyword}&group=${searchGroup}&p=${startIdx}&page_size=${pageSize}`;
if (searchPlan) {
url += `&plan_id=${searchPlan}`;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Encode the search query parameters.

These values are interpolated raw into the URL, so searches break for common inputs like user+tag@example.com or any keyword containing &. Use URLSearchParams so keyword, group, and plan_id are encoded correctly.

💡 Suggested change
-    let url = `/api/user/search?keyword=${searchKeyword}&group=${searchGroup}&p=${startIdx}&page_size=${pageSize}`;
-    if (searchPlan) {
-      url += `&plan_id=${searchPlan}`;
-    }
-    const res = await API.get(url);
+    const params = new URLSearchParams({
+      keyword: searchKeyword,
+      group: searchGroup,
+      p: String(startIdx),
+      page_size: String(pageSize),
+    });
+    if (searchPlan) {
+      params.set('plan_id', String(searchPlan));
+    }
+    const res = await API.get(`/api/user/search?${params.toString()}`);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/hooks/users/useUsersData.jsx` around lines 156 - 159, The URL is
built by interpolating raw values (url, searchKeyword, searchGroup, searchPlan,
startIdx, pageSize) which breaks for characters like & or +; replace the string
interpolation with a URLSearchParams-based builder: create a params = new
URLSearchParams(), append keyword, group, p, page_size, and conditionally append
plan_id when searchPlan is present, then set url = `/api/user/search?` +
params.toString() so all query values are correctly encoded.

"选择充值额度": "Chọn hạn ngạch nạp tiền",
"选择全部": "Chọn tất cả",
"选择分组": "Chọn nhóm",
"选择订阅": "Chọn gói đăng ký",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Ambiguous translation duplicates another key.

The translation "Chọn gói đăng ký" for "选择订阅" (Select subscription) is identical to the translation for "选择订阅套餐" (Select subscription package) at line 3451. This creates ambiguity since two different Chinese source keys map to the same Vietnamese text.

The typical pattern for "选择XXX" in this file is "Chọn XXX" (e.g., line 3221: "选择分组": "Chọn nhóm"). Consider using "Chọn đăng ký" to differentiate from the more specific "选择订阅套餐".

Suggested differentiation
-    "选择订阅": "Chọn gói đăng ký",
+    "选择订阅": "Chọn đăng ký",

This maintains consistency with the "选择XXX" → "Chọn XXX" pattern and differentiates from line 3451's "选择订阅套餐": "Chọn gói đăng ký".

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"选择订阅": "Chọn gói đăng ký",
"选择订阅": "Chọn đăng ký",
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/i18n/locales/vi.json` at line 3422, The Vietnamese translation for
the key "选择订阅" currently duplicates the text used for "选择订阅套餐"; update the
translation for "选择订阅" (the entry with source key "选择订阅") to a differentiated
form such as "Chọn đăng ký" to follow the "选择XXX" → "Chọn XXX" pattern and avoid
ambiguity with the existing "选择订阅套餐" → "Chọn gói đăng ký" entry.

@ImogeneOctaviap794

Copy link
Copy Markdown
Contributor Author

关闭后修复 review 问题重新提交

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.

1 participant