Skip to content

add top 10 user const with dashboard - #3244

Closed
gmij wants to merge 5412 commits into
QuantumNous:mainfrom
gmij:main
Closed

gmij wants to merge 5412 commits into
QuantumNous:mainfrom
gmij:main

Conversation

@gmij

@gmij gmij commented Mar 13, 2026 •

Copy link
Copy Markdown
  • 修复日志列表中, 用户名未显示为用户显示名称(如果 该值 为空时,显示用户名)
  • 在首页看板处, 添加用户调用量视图,方便查看用量大户。

Summary by CodeRabbit

  • New Features

    • Admin dashboard: added a "User consumption ranking" bar chart/tab showing top users by quota with time-window filtering.
    • Admin API: new admin-only endpoint to fetch top-users data for the chart.
  • User Experience

    • Usage logs now show user display names and avatar initials when available.
  • Internationalization

    • Added English translations for the new chart labels and related terms.

t0ng7u and others added 30 commits February 7, 2026 00:57
Add a lightweight active-subscription check to skip subscription pre-consume when none exist, reducing unnecessary transactions and locks. In the subscription UI, disable subscription-first options when no active plan is available, show the effective fallback to wallet with a clear notice, and distinguish “invalidated” from “expired” states. Update i18n strings across supported locales to reflect the new messages and status labels.
Aligns the error variable types in the subscription-first path so that quota fallback checks use the correct NewAPIError.
This prevents build failures and preserves the intended wallet fallback when subscription pre-consume returns an insufficient quota error.
Routes quota alerts through a subscription-specific check when billing from subscriptions, preventing wallet-based thresholds from triggering false warnings.
Updates the notification settings description and localization keys to clarify that both wallet and subscription balances are monitored.
…n-quota-notify

🔔 feat: Add subscription-aware quota notifications and update UI copy
…-preference-fallback

✨ chore: Improve subscription billing fallback and UI states
…tumNous#2881)

当上游为 AWS Bedrock 时,message_delta 的 usage 可能缺少 input_tokens、
cache_creation_input_tokens、cache_read_input_tokens 等字段,导致与原生
Anthropic 格式不一致。从 message_start 积累的 claudeInfo 中补全这些字段后
重新序列化,确保客户端收到一致的 usage 格式。
Modified the formatUserLogs function to include a startIdx parameter, allowing for more flexible log ID assignment. Updated calls to this function in GetLogByTokenId and GetUserLogs to pass the appropriate starting index.
feat: add Codex channel disclaimer (i18n, OpenAI terms)
feat: Force beta=true parameter for Anthropic channel
feat(oauth): implement custom OAuth provider
fix: Claude stream block index/type transitions
fix: add paragraph breaks between reasoning summary chunks
# Conflicts:
#	service/openaicompat/chat_to_responses.go
…t-stream

feat: channel test with stream=true
…fo-input-token

fix: 使用openai兼容接口调用部分渠道在最终端点为claude原生端点下还是走了openai扣减input_token的逻辑
fix: 补全 streaming message_delta 事件缺失的 input_tokens 和 cache 相关字段
…sponses

feat: /v1/messages -> /v1/responses
…ion-configurable

feat: make 5m cache-creation ratio configurable
fix: 如果模型管理有自定义配置则不合并默认配置
fix: 修复模型管理"参与官方同步"与"状态"开关无法保存的问题
Calcium-Ion and others added 7 commits March 12, 2026 19:05
- Add display_name field to Log model (read-only from users table)
- Update GetAllLogs to fetch display_name via bulk query
- Update frontend to show display_name instead of username
- Add grouping dropdown with User/Hour/Model options
- Implement grouping logic with aggregated stats

Co-authored-by: gmij <22893579+gmij@users.noreply.github.com>
The grouping feature was querying the logs table and doing client-side
aggregation, but the system has a dedicated quota_data table for
aggregated statistics.

Removed:
- Grouping dropdown UI from filters
- Client-side grouping logic (getProcessedLogs)
- Grouping state management
- Group summary rendering in columns

The logs page is now focused on viewing detailed log records.
For aggregated statistics and grouping by user/model/time, users
should use the existing Data Dashboard (/api/data endpoints) which
properly leverages the quota_data table.

This aligns with the system architecture where:
- logs table = detailed per-request records
- quota_data table = hourly aggregated statistics

Co-authored-by: gmij <22893579+gmij@users.noreply.github.com>
Co-authored-by: gmij <22893579+gmij@users.noreply.github.com>
…ropdown

feat: add top users consumption ranking to dashboard
@coderabbitai

coderabbitai Bot commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds an admin-only API and DB query to return top users by quota, enriches logs with display names via bulk user lookup, and introduces frontend hooks, chart spec, UI tab, and i18n to display an admin-only user consumption ranking.

Changes

Cohort / File(s) Summary
Backend: API handler & route
controller/usedata.go, router/api-router.go
New exported handler GetTopUsersByQuota parses start_timestamp, end_timestamp, limit (default 10, cap 100), calls model.GetTopUsersByQuota, returns JSON {success,message,data}; route registered at /api/data/top-users with AdminAuth.
Backend: Usage data query
model/usedata.go
Added GetTopUsersByQuota(startTime int64, endTime int64, limit int) that aggregates SUM(quota), COUNT(*), SUM(token_used) grouped by user_id, username, ordered by quota desc, limited to N results.
Backend: Log model enrichment
model/log.go
Added DisplayName string \json:"display_name" gorm:"->"`toLog; GetAllLogsnow bulk-fetchesdisplay_namefor distinctuser_ids and fills DisplayName` on logs.
Frontend: Dashboard charts & props
web/src/components/dashboard/ChartsPanel.jsx, web/src/components/dashboard/index.jsx
Adds admin-only "用户消耗排行" tab and renders spec_user_rank_bar when isAdminUser; index maps fetched top users into spec_user_rank_bar and passes isAdminUser.
Frontend: Charts spec hook
web/src/hooks/dashboard/useDashboardCharts.jsx
Introduces spec_user_rank_bar state and setSpecUserRankBar, exposing them from the hook with a horizontal bar chart configuration.
Frontend: Data hook & loading
web/src/hooks/dashboard/useDashboardData.js
Adds topUsersData, topUsersLoading, and loadTopUsersData (admin-only) to fetch /api/data/top-users for current time window; integrates into refresh flow and exposes states and loader.
Frontend: Usage logs display
web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx
USERNAME cell now prefers `record.display_name
i18n
web/src/i18n/locales/en.json
Added translations: "用户消耗排行" → "User consumption ranking", "个用户" → " users".

Sequence Diagram(s)

sequenceDiagram
  participant Frontend as "Frontend\n(Dashboard)"
  participant Router as "Router\n(api-router)"
  participant Controller as "Controller\nGetTopUsersByQuota"
  participant Model as "Model\nGetTopUsersByQuota"
  participant DB as "Database"

  Frontend->>Router: GET /api/data/top-users?start_timestamp&end_timestamp&limit
  Router->>Controller: invoke GetTopUsersByQuota(c)
  Controller->>Controller: parse & validate params (start,end,limit)
  Controller->>Model: GetTopUsersByQuota(start,end,limit)
  Model->>DB: SELECT user_id, username, SUM(quota), COUNT(*), SUM(token_used) ... GROUP BY user_id ORDER BY SUM(quota) DESC LIMIT N
  DB-->>Model: rows
  Model-->>Controller: []*QuotaData
  Controller-->>Frontend: JSON {success:true, message:"", data: [...]}
  Frontend->>Frontend: map data -> spec_user_rank_bar then render chart
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • seefs001
  • Calcium-Ion

Poem

🐰 I nibble logs and count each bite,
Bars hop high in admin light,
Names appear and totals gleam,
Charts parade a crunchy dream,
🥕📊

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

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.
Title check ❓ Inconclusive The title 'add top 10 user const with dashboard' is vague and generic. While it references adding top users to the dashboard, it uses unclear phrasing ('top 10 user const') and doesn't clearly convey the main objectives of both fixing display name fallback in logs and adding a user consumption ranking view. Consider using a more descriptive title that clearly summarizes both main objectives, such as 'Add user consumption ranking dashboard and fix display name in logs' or similar.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

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: 4

🧹 Nitpick comments (3)
web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx (1)

444-459: Use the same identity source for avatar text and color.

Right now the avatar character uses displayText, but color still hashes text (username). Using one source avoids subtle mismatch.

♻️ Optional consistency tweak
       render: (text, record, index) => {
         const displayText = record.display_name || text;
+        const colorSeed = displayText || text;
         return isAdminUser ? (
           <div>
             <Avatar
               size='extra-small'
-              color={stringToColor(text)}
+              color={stringToColor(colorSeed)}
               style={{ marginRight: 4 }}
               onClick={(event) => {
                 event.stopPropagation();
                 showUserInfoFunc(record.user_id);
               }}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx` around lines 444
- 459, The avatar uses displayText for the visible character but still hashes
the original text for color, causing mismatches; update the Avatar usage in the
render block (component Avatar inside UsageLogsColumnDefs) to call stringToColor
with the same source as the avatar text (displayText derived from
record.display_name || text) so both the character and color are computed from
the same value, and keep the onClick handler (showUserInfoFunc) and trimming
logic (displayText.slice(0,1)) unchanged.
web/src/components/dashboard/ChartsPanel.jsx (1)

59-82: Normalize activeChartTab when admin permission is not present.

If the state is '5' and isAdminUser becomes false, this component can render an empty chart area.

♻️ Suggested guard
 const ChartsPanel = ({
@@
   t,
 }) => {
+  React.useEffect(() => {
+    if (!isAdminUser && activeChartTab === '5') {
+      setActiveChartTab('1');
+    }
+  }, [isAdminUser, activeChartTab, setActiveChartTab]);
+
   return (
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/components/dashboard/ChartsPanel.jsx` around lines 59 - 82, When
isAdminUser flips to false while activeChartTab === '5' the panel can render
nothing; add a guard in the ChartsPanel component to normalize activeChartTab
when permissions change: inside the component (where activeChartTab and
setActiveChartTab are defined) add an effect that watches isAdminUser and
activeChartTab and, if isAdminUser is false and activeChartTab === '5', call
setActiveChartTab to a valid fallback (e.g. '1' or the current first visible
tab). This ensures the conditional render blocks (checks of activeChartTab and
isAdminUser for spec_user_rank_bar) always have a valid tab selected.
web/src/hooks/dashboard/useDashboardData.js (1)

254-259: Consider parallelizing independent refresh calls.

loadUptimeData and loadTopUsersData don’t depend on quota response, so running them concurrently can reduce refresh latency.

⚡ Suggested refactor
   const refresh = useCallback(async () => {
-    const data = await loadQuotaData();
-    await loadUptimeData();
-    await loadTopUsersData();
+    const [data] = await Promise.all([
+      loadQuotaData(),
+      loadUptimeData(),
+      loadTopUsersData(),
+    ]);
     return data;
   }, [loadQuotaData, loadUptimeData, loadTopUsersData]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/hooks/dashboard/useDashboardData.js` around lines 254 - 259, The
refresh function currently awaits loadQuotaData, then sequentially awaits
loadUptimeData and loadTopUsersData; kick off loadUptimeData and
loadTopUsersData concurrently (e.g. call them to get promises first) and then
await those promises together with Promise.all (or Promise.allSettled) while
still awaiting loadQuotaData to return its value; update the refresh
implementation (function name refresh, and calls to loadQuotaData,
loadUptimeData, loadTopUsersData) to start the two independent calls in parallel
and await them together to reduce latency.
🤖 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/usedata.go`:
- Around line 59-61: The current check resets limit to 10 for any non-positive
or overly large value; change this to clamp properly by keeping the default of
10 only when limit <= 0 and otherwise capping values > 100 to 100 — e.g. replace
the single if (limit <= 0 || limit > 100) { limit = 10 } with two checks: if
limit <= 0 { limit = 10 } else if limit > 100 { limit = 100 }; update the code
that uses the variable limit accordingly (look for the variable named "limit" in
controller/usedata.go).

In `@model/usedata.go`:
- Around line 133-137: The query currently groups by both user_id and username
(see DB.Table("quota_data") Select(...) and Group("user_id, username")) which
causes the same user to be split across rows when their username changes; change
the Group call to group only by "user_id" (Group("user_id")) and, if you still
need a username column in the Select, replace the raw username select with an
aggregated expression such as MAX(username) AS username (or similar) so the
SELECT and GROUP clauses remain consistent.

In `@web/src/components/dashboard/index.jsx`:
- Around line 144-163: The effect currently only updates the user-rank chart
when dashboardData.topUsersData has length > 0, which leaves stale chart data
when it becomes an empty array; change the logic around
dashboardData.topUsersData so it runs whenever topUsersData is defined (e.g.,
Array.isArray(dashboardData.topUsersData)), compute userRankData =
dashboardData.topUsersData.map(...) (will be [] when empty), and always call
dashboardCharts.setSpecUserRankBar to set data to the new values array and
update title.subtext to reflect the current count (userRankData.length),
ensuring the chart is cleared and subtitle shows zero when topUsersData is [].

In `@web/src/hooks/dashboard/useDashboardData.js`:
- Around line 220-243: When loading top users in loadTopUsersData, ensure stale
results are cleared on non-success and error paths by calling
setTopUsersData([]) whenever the API response is not successful (inside the else
branch) and also in the catch block; keep setTopUsersLoading(false) in finally
as-is and keep references to inputs and isAdminUser unchanged.

---

Nitpick comments:
In `@web/src/components/dashboard/ChartsPanel.jsx`:
- Around line 59-82: When isAdminUser flips to false while activeChartTab ===
'5' the panel can render nothing; add a guard in the ChartsPanel component to
normalize activeChartTab when permissions change: inside the component (where
activeChartTab and setActiveChartTab are defined) add an effect that watches
isAdminUser and activeChartTab and, if isAdminUser is false and activeChartTab
=== '5', call setActiveChartTab to a valid fallback (e.g. '1' or the current
first visible tab). This ensures the conditional render blocks (checks of
activeChartTab and isAdminUser for spec_user_rank_bar) always have a valid tab
selected.

In `@web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx`:
- Around line 444-459: The avatar uses displayText for the visible character but
still hashes the original text for color, causing mismatches; update the Avatar
usage in the render block (component Avatar inside UsageLogsColumnDefs) to call
stringToColor with the same source as the avatar text (displayText derived from
record.display_name || text) so both the character and color are computed from
the same value, and keep the onClick handler (showUserInfoFunc) and trimming
logic (displayText.slice(0,1)) unchanged.

In `@web/src/hooks/dashboard/useDashboardData.js`:
- Around line 254-259: The refresh function currently awaits loadQuotaData, then
sequentially awaits loadUptimeData and loadTopUsersData; kick off loadUptimeData
and loadTopUsersData concurrently (e.g. call them to get promises first) and
then await those promises together with Promise.all (or Promise.allSettled)
while still awaiting loadQuotaData to return its value; update the refresh
implementation (function name refresh, and calls to loadQuotaData,
loadUptimeData, loadTopUsersData) to start the two independent calls in parallel
and await them together to reduce latency.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e2f6b9d2-856f-447e-ac95-e98420d0e279

📥 Commits

Reviewing files that changed from the base of the PR and between 4e1b05e and 0c8733d.

📒 Files selected for processing (10)
  • controller/usedata.go
  • model/log.go
  • model/usedata.go
  • router/api-router.go
  • web/src/components/dashboard/ChartsPanel.jsx
  • web/src/components/dashboard/index.jsx
  • web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx
  • web/src/hooks/dashboard/useDashboardCharts.jsx
  • web/src/hooks/dashboard/useDashboardData.js
  • web/src/i18n/locales/en.json

Comment thread controller/usedata.go Resolved
Comment thread model/usedata.go Resolved
Comment thread web/src/components/dashboard/index.jsx Resolved

@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.

♻️ Duplicate comments (1)
web/src/components/dashboard/index.jsx (1)

144-164: ⚠️ Potential issue | 🟠 Major

Fix stale “用户消耗排行” chart when data becomes empty.

Line 144 still blocks updates for [], so old bars/subtitle can persist. This issue appears unresolved from the earlier review.

🔧 Suggested fix
-  useEffect(() => {
-    if (dashboardData.topUsersData && dashboardData.topUsersData.length > 0) {
-      const userRankData =  (dashboardData.topUsersData || []).map((item) => ({
-        username: item.username,
-        quota: item.quota,
-      }));
-
-      dashboardCharts.setSpecUserRankBar((prev) => ({
-        ...prev,
-        data: [
-          {
-            id: 'userRankData',
-            values: userRankData,
-          },
-        ],
-        title: {
-          ...prev.title,
-          subtext: `${dashboardData.t('总计')}:${userRankData.length}${dashboardData.t('个用户')}`,
-        },
-      }));
-    }
-  }, [dashboardData.topUsersData, dashboardData.t, dashboardCharts.setSpecUserRankBar]);
+  useEffect(() => {
+    if (!Array.isArray(dashboardData.topUsersData)) return;
+    const userRankData = dashboardData.topUsersData.map((item) => ({
+      username: item.username,
+      quota: item.quota,
+    }));
+
+    dashboardCharts.setSpecUserRankBar((prev) => ({
+      ...prev,
+      data: [
+        {
+          id: 'userRankData',
+          values: userRankData,
+        },
+      ],
+      title: {
+        ...prev.title,
+        subtext: `${dashboardData.t('总计')}:${userRankData.length}${dashboardData.t('个用户')}`,
+      },
+    }));
+  }, [dashboardData.topUsersData, dashboardData.t, dashboardCharts.setSpecUserRankBar]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/components/dashboard/index.jsx` around lines 144 - 164, The effect
currently skips updates when dashboardData.topUsersData is an empty array,
leaving stale bars and subtitle; change the logic in the effect using
dashboardData.topUsersData and dashboardCharts.setSpecUserRankBar so it always
runs for both non-empty and empty arrays: compute userRankData =
(dashboardData.topUsersData || []).map(...) (or just use the fallback empty
array), then call dashboardCharts.setSpecUserRankBar to set data to an object
with id 'userRankData' and values userRankData (which will be [] when empty) and
update the title.subtext to reflect the current count (e.g.,
`${dashboardData.t('总计')}:${userRankData.length}${dashboardData.t('个用户')}`),
removing the conditional that requires length > 0 so the chart is cleared when
data becomes empty.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@web/src/components/dashboard/index.jsx`:
- Around line 144-164: The effect currently skips updates when
dashboardData.topUsersData is an empty array, leaving stale bars and subtitle;
change the logic in the effect using dashboardData.topUsersData and
dashboardCharts.setSpecUserRankBar so it always runs for both non-empty and
empty arrays: compute userRankData = (dashboardData.topUsersData || []).map(...)
(or just use the fallback empty array), then call
dashboardCharts.setSpecUserRankBar to set data to an object with id
'userRankData' and values userRankData (which will be [] when empty) and update
the title.subtext to reflect the current count (e.g.,
`${dashboardData.t('总计')}:${userRankData.length}${dashboardData.t('个用户')}`),
removing the conditional that requires length > 0 so the chart is cleared when
data becomes empty.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ad060448-d5c3-4ccf-ab95-08118a2c736c

📥 Commits

Reviewing files that changed from the base of the PR and between 0c8733d and 80866a6.

📒 Files selected for processing (1)
  • web/src/components/dashboard/index.jsx

@gmij gmij changed the title something feature add top 10 user const with dashboard Mar 16, 2026

@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.

🧹 Nitpick comments (1)
web/src/hooks/dashboard/useDashboardData.js (1)

257-262: Sequential API calls are acceptable, but parallel execution is an option.

The refresh function awaits three API calls sequentially. For admin users viewing the dashboard, this means serial latency.

♻️ Optional: Parallel data loading for faster refresh
 const refresh = useCallback(async () => {
-  const data = await loadQuotaData();
-  await loadUptimeData();
-  await loadTopUsersData();
+  const [data] = await Promise.all([
+    loadQuotaData(),
+    loadUptimeData(),
+    loadTopUsersData(),
+  ]);
   return data;
 }, [loadQuotaData, loadUptimeData, loadTopUsersData]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/hooks/dashboard/useDashboardData.js` around lines 257 - 262, The
refresh function currently awaits three API calls sequentially (refresh) which
increases latency; modify refresh to start all three loads concurrently using
Promise.all on loadQuotaData(), loadUptimeData(), and loadTopUsersData() and
await them together so they run in parallel, then return the quota result (the
resolved value from loadQuotaData) to preserve the existing return shape; locate
the refresh function and the loadQuotaData, loadUptimeData, and loadTopUsersData
references to implement this change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@web/src/hooks/dashboard/useDashboardData.js`:
- Around line 257-262: The refresh function currently awaits three API calls
sequentially (refresh) which increases latency; modify refresh to start all
three loads concurrently using Promise.all on loadQuotaData(), loadUptimeData(),
and loadTopUsersData() and await them together so they run in parallel, then
return the quota result (the resolved value from loadQuotaData) to preserve the
existing return shape; locate the refresh function and the loadQuotaData,
loadUptimeData, and loadTopUsersData references to implement this change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fb1ee8e5-65f7-49a8-83ce-a0e8d55d17ed

📥 Commits

Reviewing files that changed from the base of the PR and between 80866a6 and 923ca51.

📒 Files selected for processing (3)
  • web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx
  • web/src/hooks/dashboard/useDashboardData.js
  • web/src/i18n/locales/en.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • web/src/components/table/usage-logs/UsageLogsColumnDefs.jsx

@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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@web/src/hooks/dashboard/useDashboardData.js`:
- Around line 239-245: The catch block in useDashboardData's top-users fetch
currently only logs errors; update the catch to surface failures to the UI by
introducing and setting an error state (e.g., add setTopUsersError via useState
or reuse an existing global error handler) instead of only console.error,
clear/initialize that error before the fetch, and optionally trigger a
user-visible notification (e.g., enqueueSnackbar or similar) so components
reading top users (references: setTopUsersData, setTopUsersLoading, and the
top-users fetch function inside useDashboardData) can display an error message;
ensure the finally block still sets setTopUsersLoading(false).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: afeb3503-d2bc-45cd-ae87-ab9ae697567f

📥 Commits

Reviewing files that changed from the base of the PR and between 923ca51 and 8f90721.

📒 Files selected for processing (1)
  • web/src/hooks/dashboard/useDashboardData.js

Comment on lines +239 to +245
} catch (err) {
setTopUsersData([]);
console.error(err);
} finally {
setTopUsersLoading(false);
}
}, [inputs, isAdminUser]);

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

Surface fetch errors to users in the catch path.

At Line 239, request failures currently only log to console, so ranking silently disappears without feedback.

🔧 Suggested patch
   const loadTopUsersData = useCallback(async () => {
@@
     } catch (err) {
       setTopUsersData([]);
+      const errMsg =
+        err?.response?.data?.message || err?.message || t('加载用户消耗排行失败');
+      showError(errMsg);
       console.error(err);
     } finally {
       setTopUsersLoading(false);
     }
-  }, [inputs, isAdminUser]);
+  }, [inputs, isAdminUser, t]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/hooks/dashboard/useDashboardData.js` around lines 239 - 245, The
catch block in useDashboardData's top-users fetch currently only logs errors;
update the catch to surface failures to the UI by introducing and setting an
error state (e.g., add setTopUsersError via useState or reuse an existing global
error handler) instead of only console.error, clear/initialize that error before
the fetch, and optionally trigger a user-visible notification (e.g.,
enqueueSnackbar or similar) so components reading top users (references:
setTopUsersData, setTopUsersLoading, and the top-users fetch function inside
useDashboardData) can display an error message; ensure the finally block still
sets setTopUsersLoading(false).

@gmij

gmij commented Mar 18, 2026

Copy link
Copy Markdown
Author

@Calcium-Ion ??? 发生了什么?强制回滚了?

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.