Repository navigation
feat(admin): 用户管理列表展示订阅信息并支持按订阅套餐筛选 - #4133
ImogeneOctaviap794 wants to merge 1 commit into
Conversation
后端: - 新增 GetActiveSubscriptionsByUserIds 批量查询活跃订阅 - 新增 POST /api/subscription/admin/users/batch_active_subscriptions 接口 - SearchUsers 支持 plan_id 参数筛选订阅用户 前端: - 用户列表新增订阅信息列,支持多订阅 Tag 展示 - 不同套餐自动分配不同颜色,过期订阅灰色 - Tooltip 显示到期时间和额度使用量 - 新增选择订阅下拉筛选框 - 批量接口替代 N+1 请求,含竞态保护 i18n: - 7 种语言新增 5 个翻译 key
WalkthroughThis 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
Sequence DiagramssequenceDiagram
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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (1)
web/bun.lockis excluded by!**/*.lock
📒 Files selected for processing (17)
controller/subscription.gocontroller/user.gomodel/subscription.gomodel/user.gorouter/api-router.goweb/src/components/table/users/UsersColumnDefs.jsxweb/src/components/table/users/UsersFilters.jsxweb/src/components/table/users/UsersTable.jsxweb/src/components/table/users/index.jsxweb/src/hooks/users/useUsersData.jsxweb/src/i18n/locales/en.jsonweb/src/i18n/locales/fr.jsonweb/src/i18n/locales/ja.jsonweb/src/i18n/locales/ru.jsonweb/src/i18n/locales/vi.jsonweb/src/i18n/locales/zh-CN.jsonweb/src/i18n/locales/zh-TW.json
| planId, parseErr := strconv.Atoi(planIdStr) | ||
| if parseErr != nil { | ||
| common.ApiError(c, parseErr) | ||
| return |
There was a problem hiding this comment.
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.
| 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.
| const endDate = sub.end_time | ||
| ? new Date(sub.end_time * 1000).toLocaleDateString() | ||
| : '-'; | ||
|
|
||
| const tooltipContent = ( | ||
| <div className='text-xs'> | ||
| <div> | ||
| {t('到期')}: {endDate} |
There was a problem hiding this comment.
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.
| 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); |
There was a problem hiding this comment.
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.
| if (!userList || userList.length === 0) { | ||
| setUserSubscriptions({}); | ||
| return; | ||
| } | ||
|
|
||
| setUserSubscriptions({}); | ||
|
|
There was a problem hiding this comment.
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.
| let url = `/api/user/search?keyword=${searchKeyword}&group=${searchGroup}&p=${startIdx}&page_size=${pageSize}`; | ||
| if (searchPlan) { | ||
| url += `&plan_id=${searchPlan}`; | ||
| } |
There was a problem hiding this comment.
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ý", |
There was a problem hiding this comment.
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.
| "选择订阅": "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.
|
关闭后修复 review 问题重新提交 |
📝 变更描述 / 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_subscriptionsmodel/user.go:SearchUsers新增可选参数planId,通过子查询筛选持有指定活跃订阅的用户controller/user.go:SearchUsers解析plan_idquery 参数并传入 model 层前端:
useUsersData.jsx:planOptions/userSubscriptionsstatefetchPlans)loadUserSubscriptions)useRef防止快速翻页时旧请求覆盖新数据(竞态保护)plan_id参数UsersFilters.jsx:新增「选择订阅」下拉筛选框UsersColumnDefs.jsx:UsersTable.jsx/index.jsx:透传planOptions和userSubscriptions到列定义i18n:
选择订阅、无订阅、到期、订阅中、订阅信息🚀 变更类型 / Type of change
🔗 关联任务 / Related Issue
N/A
✅ 提交前检查项 / Checklist
📸 运行证明 / Proof of Work
Summary by CodeRabbit
Release Notes
New Features
Localization