From ee760de2c8b85942a9e38cbab9df8c20e70b08c9 Mon Sep 17 00:00:00 2001 From: Mahdi Fallahnejhad <60172658+Zaltapar@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:06:45 +0330 Subject: [PATCH] feat(clients): show a client's usage and change history in the editor (#7031) The client editor gets a "Usage & change history" button: lifetime traffic (every closed cycle plus the open one), usage per node since the last reset, the past cycles, and a log of what changed on the client and from where. A cycle is archived in one place, whenever a traffic reset or an auto-renewal zeroes a client's counters. Both tables are bounded per client: the newest 100 cycles are kept and older ones fold into a single "earlier" row, so the lifetime total does not change; the change log keeps the newest 200 rows and is taken from the stored record before and after an operation (editor save, bulk adjust, bulk enable/disable, bot setters, auto-renewal). A rename moves the history to the new email. The history belongs to the client. Nothing is archived on delete; ReapSyncOrphansJob drops the history of emails no client holds, every five minutes. It lists them outside the traffic writer by walking the email index (about 10 ms on SQLite for 10k clients with 3M history rows) and enters the writer only to delete. Known limit: a client re-created under a deleted client's email before that job runs keeps the old client's history. Edits through an API token are logged with the source "panel". --- .github/workflows/ci.yml | 10 + docs/architecture.md | 1 + .../content/docs/en/reference/api/clients.mdx | 36 +- docs/public/openapi.json | 259 ++++++++ frontend/public/openapi.json | 259 ++++++++ .../api/queries/useClientUsageHistoryQuery.ts | 30 + frontend/src/api/queryKeys.ts | 1 + .../clients/ClientUsageHistoryModal.tsx | 268 ++++++++ frontend/src/generated/examples.ts | 59 ++ frontend/src/generated/schemas.ts | 177 ++++++ frontend/src/generated/types.ts | 37 ++ frontend/src/generated/zod.ts | 41 ++ frontend/src/lib/clients/usage-history.ts | 80 +++ frontend/src/pages/api-docs/endpoints.ts | 15 + .../src/pages/clients/ClientFormModal.tsx | 19 +- .../test/client-usage-history-modal.test.tsx | 129 ++++ internal/database/db.go | 2 + internal/database/migrate_data.go | 2 + internal/database/model/client_change_log.go | 13 + .../database/model/client_traffic_window.go | 12 + internal/web/controller/client.go | 11 + internal/web/job/reap_sync_orphans_job.go | 17 +- .../web/job/reap_sync_orphans_job_test.go | 42 ++ internal/web/service/client_bulk.go | 2 + internal/web/service/client_crud.go | 14 +- internal/web/service/client_inbound_apply.go | 4 + internal/web/service/client_traffic.go | 3 + internal/web/service/client_usage_history.go | 375 +++++++++++ .../client_usage_history_postgres_test.go | 88 +++ .../web/service/client_usage_history_test.go | 590 ++++++++++++++++++ internal/web/service/inbound_traffic.go | 15 + internal/web/translation/ar-EG.json | 32 +- internal/web/translation/en-US.json | 32 +- internal/web/translation/es-ES.json | 32 +- internal/web/translation/fa-IR.json | 32 +- internal/web/translation/id-ID.json | 32 +- internal/web/translation/ja-JP.json | 32 +- internal/web/translation/pt-BR.json | 32 +- internal/web/translation/ru-RU.json | 32 +- internal/web/translation/sk-SK.json | 32 +- internal/web/translation/tr-TR.json | 32 +- internal/web/translation/uk-UA.json | 32 +- internal/web/translation/vi-VN.json | 32 +- internal/web/translation/zh-CN.json | 32 +- internal/web/translation/zh-TW.json | 32 +- tools/openapigen/main.go | 4 + 46 files changed, 3037 insertions(+), 26 deletions(-) create mode 100644 frontend/src/api/queries/useClientUsageHistoryQuery.ts create mode 100644 frontend/src/components/clients/ClientUsageHistoryModal.tsx create mode 100644 frontend/src/lib/clients/usage-history.ts create mode 100644 frontend/src/test/client-usage-history-modal.test.tsx create mode 100644 internal/database/model/client_change_log.go create mode 100644 internal/database/model/client_traffic_window.go create mode 100644 internal/web/job/reap_sync_orphans_job_test.go create mode 100644 internal/web/service/client_usage_history.go create mode 100644 internal/web/service/client_usage_history_postgres_test.go create mode 100644 internal/web/service/client_usage_history_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d4e2337f2..08731d130 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -114,6 +114,16 @@ jobs: exit 1 fi + - name: PostgreSQL client usage history + run: | + set -o pipefail + go test ./internal/web/service -run '^TestClientUsageHistoryPostgres$' -count=1 -v | tee /tmp/postgres-usage-history.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-usage-history.log || true) + if [ "$passed" -ne 1 ]; then + echo "expected 1 passing PostgreSQL client usage history test, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL depletion query regressions run: | set -o pipefail diff --git a/docs/architecture.md b/docs/architecture.md index 4c60361ed..22cf83c74 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -418,6 +418,7 @@ All registered in `web.go` → `startTask()`. Each is a struct with a `Run()` me | `@every 10s` | `mtproto_job` | Reconcile `mtg` sidecars against enabled MTProto inbounds | | `@every 10s` | `amneziawg_job` | Reconcile embedded AmneziaWG interfaces against enabled local inbounds | | `@every 5m` | `outbound_subscription_job` | Refresh outbound provider configs | +| `@every 5m` | `reap_sync_orphans_job` | Delete sync-orphaned clients, then the history of emails no client holds | | `@every 10m` | `clear_logs_job` (`PruneXrayLogsJob`) | Truncate Xray access/error logs once either exceeds 64 MiB | | `@hourly` | `warp_ip_job`, `periodic_traffic_reset_job("hourly")` | WARP IP rotation; traffic resets | | `@daily` | `clear_logs_job`, `periodic_traffic_reset_job("daily")`, `periodic_traffic_reset_job("monthly")` | IP-limit and Xray access/error log cleanup; daily resets and due monthly resets | diff --git a/docs/content/docs/en/reference/api/clients.mdx b/docs/content/docs/en/reference/api/clients.mdx index 4fd2153cf..4194b8a0b 100644 --- a/docs/content/docs/en/reference/api/clients.mdx +++ b/docs/content/docs/en/reference/api/clients.mdx @@ -330,6 +330,23 @@ _openapi: - depth: 2 title: Traffic counters for a client identified by email. url: '#traffic-counters-for-a-client-identified-by-email' + - depth: 2 + title: "Usage and change history for one client, behind the edit modal's history + button. lifetimeUp/lifetimeDown are every archived window plus the + client's live counters; currentUp/currentDown are the still-open window. + windows lists the closed cycles, newest first (reason: reset | renew | + earlier): one is archived whenever a traffic reset or an auto-renewal + zeroes the client's counters, the newest 100 are kept and older ones are + folded into a single earlier row, so the lifetime total does not change. + nodes is the per-node upload/download accumulated since the last reset. + changes is the metadata change log, newest first, capped at the newest + 200 rows: one row per changed field (subId, expiry, dataLimit, enable, + limitIp, limitHwid, adTag, group, renewalPlan) and a name row for a + rename; source is panel | tgbot | auto-renew. A renamed client keeps its + history under the new email. The history belongs to the client: once the + client is deleted, its history is removed within five minutes. Requires + an admin token or a panel login session." + url: '#usage-and-change-history-for-one-client-behind-the-edit-modals-history-button-lifetimeuplifetimedown-are-every-archived-window-plus-the-clients-live-counters-currentupcurrentdown-are-the-still-open-window-windows-lists-the-closed-cycles-newest-first-reason-reset--renew--earlier-one-is-archived-whenever-a-traffic-reset-or-an-auto-renewal-zeroes-the-clients-counters-the-newest-100-are-kept-and-older-ones-are-folded-into-a-single-earlier-row-so-the-lifetime-total-does-not-change-nodes-is-the-per-node-uploaddownload-accumulated-since-the-last-reset-changes-is-the-metadata-change-log-newest-first-capped-at-the-newest-200-rows-one-row-per-changed-field-subid-expiry-datalimit-enable-limitip-limithwid-adtag-group-renewalplan-and-a-name-row-for-a-rename-source-is-panel--tgbot--auto-renew-a-renamed-client-keeps-its-history-under-the-new-email-the-history-belongs-to-the-client-once-the-client-is-deleted-its-history-is-removed-within-five-minutes-requires-an-admin-token-or-a-panel-login-session' - depth: 2 title: Return every protocol URL (vless://, vmess://, trojan://, ss://, hysteria://, hy2://) for clients matching the subscription ID. Same @@ -631,6 +648,23 @@ _openapi: id: map-of-client-email--last-seen-unix-timestamp - content: Traffic counters for a client identified by email. id: traffic-counters-for-a-client-identified-by-email + - content: "Usage and change history for one client, behind the edit modal's + history button. lifetimeUp/lifetimeDown are every archived window plus + the client's live counters; currentUp/currentDown are the still-open + window. windows lists the closed cycles, newest first (reason: reset | + renew | earlier): one is archived whenever a traffic reset or an + auto-renewal zeroes the client's counters, the newest 100 are kept and + older ones are folded into a single earlier row, so the lifetime total + does not change. nodes is the per-node upload/download accumulated + since the last reset. changes is the metadata change log, newest + first, capped at the newest 200 rows: one row per changed field + (subId, expiry, dataLimit, enable, limitIp, limitHwid, adTag, group, + renewalPlan) and a name row for a rename; source is panel | tgbot | + auto-renew. A renamed client keeps its history under the new email. + The history belongs to the client: once the client is deleted, its + history is removed within five minutes. Requires an admin token or a + panel login session." + id: usage-and-change-history-for-one-client-behind-the-edit-modals-history-button-lifetimeuplifetimedown-are-every-archived-window-plus-the-clients-live-counters-currentupcurrentdown-are-the-still-open-window-windows-lists-the-closed-cycles-newest-first-reason-reset--renew--earlier-one-is-archived-whenever-a-traffic-reset-or-an-auto-renewal-zeroes-the-clients-counters-the-newest-100-are-kept-and-older-ones-are-folded-into-a-single-earlier-row-so-the-lifetime-total-does-not-change-nodes-is-the-per-node-uploaddownload-accumulated-since-the-last-reset-changes-is-the-metadata-change-log-newest-first-capped-at-the-newest-200-rows-one-row-per-changed-field-subid-expiry-datalimit-enable-limitip-limithwid-adtag-group-renewalplan-and-a-name-row-for-a-rename-source-is-panel--tgbot--auto-renew-a-renamed-client-keeps-its-history-under-the-new-email-the-history-belongs-to-the-client-once-the-client-is-deleted-its-history-is-removed-within-five-minutes-requires-an-admin-token-or-a-panel-login-session - content: Return every protocol URL (vless://, vmess://, trojan://, ss://, hysteria://, hy2://) for clients matching the subscription ID. Same result set as the configured subPath endpoint, but as a JSON array — @@ -832,7 +866,7 @@ export default function Layout(props) { return ( <> {props.children} - + ); } \ No newline at end of file diff --git a/docs/public/openapi.json b/docs/public/openapi.json index d65258604..4781420a0 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -2187,6 +2187,52 @@ ], "type": "object" }, + "ClientChangeLog": { + "description": "ClientChangeLog records one metadata change to a client: one row per\nchanged field, newest read first in the client's usage history.", + "properties": { + "at": { + "example": 1735689600000, + "format": "int64", + "type": "integer" + }, + "email": { + "example": "user1@example.com", + "type": "string" + }, + "field": { + "example": "dataLimit", + "type": "string" + }, + "id": { + "example": 14825, + "format": "int64", + "type": "integer" + }, + "newValue": { + "example": "21474836480", + "type": "string" + }, + "oldValue": { + "example": "10737418240", + "type": "string" + }, + "source": { + "description": "panel | tgbot | auto-renew", + "example": "panel", + "type": "string" + } + }, + "required": [ + "at", + "email", + "field", + "id", + "newValue", + "oldValue", + "source" + ], + "type": "object" + }, "ClientInbound": { "properties": { "clientId": { @@ -2211,6 +2257,36 @@ ], "type": "object" }, + "ClientNodeUsage": { + "description": "ClientNodeUsage is one node's counters for a client since its last reset.", + "properties": { + "down": { + "example": 2097152, + "format": "int64", + "type": "integer" + }, + "nodeId": { + "example": 7, + "type": "integer" + }, + "nodeName": { + "example": "de-fra-1", + "type": "string" + }, + "up": { + "example": 1048576, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "down", + "nodeId", + "nodeName", + "up" + ], + "type": "object" + }, "ClientPageResponse": { "description": "ClientPageResponse is the shape returned by ListPaged. `Total` is the\nrow count in the DB; `Filtered` is the count after Search/Filter/Protocol\nwere applied, before pagination. The page contains at most PageSize items.\nSummary is computed across the full DB row set so dashboard counters\non the clients page stay stable as the user paginates/filters.", "properties": { @@ -2741,6 +2817,107 @@ ], "type": "object" }, + "ClientTrafficWindow": { + "description": "ClientTrafficWindow is one closed traffic window of a client: usage zeroed at a\nreset or an auto-renewal; lifetime = SUM(rows) + live counters.", + "properties": { + "at": { + "example": 1735689600000, + "format": "int64", + "type": "integer" + }, + "down": { + "example": 2097152, + "format": "int64", + "type": "integer" + }, + "email": { + "example": "user1@example.com", + "type": "string" + }, + "id": { + "example": 14825, + "format": "int64", + "type": "integer" + }, + "reason": { + "description": "reset | renew | earlier", + "example": "reset", + "type": "string" + }, + "up": { + "example": 1048576, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "at", + "down", + "email", + "id", + "reason", + "up" + ], + "type": "object" + }, + "ClientUsageHistory": { + "description": "ClientUsageHistory is what the client editor's history button shows.", + "properties": { + "changes": { + "items": { + "$ref": "#/components/schemas/ClientChangeLog" + }, + "type": "array" + }, + "currentDown": { + "example": 2097152, + "format": "int64", + "type": "integer" + }, + "currentUp": { + "example": 1048576, + "format": "int64", + "type": "integer" + }, + "email": { + "example": "user1@example.com", + "type": "string" + }, + "lifetimeDown": { + "example": 21474836480, + "format": "int64", + "type": "integer" + }, + "lifetimeUp": { + "example": 10737418240, + "format": "int64", + "type": "integer" + }, + "nodes": { + "items": { + "$ref": "#/components/schemas/ClientNodeUsage" + }, + "type": "array" + }, + "windows": { + "items": { + "$ref": "#/components/schemas/ClientTrafficWindow" + }, + "type": "array" + } + }, + "required": [ + "changes", + "currentDown", + "currentUp", + "email", + "lifetimeDown", + "lifetimeUp", + "nodes", + "windows" + ], + "type": "object" + }, "ClientsSummary": { "description": "ClientsSummary collects per-bucket counts plus the matching email lists so\nthe clients page can render the dashboard stat cards and their hover\npopovers without shipping the full client array. The counters are exact;\nthe lists stop at clientSummaryEmailCap entries and only back the popovers.", "properties": { @@ -12571,6 +12748,88 @@ } } }, + "/panel/api/clients/usageHistory/{email}": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Usage and change history for one client, behind the edit modal's history button. lifetimeUp/lifetimeDown are every archived window plus the client's live counters; currentUp/currentDown are the still-open window. windows lists the closed cycles, newest first (reason: reset | renew | earlier): one is archived whenever a traffic reset or an auto-renewal zeroes the client's counters, the newest 100 are kept and older ones are folded into a single earlier row, so the lifetime total does not change. nodes is the per-node upload/download accumulated since the last reset. changes is the metadata change log, newest first, capped at the newest 200 rows: one row per changed field (subId, expiry, dataLimit, enable, limitIp, limitHwid, adTag, group, renewalPlan) and a name row for a rename; source is panel | tgbot | auto-renew. A renamed client keeps its history under the new email. The history belongs to the client: once the client is deleted, its history is removed within five minutes. Requires an admin token or a panel login session.", + "operationId": "get_panel_api_clients_usageHistory_email", + "parameters": [ + { + "name": "email", + "in": "path", + "required": true, + "description": "Client email (unique across the panel).", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/ClientUsageHistory" + } + } + }, + "example": { + "success": true, + "obj": { + "changes": [ + { + "at": 1735689600000, + "email": "user1@example.com", + "field": "dataLimit", + "id": 14825, + "newValue": "21474836480", + "oldValue": "10737418240", + "source": "panel" + } + ], + "currentDown": 2097152, + "currentUp": 1048576, + "email": "user1@example.com", + "lifetimeDown": 21474836480, + "lifetimeUp": 10737418240, + "nodes": [ + { + "down": 2097152, + "nodeId": 7, + "nodeName": "de-fra-1", + "up": 1048576 + } + ], + "windows": [ + { + "at": 1735689600000, + "down": 2097152, + "email": "user1@example.com", + "id": 14825, + "reason": "reset", + "up": 1048576 + } + ] + } + } + } + } + } + } + } + }, "/panel/api/clients/subLinks/{subId}": { "get": { "tags": [ diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index d65258604..4781420a0 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -2187,6 +2187,52 @@ ], "type": "object" }, + "ClientChangeLog": { + "description": "ClientChangeLog records one metadata change to a client: one row per\nchanged field, newest read first in the client's usage history.", + "properties": { + "at": { + "example": 1735689600000, + "format": "int64", + "type": "integer" + }, + "email": { + "example": "user1@example.com", + "type": "string" + }, + "field": { + "example": "dataLimit", + "type": "string" + }, + "id": { + "example": 14825, + "format": "int64", + "type": "integer" + }, + "newValue": { + "example": "21474836480", + "type": "string" + }, + "oldValue": { + "example": "10737418240", + "type": "string" + }, + "source": { + "description": "panel | tgbot | auto-renew", + "example": "panel", + "type": "string" + } + }, + "required": [ + "at", + "email", + "field", + "id", + "newValue", + "oldValue", + "source" + ], + "type": "object" + }, "ClientInbound": { "properties": { "clientId": { @@ -2211,6 +2257,36 @@ ], "type": "object" }, + "ClientNodeUsage": { + "description": "ClientNodeUsage is one node's counters for a client since its last reset.", + "properties": { + "down": { + "example": 2097152, + "format": "int64", + "type": "integer" + }, + "nodeId": { + "example": 7, + "type": "integer" + }, + "nodeName": { + "example": "de-fra-1", + "type": "string" + }, + "up": { + "example": 1048576, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "down", + "nodeId", + "nodeName", + "up" + ], + "type": "object" + }, "ClientPageResponse": { "description": "ClientPageResponse is the shape returned by ListPaged. `Total` is the\nrow count in the DB; `Filtered` is the count after Search/Filter/Protocol\nwere applied, before pagination. The page contains at most PageSize items.\nSummary is computed across the full DB row set so dashboard counters\non the clients page stay stable as the user paginates/filters.", "properties": { @@ -2741,6 +2817,107 @@ ], "type": "object" }, + "ClientTrafficWindow": { + "description": "ClientTrafficWindow is one closed traffic window of a client: usage zeroed at a\nreset or an auto-renewal; lifetime = SUM(rows) + live counters.", + "properties": { + "at": { + "example": 1735689600000, + "format": "int64", + "type": "integer" + }, + "down": { + "example": 2097152, + "format": "int64", + "type": "integer" + }, + "email": { + "example": "user1@example.com", + "type": "string" + }, + "id": { + "example": 14825, + "format": "int64", + "type": "integer" + }, + "reason": { + "description": "reset | renew | earlier", + "example": "reset", + "type": "string" + }, + "up": { + "example": 1048576, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "at", + "down", + "email", + "id", + "reason", + "up" + ], + "type": "object" + }, + "ClientUsageHistory": { + "description": "ClientUsageHistory is what the client editor's history button shows.", + "properties": { + "changes": { + "items": { + "$ref": "#/components/schemas/ClientChangeLog" + }, + "type": "array" + }, + "currentDown": { + "example": 2097152, + "format": "int64", + "type": "integer" + }, + "currentUp": { + "example": 1048576, + "format": "int64", + "type": "integer" + }, + "email": { + "example": "user1@example.com", + "type": "string" + }, + "lifetimeDown": { + "example": 21474836480, + "format": "int64", + "type": "integer" + }, + "lifetimeUp": { + "example": 10737418240, + "format": "int64", + "type": "integer" + }, + "nodes": { + "items": { + "$ref": "#/components/schemas/ClientNodeUsage" + }, + "type": "array" + }, + "windows": { + "items": { + "$ref": "#/components/schemas/ClientTrafficWindow" + }, + "type": "array" + } + }, + "required": [ + "changes", + "currentDown", + "currentUp", + "email", + "lifetimeDown", + "lifetimeUp", + "nodes", + "windows" + ], + "type": "object" + }, "ClientsSummary": { "description": "ClientsSummary collects per-bucket counts plus the matching email lists so\nthe clients page can render the dashboard stat cards and their hover\npopovers without shipping the full client array. The counters are exact;\nthe lists stop at clientSummaryEmailCap entries and only back the popovers.", "properties": { @@ -12571,6 +12748,88 @@ } } }, + "/panel/api/clients/usageHistory/{email}": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Usage and change history for one client, behind the edit modal's history button. lifetimeUp/lifetimeDown are every archived window plus the client's live counters; currentUp/currentDown are the still-open window. windows lists the closed cycles, newest first (reason: reset | renew | earlier): one is archived whenever a traffic reset or an auto-renewal zeroes the client's counters, the newest 100 are kept and older ones are folded into a single earlier row, so the lifetime total does not change. nodes is the per-node upload/download accumulated since the last reset. changes is the metadata change log, newest first, capped at the newest 200 rows: one row per changed field (subId, expiry, dataLimit, enable, limitIp, limitHwid, adTag, group, renewalPlan) and a name row for a rename; source is panel | tgbot | auto-renew. A renamed client keeps its history under the new email. The history belongs to the client: once the client is deleted, its history is removed within five minutes. Requires an admin token or a panel login session.", + "operationId": "get_panel_api_clients_usageHistory_email", + "parameters": [ + { + "name": "email", + "in": "path", + "required": true, + "description": "Client email (unique across the panel).", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/ClientUsageHistory" + } + } + }, + "example": { + "success": true, + "obj": { + "changes": [ + { + "at": 1735689600000, + "email": "user1@example.com", + "field": "dataLimit", + "id": 14825, + "newValue": "21474836480", + "oldValue": "10737418240", + "source": "panel" + } + ], + "currentDown": 2097152, + "currentUp": 1048576, + "email": "user1@example.com", + "lifetimeDown": 21474836480, + "lifetimeUp": 10737418240, + "nodes": [ + { + "down": 2097152, + "nodeId": 7, + "nodeName": "de-fra-1", + "up": 1048576 + } + ], + "windows": [ + { + "at": 1735689600000, + "down": 2097152, + "email": "user1@example.com", + "id": 14825, + "reason": "reset", + "up": 1048576 + } + ] + } + } + } + } + } + } + } + }, "/panel/api/clients/subLinks/{subId}": { "get": { "tags": [ diff --git a/frontend/src/api/queries/useClientUsageHistoryQuery.ts b/frontend/src/api/queries/useClientUsageHistoryQuery.ts new file mode 100644 index 000000000..98e2bb399 --- /dev/null +++ b/frontend/src/api/queries/useClientUsageHistoryQuery.ts @@ -0,0 +1,30 @@ +import { useQuery } from '@tanstack/react-query'; + +import { keys } from '@/api/queryKeys'; +import { + normalizeClientUsageHistory, + type ClientUsageHistoryInfo, +} from '@/lib/clients/usage-history'; +import { HttpUtil } from '@/utils'; + +async function fetchClientUsageHistory(email: string): Promise { + const msg = await HttpUtil.get( + `/panel/api/clients/usageHistory/${encodeURIComponent(email)}`, + undefined, + { silent: true }, + ); + if (!msg?.success || !msg.obj) { + throw new Error(msg?.msg || 'Failed to load the usage history'); + } + return normalizeClientUsageHistory(msg.obj); +} + +// The edit modal's usage-history fetch: runs only while the modal is open +// for a real client, and caches per email so a reopen is instant. +export function useClientUsageHistoryQuery(email: string | undefined, enabled: boolean) { + return useQuery({ + queryKey: keys.clients.usageHistory(email ?? ''), + enabled: enabled && !!email, + queryFn: () => fetchClientUsageHistory(email as string), + }); +} diff --git a/frontend/src/api/queryKeys.ts b/frontend/src/api/queryKeys.ts index 3962ed0b3..c03d796ad 100644 --- a/frontend/src/api/queryKeys.ts +++ b/frontend/src/api/queryKeys.ts @@ -41,6 +41,7 @@ export const keys = { activeInbounds: () => ['clients', 'activeInbounds'] as const, lastOnline: () => ['clients', 'lastOnline'] as const, groups: () => ['clients', 'groups'] as const, + usageHistory: (email: string) => ['clients', 'usageHistory', email] as const, }, xray: { root: () => ['xray'] as const, diff --git a/frontend/src/components/clients/ClientUsageHistoryModal.tsx b/frontend/src/components/clients/ClientUsageHistoryModal.tsx new file mode 100644 index 000000000..9b52a467d --- /dev/null +++ b/frontend/src/components/clients/ClientUsageHistoryModal.tsx @@ -0,0 +1,268 @@ +import { useTranslation } from 'react-i18next'; +import { Modal, Spin, Table, Tag, Typography } from 'antd'; + +import { useClientUsageHistoryQuery } from '@/api/queries/useClientUsageHistoryQuery'; +import { useDatepicker } from '@/hooks/useDatepicker'; +import { IntlUtil, SizeFormatter } from '@/utils'; + +interface ClientUsageHistoryModalProps { + open: boolean; + email?: string; + zIndex?: number; + onClose: () => void; +} + +// Reason label for each closed traffic window; unknown reasons stay raw so a +// future reason still renders instead of blanking out. +const REASON_KEYS: Record = { + reset: 'pages.clients.reasonReset', + renew: 'pages.clients.reasonRenew', + earlier: 'pages.clients.reasonEarlier', +}; + +// Human labels for the change-log field names; unknown fields fall back to the +// raw key so a future field still renders instead of blanking out. +const FIELD_KEYS: Record = { + name: 'pages.clients.fieldName', + subId: 'pages.clients.fieldSubId', + expiry: 'pages.clients.fieldExpiry', + dataLimit: 'pages.clients.fieldDataLimit', + enable: 'pages.clients.fieldEnable', + renewalPlan: 'pages.clients.fieldRenewalPlan', + limitIp: 'pages.clients.fieldLimitIp', + limitHwid: 'pages.clients.fieldLimitHwid', + adTag: 'pages.clients.fieldAdTag', + group: 'pages.clients.fieldGroup', +}; + +function fieldLabel(t: (key: string) => string, field: string): string { + const key = FIELD_KEYS[field]; + return key ? t(key) : field; +} + +function changeValueText(field: string, value: string, formatDate: (ts: number) => string): string { + if (value === '') return '—'; + if (field === 'expiry') { + const n = Number(value); + if (Number.isFinite(n) && n > 0) return formatDate(n); + } else if (field === 'dataLimit') { + const n = Number(value); + if (Number.isFinite(n)) return SizeFormatter.sizeFormat(n); + } + return value; +} + +export default function ClientUsageHistoryModal({ + open, + email, + zIndex, + onClose, +}: ClientUsageHistoryModalProps) { + const { t } = useTranslation(); + const { data: history, isFetching, isError } = useClientUsageHistoryQuery(email, open); + const { datepicker } = useDatepicker(); + const formatDate = (ts: number) => IntlUtil.formatDate(ts, datepicker); + + const bytesCell = (value: number) => SizeFormatter.sizeFormat(value); + + const nodeColumns = [ + { + title: t('pages.clients.node'), + dataIndex: 'nodeName', + key: 'nodeName', + render: (value: string, row: { nodeId: number }) => value || `#${row.nodeId}`, + }, + { + title: t('pages.clients.upload'), + dataIndex: 'up', + key: 'up', + width: 140, + align: 'right' as const, + render: bytesCell, + }, + { + title: t('pages.clients.download'), + dataIndex: 'down', + key: 'down', + width: 140, + align: 'right' as const, + render: bytesCell, + }, + ]; + + const windowColumns = [ + { + title: t('pages.clients.time'), + dataIndex: 'at', + key: 'at', + width: 160, + render: formatDate, + }, + { + title: t('pages.clients.upload'), + dataIndex: 'up', + key: 'up', + width: 110, + align: 'right' as const, + render: bytesCell, + }, + { + title: t('pages.clients.download'), + dataIndex: 'down', + key: 'down', + width: 110, + align: 'right' as const, + render: bytesCell, + }, + { + title: t('pages.clients.reason'), + dataIndex: 'reason', + key: 'reason', + width: 90, + render: (value: string) => {REASON_KEYS[value] ? t(REASON_KEYS[value]) : value}, + }, + ]; + + const changeColumns = [ + { + title: t('pages.clients.time'), + dataIndex: 'at', + key: 'at', + width: 160, + render: formatDate, + }, + { + title: t('pages.clients.field'), + dataIndex: 'field', + key: 'field', + width: 100, + render: (value: string) => fieldLabel(t, value), + }, + { + title: t('pages.clients.oldValue'), + dataIndex: 'oldValue', + key: 'oldValue', + render: (value: string, row: { field: string }) => + changeValueText(row.field, value, formatDate), + }, + { + title: t('pages.clients.newValue'), + dataIndex: 'newValue', + key: 'newValue', + render: (value: string, row: { field: string }) => + changeValueText(row.field, value, formatDate), + }, + { + title: t('pages.clients.source'), + dataIndex: 'source', + key: 'source', + width: 90, + render: (value: string) => {value}, + }, + ]; + + const hasContent = + history !== undefined && + (history.lifetimeUp > 0 || + history.lifetimeDown > 0 || + history.windows.length > 0 || + history.nodes.length > 0 || + history.changes.length > 0); + + return ( + + {isFetching ? ( +
+ +
+ ) : isError ? ( + {t('pages.clients.historyError')} + ) : !hasContent ? ( + {t('pages.clients.noUsageHistory')} + ) : ( +
+
+ + {t('pages.clients.lifetimeTraffic')} + + + + + + + + + + + + + +
{t('pages.clients.upload')} + {SizeFormatter.sizeFormat(history!.lifetimeUp)} + {t('pages.clients.download')} + {SizeFormatter.sizeFormat(history!.lifetimeDown)} +
+ {t('pages.clients.currentCycle')}: ↑{' '} + {SizeFormatter.sizeFormat(history!.currentUp)} / ↓{' '} + {SizeFormatter.sizeFormat(history!.currentDown)} +
+
+ {history!.nodes.length > 0 && ( +
+ + {t('pages.clients.usageByNode')} + + + + )} + {history!.windows.length > 0 && ( +
+ + {t('pages.clients.pastCycles')} + +
+
+ + + )} + {history!.changes.length > 0 && ( +
+ + {t('pages.clients.changes')} + +
+
+ + + )} + + )} + + ); +} diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index e080c5c11..f4a55ffc1 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -524,12 +524,27 @@ export const EXAMPLES: Record = { } ] }, + "ClientChangeLog": { + "at": 1735689600000, + "email": "user1@example.com", + "field": "dataLimit", + "id": 14825, + "newValue": "21474836480", + "oldValue": "10737418240", + "source": "panel" + }, "ClientInbound": { "clientId": 0, "createdAt": 0, "flowOverride": "", "inboundId": 0 }, + "ClientNodeUsage": { + "down": 2097152, + "nodeId": 7, + "nodeName": "de-fra-1", + "up": 1048576 + }, "ClientPageResponse": { "filtered": 47, "groups": [ @@ -696,6 +711,50 @@ export const EXAMPLES: Record = { "up": 1048576, "uuid": "e18c9a96-71bf-48d4-933f-8b9a46d4290c" }, + "ClientTrafficWindow": { + "at": 1735689600000, + "down": 2097152, + "email": "user1@example.com", + "id": 14825, + "reason": "reset", + "up": 1048576 + }, + "ClientUsageHistory": { + "changes": [ + { + "at": 1735689600000, + "email": "user1@example.com", + "field": "dataLimit", + "id": 14825, + "newValue": "21474836480", + "oldValue": "10737418240", + "source": "panel" + } + ], + "currentDown": 2097152, + "currentUp": 1048576, + "email": "user1@example.com", + "lifetimeDown": 21474836480, + "lifetimeUp": 10737418240, + "nodes": [ + { + "down": 2097152, + "nodeId": 7, + "nodeName": "de-fra-1", + "up": 1048576 + } + ], + "windows": [ + { + "at": 1735689600000, + "down": 2097152, + "email": "user1@example.com", + "id": 14825, + "reason": "reset", + "up": 1048576 + } + ] + }, "ClientsSummary": { "active": 1850, "deactive": [ diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index 8fb853833..5e9320253 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -2161,6 +2161,52 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "ClientChangeLog": { + "description": "ClientChangeLog records one metadata change to a client: one row per\nchanged field, newest read first in the client's usage history.", + "properties": { + "at": { + "example": 1735689600000, + "format": "int64", + "type": "integer" + }, + "email": { + "example": "user1@example.com", + "type": "string" + }, + "field": { + "example": "dataLimit", + "type": "string" + }, + "id": { + "example": 14825, + "format": "int64", + "type": "integer" + }, + "newValue": { + "example": "21474836480", + "type": "string" + }, + "oldValue": { + "example": "10737418240", + "type": "string" + }, + "source": { + "description": "panel | tgbot | auto-renew", + "example": "panel", + "type": "string" + } + }, + "required": [ + "at", + "email", + "field", + "id", + "newValue", + "oldValue", + "source" + ], + "type": "object" + }, "ClientInbound": { "properties": { "clientId": { @@ -2185,6 +2231,36 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "ClientNodeUsage": { + "description": "ClientNodeUsage is one node's counters for a client since its last reset.", + "properties": { + "down": { + "example": 2097152, + "format": "int64", + "type": "integer" + }, + "nodeId": { + "example": 7, + "type": "integer" + }, + "nodeName": { + "example": "de-fra-1", + "type": "string" + }, + "up": { + "example": 1048576, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "down", + "nodeId", + "nodeName", + "up" + ], + "type": "object" + }, "ClientPageResponse": { "description": "ClientPageResponse is the shape returned by ListPaged. `Total` is the\nrow count in the DB; `Filtered` is the count after Search/Filter/Protocol\nwere applied, before pagination. The page contains at most PageSize items.\nSummary is computed across the full DB row set so dashboard counters\non the clients page stay stable as the user paginates/filters.", "properties": { @@ -2715,6 +2791,107 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "ClientTrafficWindow": { + "description": "ClientTrafficWindow is one closed traffic window of a client: usage zeroed at a\nreset or an auto-renewal; lifetime = SUM(rows) + live counters.", + "properties": { + "at": { + "example": 1735689600000, + "format": "int64", + "type": "integer" + }, + "down": { + "example": 2097152, + "format": "int64", + "type": "integer" + }, + "email": { + "example": "user1@example.com", + "type": "string" + }, + "id": { + "example": 14825, + "format": "int64", + "type": "integer" + }, + "reason": { + "description": "reset | renew | earlier", + "example": "reset", + "type": "string" + }, + "up": { + "example": 1048576, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "at", + "down", + "email", + "id", + "reason", + "up" + ], + "type": "object" + }, + "ClientUsageHistory": { + "description": "ClientUsageHistory is what the client editor's history button shows.", + "properties": { + "changes": { + "items": { + "$ref": "#/components/schemas/ClientChangeLog" + }, + "type": "array" + }, + "currentDown": { + "example": 2097152, + "format": "int64", + "type": "integer" + }, + "currentUp": { + "example": 1048576, + "format": "int64", + "type": "integer" + }, + "email": { + "example": "user1@example.com", + "type": "string" + }, + "lifetimeDown": { + "example": 21474836480, + "format": "int64", + "type": "integer" + }, + "lifetimeUp": { + "example": 10737418240, + "format": "int64", + "type": "integer" + }, + "nodes": { + "items": { + "$ref": "#/components/schemas/ClientNodeUsage" + }, + "type": "array" + }, + "windows": { + "items": { + "$ref": "#/components/schemas/ClientTrafficWindow" + }, + "type": "array" + } + }, + "required": [ + "changes", + "currentDown", + "currentUp", + "email", + "lifetimeDown", + "lifetimeUp", + "nodes", + "windows" + ], + "type": "object" + }, "ClientsSummary": { "description": "ClientsSummary collects per-bucket counts plus the matching email lists so\nthe clients page can render the dashboard stat cards and their hover\npopovers without shipping the full client array. The counters are exact;\nthe lists stop at clientSummaryEmailCap entries and only back the popovers.", "properties": { diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 4174060b1..3d851811d 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -507,6 +507,16 @@ export interface Client { wireguardDevices?: WireguardDevice[]; } +export interface ClientChangeLog { + at: number; + email: string; + field: string; + id: number; + newValue: string; + oldValue: string; + source: string; +} + export interface ClientInbound { clientId: number; createdAt: number; @@ -514,6 +524,13 @@ export interface ClientInbound { inboundId: number; } +export interface ClientNodeUsage { + down: number; + nodeId: number; + nodeName: string; + up: number; +} + export interface ClientPageResponse { filtered: number; groups: string[]; @@ -628,6 +645,26 @@ export interface ClientTraffic { uuid: string; } +export interface ClientTrafficWindow { + at: number; + down: number; + email: string; + id: number; + reason: string; + up: number; +} + +export interface ClientUsageHistory { + changes: ClientChangeLog[]; + currentDown: number; + currentUp: number; + email: string; + lifetimeDown: number; + lifetimeUp: number; + nodes: ClientNodeUsage[]; + windows: ClientTrafficWindow[]; +} + export interface ClientsSummary { active: number; deactive: string[]; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index c2ffd90aa..02164dac4 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -527,6 +527,17 @@ export const ClientSchema = z.object({ }); export type Client = z.infer; +export const ClientChangeLogSchema = z.object({ + at: z.number().int(), + email: z.string(), + field: z.string(), + id: z.number().int(), + newValue: z.string(), + oldValue: z.string(), + source: z.string(), +}); +export type ClientChangeLog = z.infer; + export const ClientInboundSchema = z.object({ clientId: z.number().int(), createdAt: z.number().int(), @@ -535,6 +546,14 @@ export const ClientInboundSchema = z.object({ }); export type ClientInbound = z.infer; +export const ClientNodeUsageSchema = z.object({ + down: z.number().int(), + nodeId: z.number().int(), + nodeName: z.string(), + up: z.number().int(), +}); +export type ClientNodeUsage = z.infer; + export const ClientPageResponseSchema = z.object({ filtered: z.number().int(), groups: z.array(z.string()), @@ -656,6 +675,28 @@ export const ClientTrafficSchema = z.object({ }); export type ClientTraffic = z.infer; +export const ClientTrafficWindowSchema = z.object({ + at: z.number().int(), + down: z.number().int(), + email: z.string(), + id: z.number().int(), + reason: z.string(), + up: z.number().int(), +}); +export type ClientTrafficWindow = z.infer; + +export const ClientUsageHistorySchema = z.object({ + changes: z.array(z.lazy(() => ClientChangeLogSchema)), + currentDown: z.number().int(), + currentUp: z.number().int(), + email: z.string(), + lifetimeDown: z.number().int(), + lifetimeUp: z.number().int(), + nodes: z.array(z.lazy(() => ClientNodeUsageSchema)), + windows: z.array(z.lazy(() => ClientTrafficWindowSchema)), +}); +export type ClientUsageHistory = z.infer; + export const ClientsSummarySchema = z.object({ active: z.number().int(), deactive: z.array(z.string()), diff --git a/frontend/src/lib/clients/usage-history.ts b/frontend/src/lib/clients/usage-history.ts new file mode 100644 index 000000000..51be9cfe6 --- /dev/null +++ b/frontend/src/lib/clients/usage-history.ts @@ -0,0 +1,80 @@ +export interface ClientTrafficWindowInfo { + id: number; + email: string; + at: number; + up: number; + down: number; + reason: string; +} + +export interface ClientNodeUsageInfo { + nodeId: number; + nodeName: string; + up: number; + down: number; +} + +export interface ClientChangeInfo { + id: number; + email: string; + at: number; + field: string; + oldValue: string; + newValue: string; + source: string; +} + +export interface ClientUsageHistoryInfo { + email: string; + lifetimeUp: number; + lifetimeDown: number; + currentUp: number; + currentDown: number; + windows: ClientTrafficWindowInfo[]; + nodes: ClientNodeUsageInfo[]; + changes: ClientChangeInfo[]; +} + +const num = (value: unknown, fallback = 0): number => + typeof value === 'number' && Number.isFinite(value) ? value : fallback; + +// The backend omits empty collections; the modal always wants real arrays. +export function normalizeClientUsageHistory(raw: unknown): ClientUsageHistoryInfo { + const obj = (raw ?? {}) as Record; + const rows = (value: unknown): Array> => + Array.isArray(value) + ? value.filter( + (entry): entry is Record => !!entry && typeof entry === 'object', + ) + : []; + return { + email: typeof obj.email === 'string' ? obj.email : '', + lifetimeUp: num(obj.lifetimeUp), + lifetimeDown: num(obj.lifetimeDown), + currentUp: num(obj.currentUp), + currentDown: num(obj.currentDown), + windows: rows(obj.windows).map((w) => ({ + id: num(w.id), + email: String(w.email ?? ''), + at: num(w.at), + up: num(w.up), + down: num(w.down), + reason: String(w.reason ?? ''), + })), + nodes: rows(obj.nodes).map((n) => ({ + nodeId: num(n.nodeId), + nodeName: String(n.nodeName ?? ''), + up: num(n.up), + down: num(n.down), + })), + changes: rows(obj.changes).map((c) => ({ + id: num(c.id), + email: String(c.email ?? ''), + at: num(c.at), + field: String(c.field ?? ''), + oldValue: String(c.oldValue ?? ''), + newValue: String(c.newValue ?? ''), + source: String(c.source ?? ''), + })), + }; +} diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index e23b82b13..b725f84f1 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -1870,6 +1870,21 @@ export const sections: readonly Section[] = [ ], responseSchema: 'ClientTraffic', }, + { + method: 'GET', + path: '/panel/api/clients/usageHistory/:email', + summary: + "Usage and change history for one client, behind the edit modal's history button. lifetimeUp/lifetimeDown are every archived window plus the client's live counters; currentUp/currentDown are the still-open window. windows lists the closed cycles, newest first (reason: reset | renew | earlier): one is archived whenever a traffic reset or an auto-renewal zeroes the client's counters, the newest 100 are kept and older ones are folded into a single earlier row, so the lifetime total does not change. nodes is the per-node upload/download accumulated since the last reset. changes is the metadata change log, newest first, capped at the newest 200 rows: one row per changed field (subId, expiry, dataLimit, enable, limitIp, limitHwid, adTag, group, renewalPlan) and a name row for a rename; source is panel | tgbot | auto-renew. A renamed client keeps its history under the new email. The history belongs to the client: once the client is deleted, its history is removed within five minutes. Requires an admin token or a panel login session.", + params: [ + { + name: 'email', + in: 'path', + type: 'string', + desc: 'Client email (unique across the panel).', + }, + ], + responseSchema: 'ClientUsageHistory', + }, { method: 'GET', path: '/panel/api/clients/subLinks/:subId', diff --git a/frontend/src/pages/clients/ClientFormModal.tsx b/frontend/src/pages/clients/ClientFormModal.tsx index 24916789c..e66963c95 100644 --- a/frontend/src/pages/clients/ClientFormModal.tsx +++ b/frontend/src/pages/clients/ClientFormModal.tsx @@ -19,7 +19,7 @@ import { Typography, message, } from 'antd'; -import { EyeOutlined, ReloadOutlined, RetweetOutlined } from '@ant-design/icons'; +import { EyeOutlined, HistoryOutlined, ReloadOutlined, RetweetOutlined } from '@ant-design/icons'; import dayjs from 'dayjs'; import type { Dayjs } from 'dayjs'; import { FormProvider, useForm, useWatch, type FieldPath } from 'react-hook-form'; @@ -36,6 +36,7 @@ import { useRawHostsQuery } from '@/api/queries/useRawHostsQuery'; import { DateTimePicker, SelectAllClearButtons, selectTagRender } from '@/components/form'; import { FormField, rhfZodValidate } from '@/components/form/rhf'; import ClientHwidListModal from '@/components/clients/ClientHwidList'; +import ClientUsageHistoryModal from '@/components/clients/ClientUsageHistoryModal'; import { TLS_FLOW_CONTROL, TRAFFIC_RESETS } from '@/schemas/primitives'; import { OptionalAmneziaWGKeepAliveInputSchema, @@ -293,6 +294,7 @@ export default function ClientFormModal({ setHwidBlocked, } = useClientHwids(client?.email); const [hwidsModalOpen, setHwidsModalOpen] = useState(false); + const [usageHistoryOpen, setUsageHistoryOpen] = useState(false); const { datepicker } = useDatepicker(); const hwidDateLabel = (ts: number) => !ts || ts <= 0 ? '-' : IntlUtil.formatDate(ts, datepicker); @@ -908,6 +910,14 @@ export default function ClientFormModal({ )} + {isEdit && client?.email && ( + + )}