mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-25 12:04:44 +03:00
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".
This commit is contained in:
committed by
GitHub
parent
a36858f36c
commit
ee760de2c8
@@ -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
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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}
|
||||
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/get","method":"get"},{"path":"/panel/api/clients/get/subId/{subId}","method":"get"},{"path":"/panel/api/clients/get/tgId/{tgId}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/renewalPreview","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/update","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/del","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/wireguardDevices","method":"get"},{"path":"/panel/api/clients/wireguardDevices","method":"post"},{"path":"/panel/api/clients/wireguardDevices/limit","method":"put"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"patch"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"delete"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkDetach","method":"post"},{"path":"/panel/api/clients/bulkResetTraffic","method":"post"},{"path":"/panel/api/clients/groups","method":"get"},{"path":"/panel/api/clients/groups/{name}/emails","method":"get"},{"path":"/panel/api/clients/groups/create","method":"post"},{"path":"/panel/api/clients/groups/rename","method":"post"},{"path":"/panel/api/clients/groups/delete","method":"post"},{"path":"/panel/api/clients/groups/resetTraffic","method":"post"},{"path":"/panel/api/clients/resetTraffic/{email}","method":"post"},{"path":"/panel/api/clients/updateTraffic/{email}","method":"post"},{"path":"/panel/api/clients/ips/{email}","method":"post"},{"path":"/panel/api/clients/clearIps/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}/block","method":"post"},{"path":"/panel/api/clients/onlines","method":"post"},{"path":"/panel/api/clients/onlinesByGuid","method":"post"},{"path":"/panel/api/clients/clientIpsByGuid","method":"post"},{"path":"/panel/api/clients/activeInbounds","method":"post"},{"path":"/panel/api/clients/lastOnline","method":"post"},{"path":"/panel/api/clients/traffic/{email}","method":"get"},{"path":"/panel/api/clients/subLinks/{subId}","method":"get"},{"path":"/panel/api/clients/happLink/{id}","method":"post"},{"path":"/panel/api/clients/links/{email}","method":"get"}]} showTitle />
|
||||
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/get","method":"get"},{"path":"/panel/api/clients/get/subId/{subId}","method":"get"},{"path":"/panel/api/clients/get/tgId/{tgId}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/renewalPreview","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/update","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/del","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/wireguardDevices","method":"get"},{"path":"/panel/api/clients/wireguardDevices","method":"post"},{"path":"/panel/api/clients/wireguardDevices/limit","method":"put"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"patch"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"delete"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkDetach","method":"post"},{"path":"/panel/api/clients/bulkResetTraffic","method":"post"},{"path":"/panel/api/clients/groups","method":"get"},{"path":"/panel/api/clients/groups/{name}/emails","method":"get"},{"path":"/panel/api/clients/groups/create","method":"post"},{"path":"/panel/api/clients/groups/rename","method":"post"},{"path":"/panel/api/clients/groups/delete","method":"post"},{"path":"/panel/api/clients/groups/resetTraffic","method":"post"},{"path":"/panel/api/clients/resetTraffic/{email}","method":"post"},{"path":"/panel/api/clients/updateTraffic/{email}","method":"post"},{"path":"/panel/api/clients/ips/{email}","method":"post"},{"path":"/panel/api/clients/clearIps/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}/block","method":"post"},{"path":"/panel/api/clients/onlines","method":"post"},{"path":"/panel/api/clients/onlinesByGuid","method":"post"},{"path":"/panel/api/clients/clientIpsByGuid","method":"post"},{"path":"/panel/api/clients/activeInbounds","method":"post"},{"path":"/panel/api/clients/lastOnline","method":"post"},{"path":"/panel/api/clients/traffic/{email}","method":"get"},{"path":"/panel/api/clients/usageHistory/{email}","method":"get"},{"path":"/panel/api/clients/subLinks/{subId}","method":"get"},{"path":"/panel/api/clients/happLink/{id}","method":"post"},{"path":"/panel/api/clients/links/{email}","method":"get"}]} showTitle />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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": [
|
||||
|
||||
@@ -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": [
|
||||
|
||||
@@ -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<ClientUsageHistoryInfo> {
|
||||
const msg = await HttpUtil.get<unknown>(
|
||||
`/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),
|
||||
});
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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<string, string> = {
|
||||
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<string, string> = {
|
||||
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) => <Tag>{REASON_KEYS[value] ? t(REASON_KEYS[value]) : value}</Tag>,
|
||||
},
|
||||
];
|
||||
|
||||
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) => <Tag>{value}</Tag>,
|
||||
},
|
||||
];
|
||||
|
||||
const hasContent =
|
||||
history !== undefined &&
|
||||
(history.lifetimeUp > 0 ||
|
||||
history.lifetimeDown > 0 ||
|
||||
history.windows.length > 0 ||
|
||||
history.nodes.length > 0 ||
|
||||
history.changes.length > 0);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={`${t('pages.clients.usageHistory')}${email ? ` — ${email}` : ''}`}
|
||||
width={720}
|
||||
zIndex={zIndex}
|
||||
onCancel={onClose}
|
||||
footer={null}
|
||||
destroyOnHidden
|
||||
>
|
||||
{isFetching ? (
|
||||
<div style={{ padding: 48, textAlign: 'center' }}>
|
||||
<Spin />
|
||||
</div>
|
||||
) : isError ? (
|
||||
<Typography.Text type="secondary">{t('pages.clients.historyError')}</Typography.Text>
|
||||
) : !hasContent ? (
|
||||
<Typography.Text type="secondary">{t('pages.clients.noUsageHistory')}</Typography.Text>
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
|
||||
<section>
|
||||
<Typography.Title level={5} style={{ marginBottom: 8 }}>
|
||||
{t('pages.clients.lifetimeTraffic')}
|
||||
</Typography.Title>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td style={{ padding: '2px 12px 2px 0' }}>{t('pages.clients.upload')}</td>
|
||||
<td style={{ textAlign: 'right' }}>
|
||||
{SizeFormatter.sizeFormat(history!.lifetimeUp)}
|
||||
</td>
|
||||
<td style={{ padding: '2px 12px' }}>{t('pages.clients.download')}</td>
|
||||
<td style={{ textAlign: 'right' }}>
|
||||
{SizeFormatter.sizeFormat(history!.lifetimeDown)}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colSpan={4} style={{ color: 'var(--ant-color-text-secondary)' }}>
|
||||
{t('pages.clients.currentCycle')}: ↑{' '}
|
||||
{SizeFormatter.sizeFormat(history!.currentUp)} / ↓{' '}
|
||||
{SizeFormatter.sizeFormat(history!.currentDown)}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
{history!.nodes.length > 0 && (
|
||||
<section>
|
||||
<Typography.Title level={5} style={{ marginBottom: 8 }}>
|
||||
{t('pages.clients.usageByNode')}
|
||||
</Typography.Title>
|
||||
<Table
|
||||
rowKey="nodeId"
|
||||
size="small"
|
||||
columns={nodeColumns}
|
||||
dataSource={history!.nodes}
|
||||
pagination={false}
|
||||
/>
|
||||
</section>
|
||||
)}
|
||||
{history!.windows.length > 0 && (
|
||||
<section>
|
||||
<Typography.Title level={5} style={{ marginBottom: 8 }}>
|
||||
{t('pages.clients.pastCycles')}
|
||||
</Typography.Title>
|
||||
<div style={{ maxHeight: 200, overflowY: 'auto' }}>
|
||||
<Table
|
||||
rowKey="id"
|
||||
size="small"
|
||||
columns={windowColumns}
|
||||
dataSource={history!.windows}
|
||||
pagination={false}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{history!.changes.length > 0 && (
|
||||
<section>
|
||||
<Typography.Title level={5} style={{ marginBottom: 8 }}>
|
||||
{t('pages.clients.changes')}
|
||||
</Typography.Title>
|
||||
<div style={{ maxHeight: 240, overflowY: 'auto' }}>
|
||||
<Table
|
||||
rowKey="id"
|
||||
size="small"
|
||||
columns={changeColumns}
|
||||
dataSource={history!.changes}
|
||||
pagination={false}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -524,12 +524,27 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
}
|
||||
]
|
||||
},
|
||||
"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<string, unknown> = {
|
||||
"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": [
|
||||
|
||||
@@ -2161,6 +2161,52 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
],
|
||||
"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<string, unknown> = {
|
||||
],
|
||||
"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<string, unknown> = {
|
||||
],
|
||||
"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": {
|
||||
|
||||
@@ -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[];
|
||||
|
||||
@@ -527,6 +527,17 @@ export const ClientSchema = z.object({
|
||||
});
|
||||
export type Client = z.infer<typeof ClientSchema>;
|
||||
|
||||
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<typeof ClientChangeLogSchema>;
|
||||
|
||||
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<typeof ClientInboundSchema>;
|
||||
|
||||
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<typeof ClientNodeUsageSchema>;
|
||||
|
||||
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<typeof ClientTrafficSchema>;
|
||||
|
||||
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<typeof ClientTrafficWindowSchema>;
|
||||
|
||||
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<typeof ClientUsageHistorySchema>;
|
||||
|
||||
export const ClientsSummarySchema = z.object({
|
||||
active: z.number().int(),
|
||||
deactive: z.array(z.string()),
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
const rows = (value: unknown): Array<Record<string, unknown>> =>
|
||||
Array.isArray(value)
|
||||
? value.filter(
|
||||
(entry): entry is Record<string, unknown> => !!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 ?? ''),
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -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',
|
||||
|
||||
@@ -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({
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
)}
|
||||
{isEdit && client?.email && (
|
||||
<Button
|
||||
icon={<HistoryOutlined aria-hidden />}
|
||||
onClick={() => setUsageHistoryOpen(true)}
|
||||
>
|
||||
{t('pages.clients.usageHistory')}
|
||||
</Button>
|
||||
)}
|
||||
<div style={{ marginInlineStart: 'auto', display: 'flex', gap: 8 }}>
|
||||
<Button onClick={close}>{t('cancel')}</Button>
|
||||
<Button type="primary" loading={submitting} onClick={onSubmit}>
|
||||
@@ -1637,6 +1647,13 @@ export default function ClientFormModal({
|
||||
onSetBlocked={setHwidBlocked}
|
||||
onClose={() => setHwidsModalOpen(false)}
|
||||
/>
|
||||
|
||||
<ClientUsageHistoryModal
|
||||
open={usageHistoryOpen}
|
||||
email={client?.email}
|
||||
zIndex={CLIENT_IP_LOG_MODAL_Z_INDEX}
|
||||
onClose={() => setUsageHistoryOpen(false)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import { act, render, screen, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import ClientUsageHistoryModal from '@/components/clients/ClientUsageHistoryModal';
|
||||
import { setDatepicker } from '@/hooks/useDatepicker';
|
||||
import { HttpUtil } from '@/utils';
|
||||
|
||||
const GiB = 1024 ** 3;
|
||||
|
||||
const history = {
|
||||
email: 'client@example.com',
|
||||
lifetimeUp: 10 * GiB,
|
||||
lifetimeDown: 20 * GiB,
|
||||
currentUp: GiB,
|
||||
currentDown: 2 * GiB,
|
||||
windows: [
|
||||
{
|
||||
id: 1,
|
||||
email: 'client@example.com',
|
||||
at: 1735689600000,
|
||||
up: 9 * GiB,
|
||||
down: 18 * GiB,
|
||||
reason: 'renew',
|
||||
},
|
||||
],
|
||||
nodes: [{ nodeId: 7, nodeName: 'de-fra-1', up: 3 * GiB, down: 4 * GiB }],
|
||||
changes: [
|
||||
{
|
||||
id: 1,
|
||||
email: 'client@example.com',
|
||||
at: 1735776000000,
|
||||
field: 'dataLimit',
|
||||
oldValue: String(10 * GiB),
|
||||
newValue: String(20 * GiB),
|
||||
source: 'panel',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function openModal() {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ClientUsageHistoryModal open email="client@example.com" onClose={() => {}} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ClientUsageHistoryModal', () => {
|
||||
afterEach(() => act(() => setDatepicker('gregorian')));
|
||||
|
||||
it('shows its dates in the calendar the panel is set to', async () => {
|
||||
act(() => setDatepicker('jalalian'));
|
||||
vi.spyOn(HttpUtil, 'get').mockResolvedValue({ success: true, msg: '', obj: history });
|
||||
|
||||
openModal();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Past cycles')).toBeTruthy();
|
||||
});
|
||||
// 2025-01-01 and 2025-01-02 are in Dey 1403: the cycle's time and the change's time.
|
||||
expect(screen.getAllByText(/۱۴۰۳/)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('shows lifetime totals, per-node usage and the change log', async () => {
|
||||
vi.spyOn(HttpUtil, 'get').mockResolvedValue({
|
||||
success: true,
|
||||
msg: '',
|
||||
obj: history,
|
||||
});
|
||||
|
||||
openModal();
|
||||
|
||||
// The content sections appear once the (mocked) fetch resolves.
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Lifetime traffic')).toBeTruthy();
|
||||
});
|
||||
// The modal title carries the email; the rest of the sections:
|
||||
expect(screen.getByText(/Usage & change history/)).toBeTruthy();
|
||||
expect(screen.getByText('Lifetime traffic')).toBeTruthy();
|
||||
expect(screen.getByText(/^Current cycle/)).toBeTruthy();
|
||||
// The per-node section carries its own up/down columns.
|
||||
expect(screen.getByText('Usage by node')).toBeTruthy();
|
||||
expect(screen.getByText('de-fra-1')).toBeTruthy();
|
||||
// The change log renders the renewed data limit with its source.
|
||||
expect(screen.getByText('Changes')).toBeTruthy();
|
||||
expect(screen.getByText('panel')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('renders the closed cycles table with the renew reason', async () => {
|
||||
vi.spyOn(HttpUtil, 'get').mockResolvedValue({
|
||||
success: true,
|
||||
msg: '',
|
||||
obj: history,
|
||||
});
|
||||
|
||||
openModal();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Past cycles')).toBeTruthy();
|
||||
});
|
||||
expect(screen.getByText('renewed')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('shows the empty state for a client without history', async () => {
|
||||
vi.spyOn(HttpUtil, 'get').mockResolvedValue({
|
||||
success: true,
|
||||
msg: '',
|
||||
obj: {
|
||||
email: 'fresh@example.com',
|
||||
lifetimeUp: 0,
|
||||
lifetimeDown: 0,
|
||||
currentUp: 0,
|
||||
currentDown: 0,
|
||||
windows: [],
|
||||
nodes: [],
|
||||
changes: [],
|
||||
},
|
||||
});
|
||||
|
||||
openModal();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('No usage or change history yet.')).toBeTruthy();
|
||||
});
|
||||
expect(screen.queryByText('Usage by node')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -87,6 +87,8 @@ func allModels() []any {
|
||||
&model.OutboundSubscription{},
|
||||
&model.SubBalancer{},
|
||||
&model.TuicTrafficReceipt{},
|
||||
&model.ClientTrafficWindow{},
|
||||
&model.ClientChangeLog{},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -61,6 +61,8 @@ func migrationModels() []any {
|
||||
&model.OutboundSubscription{},
|
||||
&model.SubBalancer{},
|
||||
&model.TuicTrafficReceipt{},
|
||||
&model.ClientTrafficWindow{},
|
||||
&model.ClientChangeLog{},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package model
|
||||
|
||||
// ClientChangeLog records one metadata change to a client: one row per
|
||||
// changed field, newest read first in the client's usage history.
|
||||
type ClientChangeLog struct {
|
||||
Id int64 `json:"id" gorm:"primaryKey;autoIncrement" example:"14825"`
|
||||
Email string `json:"email" gorm:"index:idx_client_change_log_email,composite:1;not null" example:"user1@example.com"`
|
||||
At int64 `json:"at" gorm:"index:idx_client_change_log_email,composite:2" example:"1735689600000"`
|
||||
Field string `json:"field" gorm:"size:32" example:"dataLimit"`
|
||||
OldValue string `json:"oldValue" gorm:"type:text" example:"10737418240"`
|
||||
NewValue string `json:"newValue" gorm:"type:text" example:"21474836480"`
|
||||
Source string `json:"source" gorm:"size:32" example:"panel"` // panel | tgbot | auto-renew
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package model
|
||||
|
||||
// ClientTrafficWindow is one closed traffic window of a client: usage zeroed at a
|
||||
// reset or an auto-renewal; lifetime = SUM(rows) + live counters.
|
||||
type ClientTrafficWindow struct {
|
||||
Id int64 `json:"id" gorm:"primaryKey;autoIncrement" example:"14825"`
|
||||
Email string `json:"email" gorm:"index:idx_client_traffic_window_email,composite:1;not null" example:"user1@example.com"`
|
||||
At int64 `json:"at" gorm:"index:idx_client_traffic_window_email,composite:2" example:"1735689600000"`
|
||||
Up int64 `json:"up" example:"1048576"`
|
||||
Down int64 `json:"down" example:"2097152"`
|
||||
Reason string `json:"reason" gorm:"size:16" example:"reset"` // reset | renew | earlier
|
||||
}
|
||||
@@ -58,6 +58,7 @@ func (a *ClientController) initRouter(g *gin.RouterGroup) {
|
||||
g.GET("/get/subId/:subId", a.getBySubId)
|
||||
g.GET("/get/tgId/:tgId", a.getByTgId)
|
||||
g.GET("/traffic/:email", a.getTrafficByEmail)
|
||||
g.GET("/usageHistory/:email", a.getUsageHistory)
|
||||
g.GET("/subLinks/:subId", a.getSubLinks)
|
||||
g.GET("/links/:email", a.getClientLinks)
|
||||
g.POST("/happLink/:id", a.generateHappLink)
|
||||
@@ -729,6 +730,16 @@ func (a *ClientController) getTrafficByEmail(c *gin.Context) {
|
||||
jsonObj(c, traffic, nil)
|
||||
}
|
||||
|
||||
func (a *ClientController) getUsageHistory(c *gin.Context) {
|
||||
email := c.Param("email")
|
||||
history, err := a.clientService.GetUsageHistory(email)
|
||||
if err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.trafficGetError"), err)
|
||||
return
|
||||
}
|
||||
jsonObj(c, history, nil)
|
||||
}
|
||||
|
||||
func (a *ClientController) getSubLinks(c *gin.Context) {
|
||||
links, err := a.inboundService.GetSubLinks(resolveHost(c), c.Param("subId"))
|
||||
if err != nil {
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
||||
)
|
||||
|
||||
// ReapSyncOrphansJob hard-deletes the clients the node-snapshot sweep only
|
||||
// soft-orphaned, once enough clean merges have agreed they are really gone.
|
||||
// ReapSyncOrphansJob hard-deletes the clients the node-snapshot sweep only soft-orphaned,
|
||||
// then the usage and change history of every email no client holds any more.
|
||||
type ReapSyncOrphansJob struct {
|
||||
clientService service.ClientService
|
||||
}
|
||||
@@ -16,12 +16,15 @@ func NewReapSyncOrphansJob() *ReapSyncOrphansJob {
|
||||
}
|
||||
|
||||
func (j *ReapSyncOrphansJob) Run() {
|
||||
reaped, err := j.clientService.ReapSyncOrphans()
|
||||
if err != nil {
|
||||
if reaped, err := j.clientService.ReapSyncOrphans(); err != nil {
|
||||
logger.Warning("reap sync orphans failed:", err)
|
||||
return
|
||||
}
|
||||
if reaped > 0 {
|
||||
} else if reaped > 0 {
|
||||
logger.Infof("reap sync orphans: removed %d client(s)", reaped)
|
||||
}
|
||||
// After the client reap, so a client it just removed loses its history in the same run.
|
||||
if rows, err := j.clientService.ReapOrphanClientHistory(); err != nil {
|
||||
logger.Warning("reap orphan client history failed:", err)
|
||||
} else if rows > 0 {
|
||||
logger.Infof("reap orphan client history: removed %d row(s)", rows)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package job
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
)
|
||||
|
||||
// Nothing archives or cleans up when a client is deleted, so without this run the history
|
||||
// of every deleted client stays in the database for good.
|
||||
func TestReapSyncOrphansJobDropsTheHistoryOfDeletedClients(t *testing.T) {
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
|
||||
db := database.GetDB()
|
||||
const gone, kept = "gone@example.test", "kept@example.test"
|
||||
if err := db.Create(&model.ClientRecord{Email: kept, SubID: kept, Enable: true}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, email := range []string{gone, kept} {
|
||||
if err := db.Create(&model.ClientTrafficWindow{Email: email, At: 1, Up: 5, Reason: "reset"}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.ClientChangeLog{Email: email, At: 1, Field: "enable"}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
NewReapSyncOrphansJob().Run()
|
||||
|
||||
var windows, changes []string
|
||||
if err := db.Model(&model.ClientTrafficWindow{}).Pluck("email", &windows).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Model(&model.ClientChangeLog{}).Pluck("email", &changes).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(windows) != 1 || windows[0] != kept || len(changes) != 1 || changes[0] != kept {
|
||||
t.Fatalf("after the job: windows of %v, changes of %v; want only %s in both", windows, changes, kept)
|
||||
}
|
||||
}
|
||||
@@ -366,6 +366,7 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
|
||||
if len(cleanEmails) == 0 {
|
||||
return result, false, nil
|
||||
}
|
||||
defer watchClientChanges(clientChangeSourcePanel, cleanEmails...).record()
|
||||
|
||||
db := database.GetDB()
|
||||
|
||||
@@ -1576,6 +1577,7 @@ func (s *ClientService) BulkSetEnable(inboundSvc *InboundService, emails []strin
|
||||
if len(cleanEmails) == 0 {
|
||||
return result, false, nil
|
||||
}
|
||||
defer watchClientChanges(clientChangeSourcePanel, cleanEmails...).record()
|
||||
|
||||
db := database.GetDB()
|
||||
|
||||
|
||||
@@ -704,6 +704,7 @@ func (s *ClientService) update(inboundSvc *InboundService, id int, updated model
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer watchClientChanges(clientChangeSourcePanel, existing.Email).record()
|
||||
inboundIds, err := s.GetInboundIdsForRecord(id)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -919,9 +920,16 @@ func (s *ClientService) update(inboundSvc *InboundService, id int, updated model
|
||||
// UpdateInboundClient renames the record atomically with each inbound's
|
||||
// settings JSON; this direct write only covers records with no inbound left.
|
||||
if updated.Email != existing.Email {
|
||||
if err := database.GetDB().Model(&model.ClientRecord{}).
|
||||
Where("id = ? AND email = ?", id, existing.Email).
|
||||
Update("email", updated.Email).Error; err != nil {
|
||||
// Zero rows when the inbound fan-out above already renamed the record and its history.
|
||||
if err := database.GetDB().Transaction(func(tx *gorm.DB) error {
|
||||
renamed := tx.Model(&model.ClientRecord{}).
|
||||
Where("id = ? AND email = ?", id, existing.Email).
|
||||
Update("email", updated.Email)
|
||||
if renamed.Error != nil || renamed.RowsAffected == 0 {
|
||||
return renamed.Error
|
||||
}
|
||||
return renameClientHistoryTx(tx, existing.Email, updated.Email, clientChangeSourcePanel)
|
||||
}); err != nil {
|
||||
return needRestart, err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1132,6 +1132,9 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
|
||||
if e := tx.Model(&model.ClientRecord{}).Where("email = ?", oldEmail).Update("email", clients[0].Email).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
if e := renameClientHistoryTx(tx, oldEmail, clients[0].Email, clientChangeSourcePanel); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
// detachEmails covers the rename the guard above refused: the old record
|
||||
@@ -1474,6 +1477,7 @@ func (s *ClientService) SetClientEnableByEmail(inboundSvc *InboundService, clien
|
||||
// SyncInbound over a stale sibling would revert the edit in the normalized
|
||||
// records (#5039).
|
||||
func (s *ClientService) applyClientFieldByEmail(inboundSvc *InboundService, clientEmail string, mutate func(c map[string]any)) (bool, error) {
|
||||
defer watchClientChanges(clientChangeSourceTgbot, clientEmail).record()
|
||||
inboundIds, err := s.GetInboundIdsForEmail(database.GetDB(), clientEmail)
|
||||
if err != nil {
|
||||
return false, err
|
||||
|
||||
@@ -315,6 +315,9 @@ func handDisabledEmails(tx *gorm.DB, emails []string) ([]string, error) {
|
||||
// zeroClientTraffics zeroes the counters of emails (every row when nil) and lifts their traffic
|
||||
// gate, except for keepOff: a master pushes that flag to its nodes as the client's state.
|
||||
func zeroClientTraffics(tx *gorm.DB, emails, keepOff []string) (int64, error) {
|
||||
if err := archiveClosedWindowsTx(tx, emails, trafficWindowReset); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var affected int64
|
||||
reset := map[string]any{"enable": true, "up": 0, "down": 0}
|
||||
if emails == nil {
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Why a closed window exists. "earlier" is the fold of windows past the cap.
|
||||
const (
|
||||
trafficWindowReset = "reset"
|
||||
trafficWindowRenew = "renew"
|
||||
trafficWindowEarlier = "earlier"
|
||||
)
|
||||
|
||||
const (
|
||||
clientChangeSourcePanel = "panel"
|
||||
clientChangeSourceTgbot = "tgbot"
|
||||
clientChangeSourceRenew = "auto-renew"
|
||||
)
|
||||
|
||||
// Per-client row caps: both tables stay bounded by the number of clients.
|
||||
const (
|
||||
clientTrafficWindowKeep = 100
|
||||
clientChangeLogKeep = 200
|
||||
)
|
||||
|
||||
// ClientNodeUsage is one node's counters for a client since its last reset.
|
||||
type ClientNodeUsage struct {
|
||||
NodeID int `json:"nodeId" example:"7"`
|
||||
NodeName string `json:"nodeName" example:"de-fra-1"`
|
||||
Up int64 `json:"up" example:"1048576"`
|
||||
Down int64 `json:"down" example:"2097152"`
|
||||
}
|
||||
|
||||
// ClientUsageHistory is what the client editor's history button shows.
|
||||
type ClientUsageHistory struct {
|
||||
Email string `json:"email" example:"user1@example.com"`
|
||||
LifetimeUp int64 `json:"lifetimeUp" example:"10737418240"`
|
||||
LifetimeDown int64 `json:"lifetimeDown" example:"21474836480"`
|
||||
CurrentUp int64 `json:"currentUp" example:"1048576"`
|
||||
CurrentDown int64 `json:"currentDown" example:"2097152"`
|
||||
Windows []model.ClientTrafficWindow `json:"windows"`
|
||||
Nodes []ClientNodeUsage `json:"nodes"`
|
||||
Changes []model.ClientChangeLog `json:"changes"`
|
||||
}
|
||||
|
||||
func (s *ClientService) GetUsageHistory(email string) (*ClientUsageHistory, error) {
|
||||
db := database.GetDB()
|
||||
out := &ClientUsageHistory{
|
||||
Email: email,
|
||||
Windows: []model.ClientTrafficWindow{},
|
||||
Nodes: []ClientNodeUsage{},
|
||||
Changes: []model.ClientChangeLog{},
|
||||
}
|
||||
|
||||
var live xray.ClientTraffic
|
||||
err := db.Where("email = ?", email).First(&live).Error
|
||||
if err != nil {
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
out.CurrentUp, out.CurrentDown = live.Up, live.Down
|
||||
}
|
||||
|
||||
if err := db.Where("email = ?", email).Order("at DESC, id DESC").Find(&out.Windows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out.LifetimeUp, out.LifetimeDown = out.CurrentUp, out.CurrentDown
|
||||
for _, window := range out.Windows {
|
||||
out.LifetimeUp = clampedTrafficAdd(out.LifetimeUp, window.Up)
|
||||
out.LifetimeDown = clampedTrafficAdd(out.LifetimeDown, window.Down)
|
||||
}
|
||||
if err := db.Model(&model.NodeClientTraffic{}).
|
||||
Joins("JOIN nodes n ON n.id = node_client_traffics.node_id").
|
||||
Where("node_client_traffics.email = ?", email).
|
||||
Select("node_client_traffics.node_id, n.name AS node_name, node_client_traffics.up, node_client_traffics.down").
|
||||
Order("node_client_traffics.up + node_client_traffics.down DESC").
|
||||
Scan(&out.Nodes).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := db.Where("email = ?", email).Order("at DESC, id DESC").Find(&out.Changes).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// archiveClosedWindowsTx is the one place a client's used counters become history. Call it
|
||||
// before zeroing them, in the same transaction; nil emails means every client.
|
||||
func archiveClosedWindowsTx(tx *gorm.DB, emails []string, reason string) error {
|
||||
if emails != nil && len(emails) == 0 {
|
||||
return nil
|
||||
}
|
||||
used := func() *gorm.DB {
|
||||
return tx.Model(&xray.ClientTraffic{}).Select("email, up, down").Where("up > 0 OR down > 0")
|
||||
}
|
||||
var windows []model.ClientTrafficWindow
|
||||
if emails == nil {
|
||||
if err := used().Scan(&windows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
for _, batch := range chunkStrings(emails, sqlInChunk) {
|
||||
var page []model.ClientTrafficWindow
|
||||
if err := used().Where("email IN ?", batch).Scan(&page).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
windows = append(windows, page...)
|
||||
}
|
||||
}
|
||||
if len(windows) == 0 {
|
||||
return nil
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
closed := make([]string, 0, len(windows))
|
||||
for i := range windows {
|
||||
windows[i].At, windows[i].Reason = now, reason
|
||||
closed = append(closed, windows[i].Email)
|
||||
}
|
||||
if err := tx.CreateInBatches(&windows, sqlInChunk).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return foldOldWindowsTx(tx, closed)
|
||||
}
|
||||
|
||||
// foldOldWindowsTx merges a client's windows past the cap into one "earlier" row, so the
|
||||
// table stops growing while the lifetime total it sums to stays the same.
|
||||
func foldOldWindowsTx(tx *gorm.DB, emails []string) error {
|
||||
var over []string
|
||||
for _, batch := range chunkStrings(emails, sqlInChunk) {
|
||||
var page []string
|
||||
if err := tx.Model(&model.ClientTrafficWindow{}).Where("email IN ?", batch).
|
||||
Group("email").Having("COUNT(*) > ?", clientTrafficWindowKeep+1).
|
||||
Pluck("email", &page).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
over = append(over, page...)
|
||||
}
|
||||
for _, email := range over {
|
||||
var old []model.ClientTrafficWindow
|
||||
if err := tx.Where("email = ?", email).Order("at DESC, id DESC").
|
||||
Offset(clientTrafficWindowKeep).Find(&old).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
folded := model.ClientTrafficWindow{Email: email, At: old[0].At, Reason: trafficWindowEarlier}
|
||||
ids := make([]int64, 0, len(old))
|
||||
for _, window := range old {
|
||||
folded.Up = clampedTrafficAdd(folded.Up, window.Up)
|
||||
folded.Down = clampedTrafficAdd(folded.Down, window.Down)
|
||||
ids = append(ids, window.Id)
|
||||
}
|
||||
if err := tx.Where("id IN ?", ids).Delete(&model.ClientTrafficWindow{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Create(&folded).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// logClientChangesTx appends change rows stamped with the commit time, then drops each
|
||||
// client's rows past the cap.
|
||||
func logClientChangesTx(tx *gorm.DB, entries []model.ClientChangeLog) error {
|
||||
if len(entries) == 0 {
|
||||
return nil
|
||||
}
|
||||
now := time.Now().UnixMilli()
|
||||
seen := make(map[string]struct{}, len(entries))
|
||||
emails := make([]string, 0, len(entries))
|
||||
for i := range entries {
|
||||
entries[i].At = now
|
||||
if _, dup := seen[entries[i].Email]; !dup {
|
||||
seen[entries[i].Email] = struct{}{}
|
||||
emails = append(emails, entries[i].Email)
|
||||
}
|
||||
}
|
||||
if err := tx.CreateInBatches(&entries, sqlInChunk).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, batch := range chunkStrings(emails, sqlInChunk) {
|
||||
var over []string
|
||||
if err := tx.Model(&model.ClientChangeLog{}).Where("email IN ?", batch).
|
||||
Group("email").Having("COUNT(*) > ?", clientChangeLogKeep).
|
||||
Pluck("email", &over).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, email := range over {
|
||||
var oldest model.ClientChangeLog
|
||||
if err := tx.Where("email = ?", email).Order("at DESC, id DESC").
|
||||
Offset(clientChangeLogKeep).Take(&oldest).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Where("email = ? AND (at < ? OR (at = ? AND id <= ?))", email, oldest.At, oldest.At, oldest.Id).
|
||||
Delete(&model.ClientChangeLog{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// clientChangeWatch holds client records as they were before an operation. Diffing them
|
||||
// against the stored rows afterwards logs what changed, not what a caller meant to write.
|
||||
type clientChangeWatch struct {
|
||||
source string
|
||||
before []model.ClientRecord
|
||||
}
|
||||
|
||||
func watchClientChanges(source string, emails ...string) *clientChangeWatch {
|
||||
watch := &clientChangeWatch{source: source}
|
||||
for _, batch := range chunkStrings(emails, sqlInChunk) {
|
||||
var page []model.ClientRecord
|
||||
if err := database.GetDB().Where("email IN ?", batch).Find(&page).Error; err != nil {
|
||||
logger.Warning("client change log: read records failed:", err)
|
||||
return &clientChangeWatch{source: source}
|
||||
}
|
||||
watch.before = append(watch.before, page...)
|
||||
}
|
||||
return watch
|
||||
}
|
||||
|
||||
// record pairs rows by id, so a client renamed meanwhile is logged under its new email.
|
||||
func (w *clientChangeWatch) record() {
|
||||
if len(w.before) == 0 {
|
||||
return
|
||||
}
|
||||
db := database.GetDB()
|
||||
ids := make([]int, 0, len(w.before))
|
||||
for i := range w.before {
|
||||
ids = append(ids, w.before[i].Id)
|
||||
}
|
||||
after := make(map[int]*model.ClientRecord, len(ids))
|
||||
for _, batch := range chunkInts(ids, sqlInChunk) {
|
||||
var page []model.ClientRecord
|
||||
if err := db.Where("id IN ?", batch).Find(&page).Error; err != nil {
|
||||
logger.Warning("client change log: read records failed:", err)
|
||||
return
|
||||
}
|
||||
for i := range page {
|
||||
after[page[i].Id] = &page[i]
|
||||
}
|
||||
}
|
||||
var entries []model.ClientChangeLog
|
||||
for i := range w.before {
|
||||
if now, kept := after[w.before[i].Id]; kept {
|
||||
entries = append(entries, diffClientChanges(&w.before[i], now, w.source)...)
|
||||
}
|
||||
}
|
||||
if err := db.Transaction(func(tx *gorm.DB) error { return logClientChangesTx(tx, entries) }); err != nil {
|
||||
logger.Warning("client change log: write failed:", err)
|
||||
}
|
||||
}
|
||||
|
||||
// diffClientChanges returns one row per client field that differs. The email is left
|
||||
// out: a rename is logged where the record is renamed.
|
||||
func diffClientChanges(oldRec, newRec *model.ClientRecord, source string) []model.ClientChangeLog {
|
||||
var entries []model.ClientChangeLog
|
||||
add := func(field, oldVal, newVal string) {
|
||||
entries = append(entries, model.ClientChangeLog{
|
||||
Email: newRec.Email, Field: field, OldValue: oldVal, NewValue: newVal, Source: source,
|
||||
})
|
||||
}
|
||||
if oldRec.SubID != newRec.SubID {
|
||||
add("subId", oldRec.SubID, newRec.SubID)
|
||||
}
|
||||
if oldRec.ExpiryTime != newRec.ExpiryTime {
|
||||
add("expiry", fmt.Sprint(oldRec.ExpiryTime), fmt.Sprint(newRec.ExpiryTime))
|
||||
}
|
||||
if oldRec.TotalGB != newRec.TotalGB {
|
||||
add("dataLimit", fmt.Sprint(oldRec.TotalGB), fmt.Sprint(newRec.TotalGB))
|
||||
}
|
||||
if oldRec.Enable != newRec.Enable {
|
||||
add("enable", fmt.Sprint(oldRec.Enable), fmt.Sprint(newRec.Enable))
|
||||
}
|
||||
if oldRec.LimitIP != newRec.LimitIP {
|
||||
add("limitIp", fmt.Sprint(oldRec.LimitIP), fmt.Sprint(newRec.LimitIP))
|
||||
}
|
||||
if oldRec.LimitHwid != newRec.LimitHwid {
|
||||
add("limitHwid", fmt.Sprint(oldRec.LimitHwid), fmt.Sprint(newRec.LimitHwid))
|
||||
}
|
||||
if oldRec.AdTag != newRec.AdTag {
|
||||
add("adTag", oldRec.AdTag, newRec.AdTag)
|
||||
}
|
||||
if oldRec.Group != newRec.Group {
|
||||
add("group", oldRec.Group, newRec.Group)
|
||||
}
|
||||
plan := func(r *model.ClientRecord) string {
|
||||
return fmt.Sprintf("%d/%d/%d/%d/%s:%d", r.Reset, r.ResetDay, r.ResetWeekday, r.ResetMax, r.TrafficReset, r.TrafficResetDay)
|
||||
}
|
||||
if plan(oldRec) != plan(newRec) {
|
||||
add("renewalPlan", plan(oldRec), plan(newRec))
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
// renameClientHistoryTx moves a renamed client's history to its new email and logs the
|
||||
// rename, so the history follows the client instead of being reaped with the old name.
|
||||
func renameClientHistoryTx(tx *gorm.DB, oldEmail, newEmail, source string) error {
|
||||
if oldEmail == "" || oldEmail == newEmail {
|
||||
return nil
|
||||
}
|
||||
if err := tx.Model(&model.ClientChangeLog{}).Where("email = ?", oldEmail).Update("email", newEmail).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&model.ClientTrafficWindow{}).Where("email = ?", oldEmail).Update("email", newEmail).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return logClientChangesTx(tx, []model.ClientChangeLog{{
|
||||
Email: newEmail, Field: "name", OldValue: oldEmail, NewValue: newEmail, Source: source,
|
||||
}})
|
||||
}
|
||||
|
||||
var clientHistoryTables = []struct {
|
||||
model any
|
||||
name string
|
||||
}{
|
||||
{&model.ClientTrafficWindow{}, "client_traffic_windows"},
|
||||
{&model.ClientChangeLog{}, "client_change_logs"},
|
||||
}
|
||||
|
||||
// ReapOrphanClientHistory drops the history of emails no client holds any more: every
|
||||
// path that deletes a client is covered here instead of in each of them.
|
||||
func (s *ClientService) ReapOrphanClientHistory() (int64, error) {
|
||||
var reaped int64
|
||||
for _, history := range clientHistoryTables {
|
||||
emails, err := orphanHistoryEmails(database.GetDB(), history.name)
|
||||
if err != nil {
|
||||
return reaped, err
|
||||
}
|
||||
dropped, err := deleteOrphanHistory(history.model, emails)
|
||||
reaped += dropped
|
||||
if err != nil {
|
||||
return reaped, err
|
||||
}
|
||||
}
|
||||
return reaped, nil
|
||||
}
|
||||
|
||||
// orphanHistoryEmails walks the email index one distinct value at a time, so a run that
|
||||
// finds nothing costs one seek per client instead of a scan of every history row.
|
||||
func orphanHistoryEmails(db *gorm.DB, table string) ([]string, error) {
|
||||
var emails []string
|
||||
err := db.Raw(`WITH RECURSIVE held(email) AS (
|
||||
SELECT MIN(email) FROM ` + table + `
|
||||
UNION ALL
|
||||
SELECT (SELECT MIN(email) FROM ` + table + ` WHERE email > held.email) FROM held WHERE held.email IS NOT NULL
|
||||
) SELECT email FROM held WHERE email IS NOT NULL AND email NOT IN (SELECT email FROM clients)`).Scan(&emails).Error
|
||||
return emails, err
|
||||
}
|
||||
|
||||
func deleteOrphanHistory(table any, emails []string) (int64, error) {
|
||||
var dropped int64
|
||||
for _, listed := range chunkStrings(emails, sqlInChunk) {
|
||||
var res *gorm.DB
|
||||
if err := runSerializedTx(func(tx *gorm.DB) error {
|
||||
// The list was read outside the writer; a client may hold one of the emails by now.
|
||||
res = tx.Where("email IN ?", listed).
|
||||
Where("email NOT IN (?)", tx.Model(&model.ClientRecord{}).Select("email")).Delete(table)
|
||||
return res.Error
|
||||
}); err != nil {
|
||||
return dropped, err
|
||||
}
|
||||
dropped += res.RowsAffected
|
||||
}
|
||||
return dropped, nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// The fold, the change-log cap and the reap each lean on SQL the two dialects spell
|
||||
// differently: OFFSET without LIMIT, HAVING over a group, a recursive index walk.
|
||||
func TestClientUsageHistoryPostgres(t *testing.T) {
|
||||
db := durablePostgresDB(t)
|
||||
suffix := time.Now().UnixNano()
|
||||
kept, gone := fmt.Sprintf("pg-hist-kept-%d@x", suffix), fmt.Sprintf("pg-hist-gone-%d@x", suffix)
|
||||
inbound := durableTestInbound(nil, fmt.Sprintf("pg-hist-%d", suffix), 20000+int(suffix%20000))
|
||||
if err := db.Create(inbound).Error; err != nil {
|
||||
t.Fatalf("create inbound: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
for _, table := range []any{&model.ClientTrafficWindow{}, &model.ClientChangeLog{}, &xray.ClientTraffic{}, &model.ClientRecord{}} {
|
||||
_ = db.Where("email IN ?", []string{kept, gone}).Delete(table).Error
|
||||
}
|
||||
_ = db.Delete(&model.Inbound{}, inbound.Id).Error
|
||||
})
|
||||
if err := db.Create(&model.ClientRecord{Email: kept, SubID: kept, Enable: true}).Error; err != nil {
|
||||
t.Fatalf("create client: %v", err)
|
||||
}
|
||||
if err := db.Create(&xray.ClientTraffic{InboundId: inbound.Id, Email: kept, Enable: true, Up: 7, Down: 9}).Error; err != nil {
|
||||
t.Fatalf("create client traffic: %v", err)
|
||||
}
|
||||
windows := make([]model.ClientTrafficWindow, 0, clientTrafficWindowKeep+2)
|
||||
for i := range clientTrafficWindowKeep + 1 {
|
||||
windows = append(windows, model.ClientTrafficWindow{Email: kept, At: int64(1000 + i), Up: 1, Down: 2, Reason: trafficWindowRenew})
|
||||
}
|
||||
windows = append(windows, model.ClientTrafficWindow{Email: gone, At: 1, Up: 5, Reason: trafficWindowReset})
|
||||
changes := make([]model.ClientChangeLog, 0, clientChangeLogKeep+1)
|
||||
for i := range clientChangeLogKeep {
|
||||
changes = append(changes, model.ClientChangeLog{Email: kept, At: int64(1000 + i), Field: "enable", NewValue: fmt.Sprint(i)})
|
||||
}
|
||||
changes = append(changes, model.ClientChangeLog{Email: gone, At: 1, Field: "enable"})
|
||||
if err := db.Create(&windows).Error; err != nil {
|
||||
t.Fatalf("seed windows: %v", err)
|
||||
}
|
||||
if err := db.Create(&changes).Error; err != nil {
|
||||
t.Fatalf("seed changes: %v", err)
|
||||
}
|
||||
|
||||
if err := db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := archiveClosedWindowsTx(tx, []string{kept}, trafficWindowReset); err != nil {
|
||||
return err
|
||||
}
|
||||
return logClientChangesTx(tx, []model.ClientChangeLog{{Email: kept, Field: "dataLimit", NewValue: "1"}})
|
||||
}); err != nil {
|
||||
t.Fatalf("archive and log on PostgreSQL: %v", err)
|
||||
}
|
||||
|
||||
var folded []model.ClientTrafficWindow
|
||||
if err := db.Where("email = ? AND reason = ?", kept, trafficWindowEarlier).Find(&folded).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var windowCount, changeCount, oldestChange int64
|
||||
db.Model(&model.ClientTrafficWindow{}).Where("email = ?", kept).Count(&windowCount)
|
||||
db.Model(&model.ClientChangeLog{}).Where("email = ?", kept).Count(&changeCount)
|
||||
db.Model(&model.ClientChangeLog{}).Where("email = ?", kept).Select("MIN(at)").Scan(&oldestChange)
|
||||
if windowCount != clientTrafficWindowKeep+1 || len(folded) != 1 || folded[0].Up != 2 || folded[0].Down != 4 {
|
||||
t.Fatalf("%d windows, folded %+v; want %d with one earlier row of 2/4", windowCount, folded, clientTrafficWindowKeep+1)
|
||||
}
|
||||
if changeCount != clientChangeLogKeep || oldestChange != 1001 {
|
||||
t.Fatalf("%d change rows, oldest at %d; want %d with the row at 1000 dropped", changeCount, oldestChange, clientChangeLogKeep)
|
||||
}
|
||||
|
||||
if _, err := (&ClientService{}).ReapOrphanClientHistory(); err != nil {
|
||||
t.Fatalf("reap on PostgreSQL: %v", err)
|
||||
}
|
||||
var goneWindows, goneChanges, keptWindows int64
|
||||
db.Model(&model.ClientTrafficWindow{}).Where("email = ?", gone).Count(&goneWindows)
|
||||
db.Model(&model.ClientChangeLog{}).Where("email = ?", gone).Count(&goneChanges)
|
||||
db.Model(&model.ClientTrafficWindow{}).Where("email = ?", kept).Count(&keptWindows)
|
||||
if goneWindows != 0 || goneChanges != 0 || keptWindows != clientTrafficWindowKeep+1 {
|
||||
t.Fatalf("after the reap: orphan has %d windows and %d changes, the client %d windows; want 0, 0 and %d",
|
||||
goneWindows, goneChanges, keptWindows, clientTrafficWindowKeep+1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,590 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
// seedUsageHistoryClient seeds a local VLESS inbound hosting one client and a
|
||||
// live traffic row with the given counters.
|
||||
func seedUsageHistoryClient(t *testing.T, inboundSvc *InboundService, email, uid string, up, down int64) *model.Inbound {
|
||||
t.Helper()
|
||||
setupBulkDB(t)
|
||||
svc := &ClientService{}
|
||||
|
||||
client := model.Client{Email: email, ID: uid, SubID: email, Enable: true}
|
||||
ib := mkInbound(t, 54501, model.VLESS, clientsSettings(t, []model.Client{client}))
|
||||
if err := svc.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil {
|
||||
t.Fatalf("SyncInbound: %v", err)
|
||||
}
|
||||
db := database.GetDB()
|
||||
traffic := xray.ClientTraffic{
|
||||
InboundId: ib.Id,
|
||||
Email: email,
|
||||
Enable: true,
|
||||
Up: up,
|
||||
Down: down,
|
||||
ExpiryTime: time.Now().Add(30 * 24 * time.Hour).UnixMilli(),
|
||||
Total: 1 << 40,
|
||||
}
|
||||
if err := db.Create(&traffic).Error; err != nil {
|
||||
t.Fatalf("seed client_traffics: %v", err)
|
||||
}
|
||||
return ib
|
||||
}
|
||||
|
||||
func windowsOf(t *testing.T, email string) []model.ClientTrafficWindow {
|
||||
t.Helper()
|
||||
var windows []model.ClientTrafficWindow
|
||||
if err := database.GetDB().Where("email = ?", email).Order("id").Find(&windows).Error; err != nil {
|
||||
t.Fatalf("read windows: %v", err)
|
||||
}
|
||||
return windows
|
||||
}
|
||||
|
||||
func changesOf(t *testing.T, email string) []model.ClientChangeLog {
|
||||
t.Helper()
|
||||
var changes []model.ClientChangeLog
|
||||
if err := database.GetDB().Where("email = ?", email).Order("id").Find(&changes).Error; err != nil {
|
||||
t.Fatalf("read change log: %v", err)
|
||||
}
|
||||
return changes
|
||||
}
|
||||
|
||||
// Lifetime traffic is the archived windows plus the live counters, so a reset path
|
||||
// that zeroes without archiving silently loses that cycle from the total.
|
||||
func TestEveryResetPathArchivesTheWindowItCloses(t *testing.T) {
|
||||
const email = "reset-win@example.test"
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
reset func(*InboundService, *ClientService, *model.Inbound) error
|
||||
}{
|
||||
{"one client of an inbound", func(inbounds *InboundService, _ *ClientService, ib *model.Inbound) error {
|
||||
_, err := inbounds.ResetClientTraffic(ib.Id, email)
|
||||
return err
|
||||
}},
|
||||
{"one client by email", func(inbounds *InboundService, clients *ClientService, _ *model.Inbound) error {
|
||||
_, err := clients.ResetTrafficByEmail(inbounds, email)
|
||||
return err
|
||||
}},
|
||||
{"one client's counters only", func(inbounds *InboundService, _ *ClientService, _ *model.Inbound) error {
|
||||
return inbounds.ResetClientTrafficByEmail(email)
|
||||
}},
|
||||
{"selected clients", func(inbounds *InboundService, clients *ClientService, _ *model.Inbound) error {
|
||||
_, err := clients.BulkResetTraffic(inbounds, []string{email})
|
||||
return err
|
||||
}},
|
||||
{"every client of an inbound", func(inbounds *InboundService, clients *ClientService, ib *model.Inbound) error {
|
||||
_, err := clients.ResetAllClientTraffics(inbounds, ib.Id)
|
||||
return err
|
||||
}},
|
||||
{"every client", func(_ *InboundService, clients *ClientService, _ *model.Inbound) error {
|
||||
_, err := clients.ResetAllTraffics()
|
||||
return err
|
||||
}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
inbounds, clients := &InboundService{}, &ClientService{}
|
||||
ib := seedUsageHistoryClient(t, inbounds, email, "44444444-1111-4111-8111-111111111111", 100, 200)
|
||||
if err := tc.reset(inbounds, clients, ib); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
windows := windowsOf(t, email)
|
||||
if len(windows) != 1 || windows[0].Reason != trafficWindowReset || windows[0].Up != 100 || windows[0].Down != 200 {
|
||||
t.Fatalf("windows = %+v, want exactly one reset window of 100/200", windows)
|
||||
}
|
||||
history, err := clients.GetUsageHistory(email)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if history.CurrentUp != 0 || history.CurrentDown != 0 || history.LifetimeUp != 100 || history.LifetimeDown != 200 {
|
||||
t.Fatalf("current %d/%d lifetime %d/%d, want 0/0 and 100/200",
|
||||
history.CurrentUp, history.CurrentDown, history.LifetimeUp, history.LifetimeDown)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Past the cap a client's oldest windows fold into one row: the table stops growing and
|
||||
// the lifetime total must not move. At the cap itself nothing is folded yet.
|
||||
func TestWindowsPastTheCapFoldWithoutChangingLifetime(t *testing.T) {
|
||||
const email = "capped@example.test"
|
||||
inbounds, clients := &InboundService{}, &ClientService{}
|
||||
ib := seedUsageHistoryClient(t, inbounds, email, "12121212-1111-4111-8111-111111111111", 100, 200)
|
||||
db := database.GetDB()
|
||||
seeded := make([]model.ClientTrafficWindow, 0, clientTrafficWindowKeep)
|
||||
for i := range clientTrafficWindowKeep {
|
||||
seeded = append(seeded, model.ClientTrafficWindow{Email: email, At: int64(1000 + i), Up: 1, Down: 2, Reason: trafficWindowRenew})
|
||||
}
|
||||
if err := db.Create(&seeded).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
lifetimeUp := int64(clientTrafficWindowKeep)
|
||||
for cycle, tc := range []struct {
|
||||
usedUp, usedDown int64
|
||||
folded int
|
||||
foldedUp, foldedDown int64
|
||||
}{
|
||||
{100, 200, 0, 0, 0},
|
||||
{7, 9, 1, 2, 4},
|
||||
{3, 1, 1, 3, 6},
|
||||
} {
|
||||
if err := db.Model(&xray.ClientTraffic{}).Where("email = ?", email).
|
||||
Updates(map[string]any{"up": tc.usedUp, "down": tc.usedDown}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := inbounds.ResetClientTraffic(ib.Id, email); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lifetimeUp += tc.usedUp
|
||||
windows := windowsOf(t, email)
|
||||
var folded []model.ClientTrafficWindow
|
||||
for _, window := range windows {
|
||||
if window.Reason == trafficWindowEarlier {
|
||||
folded = append(folded, window)
|
||||
}
|
||||
}
|
||||
if len(windows) != clientTrafficWindowKeep+1 || len(folded) != tc.folded ||
|
||||
(tc.folded == 1 && (folded[0].Up != tc.foldedUp || folded[0].Down != tc.foldedDown)) {
|
||||
t.Fatalf("cycle %d: %d windows, folded %+v; want %d windows with %d earlier row(s) of %d/%d",
|
||||
cycle, len(windows), folded, clientTrafficWindowKeep+1, tc.folded, tc.foldedUp, tc.foldedDown)
|
||||
}
|
||||
history, err := clients.GetUsageHistory(email)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if history.LifetimeUp != lifetimeUp {
|
||||
t.Fatalf("cycle %d: lifetime up = %d, want %d: folding changed the total", cycle, history.LifetimeUp, lifetimeUp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Lifetime is what the client used in total, so the cycle still open counts too.
|
||||
func TestLifetimeCountsTheOpenWindow(t *testing.T) {
|
||||
const email = "open-win@example.test"
|
||||
inbounds, clients := &InboundService{}, &ClientService{}
|
||||
ib := seedUsageHistoryClient(t, inbounds, email, "17171717-1111-4111-8111-111111111111", 100, 200)
|
||||
if _, err := inbounds.ResetClientTraffic(ib.Id, email); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := database.GetDB().Model(&xray.ClientTraffic{}).Where("email = ?", email).
|
||||
Updates(map[string]any{"up": 7, "down": 9}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
history, err := clients.GetUsageHistory(email)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if history.CurrentUp != 7 || history.CurrentDown != 9 || history.LifetimeUp != 107 || history.LifetimeDown != 209 {
|
||||
t.Fatalf("current %d/%d lifetime %d/%d, want 7/9 and 107/209",
|
||||
history.CurrentUp, history.CurrentDown, history.LifetimeUp, history.LifetimeDown)
|
||||
}
|
||||
}
|
||||
|
||||
// The change log keeps the newest rows of each client and never trims another client's.
|
||||
func TestChangeLogKeepsTheNewestRowsPerClient(t *testing.T) {
|
||||
const email, other = "chatty@example.test", "quiet@example.test"
|
||||
inbounds, clients := &InboundService{}, &ClientService{}
|
||||
seedUsageHistoryClient(t, inbounds, email, "13131313-1111-4111-8111-111111111111", 0, 0)
|
||||
db := database.GetDB()
|
||||
seeded := make([]model.ClientChangeLog, 0, clientChangeLogKeep+1)
|
||||
for i := range clientChangeLogKeep {
|
||||
seeded = append(seeded, model.ClientChangeLog{Email: email, At: int64(1000 + i), Field: "enable", NewValue: itoa(int64(i))})
|
||||
}
|
||||
seeded = append(seeded, model.ClientChangeLog{Email: other, At: 1, Field: "enable"})
|
||||
if err := db.Create(&seeded).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
record, err := clients.GetRecordByEmail(nil, email)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
edited := record.ToClient()
|
||||
edited.TotalGB = 5 << 30
|
||||
if _, err := clients.Update(inbounds, record.Id, *edited, record.LimitHwid); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
kept := changesOf(t, email)
|
||||
if len(kept) != clientChangeLogKeep || kept[0].NewValue != "1" || kept[len(kept)-1].Field != "dataLimit" {
|
||||
t.Fatalf("%d rows, first %+v last %+v; want %d rows from the second seeded one to the new dataLimit change",
|
||||
len(kept), kept[0], kept[len(kept)-1], clientChangeLogKeep)
|
||||
}
|
||||
if got := len(changesOf(t, other)); got != 1 {
|
||||
t.Fatalf("another client's log has %d rows, want its 1 untouched", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A bot edit and a bulk edit are logged from the stored record, under their own source.
|
||||
func TestBotAndBulkEditsAreLoggedWithTheirSource(t *testing.T) {
|
||||
const email = "edited@example.test"
|
||||
inbounds, clients := &InboundService{}, &ClientService{}
|
||||
seedUsageHistoryClient(t, inbounds, email, "14141414-1111-4111-8111-111111111111", 0, 0)
|
||||
|
||||
// The bulk add skips an unlimited client, so the bot sets a limit first.
|
||||
if _, err := clients.ResetClientTrafficLimitByEmail(inbounds, email, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := clients.BulkAdjust(inbounds, []string{email}, 0, 1<<30, "", nil, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
type row struct{ field, old, new, source string }
|
||||
var got []row
|
||||
for _, change := range changesOf(t, email) {
|
||||
got = append(got, row{change.Field, change.OldValue, change.NewValue, change.Source})
|
||||
}
|
||||
want := []row{
|
||||
{"dataLimit", "0", itoa(1 << 30), clientChangeSourceTgbot},
|
||||
{"dataLimit", itoa(1 << 30), itoa(2 << 30), clientChangeSourcePanel},
|
||||
}
|
||||
if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] {
|
||||
t.Fatalf("change log = %+v, want %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// History belongs to a client: once the client is gone the reaper drops it, and only it.
|
||||
func TestHistoryOfADeletedClientIsReaped(t *testing.T) {
|
||||
const gone, kept = "gone@example.test", "kept@example.test"
|
||||
inbounds, clients := &InboundService{}, &ClientService{}
|
||||
seedUsageHistoryClient(t, inbounds, gone, "15151515-1111-4111-8111-111111111111", 0, 0)
|
||||
stays := model.Client{Email: kept, ID: "16161616-1111-4111-8111-111111111111", SubID: kept, Enable: true}
|
||||
ib := mkInbound(t, 54506, model.VLESS, clientsSettings(t, []model.Client{stays}))
|
||||
if err := clients.SyncInbound(nil, ib.Id, []model.Client{stays}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db := database.GetDB()
|
||||
for _, email := range []string{gone, kept} {
|
||||
if err := db.Create(&model.ClientTrafficWindow{Email: email, At: 1, Up: 5, Reason: trafficWindowReset}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.ClientChangeLog{Email: email, At: 1, Field: "enable"}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
record, err := clients.GetRecordByEmail(nil, gone)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := clients.Delete(inbounds, record.Id, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reaped, err := clients.ReapOrphanClientHistory()
|
||||
if err != nil || reaped != 2 {
|
||||
t.Fatalf("reaped %d rows (err %v), want the deleted client's window and change", reaped, err)
|
||||
}
|
||||
if w, c := len(windowsOf(t, gone)), len(changesOf(t, gone)); w != 0 || c != 0 {
|
||||
t.Fatalf("deleted client still has %d windows and %d changes", w, c)
|
||||
}
|
||||
if w, c := len(windowsOf(t, kept)), len(changesOf(t, kept)); w != 1 || c != 1 {
|
||||
t.Fatalf("living client has %d windows and %d changes, want 1 and 1", w, c)
|
||||
}
|
||||
}
|
||||
|
||||
// The orphan list is read off the writer. A client that takes one of the listed emails
|
||||
// before the delete runs owns that history, renamed-in rows included.
|
||||
func TestReapSparesAnEmailClaimedAfterItWasListed(t *testing.T) {
|
||||
const claimed, held, orphan = "claimed@example.test", "held@example.test", "orphan@example.test"
|
||||
setupBulkDB(t)
|
||||
db := database.GetDB()
|
||||
if err := db.Create(&model.ClientRecord{Email: held, SubID: held, Enable: true}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, email := range []string{claimed, held, orphan} {
|
||||
if err := db.Create(&model.ClientTrafficWindow{Email: email, At: 1, Up: 5, Reason: trafficWindowReset}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
listed, err := orphanHistoryEmails(db, "client_traffic_windows")
|
||||
if err != nil || len(listed) != 2 || listed[0] != claimed || listed[1] != orphan {
|
||||
t.Fatalf("listed %v (err %v), want the two client-less emails and not the held one", listed, err)
|
||||
}
|
||||
if err := db.Create(&model.ClientRecord{Email: claimed, SubID: claimed, Enable: true}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dropped, err := deleteOrphanHistory(&model.ClientTrafficWindow{}, listed)
|
||||
if err != nil || dropped != 1 {
|
||||
t.Fatalf("dropped %d rows (err %v), want only the orphan's window", dropped, err)
|
||||
}
|
||||
if kept, gone := len(windowsOf(t, claimed)), len(windowsOf(t, orphan)); kept != 1 || gone != 0 {
|
||||
t.Fatalf("claimed email has %d windows and the orphan %d, want 1 and 0", kept, gone)
|
||||
}
|
||||
}
|
||||
|
||||
// Bulk reset archives only the rows that actually carried usage.
|
||||
func TestBulkResetArchivesUsedWindowsOnly(t *testing.T) {
|
||||
inboundSvc := &InboundService{}
|
||||
seedUsageHistoryClient(t, inboundSvc, "bulk-used@example.test", "55555555-2222-4222-8222-222222222222", 10, 5)
|
||||
svc := &ClientService{}
|
||||
|
||||
// A second zero-usage client on its own inbound.
|
||||
client2 := model.Client{Email: "bulk-idle@example.test", ID: "66666666-3333-4333-8333-333333333333", SubID: "bulk-idle@example.test", Enable: true}
|
||||
ib2 := mkInbound(t, 54502, model.VLESS, clientsSettings(t, []model.Client{client2}))
|
||||
if err := svc.SyncInbound(nil, ib2.Id, []model.Client{client2}); err != nil {
|
||||
t.Fatalf("SyncInbound: %v", err)
|
||||
}
|
||||
|
||||
idle := xray.ClientTraffic{InboundId: ib2.Id, Email: "bulk-idle@example.test", Enable: true}
|
||||
if err := database.GetDB().Create(&idle).Error; err != nil {
|
||||
t.Fatalf("seed idle client_traffics: %v", err)
|
||||
}
|
||||
|
||||
if _, err := svc.BulkResetTraffic(inboundSvc, []string{"bulk-used@example.test", "bulk-idle@example.test"}); err != nil {
|
||||
t.Fatalf("BulkResetTraffic: %v", err)
|
||||
}
|
||||
if got := len(windowsOf(t, "bulk-used@example.test")); got != 1 {
|
||||
t.Fatalf("used client windows = %d, want 1", got)
|
||||
}
|
||||
if got := len(windowsOf(t, "bulk-idle@example.test")); got != 0 {
|
||||
t.Fatalf("idle client windows = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// An auto-renewal must archive the closed quota window under reason "renew"
|
||||
// and log the expiry change under source "auto-renew".
|
||||
func TestAutoRenewArchivesRenewWindowAndLogsExpiry(t *testing.T) {
|
||||
inboundSvc := &InboundService{}
|
||||
svc := &ClientService{}
|
||||
setupBulkDB(t)
|
||||
|
||||
const email = "renew-win@example.test"
|
||||
past := time.Now().Add(-24 * time.Hour).UnixMilli()
|
||||
client := model.Client{Email: email, ID: "77777777-4444-4444-8444-444444444444", SubID: email, Enable: true, Reset: 30}
|
||||
ib := mkInbound(t, 54503, model.VLESS, clientsSettings(t, []model.Client{client}))
|
||||
if err := svc.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil {
|
||||
t.Fatalf("SyncInbound: %v", err)
|
||||
}
|
||||
db := database.GetDB()
|
||||
traffic := xray.ClientTraffic{
|
||||
InboundId: ib.Id, Email: email, Enable: true,
|
||||
Up: 300, Down: 100, Reset: 30, ExpiryTime: past, Total: 1 << 40,
|
||||
}
|
||||
if err := db.Create(&traffic).Error; err != nil {
|
||||
t.Fatalf("seed traffic: %v", err)
|
||||
}
|
||||
|
||||
_, count, err := inboundSvc.autoRenewClients(db, newTrafficMutationBatch())
|
||||
if err != nil {
|
||||
t.Fatalf("autoRenewClients: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("renewed count = %d, want 1", count)
|
||||
}
|
||||
|
||||
var live xray.ClientTraffic
|
||||
if err := db.Where("email = ?", email).First(&live).Error; err != nil {
|
||||
t.Fatalf("read live traffic row: %v", err)
|
||||
}
|
||||
if live.Up != 0 || live.Down != 0 {
|
||||
t.Fatalf("renewal did not zero counters: %d/%d", live.Up, live.Down)
|
||||
}
|
||||
windows := windowsOf(t, email)
|
||||
if len(windows) != 1 || windows[0].Reason != trafficWindowRenew || windows[0].Up != 300 || windows[0].Down != 100 {
|
||||
t.Fatalf("windows = %+v, want one renew window 300/100", windows)
|
||||
}
|
||||
changes := changesOf(t, email)
|
||||
if len(changes) != 1 || changes[0].Field != "expiry" || changes[0].Source != clientChangeSourceRenew {
|
||||
t.Fatalf("changes = %+v, want one auto-renew expiry row", changes)
|
||||
}
|
||||
if changes[0].OldValue != itoa(past) || changes[0].NewValue == changes[0].OldValue {
|
||||
t.Fatalf("expiry row = %+v, want old=%d new>old", changes[0], past)
|
||||
}
|
||||
}
|
||||
|
||||
// A save from the editor logs each field it changed and nothing else; a
|
||||
// no-op save logs nothing.
|
||||
func TestUpdateLogsChangedFieldsOnly(t *testing.T) {
|
||||
inboundSvc := &InboundService{}
|
||||
seedUsageHistoryClient(t, inboundSvc, "upd-log@example.test", "99999999-6666-4666-8666-666666666666", 0, 0)
|
||||
svc := &ClientService{}
|
||||
|
||||
rec, err := svc.GetRecordByEmail(nil, "upd-log@example.test")
|
||||
if err != nil {
|
||||
t.Fatalf("GetRecordByEmail: %v", err)
|
||||
}
|
||||
updated := rec.ToClient()
|
||||
newExpiry := time.Now().Add(60 * 24 * time.Hour).UnixMilli()
|
||||
updated.ExpiryTime = newExpiry
|
||||
updated.TotalGB = 5 << 30
|
||||
if _, err := svc.Update(inboundSvc, rec.Id, *updated, rec.LimitHwid); err != nil {
|
||||
t.Fatalf("Update: %v", err)
|
||||
}
|
||||
|
||||
fields := map[string]string{}
|
||||
for _, c := range changesOf(t, "upd-log@example.test") {
|
||||
fields[c.Field] = c.NewValue
|
||||
}
|
||||
if len(fields) != 2 {
|
||||
t.Fatalf("logged fields = %v, want exactly expiry and dataLimit", fields)
|
||||
}
|
||||
if fields["expiry"] != itoa(newExpiry) || fields["dataLimit"] != itoa(int64(5<<30)) {
|
||||
t.Fatalf("field values = %v", fields)
|
||||
}
|
||||
for _, c := range changesOf(t, "upd-log@example.test") {
|
||||
if c.Source != clientChangeSourcePanel {
|
||||
t.Fatalf("source = %q, want %q", c.Source, clientChangeSourcePanel)
|
||||
}
|
||||
}
|
||||
|
||||
// A no-op save must not grow the log.
|
||||
before := len(changesOf(t, "upd-log@example.test"))
|
||||
if _, err := svc.Update(inboundSvc, rec.Id, *updated, rec.LimitHwid); err != nil {
|
||||
t.Fatalf("no-op Update: %v", err)
|
||||
}
|
||||
if after := len(changesOf(t, "upd-log@example.test")); after != before {
|
||||
t.Fatalf("no-op save logged %d extra rows", after-before)
|
||||
}
|
||||
}
|
||||
|
||||
// Bulk enable/disable logs an "enable" row only for the clients that flipped.
|
||||
func TestBulkSetEnableLogsOnlyFlippedClients(t *testing.T) {
|
||||
inboundSvc := &InboundService{}
|
||||
seedUsageHistoryClient(t, inboundSvc, "bulk-en-a@example.test", "aaaaaaaa-7777-4777-8777-777777777777", 0, 0)
|
||||
svc := &ClientService{}
|
||||
clientB := model.Client{Email: "bulk-en-b@example.test", ID: "bbbbbbbb-8888-4888-8888-888888888888", SubID: "bulk-en-b@example.test", Enable: true}
|
||||
ib2 := mkInbound(t, 54505, model.VLESS, clientsSettings(t, []model.Client{clientB}))
|
||||
if err := svc.SyncInbound(nil, ib2.Id, []model.Client{clientB}); err != nil {
|
||||
t.Fatalf("SyncInbound: %v", err)
|
||||
}
|
||||
|
||||
if _, _, err := svc.BulkSetEnable(inboundSvc, []string{"bulk-en-a@example.test", "bulk-en-b@example.test"}, false); err != nil {
|
||||
t.Fatalf("BulkSetEnable: %v", err)
|
||||
}
|
||||
if got := len(changesOf(t, "bulk-en-a@example.test")); got != 1 {
|
||||
t.Fatalf("client A enable rows = %d, want 1", got)
|
||||
}
|
||||
if got := len(changesOf(t, "bulk-en-b@example.test")); got != 1 {
|
||||
t.Fatalf("client B enable rows = %d, want 1", got)
|
||||
}
|
||||
// Re-applying the same state must log nothing new.
|
||||
if _, _, err := svc.BulkSetEnable(inboundSvc, []string{"bulk-en-a@example.test"}, false); err != nil {
|
||||
t.Fatalf("BulkSetEnable repeat: %v", err)
|
||||
}
|
||||
if got := len(changesOf(t, "bulk-en-a@example.test")); got != 1 {
|
||||
t.Fatalf("repeat enable rows = %d, want still 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Renaming a client carries its windows and change log onto the new email and records
|
||||
// the rename once, however many inbounds the client is on.
|
||||
func TestRenameMigratesClientHistory(t *testing.T) {
|
||||
const oldEmail, newEmail = "old-name@example.test", "new-name@example.test"
|
||||
inboundSvc := &InboundService{}
|
||||
ib := seedUsageHistoryClient(t, inboundSvc, oldEmail, "cccccccc-9999-4999-8999-999999999999", 7, 9)
|
||||
svc := &ClientService{}
|
||||
same := model.Client{Email: oldEmail, ID: "cccccccc-9999-4999-8999-999999999999", SubID: oldEmail, Enable: true}
|
||||
second := mkInbound(t, 54507, model.VLESS, clientsSettings(t, []model.Client{same}))
|
||||
if err := svc.SyncInbound(nil, second.Id, []model.Client{same}); err != nil {
|
||||
t.Fatalf("SyncInbound: %v", err)
|
||||
}
|
||||
|
||||
// Close one window so there is history to migrate.
|
||||
if _, err := inboundSvc.ResetClientTraffic(ib.Id, oldEmail); err != nil {
|
||||
t.Fatalf("ResetClientTraffic: %v", err)
|
||||
}
|
||||
|
||||
rec, err := svc.GetRecordByEmail(nil, oldEmail)
|
||||
if err != nil {
|
||||
t.Fatalf("GetRecordByEmail: %v", err)
|
||||
}
|
||||
renamed := rec.ToClient()
|
||||
renamed.Email = newEmail
|
||||
renamed.TotalGB = 5 << 30
|
||||
if _, err := svc.Update(inboundSvc, rec.Id, *renamed, rec.LimitHwid); err != nil {
|
||||
t.Fatalf("rename Update: %v", err)
|
||||
}
|
||||
|
||||
if w, c := len(windowsOf(t, oldEmail)), len(changesOf(t, oldEmail)); w != 0 || c != 0 {
|
||||
t.Fatalf("old email still has %d windows and %d changes, want all of it under the new one", w, c)
|
||||
}
|
||||
windows := windowsOf(t, newEmail)
|
||||
if len(windows) != 1 || windows[0].Reason != trafficWindowReset || windows[0].Up != 7 {
|
||||
t.Fatalf("new email windows = %+v, want the migrated reset window", windows)
|
||||
}
|
||||
names, limits := 0, 0
|
||||
for _, c := range changesOf(t, newEmail) {
|
||||
switch {
|
||||
case c.Field == "name" && c.OldValue == oldEmail && c.NewValue == newEmail:
|
||||
names++
|
||||
case c.Field == "dataLimit" && c.NewValue == itoa(5<<30):
|
||||
limits++
|
||||
}
|
||||
}
|
||||
if names != 1 || limits != 1 {
|
||||
t.Fatalf("new email has %d name and %d dataLimit rows, want 1 and 1", names, limits)
|
||||
}
|
||||
}
|
||||
|
||||
// A client attached to no inbound is renamed by the record write alone; its history
|
||||
// has to follow there too, or the reaper drops it with the old email.
|
||||
func TestRenameOfAnUnattachedClientMigratesItsHistory(t *testing.T) {
|
||||
const oldEmail, newEmail = "loose-old@example.test", "loose-new@example.test"
|
||||
setupBulkDB(t)
|
||||
db := database.GetDB()
|
||||
rec := model.ClientRecord{Email: oldEmail, SubID: oldEmail, Enable: true}
|
||||
if err := db.Create(&rec).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.ClientTrafficWindow{Email: oldEmail, At: 1, Up: 5, Reason: trafficWindowReset}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
renamed := rec.ToClient()
|
||||
renamed.Email = newEmail
|
||||
if _, err := (&ClientService{}).Update(&InboundService{}, rec.Id, *renamed, rec.LimitHwid); err != nil {
|
||||
t.Fatalf("rename Update: %v", err)
|
||||
}
|
||||
|
||||
if old, moved := len(windowsOf(t, oldEmail)), len(windowsOf(t, newEmail)); old != 0 || moved != 1 {
|
||||
t.Fatalf("windows: %d under the old email and %d under the new, want 0 and 1", old, moved)
|
||||
}
|
||||
changes := changesOf(t, newEmail)
|
||||
if len(changes) != 1 || changes[0].Field != "name" || changes[0].OldValue != oldEmail || changes[0].NewValue != newEmail {
|
||||
t.Fatalf("change log = %+v, want the one rename row", changes)
|
||||
}
|
||||
}
|
||||
|
||||
// GetUsageHistory must report the node's own accumulated up/down, separated.
|
||||
func TestGetUsageHistoryReportsNodeUsage(t *testing.T) {
|
||||
inboundSvc := &InboundService{}
|
||||
seedUsageHistoryClient(t, inboundSvc, "node-usage@example.test", "eeeeeeee-bbbb-4bbb-8bbb-bbbbbbbbbbbb", 0, 0)
|
||||
db := database.GetDB()
|
||||
|
||||
node := &model.Node{
|
||||
Name: "fra-edge",
|
||||
Address: "fra.example.com",
|
||||
}
|
||||
if err := db.Create(node).Error; err != nil {
|
||||
t.Fatalf("create node: %v", err)
|
||||
}
|
||||
nodeRow := &model.NodeClientTraffic{NodeId: node.Id, Email: "node-usage@example.test", Up: 111, Down: 222}
|
||||
if err := db.Create(nodeRow).Error; err != nil {
|
||||
t.Fatalf("create node traffic: %v", err)
|
||||
}
|
||||
|
||||
history, err := (&ClientService{}).GetUsageHistory("node-usage@example.test")
|
||||
if err != nil {
|
||||
t.Fatalf("GetUsageHistory: %v", err)
|
||||
}
|
||||
if len(history.Nodes) != 1 {
|
||||
t.Fatalf("nodes = %+v, want one", history.Nodes)
|
||||
}
|
||||
if history.Nodes[0].NodeName != "fra-edge" || history.Nodes[0].Up != 111 || history.Nodes[0].Down != 222 {
|
||||
t.Fatalf("node usage = %+v, want fra-edge 111/222", history.Nodes[0])
|
||||
}
|
||||
}
|
||||
|
||||
// itoa is a tiny strconv alias kept local so the table above stays readable.
|
||||
func itoa(v int64) string {
|
||||
b, _ := json.Marshal(v)
|
||||
return string(b)
|
||||
}
|
||||
@@ -502,6 +502,7 @@ func (s *InboundService) autoRenewClients(tx *gorm.DB, mutationBatch *trafficMut
|
||||
return false, 0, err
|
||||
}
|
||||
renewedEmails := make([]string, 0, len(traffics))
|
||||
var renewedExpiries []model.ClientChangeLog
|
||||
for inbound_index := range inbounds {
|
||||
settings := map[string]any{}
|
||||
_ = json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
|
||||
@@ -524,6 +525,10 @@ func (s *InboundService) autoRenewClients(tx *gorm.DB, mutationBatch *trafficMut
|
||||
// cycles must not catch up three of them against a prepaid cap.
|
||||
newExpiryTime, renewals := catchUpClientRenewal(traffic, now, renewLocation)
|
||||
if renewals > 0 {
|
||||
renewedExpiries = append(renewedExpiries, model.ClientChangeLog{
|
||||
Email: email, Field: "expiry", Source: clientChangeSourceRenew,
|
||||
OldValue: fmt.Sprint(traffic.ExpiryTime), NewValue: fmt.Sprint(newExpiryTime),
|
||||
})
|
||||
traffic.ExpiryTime = newExpiryTime
|
||||
traffic.ResetCount += renewals
|
||||
}
|
||||
@@ -581,6 +586,13 @@ func (s *InboundService) autoRenewClients(tx *gorm.DB, mutationBatch *trafficMut
|
||||
logger.Warning("autoRenewClients sync clients: SyncInbound failed", syncErr)
|
||||
}
|
||||
}
|
||||
// The rows still hold the counters of the window this renewal closes.
|
||||
if err = archiveClosedWindowsTx(tx, renewedEmails, trafficWindowRenew); err != nil {
|
||||
return false, 0, err
|
||||
}
|
||||
if err = logClientChangesTx(tx, renewedExpiries); err != nil {
|
||||
return false, 0, err
|
||||
}
|
||||
err = saveInChunks(tx, traffics)
|
||||
if err != nil {
|
||||
return false, 0, err
|
||||
@@ -804,6 +816,9 @@ func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (b
|
||||
if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{clientEmail}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := archiveClosedWindowsTx(tx, []string{clientEmail}, trafficWindowReset); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Save(traffic).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -1127,7 +1127,37 @@
|
||||
"bulkAppendLinksHint": "تُضاف إلى كل العملاء المحددين. تُحفظ الروابط الحالية وإعداداتها وتُتخطى القيم المكررة من النوع نفسه. طبّق التعديلات الأخرى بشكل منفصل.",
|
||||
"bulkAppendLinksRequired": "أضف رابطًا خارجيًا أو اشتراكًا واحدًا على الأقل.",
|
||||
"externalLinkInvalid": "أدخل رابط مشاركة مدعومًا.",
|
||||
"externalSubscriptionInvalid": "أدخل عنوان اشتراك باستخدام http أو https."
|
||||
"externalSubscriptionInvalid": "أدخل عنوان اشتراك باستخدام http أو https.",
|
||||
"usageHistory": "سجل الاستخدام والتغييرات",
|
||||
"lifetimeTraffic": "إجمالي الاستخدام",
|
||||
"currentCycle": "الدورة الحالية",
|
||||
"pastCycles": "الدورات السابقة",
|
||||
"usageByNode": "الاستخدام حسب العُقدة",
|
||||
"upload": "رفع",
|
||||
"download": "تنزيل",
|
||||
"node": "عقدة",
|
||||
"time": "الوقت",
|
||||
"field": "الحقل",
|
||||
"oldValue": "السابق",
|
||||
"newValue": "الجديد",
|
||||
"source": "المصدر",
|
||||
"reason": "السبب",
|
||||
"reasonReset": "إعادة تعيين",
|
||||
"reasonRenew": "تجديد",
|
||||
"reasonEarlier": "أقدم",
|
||||
"noUsageHistory": "لا يوجد سجل استخدام أو تغييرات بعد.",
|
||||
"historyError": "تعذر تحميل سجل الاستخدام.",
|
||||
"fieldName": "الاسم",
|
||||
"fieldSubId": "معرف الاشتراك",
|
||||
"fieldExpiry": "انتهاء الصلاحية",
|
||||
"fieldDataLimit": "حد البيانات",
|
||||
"fieldEnable": "مفعّل",
|
||||
"fieldRenewalPlan": "خطة التجديد",
|
||||
"fieldLimitIp": "حد IP",
|
||||
"fieldLimitHwid": "حد HWID",
|
||||
"fieldAdTag": "وسم الإعلان",
|
||||
"fieldGroup": "المجموعة",
|
||||
"changes": "التغييرات"
|
||||
},
|
||||
"groups": {
|
||||
"name": "الاسم",
|
||||
|
||||
@@ -1127,7 +1127,37 @@
|
||||
"bulkAppendLinksHint": "Append to every selected client. Existing entries and their settings stay unchanged; duplicate kind and value pairs are skipped. Apply other adjustments separately.",
|
||||
"bulkAppendLinksRequired": "Add at least one external link or subscription.",
|
||||
"externalLinkInvalid": "Enter a supported share link.",
|
||||
"externalSubscriptionInvalid": "Enter an http(s) subscription URL."
|
||||
"externalSubscriptionInvalid": "Enter an http(s) subscription URL.",
|
||||
"usageHistory": "Usage & change history",
|
||||
"lifetimeTraffic": "Lifetime traffic",
|
||||
"currentCycle": "Current cycle",
|
||||
"pastCycles": "Past cycles",
|
||||
"usageByNode": "Usage by node",
|
||||
"upload": "Upload",
|
||||
"download": "Download",
|
||||
"node": "Node",
|
||||
"time": "Time",
|
||||
"field": "Field",
|
||||
"oldValue": "Old",
|
||||
"newValue": "New",
|
||||
"source": "Source",
|
||||
"reason": "Reason",
|
||||
"reasonReset": "reset",
|
||||
"reasonRenew": "renewed",
|
||||
"reasonEarlier": "earlier",
|
||||
"noUsageHistory": "No usage or change history yet.",
|
||||
"historyError": "Failed to load the usage history.",
|
||||
"fieldName": "Name",
|
||||
"fieldSubId": "Sub ID",
|
||||
"fieldExpiry": "Expiry",
|
||||
"fieldDataLimit": "Data limit",
|
||||
"fieldEnable": "Enabled",
|
||||
"fieldRenewalPlan": "Renewal plan",
|
||||
"fieldLimitIp": "IP limit",
|
||||
"fieldLimitHwid": "HWID limit",
|
||||
"fieldAdTag": "Ad tag",
|
||||
"fieldGroup": "Group",
|
||||
"changes": "Changes"
|
||||
},
|
||||
"groups": {
|
||||
"name": "Name",
|
||||
|
||||
@@ -1127,7 +1127,37 @@
|
||||
"bulkAppendLinksHint": "Se añaden a todos los clientes seleccionados. Se conservan las entradas y los ajustes existentes; se omiten los pares de tipo y valor duplicados. Aplica los demás ajustes por separado.",
|
||||
"bulkAppendLinksRequired": "Añade al menos un enlace o una suscripción externa.",
|
||||
"externalLinkInvalid": "Introduce un enlace compartido compatible.",
|
||||
"externalSubscriptionInvalid": "Introduce una URL de suscripción http(s)."
|
||||
"externalSubscriptionInvalid": "Introduce una URL de suscripción http(s).",
|
||||
"usageHistory": "Historial de uso y cambios",
|
||||
"lifetimeTraffic": "Tráfico total",
|
||||
"currentCycle": "Ciclo actual",
|
||||
"pastCycles": "Ciclos anteriores",
|
||||
"usageByNode": "Uso por nodo",
|
||||
"upload": "Subida",
|
||||
"download": "Descarga",
|
||||
"node": "Nodo",
|
||||
"time": "Hora",
|
||||
"field": "Campo",
|
||||
"oldValue": "Anterior",
|
||||
"newValue": "Nuevo",
|
||||
"source": "Origen",
|
||||
"reason": "Motivo",
|
||||
"reasonReset": "reiniciado",
|
||||
"reasonRenew": "renovado",
|
||||
"reasonEarlier": "anteriores",
|
||||
"noUsageHistory": "Aún no hay historial de uso ni cambios.",
|
||||
"historyError": "No se pudo cargar el historial.",
|
||||
"fieldName": "Nombre",
|
||||
"fieldSubId": "Sub ID",
|
||||
"fieldExpiry": "Caducidad",
|
||||
"fieldDataLimit": "Límite de datos",
|
||||
"fieldEnable": "Habilitado",
|
||||
"fieldRenewalPlan": "Plan de renovación",
|
||||
"fieldLimitIp": "Límite de IP",
|
||||
"fieldLimitHwid": "Límite de HWID",
|
||||
"fieldAdTag": "Etiqueta publicitaria",
|
||||
"fieldGroup": "Grupo",
|
||||
"changes": "Cambios"
|
||||
},
|
||||
"groups": {
|
||||
"name": "Nombre",
|
||||
|
||||
@@ -1127,7 +1127,37 @@
|
||||
"bulkAppendLinksHint": "به همه کلاینتهای انتخابشده اضافه میشود. لینکها و تنظیمات فعلی حفظ و موارد تکراری با نوع و مقدار یکسان رد میشوند. سایر تغییرات را جداگانه اعمال کنید.",
|
||||
"bulkAppendLinksRequired": "حداقل یک لینک یا اشتراک خارجی اضافه کنید.",
|
||||
"externalLinkInvalid": "یک لینک اشتراک پشتیبانیشده وارد کنید.",
|
||||
"externalSubscriptionInvalid": "نشانی اشتراک با پروتکل http یا https وارد کنید."
|
||||
"externalSubscriptionInvalid": "نشانی اشتراک با پروتکل http یا https وارد کنید.",
|
||||
"usageHistory": "تاریخچهٔ استفاده و تغییرات",
|
||||
"lifetimeTraffic": "ترافیک کل",
|
||||
"currentCycle": "چرخهٔ فعلی",
|
||||
"pastCycles": "چرخههای گذشته",
|
||||
"usageByNode": "مصرف بر اساس نود",
|
||||
"upload": "آپلود",
|
||||
"download": "دانلود",
|
||||
"node": "نود",
|
||||
"time": "زمان",
|
||||
"field": "فیلد",
|
||||
"oldValue": "قبلی",
|
||||
"newValue": "جدید",
|
||||
"source": "منبع",
|
||||
"reason": "دلیل",
|
||||
"reasonReset": "ریست",
|
||||
"reasonRenew": "تمدید",
|
||||
"reasonEarlier": "قدیمیتر",
|
||||
"noUsageHistory": "هنوز تاریخی از استفاده یا تغییرات ثبت نشده است.",
|
||||
"historyError": "تاریخچه را نمیتوان بارگذاری کرد.",
|
||||
"fieldName": "نام",
|
||||
"fieldSubId": "شناسهٔ اشتراک",
|
||||
"fieldExpiry": "انقضا",
|
||||
"fieldDataLimit": "سقف داده",
|
||||
"fieldEnable": "فعال",
|
||||
"fieldRenewalPlan": "برنامهٔ تمدید",
|
||||
"fieldLimitIp": "سقف IP",
|
||||
"fieldLimitHwid": "سقف HWID",
|
||||
"fieldAdTag": "برچسب تبلیغاتی",
|
||||
"fieldGroup": "گروه",
|
||||
"changes": "تغییرات"
|
||||
},
|
||||
"groups": {
|
||||
"name": "نام",
|
||||
|
||||
@@ -1127,7 +1127,37 @@
|
||||
"bulkAppendLinksHint": "Tambahkan ke semua klien yang dipilih. Entri dan pengaturan yang ada dipertahankan; pasangan jenis dan nilai duplikat dilewati. Terapkan penyesuaian lain secara terpisah.",
|
||||
"bulkAppendLinksRequired": "Tambahkan setidaknya satu tautan atau langganan eksternal.",
|
||||
"externalLinkInvalid": "Masukkan tautan berbagi yang didukung.",
|
||||
"externalSubscriptionInvalid": "Masukkan URL langganan http(s)."
|
||||
"externalSubscriptionInvalid": "Masukkan URL langganan http(s).",
|
||||
"usageHistory": "Riwayat penggunaan & perubahan",
|
||||
"lifetimeTraffic": "Total trafik",
|
||||
"currentCycle": "Siklus saat ini",
|
||||
"pastCycles": "Siklus sebelumnya",
|
||||
"usageByNode": "Penggunaan per node",
|
||||
"upload": "Unggah",
|
||||
"download": "Unduh",
|
||||
"node": "Node",
|
||||
"time": "Waktu",
|
||||
"field": "Kolom",
|
||||
"oldValue": "Lama",
|
||||
"newValue": "Baru",
|
||||
"source": "Sumber",
|
||||
"reason": "Alasan",
|
||||
"reasonReset": "direset",
|
||||
"reasonRenew": "diperpanjang",
|
||||
"reasonEarlier": "sebelumnya",
|
||||
"noUsageHistory": "Belum ada riwayat penggunaan maupun perubahan.",
|
||||
"historyError": "Gagal memuat riwayat penggunaan.",
|
||||
"fieldName": "Nama",
|
||||
"fieldSubId": "Sub ID",
|
||||
"fieldExpiry": "Kadaluarsa",
|
||||
"fieldDataLimit": "Batas data",
|
||||
"fieldEnable": "Aktif",
|
||||
"fieldRenewalPlan": "Rencana perpanjangan",
|
||||
"fieldLimitIp": "Batas IP",
|
||||
"fieldLimitHwid": "Batas HWID",
|
||||
"fieldAdTag": "Tag iklan",
|
||||
"fieldGroup": "Grup",
|
||||
"changes": "Perubahan"
|
||||
},
|
||||
"groups": {
|
||||
"name": "Nama",
|
||||
|
||||
@@ -1127,7 +1127,37 @@
|
||||
"bulkAppendLinksHint": "選択したすべてのクライアントに追加します。既存の項目と設定を保持し、種類と値が同じ項目はスキップします。他の調整は別に適用してください。",
|
||||
"bulkAppendLinksRequired": "外部リンクまたはサブスクリプションを1件以上追加してください。",
|
||||
"externalLinkInvalid": "対応する共有リンクを入力してください。",
|
||||
"externalSubscriptionInvalid": "http(s)のサブスクリプションURLを入力してください。"
|
||||
"externalSubscriptionInvalid": "http(s)のサブスクリプションURLを入力してください。",
|
||||
"usageHistory": "利用・変更履歴",
|
||||
"lifetimeTraffic": "累計トラフィック",
|
||||
"currentCycle": "現在の期間",
|
||||
"pastCycles": "過去の期間",
|
||||
"usageByNode": "ノード別の利用状況",
|
||||
"upload": "アップロード",
|
||||
"download": "ダウンロード",
|
||||
"node": "ノード",
|
||||
"time": "時刻",
|
||||
"field": "項目",
|
||||
"oldValue": "変更前",
|
||||
"newValue": "変更後",
|
||||
"source": "ソース",
|
||||
"reason": "理由",
|
||||
"reasonReset": "リセット",
|
||||
"reasonRenew": "更新",
|
||||
"reasonEarlier": "以前",
|
||||
"noUsageHistory": "まだ利用履歴・変更履歴はありません。",
|
||||
"historyError": "履歴を読み込めませんでした。",
|
||||
"fieldName": "名前",
|
||||
"fieldSubId": "サブ ID",
|
||||
"fieldExpiry": "有効期限",
|
||||
"fieldDataLimit": "トラフィック上限",
|
||||
"fieldEnable": "有効",
|
||||
"fieldRenewalPlan": "更新プラン",
|
||||
"fieldLimitIp": "IP 上限",
|
||||
"fieldLimitHwid": "HWID 上限",
|
||||
"fieldAdTag": "広告タグ",
|
||||
"fieldGroup": "グループ",
|
||||
"changes": "変更"
|
||||
},
|
||||
"groups": {
|
||||
"name": "名前",
|
||||
|
||||
@@ -1127,7 +1127,37 @@
|
||||
"bulkAppendLinksHint": "Adiciona a todos os clientes selecionados. Preserva as entradas e configurações existentes; ignora pares de tipo e valor duplicados. Aplique outros ajustes separadamente.",
|
||||
"bulkAppendLinksRequired": "Adicione pelo menos um link ou assinatura externa.",
|
||||
"externalLinkInvalid": "Insira um link de compartilhamento compatível.",
|
||||
"externalSubscriptionInvalid": "Insira uma URL de assinatura http(s)."
|
||||
"externalSubscriptionInvalid": "Insira uma URL de assinatura http(s).",
|
||||
"usageHistory": "Histórico de uso e alterações",
|
||||
"lifetimeTraffic": "Tráfego total",
|
||||
"currentCycle": "Ciclo atual",
|
||||
"pastCycles": "Ciclos anteriores",
|
||||
"usageByNode": "Uso por nó",
|
||||
"upload": "Upload",
|
||||
"download": "Download",
|
||||
"node": "Nó",
|
||||
"time": "Horário",
|
||||
"field": "Campo",
|
||||
"oldValue": "Anterior",
|
||||
"newValue": "Novo",
|
||||
"source": "Origem",
|
||||
"reason": "Motivo",
|
||||
"reasonReset": "reiniciado",
|
||||
"reasonRenew": "renovado",
|
||||
"reasonEarlier": "anteriores",
|
||||
"noUsageHistory": "Ainda não há histórico de uso nem alterações.",
|
||||
"historyError": "Falha ao carregar o histórico.",
|
||||
"fieldName": "Nome",
|
||||
"fieldSubId": "Sub ID",
|
||||
"fieldExpiry": "Validade",
|
||||
"fieldDataLimit": "Limite de dados",
|
||||
"fieldEnable": "Habilitado",
|
||||
"fieldRenewalPlan": "Plano de renovação",
|
||||
"fieldLimitIp": "Limite de IP",
|
||||
"fieldLimitHwid": "Limite de HWID",
|
||||
"fieldAdTag": "Tag de anúncio",
|
||||
"fieldGroup": "Grupo",
|
||||
"changes": "Alterações"
|
||||
},
|
||||
"groups": {
|
||||
"name": "Nome",
|
||||
|
||||
@@ -1127,7 +1127,37 @@
|
||||
"bulkAppendLinksHint": "Добавить всем выбранным клиентам. Существующие записи и настройки сохраняются; повторы с одинаковыми типом и значением пропускаются. Остальные изменения применяйте отдельно.",
|
||||
"bulkAppendLinksRequired": "Добавьте хотя бы одну внешнюю ссылку или подписку.",
|
||||
"externalLinkInvalid": "Введите поддерживаемую ссылку подключения.",
|
||||
"externalSubscriptionInvalid": "Введите URL подписки http(s)."
|
||||
"externalSubscriptionInvalid": "Введите URL подписки http(s).",
|
||||
"usageHistory": "История использования и изменений",
|
||||
"lifetimeTraffic": "Весь трафик",
|
||||
"currentCycle": "Текущий период",
|
||||
"pastCycles": "Прошедшие периоды",
|
||||
"usageByNode": "Использование по узлам",
|
||||
"upload": "Загрузка",
|
||||
"download": "Выгрузка",
|
||||
"node": "Узел",
|
||||
"time": "Время",
|
||||
"field": "Поле",
|
||||
"oldValue": "Было",
|
||||
"newValue": "Стало",
|
||||
"source": "Источник",
|
||||
"reason": "Причина",
|
||||
"reasonReset": "сброс",
|
||||
"reasonRenew": "продление",
|
||||
"reasonEarlier": "ранее",
|
||||
"noUsageHistory": "История использования и изменений пока отсутствует.",
|
||||
"historyError": "Не удалось загрузить историю.",
|
||||
"fieldName": "Имя",
|
||||
"fieldSubId": "Sub ID",
|
||||
"fieldExpiry": "Срок действия",
|
||||
"fieldDataLimit": "Лимит данных",
|
||||
"fieldEnable": "Включено",
|
||||
"fieldRenewalPlan": "План продления",
|
||||
"fieldLimitIp": "Лимит IP",
|
||||
"fieldLimitHwid": "Лимит HWID",
|
||||
"fieldAdTag": "Ад-тег",
|
||||
"fieldGroup": "Группа",
|
||||
"changes": "Изменения"
|
||||
},
|
||||
"groups": {
|
||||
"name": "Имя",
|
||||
|
||||
@@ -1127,7 +1127,37 @@
|
||||
"bulkAppendLinksHint": "Pridá všetkým vybraným klientom. Existujúce záznamy a nastavenia sa zachovajú; duplicitné dvojice typu a hodnoty sa preskočia. Ostatné úpravy použite samostatne.",
|
||||
"bulkAppendLinksRequired": "Pridajte aspoň jeden externý odkaz alebo odber.",
|
||||
"externalLinkInvalid": "Zadajte podporovaný odkaz na zdieľanie.",
|
||||
"externalSubscriptionInvalid": "Zadajte URL odberu http(s)."
|
||||
"externalSubscriptionInvalid": "Zadajte URL odberu http(s).",
|
||||
"usageHistory": "História použitia a zmien",
|
||||
"lifetimeTraffic": "Celkový prenos",
|
||||
"currentCycle": "Aktuálne obdobie",
|
||||
"pastCycles": "Minulé obdobia",
|
||||
"usageByNode": "Použitie podľa uzla",
|
||||
"upload": "Nahranie",
|
||||
"download": "Stiahnutie",
|
||||
"node": "Uzel",
|
||||
"time": "Čas",
|
||||
"field": "Položka",
|
||||
"oldValue": "Predtým",
|
||||
"newValue": "Teraz",
|
||||
"source": "Pôvod",
|
||||
"reason": "Dôvod",
|
||||
"reasonReset": "rešovené",
|
||||
"reasonRenew": "obnovené",
|
||||
"reasonEarlier": "staršie",
|
||||
"noUsageHistory": "Zatiaľ žiadna história použitia ani zmien.",
|
||||
"historyError": "Históriu sa nepodarilo načítať.",
|
||||
"fieldName": "Názov",
|
||||
"fieldSubId": "Sub ID",
|
||||
"fieldExpiry": "Expirácia",
|
||||
"fieldDataLimit": "Limit dátov",
|
||||
"fieldEnable": "Povolené",
|
||||
"fieldRenewalPlan": "Obnovovací plán",
|
||||
"fieldLimitIp": "Limit IP",
|
||||
"fieldLimitHwid": "Limit HWID",
|
||||
"fieldAdTag": "Reklamný štítok",
|
||||
"fieldGroup": "Skupina",
|
||||
"changes": "Zmeny"
|
||||
},
|
||||
"groups": {
|
||||
"name": "Názov",
|
||||
|
||||
@@ -1127,7 +1127,37 @@
|
||||
"bulkAppendLinksHint": "Seçilen tüm istemcilere eklenir. Mevcut girdiler ve ayarları korunur; aynı tür ve değere sahip tekrarlar atlanır. Diğer ayarlamaları ayrı uygulayın.",
|
||||
"bulkAppendLinksRequired": "En az bir harici bağlantı veya abonelik ekleyin.",
|
||||
"externalLinkInvalid": "Desteklenen bir paylaşım bağlantısı girin.",
|
||||
"externalSubscriptionInvalid": "Bir http(s) abonelik URL’si girin."
|
||||
"externalSubscriptionInvalid": "Bir http(s) abonelik URL’si girin.",
|
||||
"usageHistory": "Kullanım ve değişiklik geçmişi",
|
||||
"lifetimeTraffic": "Toplam trafik",
|
||||
"currentCycle": "Güncel dönem",
|
||||
"pastCycles": "Geçmiş dönemler",
|
||||
"usageByNode": "Düğüme göre kullanım",
|
||||
"upload": "Yükleme",
|
||||
"download": "İndirme",
|
||||
"node": "Düğüm",
|
||||
"time": "Zaman",
|
||||
"field": "Alan",
|
||||
"oldValue": "Eski",
|
||||
"newValue": "Yeni",
|
||||
"source": "Kaynak",
|
||||
"reason": "Neden",
|
||||
"reasonReset": "sıfırlandı",
|
||||
"reasonRenew": "yenilendi",
|
||||
"reasonEarlier": "önceki",
|
||||
"noUsageHistory": "Henüz kullanım veya değişiklik geçmişi yok.",
|
||||
"historyError": "Geçmiş yüklenemedi.",
|
||||
"fieldName": "Ad",
|
||||
"fieldSubId": "Sub ID",
|
||||
"fieldExpiry": "Bitiş",
|
||||
"fieldDataLimit": "Veri limiti",
|
||||
"fieldEnable": "Etkin",
|
||||
"fieldRenewalPlan": "Yenileme planı",
|
||||
"fieldLimitIp": "IP limiti",
|
||||
"fieldLimitHwid": "HWID limiti",
|
||||
"fieldAdTag": "Reklam etiketi",
|
||||
"fieldGroup": "Grup",
|
||||
"changes": "Değişiklikler"
|
||||
},
|
||||
"groups": {
|
||||
"name": "İsim",
|
||||
|
||||
@@ -1127,7 +1127,37 @@
|
||||
"bulkAppendLinksHint": "Додається всім вибраним клієнтам. Наявні записи та налаштування зберігаються; повтори з однаковими типом і значенням пропускаються. Інші зміни застосовуйте окремо.",
|
||||
"bulkAppendLinksRequired": "Додайте хоча б одне зовнішнє посилання або підписку.",
|
||||
"externalLinkInvalid": "Введіть підтримуване посилання підключення.",
|
||||
"externalSubscriptionInvalid": "Введіть URL підписки http(s)."
|
||||
"externalSubscriptionInvalid": "Введіть URL підписки http(s).",
|
||||
"usageHistory": "Історія використання та змін",
|
||||
"lifetimeTraffic": "Усього трафіку",
|
||||
"currentCycle": "Поточний цикл",
|
||||
"pastCycles": "Минулі цикли",
|
||||
"usageByNode": "Використання за вузлами",
|
||||
"upload": "Відвантаження",
|
||||
"download": "Завантаження",
|
||||
"node": "Вузол",
|
||||
"time": "Час",
|
||||
"field": "Поле",
|
||||
"oldValue": "Було",
|
||||
"newValue": "Стало",
|
||||
"source": "Джерело",
|
||||
"reason": "Причина",
|
||||
"reasonReset": "скинуто",
|
||||
"reasonRenew": "продлено",
|
||||
"reasonEarlier": "раніше",
|
||||
"noUsageHistory": "Історії використання чи змін поки немає.",
|
||||
"historyError": "Не вдалося завантажити історію.",
|
||||
"fieldName": "Ім’я",
|
||||
"fieldSubId": "Sub ID",
|
||||
"fieldExpiry": "Термін дії",
|
||||
"fieldDataLimit": "Ліміт даних",
|
||||
"fieldEnable": "Увімкнено",
|
||||
"fieldRenewalPlan": "План оновлення",
|
||||
"fieldLimitIp": "Ліміт IP",
|
||||
"fieldLimitHwid": "Ліміт HWID",
|
||||
"fieldAdTag": "Рекламний тег",
|
||||
"fieldGroup": "Група",
|
||||
"changes": "Зміни"
|
||||
},
|
||||
"groups": {
|
||||
"name": "Назва",
|
||||
|
||||
@@ -1127,7 +1127,37 @@
|
||||
"bulkAppendLinksHint": "Thêm vào mọi máy khách đã chọn. Giữ nguyên mục và cài đặt hiện có; bỏ qua các cặp loại và giá trị trùng lặp. Áp dụng các điều chỉnh khác riêng biệt.",
|
||||
"bulkAppendLinksRequired": "Thêm ít nhất một liên kết hoặc đăng ký ngoài.",
|
||||
"externalLinkInvalid": "Nhập liên kết chia sẻ được hỗ trợ.",
|
||||
"externalSubscriptionInvalid": "Nhập URL đăng ký http(s)."
|
||||
"externalSubscriptionInvalid": "Nhập URL đăng ký http(s).",
|
||||
"usageHistory": "Lịch sử sử dụng & thay đổi",
|
||||
"lifetimeTraffic": "Tổng lưu lượng",
|
||||
"currentCycle": "Chu kỳ hiện tại",
|
||||
"pastCycles": "Các chu kỳ trước",
|
||||
"usageByNode": "Sử dụng theo node",
|
||||
"upload": "Tải lên",
|
||||
"download": "Tải xuống",
|
||||
"node": "Node",
|
||||
"time": "Thời gian",
|
||||
"field": "Trường",
|
||||
"oldValue": "Giá trị cũ",
|
||||
"newValue": "Giá trị mới",
|
||||
"source": "Nguồn",
|
||||
"reason": "Lý do",
|
||||
"reasonReset": "đã đặt lại",
|
||||
"reasonRenew": "đã gia hạn",
|
||||
"reasonEarlier": "trước đó",
|
||||
"noUsageHistory": "Chưa có lịch sử sử dụng hay thay đổi nào.",
|
||||
"historyError": "Không thể tải lịch sử sử dụng.",
|
||||
"fieldName": "Tên",
|
||||
"fieldSubId": "Sub ID",
|
||||
"fieldExpiry": "Hạn dùng",
|
||||
"fieldDataLimit": "Hạn mức dữ liệu",
|
||||
"fieldEnable": "Đã bật",
|
||||
"fieldRenewalPlan": "Kế hoạch gia hạn",
|
||||
"fieldLimitIp": "Hạn mức IP",
|
||||
"fieldLimitHwid": "Hạn mức HWID",
|
||||
"fieldAdTag": "Nhãn quảng cáo",
|
||||
"fieldGroup": "Nhóm",
|
||||
"changes": "Thay đổi"
|
||||
},
|
||||
"groups": {
|
||||
"name": "Tên",
|
||||
|
||||
@@ -1127,7 +1127,37 @@
|
||||
"bulkAppendLinksHint": "追加到所有选中的客户端。保留现有条目及其设置,跳过类型和值相同的重复条目。其他调整请单独应用。",
|
||||
"bulkAppendLinksRequired": "请至少添加一个外部链接或订阅。",
|
||||
"externalLinkInvalid": "请输入支持的分享链接。",
|
||||
"externalSubscriptionInvalid": "请输入 http(s) 订阅地址。"
|
||||
"externalSubscriptionInvalid": "请输入 http(s) 订阅地址。",
|
||||
"usageHistory": "用量与变更记录",
|
||||
"lifetimeTraffic": "累计流量",
|
||||
"currentCycle": "当前周期",
|
||||
"pastCycles": "过往周期",
|
||||
"usageByNode": "各节点用量",
|
||||
"upload": "上传",
|
||||
"download": "下载",
|
||||
"node": "节点",
|
||||
"time": "时间",
|
||||
"field": "字段",
|
||||
"oldValue": "旧值",
|
||||
"newValue": "新值",
|
||||
"source": "来源",
|
||||
"reason": "原因",
|
||||
"reasonReset": "已重置",
|
||||
"reasonRenew": "已续费",
|
||||
"reasonEarlier": "更早",
|
||||
"noUsageHistory": "暂无用量或变更记录。",
|
||||
"historyError": "无法加载使用记录。",
|
||||
"fieldName": "名称",
|
||||
"fieldSubId": "订阅 ID",
|
||||
"fieldExpiry": "到期时间",
|
||||
"fieldDataLimit": "流量上限",
|
||||
"fieldEnable": "已启用",
|
||||
"fieldRenewalPlan": "续费计划",
|
||||
"fieldLimitIp": "IP 上限",
|
||||
"fieldLimitHwid": "HWID 上限",
|
||||
"fieldAdTag": "广告标签",
|
||||
"fieldGroup": "分组",
|
||||
"changes": "变更"
|
||||
},
|
||||
"groups": {
|
||||
"name": "名称",
|
||||
|
||||
@@ -1127,7 +1127,37 @@
|
||||
"bulkAppendLinksHint": "附加至所有選取的用戶端。保留現有項目及其設定,略過類型和值相同的重複項目。其他調整請單獨套用。",
|
||||
"bulkAppendLinksRequired": "請至少新增一個外部連結或訂閱。",
|
||||
"externalLinkInvalid": "請輸入支援的分享連結。",
|
||||
"externalSubscriptionInvalid": "請輸入 http(s) 訂閱網址。"
|
||||
"externalSubscriptionInvalid": "請輸入 http(s) 訂閱網址。",
|
||||
"usageHistory": "用量與變更記錄",
|
||||
"lifetimeTraffic": "累計流量",
|
||||
"currentCycle": "當前週期",
|
||||
"pastCycles": "過往週期",
|
||||
"usageByNode": "各節點用量",
|
||||
"upload": "上傳",
|
||||
"download": "下載",
|
||||
"node": "節點",
|
||||
"time": "時間",
|
||||
"field": "欄位",
|
||||
"oldValue": "舊值",
|
||||
"newValue": "新值",
|
||||
"source": "來源",
|
||||
"reason": "原因",
|
||||
"reasonReset": "已重設",
|
||||
"reasonRenew": "已續費",
|
||||
"reasonEarlier": "更早",
|
||||
"noUsageHistory": "暫無用量或變更記錄。",
|
||||
"historyError": "無法載入使用記錄。",
|
||||
"fieldName": "名稱",
|
||||
"fieldSubId": "訂閱 ID",
|
||||
"fieldExpiry": "到期時間",
|
||||
"fieldDataLimit": "流量上限",
|
||||
"fieldEnable": "已啟用",
|
||||
"fieldRenewalPlan": "續費計畫",
|
||||
"fieldLimitIp": "IP 上限",
|
||||
"fieldLimitHwid": "HWID 上限",
|
||||
"fieldAdTag": "廣告標籤",
|
||||
"fieldGroup": "分組",
|
||||
"changes": "變更"
|
||||
},
|
||||
"groups": {
|
||||
"name": "名稱",
|
||||
|
||||
@@ -41,6 +41,8 @@ func run(root, outDir string) error {
|
||||
"InboundFallback",
|
||||
"Host",
|
||||
"SubBalancer",
|
||||
"ClientTrafficWindow",
|
||||
"ClientChangeLog",
|
||||
),
|
||||
AliasAllow: setOf("Protocol"),
|
||||
Overrides: map[string][]walkOverride{
|
||||
@@ -126,6 +128,8 @@ func run(root, outDir string) error {
|
||||
"AmneziaWGLogs",
|
||||
"PeerActivity",
|
||||
"HwidSlotStatus",
|
||||
"ClientUsageHistory",
|
||||
"ClientNodeUsage",
|
||||
),
|
||||
AliasAllow: setOf("ProcessState"),
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user