From 1ac11c77833b2f62f7aa4e30a07920a287cdd593 Mon Sep 17 00:00:00 2001 From: Hamed Sanaei Date: Tue, 1 Dec 2026 11:36:45 +0330 Subject: [PATCH] fix(groups): page client dialogs and submit server-resolved scopes Keep group client tables and bulk requests bounded with paged queries, frozen selections, and a streamed subscription export. Reuse existing bulk mutations and preserve the explicit-email contracts. --- .github/workflows/ci.yml | 10 + .../content/docs/en/reference/api/clients.mdx | 98 ++-- docs/public/openapi.json | 453 +++++++++++++++++- frontend/public/openapi.json | 453 +++++++++++++++++- frontend/src/api/groupClients.ts | 48 ++ frontend/src/generated/examples.ts | 53 +- frontend/src/generated/schemas.ts | 139 ++++++ frontend/src/generated/types.ts | 37 ++ frontend/src/generated/zod.ts | 42 ++ frontend/src/hooks/useClients.ts | 64 +-- frontend/src/pages/api-docs/endpoints.ts | 91 +++- .../pages/clients/ClientBulkAdjustModal.tsx | 2 +- frontend/src/pages/clients/SubLinksModal.tsx | 135 ++++-- .../src/pages/groups/GroupAddClientsModal.tsx | 171 ------- .../src/pages/groups/GroupClientsModal.tsx | 283 +++++++++++ .../pages/groups/GroupRemoveClientsModal.tsx | 151 ------ .../src/pages/groups/GroupsPage.stories.tsx | 245 ++++++++++ frontend/src/pages/groups/GroupsPage.tsx | 220 ++++----- frontend/src/pages/inbounds/InboundsPage.tsx | 24 +- .../clients/AddClientsToGroupModal.tsx | 68 ++- frontend/src/schemas/client.ts | 2 + internal/web/controller/client.go | 39 +- internal/web/controller/group.go | 110 ++++- .../web/controller/group_client_pages_test.go | 292 +++++++++++ .../web/controller/group_client_scope_test.go | 85 ++++ .../web/service/client_attach_selection.go | 16 +- internal/web/service/client_bulk.go | 6 +- internal/web/service/client_group_scope.go | 350 ++++++++++++++ internal/web/service/client_groups.go | 181 +++---- internal/web/service/client_paging.go | 13 +- internal/web/service/setting.go | 81 ++-- internal/web/translation/ar-EG.json | 2 + internal/web/translation/en-US.json | 2 + internal/web/translation/es-ES.json | 2 + internal/web/translation/fa-IR.json | 2 + internal/web/translation/id-ID.json | 2 + internal/web/translation/ja-JP.json | 2 + internal/web/translation/pt-BR.json | 2 + internal/web/translation/ru-RU.json | 2 + internal/web/translation/sk-SK.json | 2 + internal/web/translation/tr-TR.json | 2 + internal/web/translation/uk-UA.json | 2 + internal/web/translation/vi-VN.json | 2 + internal/web/translation/zh-CN.json | 2 + internal/web/translation/zh-TW.json | 2 + tools/openapigen/main.go | 5 + 46 files changed, 3204 insertions(+), 791 deletions(-) create mode 100644 frontend/src/api/groupClients.ts delete mode 100644 frontend/src/pages/groups/GroupAddClientsModal.tsx create mode 100644 frontend/src/pages/groups/GroupClientsModal.tsx delete mode 100644 frontend/src/pages/groups/GroupRemoveClientsModal.tsx create mode 100644 frontend/src/pages/groups/GroupsPage.stories.tsx create mode 100644 internal/web/controller/group_client_pages_test.go create mode 100644 internal/web/controller/group_client_scope_test.go create mode 100644 internal/web/service/client_group_scope.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 99def0a71..e3784f8ca 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -144,6 +144,16 @@ jobs: exit 1 fi + - name: PostgreSQL paged group client workflows + run: | + set -o pipefail + go test ./internal/web/controller -run '^Test(GroupClientPageAndFrozenWriteHTTP|GroupBulkOperationsRespectFrozenMembersHTTP|GroupBulkAddResolvesInboundMembershipHTTP|GroupSubscriptionExportAndPagingHTTP|GroupAdjustCapsReportedSkipsWithoutChangingExplicitResponses)$' -count=1 -v | tee /tmp/postgres-group-clients.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-group-clients.log || true) + if [ "$passed" -ne 5 ]; then + echo "expected 5 passing PostgreSQL group client tests, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL global-traffic heartbeat regressions run: | set -o pipefail diff --git a/docs/content/docs/en/reference/api/clients.mdx b/docs/content/docs/en/reference/api/clients.mdx index 8c344b2ce..511ab6d8a 100644 --- a/docs/content/docs/en/reference/api/clients.mdx +++ b/docs/content/docs/en/reference/api/clients.mdx @@ -183,11 +183,9 @@ _openapi: changed count and per-email skip reasons. url: '#disable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-remove-each-user-returns-the-changed-count-and-per-email-skip-reasons' - depth: 2 - title: Delete many clients in one call. The server processes the list - sequentially so each delete sees the committed state of the previous one - — avoids the race the per-email fan-out had on the panel side. Pass - keepTraffic=true to retain the xray_client_traffic rows after deletion. - url: '#delete-many-clients-in-one-call-the-server-processes-the-list-sequentially-so-each-delete-sees-the-committed-state-of-the-previous-one--avoids-the-race-the-per-email-fan-out-had-on-the-panel-side-pass-keeptraffictrue-to-retain-the-xray_client_traffic-rows-after-deletion' + title: Delete clients identified by emails or by a server-resolved group. Set + keepTraffic to retain client counters. + url: '#delete-clients-identified-by-emails-or-by-a-server-resolved-group-set-keeptraffic-to-retain-client-counters' - depth: 2 title: Create many clients in one call. Body is a JSON array of {client, inboundIds} payloads — the same shape /add accepts. Items are processed @@ -196,18 +194,13 @@ _openapi: any inbound was running. url: '#create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running' - depth: 2 - title: Add many clients to a group in one call. Updates clients.group_name and - patches the matching client entry inside every owning inbound's settings - JSON in a single transaction. If the group name does not yet exist (in - client_groups or as a derived label), it is auto-created as a persistent - group. To clear the group label, use /groups/bulkRemove instead. - url: '#add-many-clients-to-a-group-in-one-call-updates-clientsgroup_name-and-patches-the-matching-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-if-the-group-name-does-not-yet-exist-in-client_groups-or-as-a-derived-label-it-is-auto-created-as-a-persistent-group-to-clear-the-group-label-use-groupsbulkremove-instead' + title: Move clients into a group and update every owning inbound's settings in + the same transaction. + url: '#move-clients-into-a-group-and-update-every-owning-inbounds-settings-in-the-same-transaction' - depth: 2 - title: Clear the group label on many clients in one call. Inverse of - /groups/bulkAdd. Clients themselves are kept — only the group label is - cleared from clients.group_name and from each owning inbound's settings - JSON. Groups become empty if all their members are removed. - url: '#clear-the-group-label-on-many-clients-in-one-call-inverse-of-groupsbulkadd-clients-themselves-are-kept--only-the-group-label-is-cleared-from-clientsgroup_name-and-from-each-owning-inbounds-settings-json-groups-become-empty-if-all-their-members-are-removed' + title: Clear group membership and preserve the clients. Use either emails or a + selection scoped to the named group. + url: '#clear-group-membership-and-preserve-the-clients-use-either-emails-or-a-selection-scoped-to-the-named-group' - depth: 2 title: Attach many existing clients to many inbounds in one call. Each client keeps its identity (email/UUID/password/subId) and a shared traffic row; @@ -258,6 +251,14 @@ _openapi: other clients are unaffected. An empty array clears the bindings. Returns the saved host group IDs. url: '#replace-the-host-groups-attached-to-a-client-group-clients-in-this-group-receive-the-bound-host-groups-instead-of-the-inbound-default-host-pool-other-clients-are-unaffected-an-empty-array-clears-the-bindings-returns-the-saved-host-group-ids' + - depth: 2 + title: Page through group candidates, members or subscription IDs. Pages are + one-based with a fixed size of 100 and an exact total. + url: '#page-through-group-candidates-members-or-subscription-ids-pages-are-one-based-with-a-fixed-size-of-100-and-an-exact-total' + - depth: 2 + title: Stream all subscription links for a group as tab-separated text. Each row + has an email and regular link, followed by a JSON link when enabled. + url: '#stream-all-subscription-links-for-a-group-as-tab-separated-text-each-row-has-an-email-and-regular-link-followed-by-a-json-link-when-enabled' - depth: 2 title: Return just the email list of clients that currently belong to the given group. Useful for fanning a single bulk action over an entire group @@ -548,30 +549,21 @@ _openapi: (local or remote node) is updated to remove each user. Returns the changed count and per-email skip reasons. id: disable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-remove-each-user-returns-the-changed-count-and-per-email-skip-reasons - - content: Delete many clients in one call. The server processes the list - sequentially so each delete sees the committed state of the previous - one — avoids the race the per-email fan-out had on the panel side. - Pass keepTraffic=true to retain the xray_client_traffic rows after - deletion. - id: delete-many-clients-in-one-call-the-server-processes-the-list-sequentially-so-each-delete-sees-the-committed-state-of-the-previous-one--avoids-the-race-the-per-email-fan-out-had-on-the-panel-side-pass-keeptraffictrue-to-retain-the-xray_client_traffic-rows-after-deletion + - content: Delete clients identified by emails or by a server-resolved group. Set + keepTraffic to retain client counters. + id: delete-clients-identified-by-emails-or-by-a-server-resolved-group-set-keeptraffic-to-retain-client-counters - content: Create many clients in one call. Body is a JSON array of {client, inboundIds} payloads — the same shape /add accepts. Items are processed sequentially; per-email skip reasons are returned for items that fail (e.g., duplicate email). Triggers a single Xray restart at the end if any inbound was running. id: create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running - - content: Add many clients to a group in one call. Updates clients.group_name and - patches the matching client entry inside every owning inbound's - settings JSON in a single transaction. If the group name does not yet - exist (in client_groups or as a derived label), it is auto-created as - a persistent group. To clear the group label, use /groups/bulkRemove - instead. - id: add-many-clients-to-a-group-in-one-call-updates-clientsgroup_name-and-patches-the-matching-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-if-the-group-name-does-not-yet-exist-in-client_groups-or-as-a-derived-label-it-is-auto-created-as-a-persistent-group-to-clear-the-group-label-use-groupsbulkremove-instead - - content: Clear the group label on many clients in one call. Inverse of - /groups/bulkAdd. Clients themselves are kept — only the group label is - cleared from clients.group_name and from each owning inbound's - settings JSON. Groups become empty if all their members are removed. - id: clear-the-group-label-on-many-clients-in-one-call-inverse-of-groupsbulkadd-clients-themselves-are-kept--only-the-group-label-is-cleared-from-clientsgroup_name-and-from-each-owning-inbounds-settings-json-groups-become-empty-if-all-their-members-are-removed + - content: Move clients into a group and update every owning inbound's settings in + the same transaction. + id: move-clients-into-a-group-and-update-every-owning-inbounds-settings-in-the-same-transaction + - content: Clear group membership and preserve the clients. Use either emails or a + selection scoped to the named group. + id: clear-group-membership-and-preserve-the-clients-use-either-emails-or-a-selection-scoped-to-the-named-group - content: Attach many existing clients to many inbounds in one call. Each client keeps its identity (email/UUID/password/subId) and a shared traffic row; all clients are added to a target inbound in a single @@ -616,6 +608,13 @@ _openapi: host pool; other clients are unaffected. An empty array clears the bindings. Returns the saved host group IDs. id: replace-the-host-groups-attached-to-a-client-group-clients-in-this-group-receive-the-bound-host-groups-instead-of-the-inbound-default-host-pool-other-clients-are-unaffected-an-empty-array-clears-the-bindings-returns-the-saved-host-group-ids + - content: Page through group candidates, members or subscription IDs. Pages are + one-based with a fixed size of 100 and an exact total. + id: page-through-group-candidates-members-or-subscription-ids-pages-are-one-based-with-a-fixed-size-of-100-and-an-exact-total + - content: Stream all subscription links for a group as tab-separated text. Each + row has an email and regular link, followed by a JSON link when + enabled. + id: stream-all-subscription-links-for-a-group-as-tab-separated-text-each-row-has-an-email-and-regular-link-followed-by-a-json-link-when-enabled - content: Return just the email list of clients that currently belong to the given group. Useful for fanning a single bulk action over an entire group without round-tripping the full client list. @@ -909,6 +908,35 @@ _openapi: previously downloaded configuration loses access after the configuration is applied. heading: delete-an-additional-wireguard-device-and-release-its-address + - content: Send emails for explicit clients or group for server-resolved members. + Optionally send an unfiltered remove scopeToken from clientPage to + reject stale membership while excluding clients created after the + scope was frozen. Group responses include skippedCount when clients + are skipped and at most 20 representative skip records. + heading: shift-expiry-andor-traffic-quota-for-many-clients-in-one-call-adddaysaddbytes-may-be-negative-clients-with-unlimited-expiry-expirytime0-or-unlimited-traffic-totalgb0-are-skipped-for-the-corresponding-field--bulk-extend-never-converts-unlimited-to-limited-a-client-that-was-auto-disabled-solely-because-it-was-depleted-expired-or-over-quota-is-automatically-re-enabled--locally-and-on-its-node--when-the-adjustment-lifts-it-out-of-depletion-a-manually-disabled-or-still-depleted-client-is-left-disabled-the-optional-flow-directive-sets-the-xtls-flow-on-every-client-none-clears-it-xtls-rprx-visionxtls-rprx-vision-udp443-set-it-where-the-inbound-supports-it-omit-or--to-leave-it-unchanged-the-optional-limithwid-sets-maximum-registered-devices-0--unlimited-the-optional-adtag-sets-mtproto-telegram-sponsor-channel-none-clears-alternatively-send-externallinks-to-append-external-share-links-and-https-subscriptions-to-each-selected-client-in-one-transaction-this-mode-cannot-be-combined-with-other-adjustments-existing-entries-metadata-and-ordering-are-preserved-duplicates-match-kind-value-per-client-including-repeated-input-rows-the-first-entry-wins-missing-clients-are-not-written-and-appear-in-skipped-externallinksadded-counts-inserted-rows-externallinksskipped-counts-duplicate-rows-across-found-clients-externallinkserrors-counts-missing-clients-and-adjusted-counts-clients-receiving-at-least-one-new-row-validation-or-database-failure-aborts-the-whole-append-without-writes-repeating-an-append-is-idempotent-and-does-not-restart-xray + - content: For group deletion, optionally send an unfiltered remove scopeToken + from clientPage to reject stale membership before deletion. Newer + clients outside the frozen scope are excluded. Group responses include + skippedCount when clients are skipped and at most 20 representative + skip records. + heading: delete-clients-identified-by-emails-or-by-a-server-resolved-group-set-keeptraffic-to-retain-client-counters + - content: Send one of emails, inboundId, or selection with the target group. + Emails and inboundId can create the group. A picker selection targets + an existing group and excludes current members. Explicit selections + use clientIds. Frozen selections use scopeToken, the original search + and up to 1,000 excludedClientIds. A stale selection makes no changes. + heading: move-clients-into-a-group-and-update-every-owning-inbounds-settings-in-the-same-transaction + - content: Explicit selections use clientIds. Frozen selections use scopeToken, + the original search and up to 1,000 excludedClientIds. Only members of + the selected group are eligible. A stale selection makes no changes. + heading: clear-group-membership-and-preserve-the-clients-use-either-emails-or-a-selection-scoped-to-the-named-group + - content: Add mode excludes current members. Remove mode selects current members. + Links mode selects members with a subscription ID. Search matches + email, comment and group. freeze=true returns only the matching count, + a scope token and the maximum ID for an add or remove selection. For + subsequent pages, send maxId and scopeSearch to mark rows inside the + frozen filter. + heading: page-through-group-candidates-members-or-subscription-ids-pages-are-one-based-with-a-fixed-size-of-100-and-an-exact-total --- {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} @@ -918,7 +946,7 @@ export default function Layout(props) { return ( <> {props.children} - + ); } \ No newline at end of file diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 4877ccf2d..fcf4eb56b 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -2120,6 +2120,10 @@ "$ref": "#/components/schemas/BulkAdjustReport" }, "type": "array" + }, + "skippedCount": { + "example": 0, + "type": "integer" } }, "required": [ @@ -2127,6 +2131,43 @@ ], "type": "object" }, + "BulkDeleteReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkDeleteResult": { + "description": "BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email\nskip reasons when an email could not be processed.", + "properties": { + "deleted": { + "type": "integer" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkDeleteReport" + }, + "type": "array" + }, + "skippedCount": { + "example": 0, + "type": "integer" + } + }, + "required": [ + "deleted" + ], + "type": "object" + }, "BulkExternalLinksResult": { "properties": { "added": { @@ -3354,6 +3395,104 @@ ], "type": "object" }, + "GroupClientPage": { + "properties": { + "items": { + "items": { + "$ref": "#/components/schemas/GroupClientRow" + }, + "type": "array" + }, + "maxId": { + "type": "integer" + }, + "scopeToken": { + "type": "string" + }, + "total": { + "example": 120, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "items", + "total" + ], + "type": "object" + }, + "GroupClientRow": { + "properties": { + "comment": { + "example": "Example client", + "type": "string" + }, + "email": { + "example": "alice", + "type": "string" + }, + "enable": { + "example": true, + "type": "boolean" + }, + "group": { + "example": "staff", + "type": "string" + }, + "id": { + "example": 1, + "type": "integer" + }, + "inScope": { + "example": true, + "type": "boolean" + }, + "subId": { + "example": "example-sub-id", + "type": "string" + } + }, + "required": [ + "comment", + "email", + "enable", + "group", + "id", + "inScope", + "subId" + ], + "type": "object" + }, + "GroupClientSelection": { + "properties": { + "clientIds": { + "items": { + "type": "integer" + }, + "type": "array" + }, + "excludedClientIds": { + "items": { + "type": "integer" + }, + "type": "array" + }, + "mode": { + "example": "allMatching", + "type": "string" + }, + "scopeToken": { + "type": "string" + }, + "search": { + "type": "string" + } + }, + "required": [ + "mode" + ], + "type": "object" + }, "HappLinkResult": { "properties": { "encryptedLink": { @@ -11862,14 +12001,24 @@ ], "summary": "Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. A client that was auto-disabled solely because it was depleted (expired or over quota) is automatically re-enabled — locally and on its node — when the adjustment lifts it out of depletion; a manually-disabled or still-depleted client is left disabled. The optional flow directive sets the XTLS flow on every client: \"none\" clears it, \"xtls-rprx-vision\"/\"xtls-rprx-vision-udp443\" set it where the inbound supports it (omit or \"\" to leave it unchanged). The optional limitHwid sets maximum registered devices (0 = unlimited). The optional adTag sets MTProto Telegram sponsor channel (\"none\" clears). Alternatively, send externalLinks to append external share links and http(s) subscriptions to each selected client in one transaction. This mode cannot be combined with other adjustments. Existing entries, metadata, and ordering are preserved. Duplicates match (kind, value) per client, including repeated input rows; the first entry wins. Missing clients are not written and appear in skipped. externalLinks.added counts inserted rows, externalLinks.skipped counts duplicate rows across found clients, externalLinks.errors counts missing clients, and adjusted counts clients receiving at least one new row. Validation or database failure aborts the whole append without writes. Repeating an append is idempotent and does not restart Xray.", "operationId": "post_panel_api_clients_bulkAdjust", + "description": "Send emails for explicit clients or group for server-resolved members. Optionally send an unfiltered remove scopeToken from clientPage to reject stale membership while excluding clients created after the scope was frozen. Group responses include skippedCount when clients are skipped and at most 20 representative skip records.", "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", - "required": [ - "emails" + "oneOf": [ + { + "required": [ + "emails" + ] + }, + { + "required": [ + "group" + ] + } ], "properties": { "emails": { @@ -11879,6 +12028,13 @@ }, "minItems": 1 }, + "group": { + "type": "string", + "minLength": 1 + }, + "scopeToken": { + "type": "string" + }, "addDays": { "type": "integer" }, @@ -11953,7 +12109,8 @@ "obj": { "adjusted": 2, "externalLinks": null, - "skipped": [] + "skipped": [], + "skippedCount": 0 } } } @@ -12083,14 +12240,45 @@ "tags": [ "Clients" ], - "summary": "Delete many clients in one call. The server processes the list sequentially so each delete sees the committed state of the previous one — avoids the race the per-email fan-out had on the panel side. Pass keepTraffic=true to retain the xray_client_traffic rows after deletion.", + "summary": "Delete clients identified by emails or by a server-resolved group. Set keepTraffic to retain client counters.", "operationId": "post_panel_api_clients_bulkDel", + "description": "For group deletion, optionally send an unfiltered remove scopeToken from clientPage to reject stale membership before deletion. Newer clients outside the frozen scope are excluded. Group responses include skippedCount when clients are skipped and at most 20 representative skip records.", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object" + "type": "object", + "oneOf": [ + { + "required": [ + "emails" + ] + }, + { + "required": [ + "group" + ] + } + ], + "properties": { + "emails": { + "type": "array", + "items": { + "type": "string" + } + }, + "group": { + "type": "string", + "minLength": 1 + }, + "scopeToken": { + "type": "string" + }, + "keepTraffic": { + "type": "boolean" + } + } }, "example": { "emails": [ @@ -12116,19 +12304,22 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkDeleteResult" + } } }, "example": { "success": true, "obj": { - "deleted": 2, + "deleted": 0, "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } - ] + ], + "skippedCount": 0 } } } @@ -12221,21 +12412,58 @@ "tags": [ "Clients" ], - "summary": "Add many clients to a group in one call. Updates clients.group_name and patches the matching client entry inside every owning inbound's settings JSON in a single transaction. If the group name does not yet exist (in client_groups or as a derived label), it is auto-created as a persistent group. To clear the group label, use /groups/bulkRemove instead.", + "summary": "Move clients into a group and update every owning inbound's settings in the same transaction.", "operationId": "post_panel_api_clients_groups_bulkAdd", + "description": "Send one of emails, inboundId, or selection with the target group. Emails and inboundId can create the group. A picker selection targets an existing group and excludes current members. Explicit selections use clientIds. Frozen selections use scopeToken, the original search and up to 1,000 excludedClientIds. A stale selection makes no changes.", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object" + "type": "object", + "required": [ + "group" + ], + "oneOf": [ + { + "required": [ + "emails" + ] + }, + { + "required": [ + "inboundId" + ] + }, + { + "required": [ + "selection" + ] + } + ], + "properties": { + "group": { + "type": "string", + "minLength": 1 + }, + "emails": { + "type": "array", + "items": { + "type": "string" + } + }, + "inboundId": { + "type": "integer", + "minimum": 1 + }, + "selection": { + "$ref": "#/components/schemas/GroupClientSelection" + } + } }, "example": { - "emails": [ - "alice", - "bob" - ], - "group": "customer-a" + "group": "customer-a", + "inboundId": 7 } } } @@ -12274,14 +12502,43 @@ "tags": [ "Clients" ], - "summary": "Clear the group label on many clients in one call. Inverse of /groups/bulkAdd. Clients themselves are kept — only the group label is cleared from clients.group_name and from each owning inbound's settings JSON. Groups become empty if all their members are removed.", + "summary": "Clear group membership and preserve the clients. Use either emails or a selection scoped to the named group.", "operationId": "post_panel_api_clients_groups_bulkRemove", + "description": "Explicit selections use clientIds. Frozen selections use scopeToken, the original search and up to 1,000 excludedClientIds. Only members of the selected group are eligible. A stale selection makes no changes.", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object" + "type": "object", + "oneOf": [ + { + "required": [ + "emails" + ] + }, + { + "required": [ + "group", + "selection" + ] + } + ], + "properties": { + "group": { + "type": "string", + "minLength": 1 + }, + "emails": { + "type": "array", + "items": { + "type": "string" + } + }, + "selection": { + "$ref": "#/components/schemas/GroupClientSelection" + } + } }, "example": { "emails": [ @@ -12705,6 +12962,164 @@ } } }, + "/panel/api/clients/groups/clientPage": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Page through group candidates, members or subscription IDs. Pages are one-based with a fixed size of 100 and an exact total.", + "operationId": "get_panel_api_clients_groups_clientPage", + "description": "Add mode excludes current members. Remove mode selects current members. Links mode selects members with a subscription ID. Search matches email, comment and group. freeze=true returns only the matching count, a scope token and the maximum ID for an add or remove selection. For subsequent pages, send maxId and scopeSearch to mark rows inside the frozen filter.", + "parameters": [ + { + "name": "group", + "in": "query", + "required": true, + "description": "Group name.", + "schema": { + "type": "string" + } + }, + { + "name": "mode", + "in": "query", + "required": true, + "description": "", + "schema": { + "type": "string", + "enum": [ + "add", + "remove", + "links" + ] + } + }, + { + "name": "page", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "integer", + "default": 1 + } + }, + { + "name": "search", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "string" + } + }, + { + "name": "freeze", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "boolean" + } + }, + { + "name": "scopeSearch", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "string" + } + }, + { + "name": "maxId", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/GroupClientPage" + } + } + }, + "example": { + "success": true, + "obj": { + "items": [ + { + "comment": "Example client", + "email": "alice", + "enable": true, + "group": "staff", + "id": 1, + "inScope": true, + "subId": "example-sub-id" + } + ], + "maxId": 0, + "scopeToken": "", + "total": 120 + } + } + } + } + } + } + } + }, + "/panel/api/clients/groups/subLinks/export": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Stream all subscription links for a group as tab-separated text. Each row has an email and regular link, followed by a JSON link when enabled.", + "operationId": "get_panel_api_clients_groups_subLinks_export", + "parameters": [ + { + "name": "group", + "in": "query", + "required": true, + "description": "Group name.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Complete subscription link export.", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Missing group or subscriptions disabled." + } + } + } + }, "/panel/api/clients/groups/{name}/emails": { "get": { "tags": [ diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 4877ccf2d..fcf4eb56b 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -2120,6 +2120,10 @@ "$ref": "#/components/schemas/BulkAdjustReport" }, "type": "array" + }, + "skippedCount": { + "example": 0, + "type": "integer" } }, "required": [ @@ -2127,6 +2131,43 @@ ], "type": "object" }, + "BulkDeleteReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkDeleteResult": { + "description": "BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email\nskip reasons when an email could not be processed.", + "properties": { + "deleted": { + "type": "integer" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkDeleteReport" + }, + "type": "array" + }, + "skippedCount": { + "example": 0, + "type": "integer" + } + }, + "required": [ + "deleted" + ], + "type": "object" + }, "BulkExternalLinksResult": { "properties": { "added": { @@ -3354,6 +3395,104 @@ ], "type": "object" }, + "GroupClientPage": { + "properties": { + "items": { + "items": { + "$ref": "#/components/schemas/GroupClientRow" + }, + "type": "array" + }, + "maxId": { + "type": "integer" + }, + "scopeToken": { + "type": "string" + }, + "total": { + "example": 120, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "items", + "total" + ], + "type": "object" + }, + "GroupClientRow": { + "properties": { + "comment": { + "example": "Example client", + "type": "string" + }, + "email": { + "example": "alice", + "type": "string" + }, + "enable": { + "example": true, + "type": "boolean" + }, + "group": { + "example": "staff", + "type": "string" + }, + "id": { + "example": 1, + "type": "integer" + }, + "inScope": { + "example": true, + "type": "boolean" + }, + "subId": { + "example": "example-sub-id", + "type": "string" + } + }, + "required": [ + "comment", + "email", + "enable", + "group", + "id", + "inScope", + "subId" + ], + "type": "object" + }, + "GroupClientSelection": { + "properties": { + "clientIds": { + "items": { + "type": "integer" + }, + "type": "array" + }, + "excludedClientIds": { + "items": { + "type": "integer" + }, + "type": "array" + }, + "mode": { + "example": "allMatching", + "type": "string" + }, + "scopeToken": { + "type": "string" + }, + "search": { + "type": "string" + } + }, + "required": [ + "mode" + ], + "type": "object" + }, "HappLinkResult": { "properties": { "encryptedLink": { @@ -11862,14 +12001,24 @@ ], "summary": "Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. A client that was auto-disabled solely because it was depleted (expired or over quota) is automatically re-enabled — locally and on its node — when the adjustment lifts it out of depletion; a manually-disabled or still-depleted client is left disabled. The optional flow directive sets the XTLS flow on every client: \"none\" clears it, \"xtls-rprx-vision\"/\"xtls-rprx-vision-udp443\" set it where the inbound supports it (omit or \"\" to leave it unchanged). The optional limitHwid sets maximum registered devices (0 = unlimited). The optional adTag sets MTProto Telegram sponsor channel (\"none\" clears). Alternatively, send externalLinks to append external share links and http(s) subscriptions to each selected client in one transaction. This mode cannot be combined with other adjustments. Existing entries, metadata, and ordering are preserved. Duplicates match (kind, value) per client, including repeated input rows; the first entry wins. Missing clients are not written and appear in skipped. externalLinks.added counts inserted rows, externalLinks.skipped counts duplicate rows across found clients, externalLinks.errors counts missing clients, and adjusted counts clients receiving at least one new row. Validation or database failure aborts the whole append without writes. Repeating an append is idempotent and does not restart Xray.", "operationId": "post_panel_api_clients_bulkAdjust", + "description": "Send emails for explicit clients or group for server-resolved members. Optionally send an unfiltered remove scopeToken from clientPage to reject stale membership while excluding clients created after the scope was frozen. Group responses include skippedCount when clients are skipped and at most 20 representative skip records.", "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", - "required": [ - "emails" + "oneOf": [ + { + "required": [ + "emails" + ] + }, + { + "required": [ + "group" + ] + } ], "properties": { "emails": { @@ -11879,6 +12028,13 @@ }, "minItems": 1 }, + "group": { + "type": "string", + "minLength": 1 + }, + "scopeToken": { + "type": "string" + }, "addDays": { "type": "integer" }, @@ -11953,7 +12109,8 @@ "obj": { "adjusted": 2, "externalLinks": null, - "skipped": [] + "skipped": [], + "skippedCount": 0 } } } @@ -12083,14 +12240,45 @@ "tags": [ "Clients" ], - "summary": "Delete many clients in one call. The server processes the list sequentially so each delete sees the committed state of the previous one — avoids the race the per-email fan-out had on the panel side. Pass keepTraffic=true to retain the xray_client_traffic rows after deletion.", + "summary": "Delete clients identified by emails or by a server-resolved group. Set keepTraffic to retain client counters.", "operationId": "post_panel_api_clients_bulkDel", + "description": "For group deletion, optionally send an unfiltered remove scopeToken from clientPage to reject stale membership before deletion. Newer clients outside the frozen scope are excluded. Group responses include skippedCount when clients are skipped and at most 20 representative skip records.", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object" + "type": "object", + "oneOf": [ + { + "required": [ + "emails" + ] + }, + { + "required": [ + "group" + ] + } + ], + "properties": { + "emails": { + "type": "array", + "items": { + "type": "string" + } + }, + "group": { + "type": "string", + "minLength": 1 + }, + "scopeToken": { + "type": "string" + }, + "keepTraffic": { + "type": "boolean" + } + } }, "example": { "emails": [ @@ -12116,19 +12304,22 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkDeleteResult" + } } }, "example": { "success": true, "obj": { - "deleted": 2, + "deleted": 0, "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } - ] + ], + "skippedCount": 0 } } } @@ -12221,21 +12412,58 @@ "tags": [ "Clients" ], - "summary": "Add many clients to a group in one call. Updates clients.group_name and patches the matching client entry inside every owning inbound's settings JSON in a single transaction. If the group name does not yet exist (in client_groups or as a derived label), it is auto-created as a persistent group. To clear the group label, use /groups/bulkRemove instead.", + "summary": "Move clients into a group and update every owning inbound's settings in the same transaction.", "operationId": "post_panel_api_clients_groups_bulkAdd", + "description": "Send one of emails, inboundId, or selection with the target group. Emails and inboundId can create the group. A picker selection targets an existing group and excludes current members. Explicit selections use clientIds. Frozen selections use scopeToken, the original search and up to 1,000 excludedClientIds. A stale selection makes no changes.", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object" + "type": "object", + "required": [ + "group" + ], + "oneOf": [ + { + "required": [ + "emails" + ] + }, + { + "required": [ + "inboundId" + ] + }, + { + "required": [ + "selection" + ] + } + ], + "properties": { + "group": { + "type": "string", + "minLength": 1 + }, + "emails": { + "type": "array", + "items": { + "type": "string" + } + }, + "inboundId": { + "type": "integer", + "minimum": 1 + }, + "selection": { + "$ref": "#/components/schemas/GroupClientSelection" + } + } }, "example": { - "emails": [ - "alice", - "bob" - ], - "group": "customer-a" + "group": "customer-a", + "inboundId": 7 } } } @@ -12274,14 +12502,43 @@ "tags": [ "Clients" ], - "summary": "Clear the group label on many clients in one call. Inverse of /groups/bulkAdd. Clients themselves are kept — only the group label is cleared from clients.group_name and from each owning inbound's settings JSON. Groups become empty if all their members are removed.", + "summary": "Clear group membership and preserve the clients. Use either emails or a selection scoped to the named group.", "operationId": "post_panel_api_clients_groups_bulkRemove", + "description": "Explicit selections use clientIds. Frozen selections use scopeToken, the original search and up to 1,000 excludedClientIds. Only members of the selected group are eligible. A stale selection makes no changes.", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object" + "type": "object", + "oneOf": [ + { + "required": [ + "emails" + ] + }, + { + "required": [ + "group", + "selection" + ] + } + ], + "properties": { + "group": { + "type": "string", + "minLength": 1 + }, + "emails": { + "type": "array", + "items": { + "type": "string" + } + }, + "selection": { + "$ref": "#/components/schemas/GroupClientSelection" + } + } }, "example": { "emails": [ @@ -12705,6 +12962,164 @@ } } }, + "/panel/api/clients/groups/clientPage": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Page through group candidates, members or subscription IDs. Pages are one-based with a fixed size of 100 and an exact total.", + "operationId": "get_panel_api_clients_groups_clientPage", + "description": "Add mode excludes current members. Remove mode selects current members. Links mode selects members with a subscription ID. Search matches email, comment and group. freeze=true returns only the matching count, a scope token and the maximum ID for an add or remove selection. For subsequent pages, send maxId and scopeSearch to mark rows inside the frozen filter.", + "parameters": [ + { + "name": "group", + "in": "query", + "required": true, + "description": "Group name.", + "schema": { + "type": "string" + } + }, + { + "name": "mode", + "in": "query", + "required": true, + "description": "", + "schema": { + "type": "string", + "enum": [ + "add", + "remove", + "links" + ] + } + }, + { + "name": "page", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "integer", + "default": 1 + } + }, + { + "name": "search", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "string" + } + }, + { + "name": "freeze", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "boolean" + } + }, + { + "name": "scopeSearch", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "string" + } + }, + { + "name": "maxId", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/GroupClientPage" + } + } + }, + "example": { + "success": true, + "obj": { + "items": [ + { + "comment": "Example client", + "email": "alice", + "enable": true, + "group": "staff", + "id": 1, + "inScope": true, + "subId": "example-sub-id" + } + ], + "maxId": 0, + "scopeToken": "", + "total": 120 + } + } + } + } + } + } + } + }, + "/panel/api/clients/groups/subLinks/export": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Stream all subscription links for a group as tab-separated text. Each row has an email and regular link, followed by a JSON link when enabled.", + "operationId": "get_panel_api_clients_groups_subLinks_export", + "parameters": [ + { + "name": "group", + "in": "query", + "required": true, + "description": "Group name.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Complete subscription link export.", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Missing group or subscriptions disabled." + } + } + } + }, "/panel/api/clients/groups/{name}/emails": { "get": { "tags": [ diff --git a/frontend/src/api/groupClients.ts b/frontend/src/api/groupClients.ts new file mode 100644 index 000000000..487c5a213 --- /dev/null +++ b/frontend/src/api/groupClients.ts @@ -0,0 +1,48 @@ +import { useQuery } from '@tanstack/react-query'; + +import { withBasePath } from '@/api/http-init'; +import { keys } from '@/api/queryKeys'; +import { GroupClientPageSchema, type GroupClientSelection } from '@/generated/zod'; +import { HttpUtil } from '@/utils'; +import { parseMsg } from '@/utils/zodValidate'; + +const PAGE_ENDPOINT = '/panel/api/clients/groups/clientPage'; +export const GROUP_CLIENT_PAGE_SIZE = 100; +export const MAX_GROUP_EXCLUSIONS = 1000; + +export type { GroupClientSelection }; +export type GroupClientMode = 'add' | 'remove' | 'links'; +export type GroupBulkScope = { group: string; scopeToken?: string }; + +type PageParams = { + group: string; + mode: GroupClientMode; + page?: number; + search?: string; + freeze?: boolean; + scopeSearch?: string; + maxId?: number; +}; + +export async function fetchGroupClients(params: PageParams, signal?: AbortSignal) { + const response = await HttpUtil.get(PAGE_ENDPOINT, params, { signal, silent: true }); + const result = parseMsg(response, GroupClientPageSchema, 'clients/groups/clientPage'); + if (!result.success || !result.obj) throw new Error(result.msg); + return result.obj; +} + +export function useGroupClientPage(params: PageParams, enabled: boolean) { + return useQuery({ + queryKey: [...keys.clients.root(), 'groupClientPage', params], + queryFn: ({ signal }) => fetchGroupClients(params, signal), + enabled, + gcTime: 0, + retry: false, + }); +} + +export function groupSubscriptionExportPath(group: string) { + return withBasePath( + '/panel/api/clients/groups/subLinks/export?' + new URLSearchParams({ group }).toString(), + ); +} diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index 081067ac9..a642d9214 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -509,7 +509,22 @@ export const EXAMPLES: Record = { "BulkAdjustResult": { "adjusted": 2, "externalLinks": null, - "skipped": [] + "skipped": [], + "skippedCount": 0 + }, + "BulkDeleteReport": { + "email": "", + "reason": "" + }, + "BulkDeleteResult": { + "deleted": 0, + "skipped": [ + { + "email": "", + "reason": "" + } + ], + "skippedCount": 0 }, "BulkExternalLinksResult": { "added": 4, @@ -877,6 +892,42 @@ export const EXAMPLES: Record = { "reason": "categoryMissing", "token": "geosite:blabla" }, + "GroupClientPage": { + "items": [ + { + "comment": "Example client", + "email": "alice", + "enable": true, + "group": "staff", + "id": 1, + "inScope": true, + "subId": "example-sub-id" + } + ], + "maxId": 0, + "scopeToken": "", + "total": 120 + }, + "GroupClientRow": { + "comment": "Example client", + "email": "alice", + "enable": true, + "group": "staff", + "id": 1, + "inScope": true, + "subId": "example-sub-id" + }, + "GroupClientSelection": { + "clientIds": [ + 0 + ], + "excludedClientIds": [ + 0 + ], + "mode": "allMatching", + "scopeToken": "", + "search": "" + }, "HappLinkResult": { "encryptedLink": "happ://crypt5/example" }, diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index e5b7085f6..8805f7860 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -2094,6 +2094,10 @@ export const SCHEMAS: Record = { "$ref": "#/components/schemas/BulkAdjustReport" }, "type": "array" + }, + "skippedCount": { + "example": 0, + "type": "integer" } }, "required": [ @@ -2101,6 +2105,43 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "BulkDeleteReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkDeleteResult": { + "description": "BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email\nskip reasons when an email could not be processed.", + "properties": { + "deleted": { + "type": "integer" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkDeleteReport" + }, + "type": "array" + }, + "skippedCount": { + "example": 0, + "type": "integer" + } + }, + "required": [ + "deleted" + ], + "type": "object" + }, "BulkExternalLinksResult": { "properties": { "added": { @@ -3328,6 +3369,104 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "GroupClientPage": { + "properties": { + "items": { + "items": { + "$ref": "#/components/schemas/GroupClientRow" + }, + "type": "array" + }, + "maxId": { + "type": "integer" + }, + "scopeToken": { + "type": "string" + }, + "total": { + "example": 120, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "items", + "total" + ], + "type": "object" + }, + "GroupClientRow": { + "properties": { + "comment": { + "example": "Example client", + "type": "string" + }, + "email": { + "example": "alice", + "type": "string" + }, + "enable": { + "example": true, + "type": "boolean" + }, + "group": { + "example": "staff", + "type": "string" + }, + "id": { + "example": 1, + "type": "integer" + }, + "inScope": { + "example": true, + "type": "boolean" + }, + "subId": { + "example": "example-sub-id", + "type": "string" + } + }, + "required": [ + "comment", + "email", + "enable", + "group", + "id", + "inScope", + "subId" + ], + "type": "object" + }, + "GroupClientSelection": { + "properties": { + "clientIds": { + "items": { + "type": "integer" + }, + "type": "array" + }, + "excludedClientIds": { + "items": { + "type": "integer" + }, + "type": "array" + }, + "mode": { + "example": "allMatching", + "type": "string" + }, + "scopeToken": { + "type": "string" + }, + "search": { + "type": "string" + } + }, + "required": [ + "mode" + ], + "type": "object" + }, "HappLinkResult": { "properties": { "encryptedLink": { diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 5bf30b7ce..8beae16de 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -500,6 +500,18 @@ export interface BulkAdjustResult { adjusted: number; externalLinks?: BulkExternalLinksResult | null; skipped?: BulkAdjustReport[]; + skippedCount?: number; +} + +export interface BulkDeleteReport { + email: string; + reason: string; +} + +export interface BulkDeleteResult { + deleted: number; + skipped?: BulkDeleteReport[]; + skippedCount?: number; } export interface BulkExternalLinksResult { @@ -768,6 +780,31 @@ export interface GeodataTokenIssue { token: string; } +export interface GroupClientPage { + items: GroupClientRow[]; + maxId?: number; + scopeToken?: string; + total: number; +} + +export interface GroupClientRow { + comment: string; + email: string; + enable: boolean; + group: string; + id: number; + inScope: boolean; + subId: string; +} + +export interface GroupClientSelection { + clientIds?: number[]; + excludedClientIds?: number[]; + mode: string; + scopeToken?: string; + search?: string; +} + export interface HappLinkResult { encryptedLink: string; } diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index 91489537e..c4c02385d 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -523,9 +523,23 @@ export const BulkAdjustResultSchema = z.object({ adjusted: z.number().int(), externalLinks: z.lazy(() => BulkExternalLinksResultSchema).nullable().optional(), skipped: z.array(z.lazy(() => BulkAdjustReportSchema)).optional(), + skippedCount: z.number().int().optional(), }); export type BulkAdjustResult = z.infer; +export const BulkDeleteReportSchema = z.object({ + email: z.string(), + reason: z.string(), +}); +export type BulkDeleteReport = z.infer; + +export const BulkDeleteResultSchema = z.object({ + deleted: z.number().int(), + skipped: z.array(z.lazy(() => BulkDeleteReportSchema)).optional(), + skippedCount: z.number().int().optional(), +}); +export type BulkDeleteResult = z.infer; + export const BulkExternalLinksResultSchema = z.object({ added: z.number().int(), errors: z.number().int(), @@ -815,6 +829,34 @@ export const GeodataTokenIssueSchema = z.object({ }); export type GeodataTokenIssue = z.infer; +export const GroupClientPageSchema = z.object({ + items: z.array(z.lazy(() => GroupClientRowSchema)), + maxId: z.number().int().optional(), + scopeToken: z.string().optional(), + total: z.number().int(), +}); +export type GroupClientPage = z.infer; + +export const GroupClientRowSchema = z.object({ + comment: z.string(), + email: z.string(), + enable: z.boolean(), + group: z.string(), + id: z.number().int(), + inScope: z.boolean(), + subId: z.string(), +}); +export type GroupClientRow = z.infer; + +export const GroupClientSelectionSchema = z.object({ + clientIds: z.array(z.number().int()).optional(), + excludedClientIds: z.array(z.number().int()).optional(), + mode: z.string(), + scopeToken: z.string().optional(), + search: z.string().optional(), +}); +export type GroupClientSelection = z.infer; + export const HappLinkResultSchema = z.object({ encryptedLink: z.string(), }); diff --git a/frontend/src/hooks/useClients.ts b/frontend/src/hooks/useClients.ts index 364035edb..cabd40a1a 100644 --- a/frontend/src/hooks/useClients.ts +++ b/frontend/src/hooks/useClients.ts @@ -3,6 +3,7 @@ import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tansta import { HttpUtil, Msg } from '@/utils'; import { parseMsg } from '@/utils/zodValidate'; +import type { GroupBulkScope, GroupClientSelection } from '@/api/groupClients'; import { keys } from '@/api/queryKeys'; import { clientManagementPath } from '@/api/client-management'; import { markLocalInvalidate } from '@/api/invalidationTracker'; @@ -357,15 +358,16 @@ export function useClients(options: UseClientsOptions = {}) { }); const bulkAddToGroupMut = useMutation({ - mutationFn: (body: { emails: string[]; group: string }) => - HttpUtil.post('/panel/api/clients/groups/bulkAdd', body, JSON_HEADERS), + mutationFn: ( + body: ({ emails: string[] } | { selection: GroupClientSelection }) & { group: string }, + ) => HttpUtil.post('/panel/api/clients/groups/bulkAdd', body, JSON_HEADERS), onSuccess: (msg) => { if (msg?.success) invalidateAll(); }, }); const bulkRemoveFromGroupMut = useMutation({ - mutationFn: (body: { emails: string[] }) => + mutationFn: (body: { emails: string[] } | { group: string; selection: GroupClientSelection }) => HttpUtil.post('/panel/api/clients/groups/bulkRemove', body, JSON_HEADERS), onSuccess: (msg) => { if (msg?.success) invalidateAll(); @@ -392,10 +394,9 @@ export function useClients(options: UseClientsOptions = {}) { }); const bulkDeleteMut = useMutation({ - mutationFn: async (payload: { - emails: string[]; - keepTraffic?: boolean; - }): Promise> => { + mutationFn: async ( + payload: ({ emails: string[] } | GroupBulkScope) & { keepTraffic?: boolean }, + ): Promise> => { const raw = await HttpUtil.post('/panel/api/clients/bulkDel', payload, JSON_HEADERS); return parseMsg(raw, BulkDeleteResultSchema, 'clients/bulkDel'); }, @@ -415,15 +416,16 @@ export function useClients(options: UseClientsOptions = {}) { }); const bulkAdjustMut = useMutation({ - mutationFn: async (payload: { - emails: string[]; - addDays: number; - addBytes: number; - flow?: string; - limitHwid?: number | null; - adTag?: string; - externalLinks?: ExternalLinkInput[]; - }): Promise> => { + mutationFn: async ( + payload: ({ emails: string[] } | GroupBulkScope) & { + addDays: number; + addBytes: number; + flow?: string; + limitHwid?: number | null; + adTag?: string; + externalLinks?: ExternalLinkInput[]; + }, + ): Promise> => { if (payload.externalLinks !== undefined) await ExternalLinksAppendSchema.parseAsync(payload); const raw = await HttpUtil.post('/panel/api/clients/bulkAdjust', payload, JSON_HEADERS); return parseMsg(raw, BulkAdjustResultSchema, 'clients/bulkAdjust'); @@ -576,10 +578,13 @@ export function useClients(options: UseClientsOptions = {}) { [removeMut], ); const bulkDelete = useCallback( - (emails: string[], keepTraffic = false) => { - if (!Array.isArray(emails) || emails.length === 0) + (scope: string[] | GroupBulkScope, keepTraffic = false) => { + if (Array.isArray(scope) && scope.length === 0) return Promise.resolve(null as unknown as Msg); - return bulkDeleteMut.mutateAsync({ emails, keepTraffic }); + return bulkDeleteMut.mutateAsync({ + ...(Array.isArray(scope) ? { emails: scope } : scope), + keepTraffic, + }); }, [bulkDeleteMut], ); @@ -593,7 +598,7 @@ export function useClients(options: UseClientsOptions = {}) { ); const bulkAdjust = useCallback( ( - emails: string[], + scope: string[] | GroupBulkScope, addDays: number, addBytes: number, flow = '', @@ -601,9 +606,9 @@ export function useClients(options: UseClientsOptions = {}) { adTag?: string, externalLinks?: ExternalLinkInput[], ) => { - if (!Array.isArray(emails) || emails.length === 0) return Promise.resolve(null); + if (Array.isArray(scope) && scope.length === 0) return Promise.resolve(null); return bulkAdjustMut.mutateAsync({ - emails, + ...(Array.isArray(scope) ? { emails: scope } : scope), addDays, addBytes, flow, @@ -631,16 +636,19 @@ export function useClients(options: UseClientsOptions = {}) { [bulkSetEnableMut], ); const bulkAddToGroup = useCallback( - (emails: string[], group: string) => { - if (!Array.isArray(emails) || emails.length === 0) return Promise.resolve(null); - return bulkAddToGroupMut.mutateAsync({ emails, group }); + (scope: string[] | GroupClientSelection, group: string) => { + if (Array.isArray(scope) && scope.length === 0) return Promise.resolve(null); + return bulkAddToGroupMut.mutateAsync({ + ...(Array.isArray(scope) ? { emails: scope } : { selection: scope }), + group, + }); }, [bulkAddToGroupMut], ); const bulkRemoveFromGroup = useCallback( - (emails: string[]) => { - if (!Array.isArray(emails) || emails.length === 0) return Promise.resolve(null); - return bulkRemoveFromGroupMut.mutateAsync({ emails }); + (scope: string[] | { group: string; selection: GroupClientSelection }) => { + if (Array.isArray(scope) && scope.length === 0) return Promise.resolve(null); + return bulkRemoveFromGroupMut.mutateAsync(Array.isArray(scope) ? { emails: scope } : scope); }, [bulkRemoveFromGroupMut], ); diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index 8eb435b29..a7ae3ee71 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -1633,11 +1633,15 @@ export const sections: readonly Section[] = [ path: '/panel/api/clients/bulkAdjust', summary: 'Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. A client that was auto-disabled solely because it was depleted (expired or over quota) is automatically re-enabled — locally and on its node — when the adjustment lifts it out of depletion; a manually-disabled or still-depleted client is left disabled. The optional flow directive sets the XTLS flow on every client: "none" clears it, "xtls-rprx-vision"/"xtls-rprx-vision-udp443" set it where the inbound supports it (omit or "" to leave it unchanged). The optional limitHwid sets maximum registered devices (0 = unlimited). The optional adTag sets MTProto Telegram sponsor channel ("none" clears). Alternatively, send externalLinks to append external share links and http(s) subscriptions to each selected client in one transaction. This mode cannot be combined with other adjustments. Existing entries, metadata, and ordering are preserved. Duplicates match (kind, value) per client, including repeated input rows; the first entry wins. Missing clients are not written and appear in skipped. externalLinks.added counts inserted rows, externalLinks.skipped counts duplicate rows across found clients, externalLinks.errors counts missing clients, and adjusted counts clients receiving at least one new row. Validation or database failure aborts the whole append without writes. Repeating an append is idempotent and does not restart Xray.', + description: + 'Send emails for explicit clients or group for server-resolved members. Optionally send an unfiltered remove scopeToken from clientPage to reject stale membership while excluding clients created after the scope was frozen. Group responses include skippedCount when clients are skipped and at most 20 representative skip records.', requestSchema: { type: 'object', - required: ['emails'], + oneOf: [{ required: ['emails'] }, { required: ['group'] }], properties: { emails: { type: 'array', items: { type: 'string' }, minItems: 1 }, + group: { type: 'string', minLength: 1 }, + scopeToken: { type: 'string' }, addDays: { type: 'integer' }, addBytes: { type: 'integer' }, flow: { type: 'string' }, @@ -1697,10 +1701,21 @@ export const sections: readonly Section[] = [ method: 'POST', path: '/panel/api/clients/bulkDel', summary: - 'Delete many clients in one call. The server processes the list sequentially so each delete sees the committed state of the previous one — avoids the race the per-email fan-out had on the panel side. Pass keepTraffic=true to retain the xray_client_traffic rows after deletion.', - body: '{\n "emails": ["alice", "bob"],\n "keepTraffic": false\n}', - response: - '{\n "success": true,\n "obj": {\n "deleted": 2,\n "skipped": [\n { "email": "carol", "reason": "client not found" }\n ]\n }\n}', + 'Delete clients identified by emails or by a server-resolved group. Set keepTraffic to retain client counters.', + description: + 'For group deletion, optionally send an unfiltered remove scopeToken from clientPage to reject stale membership before deletion. Newer clients outside the frozen scope are excluded. Group responses include skippedCount when clients are skipped and at most 20 representative skip records.', + requestSchema: { + type: 'object', + oneOf: [{ required: ['emails'] }, { required: ['group'] }], + properties: { + emails: { type: 'array', items: { type: 'string' } }, + group: { type: 'string', minLength: 1 }, + scopeToken: { type: 'string' }, + keepTraffic: { type: 'boolean' }, + }, + }, + body: JSON.stringify({ emails: ['alice', 'bob'], keepTraffic: false }, null, 2), + responseSchema: 'BulkDeleteResult', }, { method: 'POST', @@ -1715,15 +1730,43 @@ export const sections: readonly Section[] = [ method: 'POST', path: '/panel/api/clients/groups/bulkAdd', summary: - "Add many clients to a group in one call. Updates clients.group_name and patches the matching client entry inside every owning inbound's settings JSON in a single transaction. If the group name does not yet exist (in client_groups or as a derived label), it is auto-created as a persistent group. To clear the group label, use /groups/bulkRemove instead.", - body: '{\n "emails": ["alice", "bob"],\n "group": "customer-a"\n}', + "Move clients into a group and update every owning inbound's settings in the same transaction.", + description: + 'Send one of emails, inboundId, or selection with the target group. Emails and inboundId can create the group. A picker selection targets an existing group and excludes current members. Explicit selections use clientIds. Frozen selections use scopeToken, the original search and up to 1,000 excludedClientIds. A stale selection makes no changes.', + requestSchema: { + type: 'object', + required: ['group'], + oneOf: [ + { required: ['emails'] }, + { required: ['inboundId'] }, + { required: ['selection'] }, + ], + properties: { + group: { type: 'string', minLength: 1 }, + emails: { type: 'array', items: { type: 'string' } }, + inboundId: { type: 'integer', minimum: 1 }, + selection: { $ref: '#/components/schemas/GroupClientSelection' }, + }, + }, + body: JSON.stringify({ group: 'customer-a', inboundId: 7 }, null, 2), response: '{\n "success": true,\n "obj": {\n "affected": 2\n }\n}', }, { method: 'POST', path: '/panel/api/clients/groups/bulkRemove', summary: - "Clear the group label on many clients in one call. Inverse of /groups/bulkAdd. Clients themselves are kept — only the group label is cleared from clients.group_name and from each owning inbound's settings JSON. Groups become empty if all their members are removed.", + 'Clear group membership and preserve the clients. Use either emails or a selection scoped to the named group.', + description: + 'Explicit selections use clientIds. Frozen selections use scopeToken, the original search and up to 1,000 excludedClientIds. Only members of the selected group are eligible. A stale selection makes no changes.', + requestSchema: { + type: 'object', + oneOf: [{ required: ['emails'] }, { required: ['group', 'selection'] }], + properties: { + group: { type: 'string', minLength: 1 }, + emails: { type: 'array', items: { type: 'string' } }, + selection: { $ref: '#/components/schemas/GroupClientSelection' }, + }, + }, body: '{\n "emails": ["alice", "bob"]\n}', response: '{\n "success": true,\n "obj": {\n "affected": 2\n }\n}', }, @@ -1821,6 +1864,38 @@ export const sections: readonly Section[] = [ body: '{\n "hostGroupIds": ["cdn-front"]\n}', response: '{\n "success": true,\n "obj": {\n "hostGroupIds": ["cdn-front"]\n }\n}', }, + { + method: 'GET', + path: '/panel/api/clients/groups/clientPage', + summary: + 'Page through group candidates, members or subscription IDs. Pages are one-based with a fixed size of 100 and an exact total.', + description: + 'Add mode excludes current members. Remove mode selects current members. Links mode selects members with a subscription ID. Search matches email, comment and group. freeze=true returns only the matching count, a scope token and the maximum ID for an add or remove selection. For subsequent pages, send maxId and scopeSearch to mark rows inside the frozen filter.', + params: [ + { name: 'group', in: 'query', type: 'string', desc: 'Group name.' }, + { name: 'mode', in: 'query', type: 'string', enum: ['add', 'remove', 'links'] }, + { name: 'page', in: 'query', type: 'integer', optional: true, defaultValue: 1 }, + { name: 'search', in: 'query', type: 'string', optional: true }, + { name: 'freeze', in: 'query', type: 'boolean', optional: true }, + { name: 'scopeSearch', in: 'query', type: 'string', optional: true }, + { name: 'maxId', in: 'query', type: 'integer', optional: true }, + ], + responseSchema: 'GroupClientPage', + }, + { + method: 'GET', + path: '/panel/api/clients/groups/subLinks/export', + summary: + 'Stream all subscription links for a group as tab-separated text. Each row has an email and regular link, followed by a JSON link when enabled.', + params: [{ name: 'group', in: 'query', type: 'string', desc: 'Group name.' }], + responses: { + '200': { + description: 'Complete subscription link export.', + content: { 'text/plain': { schema: { type: 'string' } } }, + }, + '400': { description: 'Missing group or subscriptions disabled.' }, + }, + }, { method: 'GET', path: '/panel/api/clients/groups/:name/emails', diff --git a/frontend/src/pages/clients/ClientBulkAdjustModal.tsx b/frontend/src/pages/clients/ClientBulkAdjustModal.tsx index 43028383d..5850b104e 100644 --- a/frontend/src/pages/clients/ClientBulkAdjustModal.tsx +++ b/frontend/src/pages/clients/ClientBulkAdjustModal.tsx @@ -101,7 +101,7 @@ export default function ClientBulkAdjustModal({ const result = await onSubmit(days, bytes, flowValue, limitHwid, adTag, externalLinks); if (!result) return; const ok = result.adjusted ?? 0; - const skipped = result.skipped?.length ?? 0; + const skipped = result.skippedCount ?? result.skipped?.length ?? 0; if (result.externalLinks) { const summary = t('pages.clients.toasts.bulkLinksAppended', { clients: ok, diff --git a/frontend/src/pages/clients/SubLinksModal.tsx b/frontend/src/pages/clients/SubLinksModal.tsx index 83b8064db..249cb7870 100644 --- a/frontend/src/pages/clients/SubLinksModal.tsx +++ b/frontend/src/pages/clients/SubLinksModal.tsx @@ -1,9 +1,15 @@ -import { useMemo } from 'react'; +import { useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Alert, Button, Modal, Table, Tooltip, Typography, message } from 'antd'; import type { TableColumnType } from 'antd'; import { CopyOutlined, DownloadOutlined } from '@ant-design/icons'; +import { + GROUP_CLIENT_PAGE_SIZE, + groupSubscriptionExportPath, + useGroupClientPage, +} from '@/api/groupClients'; + import type { ClientRecord } from '@/hooks/useClients'; interface SubSettings { @@ -13,13 +19,14 @@ interface SubSettings { subJsonEnable: boolean; } -interface SubLinksModalProps { +type SubLinksModalProps = { open: boolean; - emails: string[]; - clients: ClientRecord[]; subSettings?: SubSettings; onOpenChange: (open: boolean) => void; -} +} & ( + | { emails: string[]; clients: ClientRecord[]; group?: never } + | { group: string; emails?: never; clients?: never } +); interface Row { key: string; @@ -33,6 +40,7 @@ export default function SubLinksModal({ open, emails, clients, + group, subSettings, onOpenChange, }: SubLinksModalProps) { @@ -42,33 +50,73 @@ export default function SubLinksModal({ const enabled = !!subSettings?.enable && !!subSettings?.subURI; const jsonEnabled = !!subSettings?.subJsonEnable && !!subSettings?.subJsonURI; + const [page, setPage] = useState(1); + const [copying, setCopying] = useState(false); + const groupPage = useGroupClientPage( + { group: group ?? '', mode: 'links', page }, + !!group && open && enabled, + ); + const exportPath = group ? groupSubscriptionExportPath(group) : undefined; const rows = useMemo(() => { if (!enabled) return []; - const byEmail = new Map(clients.map((c) => [c.email, c])); - const out: Row[] = []; - for (const email of emails) { - const c = byEmail.get(email); - if (!c?.subId) continue; - out.push({ + function row(email: string, subId: string): Row { + return { key: email, email, - subId: c.subId, - link: subSettings!.subURI + c.subId, - jsonLink: jsonEnabled ? subSettings!.subJsonURI + c.subId : '', - }); + subId, + link: subSettings!.subURI + subId, + jsonLink: jsonEnabled ? subSettings!.subJsonURI + subId : '', + }; + } + if (group) return (groupPage.data?.items ?? []).map(({ email, subId }) => row(email, subId)); + const byEmail = new Map((clients ?? []).map((client) => [client.email, client.subId])); + const out: Row[] = []; + for (const email of emails ?? []) { + const subId = byEmail.get(email); + if (subId) out.push(row(email, subId)); } return out; - }, [emails, clients, enabled, jsonEnabled, subSettings]); + }, [emails, clients, enabled, group, groupPage.data?.items, jsonEnabled, subSettings]); + const total = group ? (groupPage.data?.total ?? 0) : rows.length; - const allText = useMemo( - () => - rows - .map((r) => - jsonEnabled ? `${r.email}\t${r.link}\t${r.jsonLink}` : `${r.email}\t${r.link}`, - ) - .join('\n'), - [rows, jsonEnabled], - ); + function allText() { + return rows + .map(({ email, link, jsonLink }) => + jsonEnabled ? `${email}\t${link}\t${jsonLink}` : `${email}\t${link}`, + ) + .join('\n'); + } + + async function copyAll() { + if (!exportPath) { + await copy(allText(), t('pages.clients.subLinksCopiedAll', { count: total })); + return; + } + setCopying(true); + try { + const content = async () => { + const response = await fetch(exportPath, { credentials: 'same-origin' }); + if (!response.ok || !response.headers.get('Content-Type')?.startsWith('text/plain')) { + throw new Error(t('somethingWentWrong')); + } + return response.blob(); + }; + if (typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) { + await navigator.clipboard.write([ + new ClipboardItem({ + 'text/plain': content().then((blob) => new Blob([blob], { type: 'text/plain' })), + }), + ]); + } else { + await navigator.clipboard.writeText(await (await content()).text()); + } + messageApi.success(t('copied')); + } catch { + messageApi.error(t('somethingWentWrong')); + } finally { + setCopying(false); + } + } async function copy(text: string, label?: string) { try { @@ -80,7 +128,7 @@ export default function SubLinksModal({ } function download() { - const blob = new Blob([allText], { type: 'text/plain;charset=utf-8' }); + const blob = new Blob([allText()], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); @@ -150,7 +198,7 @@ export default function SubLinksModal({ {messageContextHolder} @@ -158,18 +206,19 @@ export default function SubLinksModal({
@@ -187,7 +236,7 @@ export default function SubLinksModal({ style={{ marginBottom: 12 }} /> )} - {enabled && rows.length === 0 && ( + {enabled && !total && !groupPage.isFetching && !groupPage.isError && ( )} - {rows.length > 0 && ( + {groupPage.isError && ( + + )} + {enabled && (total > 0 || groupPage.isFetching) && ( dataSource={rows} columns={columns} size="small" - pagination={false} + loading={groupPage.isFetching} + pagination={ + group + ? { + current: page, + pageSize: GROUP_CLIENT_PAGE_SIZE, + total, + showSizeChanger: false, + onChange: setPage, + } + : false + } scroll={{ y: 360 }} /> )} diff --git a/frontend/src/pages/groups/GroupAddClientsModal.tsx b/frontend/src/pages/groups/GroupAddClientsModal.tsx deleted file mode 100644 index 5655cd38a..000000000 --- a/frontend/src/pages/groups/GroupAddClientsModal.tsx +++ /dev/null @@ -1,171 +0,0 @@ -import { useMemo, useState } from 'react'; -import { useTranslation } from 'react-i18next'; -import { Alert, Input, Modal, Space, Table, Tag, Typography, message } from 'antd'; -import type { ColumnsType } from 'antd/es/table'; - -import type { ClientRecord } from '@/hooks/useClients'; - -interface GroupAddClientsModalProps { - open: boolean; - groupName: string | null; - candidates: ClientRecord[]; - onClose: () => void; - onSubmit: (emails: string[]) => Promise<{ affected?: number } | null>; -} - -interface ClientRow { - email: string; - comment: string; - enable: boolean; - currentGroup: string; -} - -export default function GroupAddClientsModal({ - open, - groupName, - candidates, - onClose, - onSubmit, -}: GroupAddClientsModalProps) { - const { t } = useTranslation(); - const [messageApi, messageContextHolder] = message.useMessage(); - const [saving, setSaving] = useState(false); - const [selectedEmails, setSelectedEmails] = useState([]); - const [search, setSearch] = useState(''); - - const rows = useMemo( - () => - (candidates || []) - .map((c) => ({ - email: (c.email || '').trim(), - comment: (c.comment || '').trim(), - enable: c.enable !== false, - currentGroup: (c.group || '').trim(), - })) - .filter((r) => r.email), - [candidates], - ); - - // React resets this during render rather than in an effect so the modal's - // first open frame already shows cleared fields. - const [wasOpen, setWasOpen] = useState(false); - if (open !== wasOpen) { - setWasOpen(open); - if (open) { - setSelectedEmails([]); - setSearch(''); - } - } - - const filteredRows = useMemo(() => { - const q = search.trim().toLowerCase(); - if (!q) return rows; - return rows.filter( - (r) => - r.email.toLowerCase().includes(q) || - r.comment.toLowerCase().includes(q) || - r.currentGroup.toLowerCase().includes(q), - ); - }, [rows, search]); - - const columns: ColumnsType = useMemo( - () => [ - { title: t('pages.inbounds.email'), dataIndex: 'email', key: 'email', ellipsis: true }, - { title: t('comment'), dataIndex: 'comment', key: 'comment', ellipsis: true }, - { - title: t('pages.clients.group'), - dataIndex: 'currentGroup', - key: 'currentGroup', - width: 140, - ellipsis: true, - render: (g: string) => - g ? ( - {g} - ) : ( - — - ), - }, - { - title: t('enable'), - dataIndex: 'enable', - key: 'enable', - width: 90, - render: (enabled: boolean) => - enabled ? ( - {t('enable')} - ) : ( - {t('pages.inbounds.attachClientsStatusDisabled')} - ), - }, - ], - [t], - ); - - async function submit() { - if (!groupName || selectedEmails.length === 0) return; - setSaving(true); - try { - const result = await onSubmit(selectedEmails); - if (!result) return; - const affected = result.affected ?? selectedEmails.length; - messageApi.success(t('pages.groups.addToGroupResult', { count: affected, name: groupName })); - onClose(); - } finally { - setSaving(false); - } - } - - return ( - - {messageContextHolder} - - {t('pages.groups.addToGroupDesc')} - - - - - setSearch(e.target.value)} - placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')} - aria-label={t('pages.inbounds.attachClientsSearchPlaceholder')} - style={{ maxWidth: 320 }} - /> - - {t('pages.inbounds.attachClientsSelectedCount', { - selected: selectedEmails.length, - total: rows.length, - })} - - - {rows.length === 0 ? ( - - ) : ( - - size="small" - rowKey="email" - columns={columns} - dataSource={filteredRows} - pagination={false} - scroll={{ y: 320 }} - rowSelection={{ - selectedRowKeys: selectedEmails, - onChange: (keys) => setSelectedEmails(keys as string[]), - preserveSelectedRowKeys: true, - }} - /> - )} - - - ); -} diff --git a/frontend/src/pages/groups/GroupClientsModal.tsx b/frontend/src/pages/groups/GroupClientsModal.tsx new file mode 100644 index 000000000..3fcf59aa4 --- /dev/null +++ b/frontend/src/pages/groups/GroupClientsModal.tsx @@ -0,0 +1,283 @@ +import { useEffect, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Alert, Button, Input, Modal, Space, Table, Tag, Typography, message } from 'antd'; +import type { ColumnsType } from 'antd/es/table'; + +import { + GROUP_CLIENT_PAGE_SIZE, + MAX_GROUP_EXCLUSIONS, + fetchGroupClients, + useGroupClientPage, + type GroupClientSelection, +} from '@/api/groupClients'; +import type { GroupClientRow } from '@/generated/zod'; + +interface GroupClientsModalProps { + group: string; + mode: 'add' | 'remove'; + onClose: () => void; + onSubmit: (selection: GroupClientSelection) => Promise<{ affected?: number } | null>; +} + +export default function GroupClientsModal({ + group, + mode, + onClose, + onSubmit, +}: GroupClientsModalProps) { + const { t } = useTranslation(); + const [messages, holder] = message.useMessage(); + const [page, setPage] = useState(1); + const [search, setSearch] = useState(''); + const [debouncedSearch, setDebouncedSearch] = useState(''); + const [choices, setChoices] = useState(new Set()); + const [frozen, setFrozen] = useState<{ + token: string; + count: number; + maxId: number; + search: string; + }>(); + const [busy, setBusy] = useState<'freeze' | 'submit'>(); + const action = useRef(false); + + useEffect(() => { + const timer = window.setTimeout(() => setDebouncedSearch(search), 220); + return () => window.clearTimeout(timer); + }, [search]); + + const query = useGroupClientPage( + { + group, + mode, + page, + search: debouncedSearch, + maxId: frozen?.maxId, + scopeSearch: frozen?.search, + }, + search === debouncedSearch, + ); + const loading = search !== debouncedSearch || query.isFetching; + const rows = loading ? [] : (query.data?.items ?? []); + const selected = frozen ? frozen.count - choices.size : choices.size; + const visible = rows.filter((row) => !frozen || row.inScope); + const add = mode === 'add'; + + function clearSelection() { + setFrozen(undefined); + setChoices(new Set()); + } + + function selectVisible(keys: React.Key[]) { + const checked = new Set(keys); + const next = new Set(choices); + for (const row of visible) { + if (frozen ? !checked.has(row.id) : checked.has(row.id)) next.add(row.id); + else next.delete(row.id); + } + if (next.size > (frozen ? MAX_GROUP_EXCLUSIONS : 50_000)) { + messages.warning( + t('pages.groups.selectionLimit', { count: frozen ? MAX_GROUP_EXCLUSIONS : 50_000 }), + ); + return; + } + setChoices(next); + } + + async function selectAll() { + if (action.current || loading) return; + action.current = true; + setBusy('freeze'); + try { + const result = await fetchGroupClients({ + group, + mode, + search: debouncedSearch, + freeze: true, + }); + if (!result.scopeToken || !result.maxId || !result.total) { + clearSelection(); + return; + } + setChoices(new Set()); + setFrozen({ + token: result.scopeToken, + maxId: result.maxId, + count: result.total, + search: debouncedSearch, + }); + } catch (error) { + messages.error((error instanceof Error && error.message) || t('somethingWentWrong')); + } finally { + action.current = false; + setBusy(undefined); + } + } + + async function submit() { + if (action.current || selected <= 0) return; + action.current = true; + setBusy('submit'); + try { + const selection: GroupClientSelection = frozen + ? { + mode: 'allMatching', + scopeToken: frozen.token, + search: frozen.search, + excludedClientIds: [...choices], + } + : { mode: 'explicit', clientIds: [...choices] }; + const result = await onSubmit(selection); + if (result) { + messages.success( + t(add ? 'pages.groups.addToGroupResult' : 'pages.groups.removeFromGroupResult', { + count: result.affected ?? 0, + name: group, + }), + ); + onClose(); + } + } finally { + action.current = false; + setBusy(undefined); + } + } + + const columns: ColumnsType = [ + { title: t('pages.inbounds.email'), dataIndex: 'email', width: 220, ellipsis: true }, + { title: t('comment'), dataIndex: 'comment', ellipsis: true }, + ...(add + ? [ + { + title: t('pages.clients.group'), + dataIndex: 'group', + width: 140, + ellipsis: true, + render: (label: string) => (label ? {label} : '—'), + }, + ] + : []), + { + title: t('enable'), + dataIndex: 'enable', + width: 100, + render: (enabled: boolean) => ( + + {t(enabled ? 'enable' : 'pages.inbounds.attachClientsStatusDisabled')} + + ), + }, + ]; + + return ( + { + if (!action.current) onClose(); + }} + onOk={submit} + okButtonProps={{ disabled: selected <= 0 || !!busy, danger: !add }} + confirmLoading={busy === 'submit'} + okText={t(add ? 'add' : 'remove')} + cancelText={t('cancel')} + cancelButtonProps={{ disabled: !!busy }} + title={t(add ? 'pages.groups.addToGroupTitle' : 'pages.groups.removeFromGroupTitle', { + name: group, + })} + width={720} + > + {holder} + + {t(add ? 'pages.groups.addToGroupDesc' : 'pages.groups.removeFromGroupDesc')} + + + { + setSearch(event.target.value); + setPage(1); + }} + maxLength={256} + placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')} + aria-label={t('pages.inbounds.attachClientsSearchPlaceholder')} + style={{ maxWidth: 320 }} + /> + + + + + {frozen && choices.size > 0 && ( + + )} + + {t('pages.inbounds.attachClientsSelectedCount', { + selected, + total: frozen?.count ?? query.data?.total ?? 0, + })} + + + {query.isError && ( + + )} + {!loading && !query.isError && !search && query.data?.total === 0 && ( + + )} + + size="small" + rowKey="id" + virtual + columns={columns} + dataSource={rows} + loading={loading} + scroll={{ x: 620, y: 320 }} + pagination={{ + current: page, + pageSize: GROUP_CLIENT_PAGE_SIZE, + total: query.data?.total ?? 0, + showSizeChanger: false, + disabled: !!busy, + onChange: setPage, + }} + rowSelection={{ + selectedRowKeys: visible + .filter((row) => choices.has(row.id) !== !!frozen) + .map((row) => row.id), + onChange: selectVisible, + getTitleCheckboxProps: () => ({ 'aria-label': t('pages.inbounds.attachSelectPage') }), + getCheckboxProps: (row) => ({ + 'aria-label': row.email, + disabled: !!busy || (!!frozen && !row.inScope), + }), + }} + /> + + + ); +} diff --git a/frontend/src/pages/groups/GroupRemoveClientsModal.tsx b/frontend/src/pages/groups/GroupRemoveClientsModal.tsx deleted file mode 100644 index c462c8a49..000000000 --- a/frontend/src/pages/groups/GroupRemoveClientsModal.tsx +++ /dev/null @@ -1,151 +0,0 @@ -import { useMemo, useState } from 'react'; -import { useTranslation } from 'react-i18next'; -import { Input, Modal, Space, Table, Tag, Typography, message } from 'antd'; -import type { ColumnsType } from 'antd/es/table'; - -import type { ClientRecord } from '@/hooks/useClients'; - -interface GroupRemoveClientsModalProps { - open: boolean; - groupName: string | null; - members: ClientRecord[]; - onClose: () => void; - onSubmit: (emails: string[]) => Promise<{ affected?: number } | null>; -} - -interface ClientRow { - email: string; - comment: string; - enable: boolean; -} - -export default function GroupRemoveClientsModal({ - open, - groupName, - members, - onClose, - onSubmit, -}: GroupRemoveClientsModalProps) { - const { t } = useTranslation(); - const [messageApi, messageContextHolder] = message.useMessage(); - const [saving, setSaving] = useState(false); - const [selectedEmails, setSelectedEmails] = useState([]); - const [search, setSearch] = useState(''); - - const rows = useMemo( - () => - (members || []) - .map((c) => ({ - email: (c.email || '').trim(), - comment: (c.comment || '').trim(), - enable: c.enable !== false, - })) - .filter((r) => r.email), - [members], - ); - - // React resets this during render rather than in an effect so the modal's - // first open frame already shows cleared fields. - const [wasOpen, setWasOpen] = useState(false); - if (open !== wasOpen) { - setWasOpen(open); - if (open) { - setSelectedEmails([]); - setSearch(''); - } - } - - const filteredRows = useMemo(() => { - const q = search.trim().toLowerCase(); - if (!q) return rows; - return rows.filter( - (r) => r.email.toLowerCase().includes(q) || r.comment.toLowerCase().includes(q), - ); - }, [rows, search]); - - const columns: ColumnsType = useMemo( - () => [ - { title: t('pages.inbounds.email'), dataIndex: 'email', key: 'email', ellipsis: true }, - { title: t('comment'), dataIndex: 'comment', key: 'comment', ellipsis: true }, - { - title: t('enable'), - dataIndex: 'enable', - key: 'enable', - width: 90, - render: (enabled: boolean) => - enabled ? ( - {t('enable')} - ) : ( - {t('pages.inbounds.attachClientsStatusDisabled')} - ), - }, - ], - [t], - ); - - async function submit() { - if (!groupName || selectedEmails.length === 0) return; - setSaving(true); - try { - const result = await onSubmit(selectedEmails); - if (!result) return; - const affected = result.affected ?? selectedEmails.length; - messageApi.success( - t('pages.groups.removeFromGroupResult', { count: affected, name: groupName }), - ); - onClose(); - } finally { - setSaving(false); - } - } - - return ( - - {messageContextHolder} - - {t('pages.groups.removeFromGroupDesc')} - - - - - setSearch(e.target.value)} - placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')} - aria-label={t('pages.inbounds.attachClientsSearchPlaceholder')} - style={{ maxWidth: 320 }} - /> - - {t('pages.inbounds.attachClientsSelectedCount', { - selected: selectedEmails.length, - total: rows.length, - })} - - - - size="small" - rowKey="email" - columns={columns} - dataSource={filteredRows} - pagination={false} - scroll={{ y: 280 }} - rowSelection={{ - selectedRowKeys: selectedEmails, - onChange: (keys) => setSelectedEmails(keys as string[]), - preserveSelectedRowKeys: true, - }} - /> - - - ); -} diff --git a/frontend/src/pages/groups/GroupsPage.stories.tsx b/frontend/src/pages/groups/GroupsPage.stories.tsx new file mode 100644 index 000000000..4aad951a6 --- /dev/null +++ b/frontend/src/pages/groups/GroupsPage.stories.tsx @@ -0,0 +1,245 @@ +import { useState } from 'react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect, waitFor, within } from 'storybook/test'; +import { Button } from 'antd'; +import { MemoryRouter } from 'react-router'; + +import { ThemeProvider } from '@/hooks/useTheme'; +import AddClientsToGroupModal from '@/pages/inbounds/clients/AddClientsToGroupModal'; +import GroupsPage from './GroupsPage'; + +const api = '/panel/api/clients'; +const group = 'staff'; +const groupCount = 10_000; +const requests: { path: string; query: URLSearchParams; body?: Record }[] = []; +const exportedLinks = Array.from({ length: groupCount }, (_, index) => { + const id = index + 1; + return `client-${id}@example.test\thttps://sub.example.test/plain/s${id}`; +}).join('\n'); +let copiedLinks = ''; + +function GroupFixture() { + const [queryClient] = useState(() => new QueryClient()); + const [inboundOpen, setInboundOpen] = useState(false); + return ( + + + + + + setInboundOpen(false)} + /> + + + + ); +} + +function response(obj: unknown) { + return Promise.resolve(Response.json({ success: true, msg: '', obj })); +} + +const meta = { + title: 'Pages/Groups/Client management', + component: GroupsPage, + render: () => , +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const LargeGroup: Story = { + parameters: { a11y: { context: '.ant-modal' } }, + beforeEach: () => { + requests.length = 0; + copiedLinks = ''; + const original = window.fetch; + const clipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard'); + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { + writeText: async (value: string) => { + copiedLinks = value; + }, + write: async (items: ClipboardItem[]) => { + copiedLinks = await (await items[0]!.getType('text/plain')).text(); + }, + }, + }); + window.fetch = (input, init) => { + const url = new URL(input instanceof Request ? input.url : input, window.location.href); + const path = url.pathname; + const query = url.searchParams; + const body = + typeof init?.body === 'string' && init.body.startsWith('{') + ? (JSON.parse(init.body) as Record) + : undefined; + requests.push({ path, query, body }); + if (path === api + '/groups') { + return response([ + { + id: 1, + name: group, + clientCount: groupCount, + hostGroupIds: [], + trafficUsed: 0, + up: 0, + down: 0, + }, + ]); + } + if (path === '/panel/api/setting/defaultSettings') { + return response({ subEnable: true, subURI: 'https://sub.example.test/plain/' }); + } + if (path === '/panel/api/setting/all') return response({}); + if (path === '/csrf-token') return response('story-token'); + if (path === api + '/groups/clientPage') { + const mode = query.get('mode'); + const search = query.get('search'); + const total = search ? 1 : mode === 'add' ? 40_000 : groupCount; + const maxId = mode === 'add' ? 50_000 : 10_000; + if (query.get('freeze') === 'true') { + return response({ items: [], total, scopeToken: `scope-${mode}-${search ?? ''}`, maxId }); + } + const offset = (Number(query.get('page') ?? '1') - 1) * 100; + const items = Array.from({ length: Math.min(100, total) }, (_, index) => { + const id = search ? 10101 : (mode === 'add' ? groupCount : 0) + offset + index + 1; + return { + id, + email: `client-${id}@example.test`, + comment: '', + group: mode === 'add' ? '' : group, + enable: true, + subId: `s${id}`, + inScope: !query.get('scopeSearch') || id === 10101, + }; + }); + return response({ items, total }); + } + if (path === api + '/groups/subLinks/export') { + return Promise.resolve( + new Response(exportedLinks, { headers: { 'Content-Type': 'text/plain' } }), + ); + } + if (path === api + '/bulkAdjust') return response({ adjusted: groupCount }); + if (path === api + '/bulkDel') return response({ deleted: groupCount }); + if (path.endsWith('/bulkAdd') || path.endsWith('/bulkRemove')) + return response({ affected: 1 }); + if (path.startsWith('/panel/api/')) return response([]); + return original(input, init); + }; + return () => { + window.fetch = original; + if (clipboard) Object.defineProperty(navigator, 'clipboard', clipboard); + else Reflect.deleteProperty(navigator, 'clipboard'); + }; + }, + play: async ({ userEvent }) => { + const screen = within(document.body); + const open = async (label: RegExp) => { + await userEvent.click((await screen.findAllByRole('button', { name: 'more' }))[0]!); + await userEvent.click(await screen.findByRole('menuitem', { name: label })); + return within(await screen.findByRole('dialog')); + }; + const close = async (dialog: ReturnType, name = 'Cancel') => { + await userEvent.click(dialog.getAllByRole('button', { name }).at(-1)!); + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); + }; + const add = await open(/add clients…/i); + await add.findByText('client-10001@example.test'); + await expect(add.getAllByRole('checkbox').length).toBeLessThan(101); + await userEvent.click(add.getByRole('button', { name: 'Select this page' })); + const nextPage = screen.getByRole('dialog').querySelector('.ant-pagination-next button'); + if (!(nextPage instanceof HTMLButtonElement)) { + throw new Error( + 'Next page control missing: ' + + screen.getByRole('dialog').querySelector('.ant-pagination')?.outerHTML, + ); + } + await userEvent.click(nextPage); + await waitFor(() => { + const loaded = requests + .filter((request) => request.path.endsWith('/clientPage')) + .map((request) => request.query.toString()); + expect(loaded).toContain('group=staff&mode=add&page=2&search='); + }); + await add.findByText('client-10101@example.test'); + await expect(add.getByRole('status')).toHaveTextContent('100 of 40000 selected'); + const selectAll = add.getByRole('button', { name: /Select all matching clients/i }); + await userEvent.click(selectAll); + await waitFor(() => expect(selectAll).toHaveAttribute('aria-pressed', 'true')); + const checkbox = await add.findByRole('checkbox', { name: 'client-10101@example.test' }); + await waitFor(() => expect(checkbox).toBeChecked()); + await userEvent.click(checkbox); + await userEvent.type(add.getByRole('searchbox'), '10101'); + await waitFor(() => expect(requests.some((r) => r.query.get('search') === '10101')).toBe(true)); + await userEvent.click(add.getByRole('button', { name: /^Add$/ })); + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); + await expect(requests.find((r) => r.path === api + '/groups/bulkAdd')?.body).toEqual({ + group, + selection: { + mode: 'allMatching', + scopeToken: 'scope-add-', + search: '', + excludedClientIds: [10101], + }, + }); + + const remove = await open(/remove clients…/i); + await remove.findByText('client-1@example.test'); + await expect(remove.getAllByRole('checkbox').length).toBeLessThan(101); + await close(remove); + + const links = await open(/sub links/i); + await links.findByText('https://sub.example.test/plain/s1'); + await expect(links.getAllByRole('row').length).toBeLessThanOrEqual(101); + await expect(links.getByRole('link', { name: 'Download' })).toHaveAttribute( + 'href', + api + '/groups/subLinks/export?group=staff', + ); + await userEvent.click(links.getByRole('button', { name: /copy all/i })); + await waitFor(() => expect(copiedLinks).toBe(exportedLinks)); + await close(links, 'Close'); + + const adjust = await open(/adjust/i); + await userEvent.type(adjust.getByLabelText('Add days'), '1'); + await userEvent.click(adjust.getByRole('button', { name: 'Confirm' })); + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); + await expect(requests.find((r) => r.path === api + '/bulkAdjust')?.body).toMatchObject({ + group, + scopeToken: 'scope-remove-', + addDays: 1, + }); + const del = await open(/delete clients in group/i); + await userEvent.click(del.getByRole('button', { name: /^Delete$/ })); + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); + await expect(requests.find((r) => r.path === api + '/bulkDel')?.body).toEqual({ + group, + scopeToken: 'scope-remove-', + keepTraffic: false, + }); + + await userEvent.click(screen.getByRole('button', { name: 'Group the source inbound' })); + const inbound = within(await screen.findByRole('dialog')); + await userEvent.type(inbound.getByRole('combobox'), group); + await userEvent.click(inbound.getByRole('button', { name: /^Add$/ })); + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); + await expect(requests.filter((r) => r.path === api + '/groups/bulkAdd').at(-1)?.body).toEqual({ + inboundId: 7, + group, + }); + await expect( + requests.some( + (r) => + r.path === api + '/list' || r.path.endsWith('/emails') || Array.isArray(r.body?.emails), + ), + ).toBe(false); + const picker = await open(/add clients…/i); + await picker.findByRole('checkbox', { name: 'client-10001@example.test' }); + }, +}; diff --git a/frontend/src/pages/groups/GroupsPage.tsx b/frontend/src/pages/groups/GroupsPage.tsx index 407785f70..eba2eb841 100644 --- a/frontend/src/pages/groups/GroupsPage.tsx +++ b/frontend/src/pages/groups/GroupsPage.tsx @@ -1,4 +1,4 @@ -import { lazy, useCallback, useEffect, useId, useMemo, useState } from 'react'; +import { lazy, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Button, @@ -39,7 +39,6 @@ import { UsergroupDeleteOutlined, } from '@ant-design/icons'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; -import { z } from 'zod'; import { useTheme } from '@/hooks/useTheme'; import { useMediaQuery } from '@/hooks/useMediaQuery'; @@ -50,24 +49,14 @@ import { setMessageInstance } from '@/utils/messageBus'; import AppSidebar from '@/layouts/AppSidebar'; import { LazyMount } from '@/components/utility'; import { keys } from '@/api/queryKeys'; -import { - ClientRecordSchema, - GroupSummaryListSchema, - type ClientRecord, - type GroupSummary, -} from '@/schemas/client'; +import { fetchGroupClients, type GroupBulkScope } from '@/api/groupClients'; +import { GroupSummaryListSchema, type GroupSummary } from '@/schemas/client'; import { parseMsg } from '@/utils/zodValidate'; import HostGroupSelect from './HostGroupSelect'; -const ClientRecordListSchema = z - .array(ClientRecordSchema) - .nullable() - .transform((v) => v ?? []); - const SubLinksModal = lazy(() => import('../clients/SubLinksModal')); const ClientBulkAdjustModal = lazy(() => import('../clients/ClientBulkAdjustModal')); -const GroupAddClientsModal = lazy(() => import('./GroupAddClientsModal')); -const GroupRemoveClientsModal = lazy(() => import('./GroupRemoveClientsModal')); +const GroupClientsModal = lazy(() => import('./GroupClientsModal')); const GroupHostRulesModal = lazy(() => import('./GroupHostRulesModal')); const JSON_HEADERS = { headers: { 'Content-Type': 'application/json' } } as const; @@ -85,16 +74,6 @@ async function fetchGroups(): Promise { return validated.obj ?? []; } -async function fetchEmailsForGroup(name: string): Promise { - const msg = await HttpUtil.get( - `/panel/api/clients/groups/${encodeURIComponent(name)}/emails`, - undefined, - { silent: true }, - ); - if (!msg?.success || !Array.isArray(msg.obj)) return []; - return msg.obj; -} - export default function GroupsPage() { usePageTitle(); const { t } = useTranslation(); @@ -184,22 +163,10 @@ export default function GroupsPage() { const [adjustOpen, setAdjustOpen] = useState(false); const [addClientsOpen, setAddClientsOpen] = useState(false); const [removeClientsOpen, setRemoveClientsOpen] = useState(false); - const [groupEmails, setGroupEmails] = useState([]); + const [adjustScope, setAdjustScope] = useState<(GroupBulkScope & { count: number }) | null>(null); + const scopeRequest = useRef(0); const [groupForAction, setGroupForAction] = useState(null); - const allClientsQuery = useQuery({ - queryKey: keys.clients.all(), - queryFn: async () => { - const msg = await HttpUtil.get('/panel/api/clients/list', undefined, { silent: true }); - if (!msg?.success) throw new Error(msg?.msg || 'Failed to load clients'); - const validated = parseMsg(msg, ClientRecordListSchema, 'clients/list'); - return validated.obj ?? []; - }, - enabled: addClientsOpen || removeClientsOpen || subLinksOpen, - staleTime: 30_000, - }); - const allClients = allClientsQuery.data ?? []; - const totalGroups = groups.length; const totalClients = useMemo( () => groups.reduce((acc, g) => acc + (g.clientCount || 0), 0), @@ -289,37 +256,47 @@ export default function GroupsPage() { }); } - async function openSubLinksFor(g: GroupSummary) { + function openSubLinksFor(g: GroupSummary) { if (!g.clientCount) { messageApi.info(t('pages.groups.emptyForAction')); return; } - const emails = await fetchEmailsForGroup(g.name); - if (emails.length === 0) { - messageApi.info(t('pages.groups.emptyForAction')); - return; - } + scopeRequest.current++; setGroupForAction(g); - setGroupEmails(emails); setSubLinksOpen(true); } - async function openAdjustFor(g: GroupSummary) { + async function freezeGroup(g: GroupSummary) { if (!g.clientCount) { messageApi.info(t('pages.groups.emptyForAction')); - return; + return null; } - const emails = await fetchEmailsForGroup(g.name); - if (emails.length === 0) { - messageApi.info(t('pages.groups.emptyForAction')); - return; + const request = ++scopeRequest.current; + try { + const result = await fetchGroupClients({ group: g.name, mode: 'remove', freeze: true }); + if (scopeRequest.current !== request) return null; + if (!result.total || !result.scopeToken) { + messageApi.info(t('pages.groups.emptyForAction')); + return null; + } + return { group: g.name, count: result.total, scopeToken: result.scopeToken }; + } catch (error) { + if (scopeRequest.current === request) { + messageApi.error((error instanceof Error && error.message) || t('somethingWentWrong')); + } + return null; } - setGroupForAction(g); - setGroupEmails(emails); + } + + async function openAdjustFor(g: GroupSummary) { + const scope = await freezeGroup(g); + if (!scope) return; + setAdjustScope(scope); setAdjustOpen(true); } function openAddClientsFor(g: GroupSummary) { + scopeRequest.current++; setGroupForAction(g); setAddClientsOpen(true); } @@ -344,29 +321,26 @@ export default function GroupsPage() { messageApi.info(t('pages.groups.emptyForAction')); return; } + scopeRequest.current++; setGroupForAction(g); setRemoveClientsOpen(true); } - function onDeleteClients(g: GroupSummary) { - if (!g.clientCount) { - messageApi.info(t('pages.groups.emptyForAction')); - return; - } + async function onDeleteClients(g: GroupSummary) { + const scope = await freezeGroup(g); + if (!scope) return; modal.confirm({ title: t('pages.groups.deleteClientsConfirmTitle', { name: g.name }), - content: t('pages.groups.deleteClientsConfirmContent', { count: g.clientCount }), + content: t('pages.groups.deleteClientsConfirmContent', { count: scope.count }), okText: t('delete'), okType: 'danger', cancelText: t('cancel'), onOk: async () => { - const emails = await fetchEmailsForGroup(g.name); - if (emails.length === 0) return; - const msg = await bulkDelete(emails); + const msg = await bulkDelete({ group: scope.group, scopeToken: scope.scopeToken }); if (msg?.success) { const ok = msg.obj?.deleted ?? 0; const skipped = msg.obj?.skipped ?? []; - const failed = skipped.length; + const failed = msg.obj?.skippedCount ?? skipped.length; if (failed === 0) { messageApi.success(t('pages.groups.deleteClientsSuccess', { count: ok })); } else { @@ -750,69 +724,67 @@ export default function GroupsPage() { /> - - - + {subLinksOpen && groupForAction && ( + + + + )} - - { - const msg = await bulkAdjust(groupEmails, addDays, addBytes, flow, limitHwid, adTag); - if (msg?.success) { - const obj = msg.obj ?? { adjusted: 0 }; - messageApi.success( - t('pages.groups.adjustSuccess', { - count: obj.adjusted ?? 0, - name: groupForAction?.name ?? '', - }), + {adjustOpen && adjustScope && ( + + { + const { group, scopeToken } = adjustScope; + const msg = await bulkAdjust( + { group, scopeToken }, + addDays, + addBytes, + flow, + limitHwid, + adTag, + externalLinks, ); - return obj; - } - return null; - }} - /> - + if (!msg?.success || !msg.obj) return null; + messageApi.success( + t('pages.groups.adjustSuccess', { count: msg.obj.adjusted, name: group }), + ); + return msg.obj; + }} + /> + + )} - - c.group !== groupForAction?.name)} - onClose={() => setAddClientsOpen(false)} - onSubmit={async (emails) => { - const msg = await bulkAddToGroup(emails, groupForAction?.name ?? ''); - if (msg?.success) { - return (msg.obj as { affected?: number } | undefined) ?? { affected: 0 }; - } - return null; - }} - /> - - - - c.group === groupForAction?.name)} - onClose={() => setRemoveClientsOpen(false)} - onSubmit={async (emails) => { - const msg = await bulkRemoveFromGroup(emails); - if (msg?.success) { - return (msg.obj as { affected?: number } | undefined) ?? { affected: 0 }; - } - return null; - }} - /> - + {(addClientsOpen || removeClientsOpen) && groupForAction && ( + + { + setAddClientsOpen(false); + setRemoveClientsOpen(false); + }} + onSubmit={async (selection) => { + const group = groupForAction.name; + const msg = addClientsOpen + ? await bulkAddToGroup(selection, group) + : await bulkRemoveFromGroup({ group, selection }); + return msg?.success + ? ((msg.obj as { affected?: number } | undefined) ?? { affected: 0 }) + : null; + }} + /> + + )} ); diff --git a/frontend/src/pages/inbounds/InboundsPage.tsx b/frontend/src/pages/inbounds/InboundsPage.tsx index 7ffaf5de0..6cfadcdba 100644 --- a/frontend/src/pages/inbounds/InboundsPage.tsx +++ b/frontend/src/pages/inbounds/InboundsPage.tsx @@ -173,7 +173,7 @@ export default function InboundsPage() { const [detachSource, setDetachSource] = useState(null); const [groupOpen, setGroupOpen] = useState(false); - const [groupSource, setGroupSource] = useState(null); + const [groupSourceID, setGroupSourceID] = useState(null); const [cloneOpen, setCloneOpen] = useState(false); const [cloneSource, setCloneSource] = useState(null); @@ -646,7 +646,6 @@ export default function InboundsPage() { 'clipboard', 'clone', 'attachClients', - 'addToGroup', ]; let target = dbInbound; if (hydratingKeys.includes(key)) { @@ -693,7 +692,7 @@ export default function InboundsPage() { setDetachOpen(true); break; case 'addToGroup': - setGroupSource(target); + setGroupSourceID(target.id); setGroupOpen(true); break; case 'clone': @@ -874,14 +873,17 @@ export default function InboundsPage() { source={detachSource} /> - - setGroupOpen(false)} - onAdded={refresh} - source={groupSource} - /> - + {groupSourceID !== null && ( + + setGroupOpen(false)} + onAdded={refresh} + inboundId={groupSourceID} + count={clientCount[groupSourceID]?.clients ?? 0} + /> + + )} import('@/pages/clients/BulkAddToGroupModal')); interface AddClientsToGroupModalProps { open: boolean; - source: DBInbound | null; + inboundId: number; + count: number; onClose: () => void; onAdded?: () => void; } -function readClientEmails(settings: unknown): string[] { - const parsed = coerceInboundJsonField(settings) as { clients?: Array<{ email?: string }> }; - const clients = Array.isArray(parsed?.clients) ? parsed.clients : []; - return clients.map((c) => (c?.email || '').trim()).filter(Boolean); -} - export default function AddClientsToGroupModal({ open, - source, + inboundId, + count, onClose, onAdded, }: AddClientsToGroupModalProps) { - const [groups, setGroups] = useState([]); - - const emails = useMemo(() => (source ? readClientEmails(source.settings) : []), [source]); - - useEffect(() => { - if (!open) return; - let cancelled = false; - (async () => { - const msg = await HttpUtil.get('/panel/api/clients/groups', undefined, { silent: true }); - if (cancelled) return; - const list = Array.isArray(msg?.obj) ? (msg.obj as Array<{ name?: string }>) : []; - setGroups(list.map((g) => g?.name || '').filter(Boolean)); - })(); - return () => { - cancelled = true; - }; - }, [open]); - + const queryClient = useQueryClient(); + const groups = useQuery({ + queryKey: keys.clients.groups(), + enabled: open, + queryFn: async ({ signal }) => { + const response = await HttpUtil.get('/panel/api/clients/groups', undefined, { + signal, + silent: true, + }); + const result = parseMsg(response, GroupSummaryListSchema, 'clients/groups'); + if (!result.success) throw new Error(result.msg); + return result.obj ?? []; + }, + }); return ( { - if (!o) onClose(); + count={count} + groups={groups.data?.map((group) => group.name) ?? []} + onOpenChange={(value) => { + if (!value) onClose(); }} onSubmit={async (group) => { - const msg = await HttpUtil.post( + const response = await HttpUtil.post<{ affected?: number }>( '/panel/api/clients/groups/bulkAdd', - { emails, group }, + { inboundId, group }, { headers: { 'Content-Type': 'application/json' } }, ); - if (!msg?.success) return null; + if (!response?.success) return null; + void queryClient.invalidateQueries({ queryKey: keys.clients.root() }); onAdded?.(); - return (msg.obj as { affected?: number } | undefined) ?? { affected: 0 }; + return response.obj ?? { affected: 0 }; }} /> ); diff --git a/frontend/src/schemas/client.ts b/frontend/src/schemas/client.ts index d7ca6016e..b45e1e776 100644 --- a/frontend/src/schemas/client.ts +++ b/frontend/src/schemas/client.ts @@ -220,6 +220,7 @@ export const ClientHydrateSchema = z.object({ }); export const BulkAdjustResultSchema = z.object({ + skippedCount: z.number().optional(), adjusted: z.number(), skipped: z.array(z.object({ email: z.string(), reason: z.string() })).optional(), externalLinks: z @@ -228,6 +229,7 @@ export const BulkAdjustResultSchema = z.object({ }); export const BulkDeleteResultSchema = z.object({ + skippedCount: z.number().optional(), deleted: z.number(), skipped: z.array(z.object({ email: z.string(), reason: z.string() })).optional(), }); diff --git a/internal/web/controller/client.go b/internal/web/controller/client.go index 9380e28df..3a54eecdc 100644 --- a/internal/web/controller/client.go +++ b/internal/web/controller/client.go @@ -399,6 +399,8 @@ func (a *ClientController) resetAllTraffics(c *gin.Context) { } type bulkAdjustRequest struct { + Group string `json:"group"` + ScopeToken string `json:"scopeToken"` Emails []string `json:"emails"` AddDays int `json:"addDays"` AddBytes int64 `json:"addBytes"` @@ -414,22 +416,30 @@ func (a *ClientController) bulkAdjust(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + emails, err := a.resolveGroupBulkEmails(c, req.Emails, req.Group, req.ScopeToken) + if err != nil { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + return + } var result service.BulkAdjustResult var needRestart bool - var err error if req.ExternalLinks != nil { if req.AddDays != 0 || req.AddBytes != 0 || req.Flow != "" || req.LimitHwid != nil || req.AdTag != "" { jsonMsg(c, "append external links separately from other adjustments", errors.New("externalLinks cannot be combined with other adjustments")) return } - result, err = a.clientService.BulkAppendExternalLinks(req.Emails, req.ExternalLinks) + result, err = a.clientService.BulkAppendExternalLinks(emails, req.ExternalLinks) } else { - result, needRestart, err = a.clientService.BulkAdjust(&a.inboundService, req.Emails, req.AddDays, req.AddBytes, req.Flow, req.LimitHwid, req.AdTag) + result, needRestart, err = a.clientService.BulkAdjust(&a.inboundService, emails, req.AddDays, req.AddBytes, req.Flow, req.LimitHwid, req.AdTag) } if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + if req.Group != "" && len(result.Skipped) > 0 { + result.SkippedCount = len(result.Skipped) + result.Skipped = result.Skipped[:min(len(result.Skipped), 20)] + } jsonObj(c, result, nil) if needRestart { a.xrayService.SetToNeedRestart() @@ -438,10 +448,22 @@ func (a *ClientController) bulkAdjust(c *gin.Context) { } type bulkDeleteRequest struct { + Group string `json:"group"` + ScopeToken string `json:"scopeToken"` Emails []string `json:"emails"` KeepTraffic bool `json:"keepTraffic"` } +func (a *ClientController) resolveGroupBulkEmails(c *gin.Context, emails []string, group, scopeToken string) ([]string, error) { + if group == "" && scopeToken == "" { + return emails, nil + } + if len(emails) != 0 || strings.TrimSpace(group) == "" { + return nil, errors.New("use either emails or a group scope") + } + return a.clientService.GroupOperationEmails(c.Request.Context(), group, scopeToken) +} + type bulkAttachRequest struct { Emails []string `json:"emails"` InboundIds []int `json:"inboundIds"` @@ -503,11 +525,20 @@ func (a *ClientController) bulkDelete(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - result, needRestart, err := a.clientService.BulkDelete(&a.inboundService, req.Emails, req.KeepTraffic) + emails, err := a.resolveGroupBulkEmails(c, req.Emails, req.Group, req.ScopeToken) if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + result, needRestart, err := a.clientService.BulkDelete(&a.inboundService, emails, req.KeepTraffic) + if err != nil { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + return + } + if req.Group != "" && len(result.Skipped) > 0 { + result.SkippedCount = len(result.Skipped) + result.Skipped = result.Skipped[:min(len(result.Skipped), 20)] + } jsonObj(c, result, nil) if needRestart { a.xrayService.SetToNeedRestart() diff --git a/internal/web/controller/group.go b/internal/web/controller/group.go index 3abac34b5..11af7517f 100644 --- a/internal/web/controller/group.go +++ b/internal/web/controller/group.go @@ -1,8 +1,12 @@ package controller import ( + "bufio" + "fmt" + "net/http" "strings" + "github.com/mhsanaei/3x-ui/v3/internal/logger" "github.com/mhsanaei/3x-ui/v3/internal/util/common" "github.com/mhsanaei/3x-ui/v3/internal/web/service" @@ -10,8 +14,9 @@ import ( ) type GroupController struct { - clientService service.ClientService - xrayService service.XrayService + clientService service.ClientService + xrayService service.XrayService + settingService service.SettingService } func NewGroupController(g *gin.RouterGroup) *GroupController { @@ -22,6 +27,8 @@ func NewGroupController(g *gin.RouterGroup) *GroupController { func (a *GroupController) initRouter(g *gin.RouterGroup) { g.GET("/groups", a.list) + g.GET("/groups/clientPage", a.clientPage) + g.GET("/groups/subLinks/export", a.exportSubLinks) g.GET("/groups/:name/emails", a.emails) g.POST("/groups/create", a.create) g.POST("/groups/rename", a.rename) @@ -158,8 +165,10 @@ func (a *GroupController) resetTraffic(c *gin.Context) { } type bulkAddToGroupRequest struct { - Emails []string `json:"emails"` - Group string `json:"group"` + Emails []string `json:"emails"` + Group string `json:"group"` + InboundID *int `json:"inboundId"` + Selection *service.GroupClientSelection `json:"selection"` } func (a *GroupController) bulkAdd(c *gin.Context) { @@ -172,7 +181,21 @@ func (a *GroupController) bulkAdd(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("group name is required")) return } - affected, err := a.clientService.AddToGroup(req.Emails, req.Group) + if (req.InboundID != nil && (*req.InboundID <= 0 || req.Selection != nil || len(req.Emails) != 0)) || + (req.Selection != nil && len(req.Emails) != 0) { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("use one client scope")) + return + } + var affected int + var err error + switch { + case req.InboundID != nil: + affected, err = a.clientService.AddInboundToGroup(c.Request.Context(), *req.InboundID, req.Group) + case req.Selection != nil: + affected, err = a.clientService.ChangeGroupSelection(c.Request.Context(), req.Group, "add", *req.Selection) + default: + affected, err = a.clientService.AddToGroup(req.Emails, req.Group) + } if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return @@ -182,7 +205,9 @@ func (a *GroupController) bulkAdd(c *gin.Context) { } type bulkRemoveFromGroupRequest struct { - Emails []string `json:"emails"` + Emails []string `json:"emails"` + Group string `json:"group"` + Selection *service.GroupClientSelection `json:"selection"` } func (a *GroupController) bulkRemove(c *gin.Context) { @@ -191,12 +216,79 @@ func (a *GroupController) bulkRemove(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - affected, err := a.clientService.RemoveFromGroup(req.Emails) + if (req.Selection != nil && len(req.Emails) != 0) || (req.Selection == nil && req.Group != "") { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("use one client scope")) + return + } + var affected int + var err error + if req.Selection != nil { + affected, err = a.clientService.ChangeGroupSelection(c.Request.Context(), req.Group, "remove", *req.Selection) + } else { + affected, err = a.clientService.RemoveFromGroup(req.Emails) + } if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } jsonObj(c, gin.H{"affected": affected}, nil) - a.xrayService.SetToNeedRestart() - notifyClientsChanged() + if affected > 0 { + a.xrayService.SetToNeedRestart() + notifyClientsChanged() + } +} + +func (a *GroupController) clientPage(c *gin.Context) { + var params service.GroupClientPageParams + if err := c.ShouldBindQuery(¶ms); err != nil { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + return + } + page, err := a.clientService.ListGroupClients(c.Request.Context(), params) + jsonObj(c, page, err) +} + +func (a *GroupController) exportSubLinks(c *gin.Context) { + links, err := a.settingService.GetPanelSubscriptionLinks(c.Request.Host) + if err != nil { + c.String(http.StatusInternalServerError, "%s", I18nWeb(c, "somethingWentWrong")) + return + } + group := strings.TrimSpace(c.Query("group")) + if !links.Enable || links.URI == "" || group == "" { + c.String(http.StatusBadRequest, "group and enabled subscriptions are required") + return + } + + c.Header("Content-Type", "text/plain; charset=utf-8") + c.Header("Content-Disposition", `attachment; filename="sub-links.txt"`) + c.Header("Cache-Control", "no-store") + out := bufio.NewWriter(c.Writer) + first := true + err = a.clientService.WalkGroupSubscriptionClients(c.Request.Context(), group, func(email, subID string) error { + if !first { + if err := out.WriteByte('\n'); err != nil { + return err + } + } + first = false + if _, err := fmt.Fprintf(out, "%s\t%s%s", email, links.URI, subID); err != nil { + return err + } + if links.JSONEnable && links.JSONURI != "" { + _, err := fmt.Fprintf(out, "\t%s%s", links.JSONURI, subID) + return err + } + return nil + }) + if err == nil { + err = out.Flush() + } + if err != nil && c.Request.Context().Err() == nil { + logger.Warning("group subscription export failed:", err) + if !c.Writer.Written() { + c.Header("Content-Disposition", "") + c.String(http.StatusInternalServerError, "%s", I18nWeb(c, "somethingWentWrong")) + } + } } diff --git a/internal/web/controller/group_client_pages_test.go b/internal/web/controller/group_client_pages_test.go new file mode 100644 index 000000000..65a6ef3b2 --- /dev/null +++ b/internal/web/controller/group_client_pages_test.go @@ -0,0 +1,292 @@ +package controller + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/gin-gonic/gin" + + "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" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" + "github.com/mhsanaei/3x-ui/v3/internal/web/service" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +const groupAPI = "/panel/api/clients" + +func groupTestRouter(t *testing.T) *gin.Engine { + t.Helper() + cleanup, err := testpg.IsolatePackage("group_client_http") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db")) + router := gin.New() + routes := router.Group(groupAPI) + NewGroupController(routes) + NewClientController(routes) + return router +} + +func groupAPIRequest(router *gin.Engine, method, route, body string) *httptest.ResponseRecorder { + out := httptest.NewRecorder() + req := httptest.NewRequest(method, groupAPI+route, strings.NewReader(body)) + if method == http.MethodPost { + req.Header.Set("Content-Type", "application/json") + } + router.ServeHTTP(out, req) + return out +} + +func groupPage(t *testing.T, router *gin.Engine, query string) service.GroupClientPage { + t.Helper() + out := groupAPIRequest(router, http.MethodGet, "/groups/clientPage?"+query, "") + var result struct { + Success bool + Obj service.GroupClientPage + } + if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || !result.Success { + t.Fatalf("group page %q returned %s (%v)", query, out.Body, err) + } + return result.Obj +} + +func groupMutation(t *testing.T, router *gin.Engine, route string, body any, success bool, field string, want int) { + t.Helper() + payload, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + out := groupAPIRequest(router, http.MethodPost, route, string(payload)) + var result struct { + Success bool + Obj map[string]json.RawMessage + } + if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || result.Success != success { + t.Fatalf("%s returned %s (wanted success=%t): %v", route, out.Body, success, err) + } + if success { + var got int + if err := json.Unmarshal(result.Obj[field], &got); err != nil || got != want { + t.Fatalf("%s returned %s, want %s=%d", route, out.Body, field, want) + } + } +} + +func createTestGroupClients(t *testing.T, size, memberCount int) []model.ClientRecord { + t.Helper() + db := database.GetDB() + if err := db.Create(&model.ClientGroup{Name: "staff"}).Error; err != nil { + t.Fatal(err) + } + rows := make([]model.ClientRecord, size) + for i := range rows { + rows[i] = model.ClientRecord{Email: fmt.Sprintf("client-%06d", i), SubID: fmt.Sprintf("s-%06d", i), Comment: "literal_%", Group: "previous", TotalGB: 1024, Enable: true} + if i < memberCount { + rows[i].Group = "staff" + } + } + if err := db.CreateInBatches(rows, 300).Error; err != nil { + t.Fatal(err) + } + return rows +} + +func TestGroupClientPageAndFrozenWriteHTTP(t *testing.T) { + router := groupTestRouter(t) + rows := createTestGroupClients(t, 230, 110) + page := groupPage(t, router, "group=staff&mode=add&page=2") + if page.Total != 120 || len(page.Items) != 20 || page.Items[0].ID != rows[210].Id { + t.Fatalf("second add page = %d rows out of %d, expected clients 210–229", len(page.Items), page.Total) + } + search := url.QueryEscape("literal_%") + frozen := groupPage(t, router, "group=STAFF&mode=add&freeze=true&search="+search) + if frozen.Total != 120 || len(frozen.Items) != 0 || frozen.MaxID != rows[229].Id { + t.Fatalf("frozen add scope = %+v", frozen) + } + db := database.GetDB() + newer := model.ClientRecord{Email: "newer", Comment: "literal_%", Group: "previous"} + if err := db.Create(&newer).Error; err != nil { + t.Fatal(err) + } + alternate := model.ClientRecord{Email: "wildcard-would-match", Comment: "literalXY", Group: "previous"} + if err := db.Create(&alternate).Error; err != nil { + t.Fatal(err) + } + last := groupPage(t, router, fmt.Sprintf("group=staff&mode=add&page=2&maxId=%d&scopeSearch=%s", frozen.MaxID, search)) + if len(last.Items) != 22 || last.Items[20].InScope || last.Items[21].InScope || !last.Items[19].InScope { + t.Fatalf("new and out-of-filter clients were included in the frozen scope: %+v", last.Items) + } + selection := service.GroupClientSelection{ + Mode: "allMatching", ScopeToken: frozen.ScopeToken, + Search: "literal_%", ExcludedClientIDs: []int{rows[110].Id}, + } + body := map[string]any{"group": "staff", "selection": selection} + if err := db.Model(&rows[111]).UpdateColumn("group_name", "staff").Error; err != nil { + t.Fatal(err) + } + groupMutation(t, router, "/groups/bulkAdd", body, false, "", 0) + staff := groupPage(t, router, "group=staff&mode=remove") + if staff.Total != 111 { + t.Fatalf("stale selection changed client groups: staff=%d", staff.Total) + } + if err := db.Model(&rows[111]).UpdateColumn("group_name", "previous").Error; err != nil { + t.Fatal(err) + } + groupMutation(t, router, "/groups/bulkAdd", body, true, "affected", 119) + groupMutation(t, router, "/groups/bulkAdd", body, false, "", 0) + for _, id := range []int{rows[110].Id, newer.Id, alternate.Id} { + var row model.ClientRecord + if err := db.First(&row, id).Error; err != nil || row.Group != "previous" { + t.Fatalf("client %d left its group: %q, err=%v", id, row.Group, err) + } + } + selection = service.GroupClientSelection{Mode: "explicit", ClientIDs: []int{rows[0].Id, newer.Id}} + groupMutation(t, router, "/groups/bulkRemove", map[string]any{"group": "staff", "selection": selection}, false, "", 0) + selection.ClientIDs = []int{rows[0].Id, rows[0].Id} + groupMutation(t, router, "/groups/bulkRemove", map[string]any{"group": "staff", "selection": selection}, true, "affected", 1) + if page := groupPage(t, router, "group=staff&mode=remove&page=3"); page.Total != 228 || len(page.Items) != 28 { + t.Fatalf("remove page after mutations = %d out of %d", len(page.Items), page.Total) + } +} + +func TestGroupBulkOperationsRespectFrozenMembersHTTP(t *testing.T) { + router := groupTestRouter(t) + rows := createTestGroupClients(t, 6, 2) + freeze := groupPage(t, router, "group=staff&mode=remove&freeze=true") + db := database.GetDB() + if err := db.Model(&rows[0]).UpdateColumn("group_name", "previous").Error; err != nil { + t.Fatal(err) + } + groupMutation(t, router, "/bulkDel", map[string]any{"group": "staff", "scopeToken": freeze.ScopeToken}, false, "", 0) + + freeze = groupPage(t, router, "group=staff&mode=remove&freeze=true") + body := map[string]any{"group": "staff", "scopeToken": freeze.ScopeToken} + newer := model.ClientRecord{Email: "new-member", Group: "staff", TotalGB: 1024} + if err := db.Create(&newer).Error; err != nil { + t.Fatal(err) + } + for _, record := range []model.ClientRecord{rows[0], rows[1], newer} { + if err := db.Create(&xray.ClientTraffic{Email: record.Email, Total: record.TotalGB, Enable: true}).Error; err != nil { + t.Fatal(err) + } + } + groupMutation(t, router, "/bulkAdjust", map[string]any{ + "group": "staff", "scopeToken": freeze.ScopeToken, "addBytes": 256, + }, true, "adjusted", 1) + for email, want := range map[string]int64{rows[0].Email: 1024, rows[1].Email: 1280, newer.Email: 1024} { + var row xray.ClientTraffic + if err := db.Where("email = ?", email).First(&row).Error; err != nil || row.Total != want { + t.Fatalf("client %s quota = %d, want %d: %v", email, row.Total, want, err) + } + } + groupMutation(t, router, "/bulkDel", body, true, "deleted", 1) + groupMutation(t, router, "/bulkDel", body, false, "", 0) + groupMutation(t, router, "/bulkDel", map[string]any{"emails": []string{rows[0].Email}}, true, "deleted", 1) + if page := groupPage(t, router, "group=staff&mode=remove"); page.Total != 1 || page.Items[0].ID != newer.Id { + t.Fatalf("bulk deletion selected clients outside the frozen scope: %+v", page) + } +} + +func TestGroupAdjustCapsReportedSkipsWithoutChangingExplicitResponses(t *testing.T) { + router := groupTestRouter(t) + rows := createTestGroupClients(t, 25, 25) + if err := database.GetDB().Model(&model.ClientRecord{}). + Where("group_name = ?", "staff").UpdateColumn("total_gb", 0).Error; err != nil { + t.Fatal(err) + } + emails := make([]string, len(rows)) + for i, row := range rows { + emails[i] = row.Email + } + var result struct { + Success bool + Obj service.BulkAdjustResult + } + groupResponse := groupAPIRequest(router, http.MethodPost, "/bulkAdjust", `{"group":"staff","addBytes":1}`) + if err := json.Unmarshal(groupResponse.Body.Bytes(), &result); err != nil || !result.Success || + result.Obj.Adjusted != 0 || len(result.Obj.Skipped) != 20 || result.Obj.SkippedCount != 25 { + t.Fatalf("group adjust response = %s (%v)", groupResponse.Body, err) + } + body, err := json.Marshal(map[string]any{"emails": emails, "addBytes": 1}) + if err != nil { + t.Fatal(err) + } + out := groupAPIRequest(router, http.MethodPost, "/bulkAdjust", string(body)) + result.Obj = service.BulkAdjustResult{} + if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || !result.Success || + result.Obj.Adjusted != 0 || len(result.Obj.Skipped) != 25 || strings.Contains(out.Body.String(), "skippedCount") { + t.Fatalf("explicit adjust response = %s (%v)", out.Body, err) + } +} + +func TestGroupSubscriptionExportAndPagingHTTP(t *testing.T) { + sizes := []int{1000} + if os.Getenv("XUI_SCALE_TEST") != "" { + sizes = append(sizes, 10000, 50000) + } + for _, size := range sizes { + t.Run(fmt.Sprint(size), func(t *testing.T) { + testGroupSubscriptionExportAndPaging(t, size) + }) + } +} + +func testGroupSubscriptionExportAndPaging(t *testing.T, size int) { + t.Helper() + router := groupTestRouter(t) + rows := createTestGroupClients(t, size, min(size, 10000)) + db := database.GetDB() + if err := db.Model(&rows[1]).UpdateColumn("sub_id", "").Error; err != nil { + t.Fatal(err) + } + for key, val := range map[string]string{ + "subEnable": "true", "subURI": "https://sub.example.test/plain/", "subJsonEnable": "true", "subJsonURI": "https://sub.example.test/json/", + } { + var setting model.Setting + if err := db.Where("key = ?", key).Assign(model.Setting{Value: val}).FirstOrCreate(&setting, model.Setting{Key: key}).Error; err != nil { + t.Fatal(err) + } + } + total := min(size, 10000) - 1 + page := groupPage(t, router, "group=staff&mode=links") + if os.Getenv("XUI_SCALE_TEST") != "" { + pageResponse := groupAPIRequest(router, http.MethodGet, "/groups/clientPage?group=staff&mode=links", "") + emailResponse := groupAPIRequest(router, http.MethodGet, "/groups/staff/emails", "") + t.Logf("%d clients, %d links: page %d bytes, legacy emails %d bytes", size, total, pageResponse.Body.Len(), emailResponse.Body.Len()) + } + if page.Total != int64(total) || len(page.Items) != 100 || page.Items[1].Email != rows[2].Email { + t.Fatalf("link page returned %d rows out of %d", len(page.Items), page.Total) + } + if size == 50000 { + add := groupPage(t, router, "group=staff&mode=add&page=400") + if add.Total != 40000 || len(add.Items) != 100 || add.Items[99].Email != rows[49999].Email { + t.Fatalf("last page of 40,000 candidates returned %d out of %d", len(add.Items), add.Total) + } + } + out := groupAPIRequest(router, http.MethodGet, "/groups/subLinks/export?group=staff", "") + lines := strings.Split(out.Body.String(), "\n") + if out.Code != http.StatusOK || out.Header().Get("Cache-Control") != "no-store" || len(lines) != total { + t.Fatalf("export returned HTTP %d and %d rows, want %d rows", out.Code, len(lines), total) + } + for index, line := range lines { + if index > 0 { + index++ + } + row := rows[index] + want := row.Email + "\thttps://sub.example.test/plain/" + row.SubID + "\thttps://sub.example.test/json/" + row.SubID + if line != want { + t.Fatalf("export row %d = %q, want %q", index, line, want) + } + } +} diff --git a/internal/web/controller/group_client_scope_test.go b/internal/web/controller/group_client_scope_test.go new file mode 100644 index 000000000..6fd83876a --- /dev/null +++ b/internal/web/controller/group_client_scope_test.go @@ -0,0 +1,85 @@ +package controller + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + + "github.com/gin-gonic/gin" + + "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" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" +) + +func TestGroupBulkAddResolvesInboundMembershipHTTP(t *testing.T) { + cleanup, err := testpg.IsolatePackage("group_client_http") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db")) + db := database.GetDB() + first := model.Inbound{Tag: "source", Port: 50111, Protocol: model.VLESS, Settings: `{"clients":[{"email":"shared"}]}`} + second := model.Inbound{Tag: "other", Port: 50112, Protocol: model.VLESS, Settings: `{"clients":[{"email":"shared"},{"email":"other"}]}`} + shared := model.ClientRecord{Email: "shared", Group: "previous"} + other := model.ClientRecord{Email: "other", Group: "previous"} + for _, row := range []any{&first, &second, &shared, &other} { + if err := db.Create(row).Error; err != nil { + t.Fatal(err) + } + } + links := []model.ClientInbound{ + {ClientId: shared.Id, InboundId: first.Id}, + {ClientId: shared.Id, InboundId: second.Id}, + {ClientId: other.Id, InboundId: second.Id}, + } + if err := db.Create(&links).Error; err != nil { + t.Fatal(err) + } + originalSettings := second.Settings + if err := db.Model(&second).UpdateColumn("settings", "{").Error; err != nil { + t.Fatal(err) + } + router := gin.New() + NewGroupController(router.Group("/panel/api/clients")) + groupMutation(t, router, "/groups/bulkAdd", map[string]any{"group": "staff", "inboundId": first.Id}, false, "", 0) + var unchanged model.ClientRecord + if err := db.First(&unchanged, shared.Id).Error; err != nil || unchanged.Group != "previous" { + t.Fatalf("malformed sibling inbound left a committed group change: %q, err=%v", unchanged.Group, err) + } + if err := db.Model(&second).UpdateColumn("settings", originalSettings).Error; err != nil { + t.Fatal(err) + } + body := fmt.Sprintf(`{"group":"staff","inboundId":%d}`, first.Id) + for _, want := range []int{1, 0} { + req := httptest.NewRequest(http.MethodPost, "/panel/api/clients/groups/bulkAdd", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + out := httptest.NewRecorder() + router.ServeHTTP(out, req) + var result struct { + Success bool + Obj struct{ Affected int } + } + if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || !result.Success || result.Obj.Affected != want { + t.Fatalf("group add returned %s, want %d changed: %v", out.Body, want, err) + } + } + for id, want := range map[int]string{shared.Id: "staff", other.Id: "previous"} { + var got model.ClientRecord + if err := db.First(&got, id).Error; err != nil || got.Group != want { + t.Fatalf("client %d group = %q, want %q: %v", id, got.Group, want, err) + } + } + for _, id := range []int{first.Id, second.Id} { + var inbound model.Inbound + if err := db.First(&inbound, id).Error; err != nil || !strings.Contains(inbound.Settings, `"group":"staff"`) { + t.Fatalf("inbound %d settings were not updated: %s (%v)", id, inbound.Settings, err) + } + } +} diff --git a/internal/web/service/client_attach_selection.go b/internal/web/service/client_attach_selection.go index a02179f11..5b5654f02 100644 --- a/internal/web/service/client_attach_selection.go +++ b/internal/web/service/client_attach_selection.go @@ -148,7 +148,7 @@ func filteredAttachCandidates(q *gorm.DB, sourceID int, search, group string) *g return q } -func writeAttachID(h hash.Hash, id int) { +func writeClientScopeID(h hash.Hash, id int) { var buf [8]byte binary.BigEndian.PutUint64(buf[:], uint64(id)) _, _ = h.Write(buf[:]) @@ -156,10 +156,10 @@ func writeAttachID(h hash.Hash, id int) { func attachScopeHash(sourceID int, targets []int) hash.Hash { h := sha256.New() - writeAttachID(h, sourceID) - writeAttachID(h, len(targets)) + writeClientScopeID(h, sourceID) + writeClientScopeID(h, len(targets)) for _, id := range targets { - writeAttachID(h, id) + writeClientScopeID(h, id) } return h } @@ -201,14 +201,14 @@ func (s *ClientService) ListAttachCandidates(ctx context.Context, p AttachCandid if err := rows.Scan(&id); err != nil { return nil, err } - writeAttachID(h, id) + writeClientScopeID(h, id) resp.Eligible++ resp.MaxID = id } if err := rows.Err(); err != nil { return nil, err } - writeAttachID(h, resp.MaxID) + writeClientScopeID(h, resp.MaxID) resp.ScopeToken = strconv.Itoa(resp.MaxID) + "." + hex.EncodeToString(h.Sum(nil)) return resp, nil } @@ -294,14 +294,14 @@ func (s *ClientService) BulkAttachSelection(ctx context.Context, inboundSvc *Inb } records = eligibleRecords[:0] for _, record := range eligibleRecords { - writeAttachID(h, record.Id) + writeClientScopeID(h, record.Id) if _, skip := excluded[record.Id]; skip { delete(excluded, record.Id) continue } records = append(records, record) } - writeAttachID(h, maxID) + writeClientScopeID(h, maxID) if len(excluded) > 0 || hex.EncodeToString(h.Sum(nil)) != digest { return nil, false, stale } diff --git a/internal/web/service/client_bulk.go b/internal/web/service/client_bulk.go index ea249ba19..28f8124cf 100644 --- a/internal/web/service/client_bulk.go +++ b/internal/web/service/client_bulk.go @@ -296,6 +296,7 @@ type inboundApplyOutcome struct { // BulkAdjustResult reports changed clients and per-client skip reasons. // ExternalLinks contains row counts only for append requests. type BulkAdjustResult struct { + SkippedCount int `json:"skippedCount,omitempty" example:"0"` Adjusted int `json:"adjusted" example:"2"` Skipped []BulkAdjustReport `json:"skipped,omitempty" example:"[]"` ExternalLinks *BulkExternalLinksResult `json:"externalLinks,omitempty"` @@ -879,8 +880,9 @@ func (s *ClientService) bulkAdjustInboundClients( // BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email // skip reasons when an email could not be processed. type BulkDeleteResult struct { - Deleted int `json:"deleted"` - Skipped []BulkDeleteReport `json:"skipped,omitempty"` + SkippedCount int `json:"skippedCount,omitempty" example:"0"` + Deleted int `json:"deleted"` + Skipped []BulkDeleteReport `json:"skipped,omitempty"` } type BulkDeleteReport struct { diff --git a/internal/web/service/client_group_scope.go b/internal/web/service/client_group_scope.go new file mode 100644 index 000000000..186f042e6 --- /dev/null +++ b/internal/web/service/client_group_scope.go @@ -0,0 +1,350 @@ +package service + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "hash" + "strconv" + "strings" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +const ( + groupClientPageSize = 100 + maxGroupSelectionExclusions = 1000 +) + +var errGroupSelectionStale = errors.New("client group selection changed. Reopen the action or select clients again.") + +type GroupClientPageParams struct { + Group string `form:"group"` + Mode string `form:"mode"` + Page int `form:"page"` + Search string `form:"search"` + Freeze bool `form:"freeze"` + ScopeSearch string `form:"scopeSearch"` + MaxID *int `form:"maxId"` +} + +type GroupClientRow struct { + ID int `json:"id" example:"1"` + Email string `json:"email" example:"alice"` + Comment string `json:"comment" example:"Example client"` + Group string `json:"group" example:"staff"` + Enable bool `json:"enable" example:"true"` + SubID string `json:"subId" example:"example-sub-id"` + InScope bool `json:"inScope" example:"true"` +} + +type GroupClientPage struct { + Items []GroupClientRow `json:"items"` + Total int64 `json:"total" example:"120"` + ScopeToken string `json:"scopeToken,omitempty"` + MaxID int `json:"maxId,omitempty"` +} + +type GroupClientSelection struct { + Mode string `json:"mode" example:"allMatching"` + ClientIDs []int `json:"clientIds,omitempty"` + ExcludedClientIDs []int `json:"excludedClientIds,omitempty"` + ScopeToken string `json:"scopeToken,omitempty"` + Search string `json:"search,omitempty"` +} + +type groupClientScope struct { + name string + mode string +} + +func (scope groupClientScope) candidates(db *gorm.DB) *gorm.DB { + q := attachCandidates(db, 0) + if scope.mode == "add" { + return q.Where("COALESCE(c.group_name, '') <> ?", scope.name) + } + q = q.Where("c.group_name = ?", scope.name) + if scope.mode == "links" { + q = q.Where("c.sub_id <> ''") + } + return q +} + +func findGroupClientScope(db *gorm.DB, group, mode string) (groupClientScope, error) { + group = strings.TrimSpace(group) + if group == "" || (mode != "add" && mode != "remove" && mode != "links") { + return groupClientScope{}, fmt.Errorf("invalid client group scope") + } + if mode != "add" { + return groupClientScope{name: group, mode: mode}, nil + } + var stored model.ClientGroup + err := db.Where("LOWER(name) = LOWER(?)", group).Order("id").Take(&stored).Error + if err == nil { + return groupClientScope{name: stored.Name, mode: mode}, nil + } + if !errors.Is(err, gorm.ErrRecordNotFound) { + return groupClientScope{}, err + } + var derived model.ClientRecord + err = db.Table("clients").Where("group_name = ?", group).Select("id").Take(&derived).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return groupClientScope{}, fmt.Errorf("client group no longer exists") + } + return groupClientScope{name: group, mode: mode}, err +} + +func groupSearchCond(needle string) (string, []any) { + parts, args := clientTextSearch(caseVariants(needle), []string{"c.email", "c.comment", "c.group_name"}) + return "(" + strings.Join(parts, " OR ") + ")", args +} + +func groupClientSearch(q *gorm.DB, search string) *gorm.DB { + if needle := strings.TrimSpace(search); needle != "" { + filter, args := groupSearchCond(needle) + return q.Where(filter, args...) + } + return q +} + +func (scope groupClientScope) digest(search string) hash.Hash { + h := sha256.New() + for _, part := range []string{"group-client-scope", scope.mode, scope.name, strings.TrimSpace(search)} { + writeClientScopeID(h, len(part)) + _, _ = h.Write([]byte(part)) + } + return h +} + +func groupClientToken(h hash.Hash, maxID int) string { + writeClientScopeID(h, maxID) + return strconv.Itoa(maxID) + "." + hex.EncodeToString(h.Sum(nil)) +} + +func (s *ClientService) ListGroupClients(ctx context.Context, p GroupClientPageParams) (*GroupClientPage, error) { + if p.Page < 0 || p.Page > 1_000_000 || len(p.Search) > 1024 || len(p.ScopeSearch) > 1024 || + (p.MaxID != nil && *p.MaxID < 1) || (p.Freeze && p.Mode == "links") { + return nil, fmt.Errorf("invalid client group page") + } + db := database.GetDB().WithContext(ctx) + scope, err := findGroupClientScope(db, p.Group, p.Mode) + if err != nil { + return nil, err + } + page := &GroupClientPage{Items: []GroupClientRow{}} + q := groupClientSearch(scope.candidates(db), p.Search) + if p.Freeze { + rows, err := q.Select("c.id").Order("c.id").Rows() + if err != nil { + return nil, err + } + defer rows.Close() + h := scope.digest(p.Search) + for rows.Next() { + if err := rows.Scan(&page.MaxID); err != nil { + return nil, err + } + writeClientScopeID(h, page.MaxID) + page.Total++ + } + if err := rows.Err(); err != nil { + return nil, err + } + page.ScopeToken = groupClientToken(h, page.MaxID) + return page, nil + } + + if err := q.Session(&gorm.Session{}).Count(&page.Total).Error; err != nil { + return nil, err + } + const fields = "c.id, c.email, COALESCE(c.comment, '') AS comment, COALESCE(c.group_name, '') AS \"group\", COALESCE(c.enable, false) AS enable, COALESCE(c.sub_id, '') AS sub_id, " + inScope := "true" + var args []any + if p.MaxID != nil { + inScope = "(c.id <= ?)" + args = append(args, *p.MaxID) + if needle := strings.TrimSpace(p.ScopeSearch); needle != "" { + filter, filterArgs := groupSearchCond(needle) + inScope = "(" + inScope + " AND COALESCE(" + filter + ", false))" + args = append(args, filterArgs...) + } + } + order := "c.id" + if p.Mode == "links" { + order = "c.email, c.id" + } + err = q.Select(fields+inScope+" AS in_scope", args...).Order(order). + Offset(max(0, p.Page-1) * groupClientPageSize).Limit(groupClientPageSize).Scan(&page.Items).Error + return page, err +} + +func (scope groupClientScope) selectionEmails(db *gorm.DB, selection GroupClientSelection) ([]string, error) { + q := scope.candidates(db) + switch selection.Mode { + case "explicit": + if len(selection.ClientIDs) == 0 || len(selection.ClientIDs) > 50_000 || selection.ScopeToken != "" || + len(selection.ExcludedClientIDs) != 0 || selection.Search != "" { + return nil, fmt.Errorf("invalid explicit client group selection") + } + ids := uniqueInts(selection.ClientIDs) + var emails []string + for _, chunk := range chunkInts(ids, sqlInChunk) { + var part []string + if err := q.Session(&gorm.Session{}).Where("c.id IN ?", chunk).Pluck("c.email", &part).Error; err != nil { + return nil, err + } + if len(part) != len(chunk) { + return nil, errGroupSelectionStale + } + emails = append(emails, part...) + } + return emails, nil + case "allMatching": + return scope.frozenEmails(q, selection) + default: + return nil, fmt.Errorf("invalid client group selection mode") + } +} + +func (scope groupClientScope) frozenEmails(q *gorm.DB, selection GroupClientSelection) ([]string, error) { + cutoff, digest, ok := strings.Cut(selection.ScopeToken, ".") + maxID, parseErr := strconv.Atoi(cutoff) + if !ok || parseErr != nil || maxID < 0 || len(digest) != sha256.Size*2 || len(selection.ClientIDs) != 0 || + len(selection.ExcludedClientIDs) > maxGroupSelectionExclusions || len(selection.Search) > 1024 { + return nil, fmt.Errorf("invalid frozen client group selection") + } + excluded := make(map[int]struct{}, len(selection.ExcludedClientIDs)) + for _, id := range selection.ExcludedClientIDs { + excluded[id] = struct{}{} + } + rows, err := groupClientSearch(q, selection.Search).Where("c.id <= ?", maxID). + Select("c.id, c.email").Order("c.id").Rows() + if err != nil { + return nil, err + } + defer rows.Close() + h := scope.digest(selection.Search) + var emails []string + for rows.Next() { + var id int + var email string + if err := rows.Scan(&id, &email); err != nil { + return nil, err + } + writeClientScopeID(h, id) + if _, skip := excluded[id]; skip { + delete(excluded, id) + } else { + emails = append(emails, email) + } + } + if err := rows.Err(); err != nil { + return nil, err + } + if len(excluded) != 0 || groupClientToken(h, maxID) != selection.ScopeToken { + return nil, errGroupSelectionStale + } + return emails, nil +} + +func (s *ClientService) GroupOperationEmails(ctx context.Context, group, token string) ([]string, error) { + db := database.GetDB().WithContext(ctx) + scope, err := findGroupClientScope(db, group, "remove") + if err != nil { + return nil, err + } + if token != "" { + return scope.selectionEmails(db, GroupClientSelection{Mode: "allMatching", ScopeToken: token}) + } + var emails []string + err = scope.candidates(db).Order("c.id").Pluck("c.email", &emails).Error + return emails, err +} + +func (s *ClientService) ChangeGroupSelection(ctx context.Context, group, mode string, selection GroupClientSelection) (int, error) { + if mode != "add" && mode != "remove" { + return 0, fmt.Errorf("invalid client group action") + } + var affected int + err := runSerializedTx(func(tx *gorm.DB) error { + tx = tx.WithContext(ctx) + scope, err := findGroupClientScope(tx, group, mode) + if err != nil { + return err + } + emails, err := scope.selectionEmails(tx, selection) + if err != nil { + return err + } + target := "" + if mode == "add" && len(emails) != 0 { + record, err := database.EnsureClientGroup(tx, scope.name) + if err != nil { + return err + } + target = record.Name + } + affected, err = applyClientGroup(tx, emails, target) + return err + }) + return affected, err +} + +func (s *ClientService) AddInboundToGroup(ctx context.Context, inboundID int, group string) (int, error) { + if inboundID <= 0 { + return 0, fmt.Errorf("invalid source inbound ID") + } + var affected int + err := runSerializedTx(func(tx *gorm.DB) error { + tx = tx.WithContext(ctx) + var inbound model.Inbound + if err := tx.Select("id").First(&inbound, inboundID).Error; err != nil { + return err + } + var emails []string + if err := attachCandidates(tx, inbound.Id).Pluck("c.email", &emails).Error; err != nil { + return err + } + if len(emails) == 0 { + return nil + } + target, err := database.EnsureClientGroup(tx, group) + if err != nil { + return err + } + if target == nil { + return fmt.Errorf("group name is required") + } + affected, err = applyClientGroup(tx, emails, target.Name) + return err + }) + return affected, err +} + +func (s *ClientService) WalkGroupSubscriptionClients(ctx context.Context, group string, visit func(email, subID string) error) error { + db := database.GetDB().WithContext(ctx) + scope, err := findGroupClientScope(db, group, "links") + if err != nil { + return err + } + rows, err := scope.candidates(db).Select("c.email, c.sub_id").Order("c.email, c.id").Rows() + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var email, subID string + if err := rows.Scan(&email, &subID); err != nil { + return err + } + if err := visit(email, subID); err != nil { + return err + } + } + return rows.Err() +} diff --git a/internal/web/service/client_groups.go b/internal/web/service/client_groups.go index 5bee1cd68..052c908cd 100644 --- a/internal/web/service/client_groups.go +++ b/internal/web/service/client_groups.go @@ -340,129 +340,132 @@ func (s *ClientService) AddToGroup(emails []string, group string) (int, error) { if len(emails) == 0 { return 0, nil } - db := database.GetDB() - - if group != "" { - record, err := database.EnsureClientGroup(db, group) - if err != nil { - return 0, err + var affected int + err := runSerializedTx(func(tx *gorm.DB) error { + if group != "" { + record, err := database.EnsureClientGroup(tx, group) + if err != nil { + return err + } + group = record.Name } - group = record.Name - } + var err error + affected, err = applyClientGroup(tx, emails, group) + return err + }) + return affected, err +} - var records []model.ClientRecord - for _, batch := range chunkStrings(emails, sqlInChunk) { - var rows []model.ClientRecord - if err := db.Where("email IN ?", batch). - Where("group_name IS NULL OR group_name <> ?", group). - Find(&rows).Error; err != nil { - return 0, err - } - records = append(records, rows...) - } - if len(records) == 0 { - return 0, nil - } - affectedEmails := make([]string, 0, len(records)) - for _, r := range records { - affectedEmails = append(affectedEmails, r.Email) - } - - tx := db.Begin() +func applyClientGroup(tx *gorm.DB, emails []string, group string) (int, error) { + var affectedEmails []string var affected int64 - for _, batch := range chunkStrings(affectedEmails, sqlInChunk) { - result := tx.Model(&model.ClientRecord{}). - Where("email IN ?", batch). - Where("group_name IS NULL OR group_name <> ?", group). - UpdateColumn("group_name", group) + inboundIDs := make(map[int]struct{}) + for _, batch := range chunkStrings(emails, sqlInChunk) { + var changed []string + if err := tx.Model(&model.ClientRecord{}). + Where("email IN ? AND (group_name IS NULL OR group_name <> ?)", batch, group). + Pluck("email", &changed).Error; err != nil { + return 0, err + } + if len(changed) == 0 { + continue + } + result := tx.Model(&model.ClientRecord{}).Where("email IN ?", changed).UpdateColumn("group_name", group) if result.Error != nil { - tx.Rollback() return 0, result.Error } affected += result.RowsAffected - } + affectedEmails = append(affectedEmails, changed...) - var inboundIDs []int - inboundIDSeen := make(map[int]struct{}) - for _, batch := range chunkStrings(affectedEmails, sqlInChunk) { var ids []int if err := tx.Table("client_inbounds"). Joins("JOIN clients ON clients.id = client_inbounds.client_id"). - Where("clients.email IN ?", batch). + Where("clients.email IN ?", changed). Distinct("client_inbounds.inbound_id"). Pluck("inbound_id", &ids).Error; err != nil { - tx.Rollback() return 0, err } for _, id := range ids { - if _, ok := inboundIDSeen[id]; !ok { - inboundIDSeen[id] = struct{}{} - inboundIDs = append(inboundIDs, id) - } + inboundIDs[id] = struct{}{} } } - emailSet := make(map[string]struct{}, len(affectedEmails)) - for _, e := range affectedEmails { - emailSet[e] = struct{}{} + for _, email := range affectedEmails { + emailSet[email] = struct{}{} } - - for _, ibID := range inboundIDs { + dirtyNodes := make(map[int]struct{}) + for _, id := range sortedInboundIds(inboundIDs) { var ib model.Inbound - if err := tx.First(&ib, ibID).Error; err != nil { - tx.Rollback() + if err := tx.Select("id", "settings", "node_id").First(&ib, id).Error; err != nil { return 0, err } - var settings map[string]any - if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil { - continue + settings, changed, err := patchInboundClientGroup(ib.Settings, emailSet, group) + if err != nil { + return 0, err } - clients, ok := settings["clients"].([]any) - if !ok { - continue - } - modified := false - for i := range clients { - cm, ok := clients[i].(map[string]any) - if !ok { - continue - } - email, _ := cm["email"].(string) - if _, hit := emailSet[email]; !hit { - continue - } - if group == "" { - delete(cm, "group") - } else { - cm["group"] = group - } - clients[i] = cm - modified = true - } - if modified { - settings["clients"] = clients - newSettings, err := json.Marshal(settings) - if err != nil { - continue - } - ib.Settings = string(newSettings) - if err := tx.Save(&ib).Error; err != nil { - tx.Rollback() + if changed { + if err := tx.Model(&ib).UpdateColumn("settings", settings).Error; err != nil { return 0, err } + if ib.NodeID != nil { + dirtyNodes[*ib.NodeID] = struct{}{} + } } } - - if err := tx.Commit().Error; err != nil { - return 0, err + for _, id := range sortedInboundIds(dirtyNodes) { + if err := (&NodeService{}).MarkNodeDirtyTx(tx, id); err != nil { + return 0, err + } } return int(affected), nil } +func patchInboundClientGroup(raw string, emails map[string]struct{}, group string) (string, bool, error) { + settings, entries, ok := splitSettingsClients(raw) + if !ok { + return "", false, common.NewError("invalid inbound client settings") + } + groupValue, err := json.Marshal(group) + if err != nil { + return "", false, err + } + changed := false + for i, entry := range entries { + client, ok := readSettingsClient(entry) + if !ok { + continue + } + if _, match := emails[client.Email]; !match { + continue + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(entry, &fields); err != nil { + return "", false, err + } + if group == "" { + delete(fields, "group") + } else { + fields["group"] = groupValue + } + entries[i], err = json.Marshal(fields) + if err != nil { + return "", false, err + } + changed = true + } + if !changed { + return raw, false, nil + } + out, ok := joinSettingsClients(raw, settings, entries) + if !ok { + return "", false, common.NewError("invalid inbound client settings") + } + return out, true, nil +} + func (s *ClientService) replaceGroupValue(oldName, newName string, hostGroupIDs *[]string) (int, error) { - db := database.GetDB() affected := 0 - err := db.Transaction(func(tx *gorm.DB) error { + err := runSerializedTx(func(tx *gorm.DB) error { var hostGroupValues []string if hostGroupIDs != nil { hostGroupValues = normalizeHostGroupIDs(*hostGroupIDs) diff --git a/internal/web/service/client_paging.go b/internal/web/service/client_paging.go index 8c3c0e55f..98814826d 100644 --- a/internal/web/service/client_paging.go +++ b/internal/web/service/client_paging.go @@ -140,10 +140,17 @@ func caseVariants(s string) []string { // clientSearchCond builds the search predicate for the given needle variants // (lowered first) and returns its arguments. func clientSearchCond(variants []string) (string, []any) { + parts, args := clientTextSearch(variants, clientSearchCols) + parts = append(parts, "(COALESCE(c.tg_id, 0) <> 0 AND CAST(c.tg_id AS TEXT) LIKE ? ESCAPE '\\')") + args = append(args, "%"+escapeLikeLiteral(variants[0])+"%") + return "(" + strings.Join(parts, " OR ") + ")", args +} + +func clientTextSearch(variants, columns []string) ([]string, []any) { var parts []string var args []any like := func(v string) string { return "%" + escapeLikeLiteral(v) + "%" } - for _, col := range clientSearchCols { + for _, col := range columns { parts = append(parts, "LOWER("+col+") LIKE ? ESCAPE '\\'") args = append(args, like(variants[0])) for _, v := range variants { @@ -151,9 +158,7 @@ func clientSearchCond(variants []string) (string, []any) { args = append(args, like(v)) } } - parts = append(parts, "(COALESCE(c.tg_id, 0) <> 0 AND CAST(c.tg_id AS TEXT) LIKE ? ESCAPE '\\')") - args = append(args, like(variants[0])) - return "(" + strings.Join(parts, " OR ") + ")", args + return parts, args } // clientQuery builds the statements behind the clients page: a clients row diff --git a/internal/web/service/setting.go b/internal/web/service/setting.go index f801e920e..3857f46ed 100644 --- a/internal/web/service/setting.go +++ b/internal/web/service/setting.go @@ -2123,6 +2123,42 @@ func (s *SettingService) BuildSubURIBase(host string) string { return fmt.Sprintf("%s://%s:%d", scheme, subDomain, subPort) } +type PanelSubscriptionLinks struct { + Enable bool + JSONEnable bool + URI string + JSONURI string +} + +func (s *SettingService) GetPanelSubscriptionLinks(host string) (PanelSubscriptionLinks, error) { + var links PanelSubscriptionLinks + var err error + if links.Enable, err = s.GetSubEnable(); err != nil { + return links, err + } + if links.JSONEnable, err = s.GetSubJsonEnable(); err != nil { + return links, err + } + if links.URI, err = s.GetSubURI(); err != nil { + return links, err + } + if links.JSONURI, err = s.GetSubJsonURI(); err != nil { + return links, err + } + if (links.Enable && links.URI == "") || (links.JSONEnable && links.JSONURI == "") { + base := s.BuildSubURIBase(host) + if links.Enable && links.URI == "" { + path, _ := s.GetSubPath() + links.URI = base + path + } + if links.JSONEnable && links.JSONURI == "" { + path, _ := s.GetSubJsonPath() + links.JSONURI = base + path + } + } + return links, nil +} + func (s *SettingService) GetDefaultSettings(host string) (any, error) { type settingFunc func() (any, error) settings := map[string]settingFunc{ @@ -2134,12 +2170,8 @@ func (s *SettingService) GetDefaultSettings(host string) (any, error) { "tgBotEnable": func() (any, error) { return s.GetTgbotEnabled() }, "subThemeDir": func() (any, error) { return s.GetSubThemeDir() }, "happLinkEnable": func() (any, error) { return s.GetHappLinkEnable() }, - "subEnable": func() (any, error) { return s.GetSubEnable() }, - "subJsonEnable": func() (any, error) { return s.GetSubJsonEnable() }, "subClashEnable": func() (any, error) { return s.GetSubClashEnable() }, "subTitle": func() (any, error) { return s.GetSubTitle() }, - "subURI": func() (any, error) { return s.GetSubURI() }, - "subJsonURI": func() (any, error) { return s.GetSubJsonURI() }, "subClashURI": func() (any, error) { return s.GetSubClashURI() }, "datepicker": func() (any, error) { return s.GetDatepicker() }, "ipLimitEnable": func() (any, error) { return s.GetIpLimitEnable() }, @@ -2160,39 +2192,18 @@ func (s *SettingService) GetDefaultSettings(host string) (any, error) { result[key] = value } - subEnable := result["subEnable"].(bool) - subJsonEnable := false - if v, ok := result["subJsonEnable"]; ok { - if b, ok2 := v.(bool); ok2 { - subJsonEnable = b - } + links, err := s.GetPanelSubscriptionLinks(host) + if err != nil { + return "", err } - subClashEnable := false - if v, ok := result["subClashEnable"]; ok { - if b, ok2 := v.(bool); ok2 { - subClashEnable = b - } + result["subEnable"] = links.Enable + result["subJsonEnable"] = links.JSONEnable + result["subURI"] = links.URI + result["subJsonURI"] = links.JSONURI + if result["subClashEnable"].(bool) && result["subClashURI"].(string) == "" { + path, _ := s.GetSubClashPath() + result["subClashURI"] = s.BuildSubURIBase(host) + path } - if (subEnable && result["subURI"].(string) == "") || (subJsonEnable && result["subJsonURI"].(string) == "") || (subClashEnable && result["subClashURI"].(string) == "") { - subURI := s.BuildSubURIBase(host) - subTitle, _ := s.GetSubTitle() - subPath, _ := s.GetSubPath() - subJsonPath, _ := s.GetSubJsonPath() - subClashPath, _ := s.GetSubClashPath() - if subEnable && result["subURI"].(string) == "" { - result["subURI"] = subURI + subPath - } - if result["subTitle"].(string) == "" { - result["subTitle"] = subTitle - } - if subJsonEnable && result["subJsonURI"].(string) == "" { - result["subJsonURI"] = subURI + subJsonPath - } - if subClashEnable && result["subClashURI"].(string) == "" { - result["subClashURI"] = subURI + subClashPath - } - } - return result, nil } diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index 7238b0965..fc6697f0b 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -1202,6 +1202,8 @@ "addToGroupEmpty": "لا يوجد عملاء آخرون للإضافة.", "addToGroupResult": "تمت إضافة {count} عميل إلى {name}.", "removeFromGroup": "إزالة عملاء…", + "selectAllMatching": "تحديد كل العملاء المطابقين", + "selectionLimit": "الحد الأقصى للاختيارات أو الاستثناءات هو {count}.", "removeFromGroupTitle": "إزالة عملاء من المجموعة «{name}»", "removeFromGroupDesc": "اختر الأعضاء لإزالتهم من هذه المجموعة. يُحفظ العملاء (استخدم «حذف عملاء المجموعة» للإزالة الكاملة).", "removeFromGroupResult": "تمت إزالة {count} عميل من {name}.", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 5df5f1e61..4d82ec559 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -1202,6 +1202,8 @@ "addToGroupEmpty": "No other clients available to add.", "addToGroupResult": "Added {count} client(s) to {name}.", "removeFromGroup": "Remove clients…", + "selectAllMatching": "Select all matching clients", + "selectionLimit": "Limit selections or exclusions to {count}.", "removeFromGroupTitle": "Remove clients from group \"{name}\"", "removeFromGroupDesc": "Select members to remove from this group. Clients themselves are kept (use \"Delete clients in group\" to remove them entirely).", "removeFromGroupResult": "Removed {count} client(s) from {name}.", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index df05bd18f..65023c1bd 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -1202,6 +1202,8 @@ "addToGroupEmpty": "No hay otros clientes disponibles para añadir.", "addToGroupResult": "Añadidos {count} cliente(s) a {name}.", "removeFromGroup": "Quitar clientes…", + "selectAllMatching": "Seleccionar todos los clientes coincidentes", + "selectionLimit": "Limita la selección o las exclusiones a {count}.", "removeFromGroupTitle": "Quitar clientes del grupo «{name}»", "removeFromGroupDesc": "Selecciona miembros para quitar de este grupo. Los clientes se conservan (usa «Eliminar clientes del grupo» para eliminarlos por completo).", "removeFromGroupResult": "Quitados {count} cliente(s) de {name}.", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index b89862162..b4c7f4f93 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -1202,6 +1202,8 @@ "addToGroupEmpty": "کاربر دیگری برای افزودن در دسترس نیست.", "addToGroupResult": "{count} کاربر به {name} اضافه شد.", "removeFromGroup": "حذف کاربران…", + "selectAllMatching": "انتخاب همهٔ کاربران مطابق جستجو", + "selectionLimit": "تعداد انتخاب‌ها یا استثناها را به {count} محدود کنید.", "removeFromGroupTitle": "حذف کاربران از گروه «{name}»", "removeFromGroupDesc": "اعضایی را برای حذف از این گروه انتخاب کنید. خود کاربران حفظ می‌شوند (برای حذف کامل از «حذف کاربران گروه» استفاده کنید).", "removeFromGroupResult": "{count} کاربر از {name} حذف شد.", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 77df99297..1490a9267 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -1202,6 +1202,8 @@ "addToGroupEmpty": "Tidak ada klien lain untuk ditambahkan.", "addToGroupResult": "{count} klien ditambahkan ke {name}.", "removeFromGroup": "Hapus klien…", + "selectAllMatching": "Pilih semua klien yang cocok", + "selectionLimit": "Batasi pilihan atau pengecualian hingga {count}.", "removeFromGroupTitle": "Hapus klien dari grup «{name}»", "removeFromGroupDesc": "Pilih anggota untuk dihapus dari grup ini. Klien tetap dipertahankan (gunakan «Hapus klien di grup» untuk menghapus sepenuhnya).", "removeFromGroupResult": "{count} klien dihapus dari {name}.", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index 34cdd4de0..fed3bb1cf 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -1202,6 +1202,8 @@ "addToGroupEmpty": "追加可能な他のクライアントはありません。", "addToGroupResult": "{count} クライアントを {name} に追加しました。", "removeFromGroup": "クライアントを削除…", + "selectAllMatching": "一致するクライアントをすべて選択", + "selectionLimit": "選択または除外は {count} 件までです。", "removeFromGroupTitle": "グループ「{name}」からクライアントを削除", "removeFromGroupDesc": "このグループから外すメンバーを選択してください。クライアント自体は保持されます (完全に削除するには「グループのクライアントを削除」を使用)。", "removeFromGroupResult": "{count} クライアントを {name} から外しました。", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index 781f6cdb6..96872dda3 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -1202,6 +1202,8 @@ "addToGroupEmpty": "Não há outros clientes disponíveis para adicionar.", "addToGroupResult": "Adicionados {count} cliente(s) a {name}.", "removeFromGroup": "Remover clientes…", + "selectAllMatching": "Selecionar todos os clientes correspondentes", + "selectionLimit": "Limite as seleções ou exclusões a {count}.", "removeFromGroupTitle": "Remover clientes do grupo «{name}»", "removeFromGroupDesc": "Selecione membros para remover deste grupo. Os clientes em si são mantidos (use «Excluir clientes do grupo» para removê-los por completo).", "removeFromGroupResult": "Removidos {count} cliente(s) de {name}.", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 5b5065d8f..5fd430e96 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -1202,6 +1202,8 @@ "addToGroupEmpty": "Нет других клиентов для добавления.", "addToGroupResult": "Добавлено {count} клиент(ов) в {name}.", "removeFromGroup": "Удалить клиентов…", + "selectAllMatching": "Выбрать всех подходящих клиентов", + "selectionLimit": "Ограничьте число выбранных или исключённых клиентов до {count}.", "removeFromGroupTitle": "Удалить клиентов из группы «{name}»", "removeFromGroupDesc": "Выберите участников для удаления из этой группы. Сами клиенты сохраняются (используйте «Удалить клиентов группы» для полного удаления).", "removeFromGroupResult": "Удалено {count} клиент(ов) из {name}.", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index 175906240..18797252a 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -1202,6 +1202,8 @@ "addToGroupEmpty": "Nie sú dostupní žiadni ďalší klienti na pridanie.", "addToGroupResult": "Pridané do skupiny {name}: {count}.", "removeFromGroup": "Odobrať klientov…", + "selectAllMatching": "Vybrať všetkých zodpovedajúcich klientov", + "selectionLimit": "Obmedzte počet vybraných alebo vylúčených klientov na {count}.", "removeFromGroupTitle": "Odobrať klientov zo skupiny „{name}“", "removeFromGroupDesc": "Vyberte členov, ktorých chcete odobrať zo skupiny. Samotní klienti zostanú zachovaní. Na ich úplné odstránenie použite akciu „Odstrániť klientov v skupine“.", "removeFromGroupResult": "Odobraté zo skupiny {name}: {count}.", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index fbab4b889..0b849f394 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -1202,6 +1202,8 @@ "addToGroupEmpty": "Eklenecek başka kullanıcı yok.", "addToGroupResult": "{count} kullanıcı {name} grubuna eklendi.", "removeFromGroup": "Kullanıcı Çıkar…", + "selectAllMatching": "Eşleşen tüm istemcileri seç", + "selectionLimit": "Seçimleri veya hariç tutulanları {count} ile sınırlandırın.", "removeFromGroupTitle": "«{name}» Grubundan Kullanıcı Çıkar", "removeFromGroupDesc": "Bu gruptan çıkarılacak üyeleri seçin. Kullanıcılar korunur (tamamen kaldırmak için «Gruptaki kullanıcıları sil» kullanın).", "removeFromGroupResult": "{name} grubundan {count} kullanıcı çıkarıldı.", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index fb302d746..a06eff8e9 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -1202,6 +1202,8 @@ "addToGroupEmpty": "Немає інших клієнтів для додавання.", "addToGroupResult": "Додано {count} клієнт(ів) до {name}.", "removeFromGroup": "Видалити клієнтів…", + "selectAllMatching": "Вибрати всіх відповідних клієнтів", + "selectionLimit": "Обмежте кількість вибраних або виключених клієнтів до {count}.", "removeFromGroupTitle": "Видалити клієнтів з групи «{name}»", "removeFromGroupDesc": "Виберіть учасників для видалення з цієї групи. Самі клієнти зберігаються (використовуйте «Видалити клієнтів групи» для повного видалення).", "removeFromGroupResult": "Видалено {count} клієнт(ів) з {name}.", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index 52570f998..293ec83d5 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -1202,6 +1202,8 @@ "addToGroupEmpty": "Không có client khác để thêm.", "addToGroupResult": "Đã thêm {count} client vào {name}.", "removeFromGroup": "Xóa client…", + "selectAllMatching": "Chọn tất cả máy khách phù hợp", + "selectionLimit": "Giới hạn lựa chọn hoặc ngoại lệ ở mức {count}.", "removeFromGroupTitle": "Xóa client khỏi nhóm «{name}»", "removeFromGroupDesc": "Chọn thành viên để xóa khỏi nhóm này. Bản thân client được giữ lại (dùng «Xóa client trong nhóm» để xóa hoàn toàn).", "removeFromGroupResult": "Đã xóa {count} client khỏi {name}.", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index d10a4f91b..60d94a257 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -1202,6 +1202,8 @@ "addToGroupEmpty": "没有其他可添加的客户端。", "addToGroupResult": "已将 {count} 个客户端添加到 {name}。", "removeFromGroup": "移除客户端…", + "selectAllMatching": "选择所有匹配的客户端", + "selectionLimit": "选择或排除的项目最多为 {count} 个。", "removeFromGroupTitle": "从分组 “{name}” 移除客户端", "removeFromGroupDesc": "选择要从此分组中移除的成员。客户端本身保留(使用 “删除分组中的客户端” 完全移除)。", "removeFromGroupResult": "已从 {name} 移除 {count} 个客户端。", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index a736e06b7..cea16fcde 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -1202,6 +1202,8 @@ "addToGroupEmpty": "沒有其他可加入的客戶端。", "addToGroupResult": "已將 {count} 個客戶端加入 {name}。", "removeFromGroup": "移除客戶端…", + "selectAllMatching": "選取所有相符的用戶端", + "selectionLimit": "選取或排除的項目最多為 {count} 個。", "removeFromGroupTitle": "從群組「{name}」移除客戶端", "removeFromGroupDesc": "選擇要從此群組移除的成員。客戶端本身保留(用「刪除群組中的客戶端」完全移除)。", "removeFromGroupResult": "已從 {name} 移除 {count} 個客戶端。", diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go index f40382268..fe35e4bb3 100644 --- a/tools/openapigen/main.go +++ b/tools/openapigen/main.go @@ -114,6 +114,11 @@ func run(root, outDir string) error { "ClientPageResponse", "AttachCandidate", "AttachCandidatePage", + "GroupClientPage", + "GroupClientRow", + "GroupClientSelection", + "BulkDeleteResult", + "BulkDeleteReport", "AttachSelectionResult", "BulkAdjustResult", "BulkAdjustReport",