From 75dc6dc61c4d1a8eabd89287a4d5e43ff625cd7c Mon Sep 17 00:00:00 2001 From: Hamed Date: Sat, 28 Nov 2026 18:00:53 +0330 Subject: [PATCH] fix(inbounds): scale bulk client attachment selection (#7243) With around 10,000 clients both attach dialogs loaded every client, pre-selected all of them and rendered every row, which locked the browser for minutes. Both dialogs now ask the server for 100 rows at a time and render only the visible ones. Select All freezes the eligible client IDs that match the current search and group into a small server-issued token; the browser keeps that token plus the clients the operator unticked instead of thousands of emails, and the listing marks each row against the frozen filter so rows outside it stay unselected. On submit the server re-derives the same set and rejects the job before any write when its membership changed; clients created after the freeze stay outside it. The attach runs as a background job the dialog polls for counts. Requests that post an email list keep their synchronous response. The Postgres job now runs the selection tests, which build their predicates by hand for both dialects. Fixes #7236 --- .github/workflows/ci.yml | 10 + .../content/docs/en/reference/api/clients.mdx | 51 +- docs/public/openapi.json | 324 +++++++++++- frontend/public/openapi.json | 324 +++++++++++- frontend/src/generated/examples.ts | 40 ++ frontend/src/generated/schemas.ts | 134 +++++ frontend/src/generated/types.ts | 32 ++ frontend/src/generated/zod.ts | 36 ++ frontend/src/pages/api-docs/endpoints.ts | 92 +++- .../clients/AttachClientPickerModal.tsx | 497 ++++++++++++++++++ .../inbounds/clients/AttachClientsModal.tsx | 214 +------- .../clients/AttachExistingClientsModal.tsx | 244 +-------- .../src/test/attach-clients-modal.test.tsx | 224 +++++++- internal/web/controller/client.go | 30 +- internal/web/controller/client_attach_jobs.go | 118 +++++ .../web/controller/client_attach_jobs_test.go | 51 ++ .../web/service/client_attach_selection.go | 319 +++++++++++ .../service/client_attach_selection_test.go | 278 ++++++++++ internal/web/service/client_bulk.go | 28 +- internal/web/translation/ar-EG.json | 6 + internal/web/translation/en-US.json | 6 + internal/web/translation/es-ES.json | 6 + internal/web/translation/fa-IR.json | 6 + internal/web/translation/id-ID.json | 6 + internal/web/translation/ja-JP.json | 6 + internal/web/translation/pt-BR.json | 6 + internal/web/translation/ru-RU.json | 6 + internal/web/translation/sk-SK.json | 6 + internal/web/translation/tr-TR.json | 6 + internal/web/translation/uk-UA.json | 6 + internal/web/translation/vi-VN.json | 6 + internal/web/translation/zh-CN.json | 6 + internal/web/translation/zh-TW.json | 6 + tools/openapigen/main.go | 5 +- 34 files changed, 2643 insertions(+), 492 deletions(-) create mode 100644 frontend/src/pages/inbounds/clients/AttachClientPickerModal.tsx create mode 100644 internal/web/controller/client_attach_jobs.go create mode 100644 internal/web/controller/client_attach_jobs_test.go create mode 100644 internal/web/service/client_attach_selection.go create mode 100644 internal/web/service/client_attach_selection_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d244279bf..b48c8f061 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -163,6 +163,16 @@ jobs: exit 1 fi + - name: PostgreSQL attach candidate selection + run: | + set -o pipefail + go test ./internal/web/service -run '^Test(AttachCandidatesSelection|FrozenAttachSelectionFollowsFilter)Postgres$' -count=1 -v | tee /tmp/postgres-attach-selection.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-attach-selection.log || true) + if [ "$passed" -ne 2 ]; then + echo "expected 2 passing PostgreSQL attach selection tests, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL depletion query 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 eae5f2d48..8c344b2ce 100644 --- a/docs/content/docs/en/reference/api/clients.mdx +++ b/docs/content/docs/en/reference/api/clients.mdx @@ -13,6 +13,13 @@ _openapi: reverse field, if set, is returned as a nested JSON object (legacy JSON-encoded-string form is still accepted on write). url: '#list-every-client-with-its-attached-inbound-ids-and-traffic-record-the-reverse-field-if-set-is-returned-as-a-nested-json-object-legacy-json-encoded-string-form-is-still-accepted-on-write' + - depth: 2 + title: List up to 100 clients for the inbound attachment picker. Counts + distinguish filtered rows and all eligible clients. A freeze request + returns only the eligible count, maximum ID and a scope token covering + the eligible IDs that match the given search and group for the chosen + source and targets. + url: '#list-up-to-100-clients-for-the-inbound-attachment-picker-counts-distinguish-filtered-rows-and-all-eligible-clients-a-freeze-request-returns-only-the-eligible-count-maximum-id-and-a-scope-token-covering-the-eligible-ids-that-match-the-given-search-and-group-for-the-chosen-source-and-targets' - depth: 2 title: 'Filter, sort, and paginate clients on the server. Each item is a slim row (no uuid/password/auth/flow/security/reverse/tgId) so the clients @@ -206,9 +213,21 @@ _openapi: keeps its identity (email/UUID/password/subId) and a shared traffic row; all clients are added to a target inbound in a single AddInboundClient call. Clients already present on a target are reported under skipped. - Returns per-email attached/skipped/errors lists and triggers a single - Xray restart if any target inbound was running. - url: '#attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-returns-per-email-attachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running' + Explicit email requests return per-email lists. Alternatively submit + selection with explicit clientIds or a frozen allMatching scopeToken + plus excludedClientIds and the search and group it was frozen under. + Scoped requests start a background job and return {jobId}. Poll GET + /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay + outside the frozen scope. Changes to the frozen membership are rejected + before applying changes. Triggers a single Xray restart if any target + inbound was running. + url: '#attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-explicit-email-requests-return-per-email-lists-alternatively-submit-selection-with-explicit-clientids-or-a-frozen-allmatching-scopetoken-plus-excludedclientids-and-the-search-and-group-it-was-frozen-under-scoped-requests-start-a-background-job-and-return-jobid-poll-get-bulkattachid-for-counts-or-a-stale-selection-error-newer-ids-stay-outside-the-frozen-scope-changes-to-the-frozen-membership-are-rejected-before-applying-changes-triggers-a-single-xray-restart-if-any-target-inbound-was-running' + - depth: 2 + title: Poll a scoped attachment job. The result contains counts per target + (attached, skipped, errors); an operation failure sets error instead. + Completed results are retained for up to 15 minutes in the running panel + process. + url: '#poll-a-scoped-attachment-job-the-result-contains-counts-per-target-attached-skipped-errors-an-operation-failure-sets-error-instead-completed-results-are-retained-for-up-to-15-minutes-in-the-running-panel-process' - depth: 2 title: "Mirror of bulkAttach: detach many existing clients from many inbounds in one call. For each email, intersects the client's current inbounds with @@ -386,6 +405,12 @@ _openapi: reverse field, if set, is returned as a nested JSON object (legacy JSON-encoded-string form is still accepted on write). id: list-every-client-with-its-attached-inbound-ids-and-traffic-record-the-reverse-field-if-set-is-returned-as-a-nested-json-object-legacy-json-encoded-string-form-is-still-accepted-on-write + - content: List up to 100 clients for the inbound attachment picker. Counts + distinguish filtered rows and all eligible clients. A freeze request + returns only the eligible count, maximum ID and a scope token covering + the eligible IDs that match the given search and group for the chosen + source and targets. + id: list-up-to-100-clients-for-the-inbound-attachment-picker-counts-distinguish-filtered-rows-and-all-eligible-clients-a-freeze-request-returns-only-the-eligible-count-maximum-id-and-a-scope-token-covering-the-eligible-ids-that-match-the-given-search-and-group-for-the-chosen-source-and-targets - content: 'Filter, sort, and paginate clients on the server. Each item is a slim row (no uuid/password/auth/flow/security/reverse/tgId) so the clients page can ship 25-ish rows in a few KB instead of the full table. The @@ -551,10 +576,20 @@ _openapi: keeps its identity (email/UUID/password/subId) and a shared traffic row; all clients are added to a target inbound in a single AddInboundClient call. Clients already present on a target are - reported under skipped. Returns per-email attached/skipped/errors - lists and triggers a single Xray restart if any target inbound was - running. - id: attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-returns-per-email-attachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running + reported under skipped. Explicit email requests return per-email + lists. Alternatively submit selection with explicit clientIds or a + frozen allMatching scopeToken plus excludedClientIds and the search + and group it was frozen under. Scoped requests start a background job + and return {jobId}. Poll GET /bulkAttach/:id for counts or a + stale-selection error. Newer IDs stay outside the frozen scope. + Changes to the frozen membership are rejected before applying changes. + Triggers a single Xray restart if any target inbound was running. + id: attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-explicit-email-requests-return-per-email-lists-alternatively-submit-selection-with-explicit-clientids-or-a-frozen-allmatching-scopetoken-plus-excludedclientids-and-the-search-and-group-it-was-frozen-under-scoped-requests-start-a-background-job-and-return-jobid-poll-get-bulkattachid-for-counts-or-a-stale-selection-error-newer-ids-stay-outside-the-frozen-scope-changes-to-the-frozen-membership-are-rejected-before-applying-changes-triggers-a-single-xray-restart-if-any-target-inbound-was-running + - content: Poll a scoped attachment job. The result contains counts per target + (attached, skipped, errors); an operation failure sets error instead. + Completed results are retained for up to 15 minutes in the running + panel process. + id: poll-a-scoped-attachment-job-the-result-contains-counts-per-target-attached-skipped-errors-an-operation-failure-sets-error-instead-completed-results-are-retained-for-up-to-15-minutes-in-the-running-panel-process - content: "Mirror of bulkAttach: detach many existing clients from many inbounds in one call. For each email, intersects the client's current inbounds with the requested set and detaches from those only; (email, inbound) @@ -883,7 +918,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 32d2940e5..483eae866 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -1903,6 +1903,140 @@ ], "type": "object" }, + "AttachCandidate": { + "properties": { + "alreadyAttached": { + "example": false, + "type": "boolean" + }, + "comment": { + "example": "Example client", + "type": "string" + }, + "email": { + "example": "alice@example.test", + "type": "string" + }, + "enable": { + "example": true, + "type": "boolean" + }, + "group": { + "example": "staff", + "type": "string" + }, + "id": { + "example": 1, + "type": "integer" + }, + "inScope": { + "example": true, + "type": "boolean" + } + }, + "required": [ + "alreadyAttached", + "comment", + "email", + "enable", + "group", + "id", + "inScope" + ], + "type": "object" + }, + "AttachCandidatePage": { + "properties": { + "eligible": { + "example": 118, + "format": "int64", + "type": "integer" + }, + "groups": { + "example": [ + "staff" + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "items": { + "items": { + "$ref": "#/components/schemas/AttachCandidate" + }, + "type": "array" + }, + "maxId": { + "type": "integer" + }, + "scopeToken": { + "type": "string" + }, + "total": { + "example": 120, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "eligible", + "groups", + "items", + "total" + ], + "type": "object" + }, + "AttachJobStatus": { + "properties": { + "ended": { + "format": "date-time", + "type": "string" + }, + "error": { + "type": "string" + }, + "result": { + "allOf": [ + { + "$ref": "#/components/schemas/AttachSelectionResult" + } + ], + "nullable": true + }, + "running": { + "example": false, + "type": "boolean" + } + }, + "required": [ + "ended", + "running" + ], + "type": "object" + }, + "AttachSelectionResult": { + "properties": { + "attached": { + "example": 9997, + "type": "integer" + }, + "errors": { + "example": 0, + "type": "integer" + }, + "skipped": { + "example": 0, + "type": "integer" + } + }, + "required": [ + "attached", + "errors", + "skipped" + ], + "type": "object" + }, "Blocker": { "description": "Blocker is one unmet requirement.", "properties": { @@ -9479,6 +9613,135 @@ } } }, + "/panel/api/clients/attachCandidates": { + "get": { + "tags": [ + "Clients" + ], + "summary": "List up to 100 clients for the inbound attachment picker. Counts distinguish filtered rows and all eligible clients. A freeze request returns only the eligible count, maximum ID and a scope token covering the eligible IDs that match the given search and group for the chosen source and targets.", + "operationId": "get_panel_api_clients_attachCandidates", + "parameters": [ + { + "name": "sourceId", + "in": "query", + "required": false, + "description": "Restrict candidates to clients on this inbound.", + "schema": { + "type": "integer" + } + }, + { + "name": "inboundIds", + "in": "query", + "required": false, + "description": "Comma-separated target IDs. Required for freeze and if no source ID is specified.", + "schema": { + "type": "string" + } + }, + { + "name": "page", + "in": "query", + "required": false, + "description": "1-indexed page, defaults to 1.", + "schema": { + "type": "integer" + } + }, + { + "name": "search", + "in": "query", + "required": false, + "description": "Match email and either comment (with a source) or group.", + "schema": { + "type": "string" + } + }, + { + "name": "group", + "in": "query", + "required": false, + "description": "Filter by exact group when there is no source.", + "schema": { + "type": "string" + } + }, + { + "name": "freeze", + "in": "query", + "required": false, + "description": "Freeze the eligible IDs matching search and group, independently of page.", + "schema": { + "type": "boolean" + } + }, + { + "name": "scopeSearch", + "in": "query", + "required": false, + "description": "Search a frozen selection was taken under; rows outside it report inScope false.", + "schema": { + "type": "string" + } + }, + { + "name": "scopeGroup", + "in": "query", + "required": false, + "description": "Group a frozen selection was taken under; rows outside it report inScope false.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/AttachCandidatePage" + } + } + }, + "example": { + "success": true, + "obj": { + "eligible": 118, + "groups": [ + "staff" + ], + "items": [ + { + "alreadyAttached": false, + "comment": "Example client", + "email": "alice@example.test", + "enable": true, + "group": "staff", + "id": 1, + "inScope": true + } + ], + "maxId": 0, + "scopeToken": "", + "total": 120 + } + } + } + } + } + } + } + }, "/panel/api/clients/list/paged": { "get": { "tags": [ @@ -11719,7 +11982,7 @@ "tags": [ "Clients" ], - "summary": "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 AddInboundClient call. Clients already present on a target are reported under skipped. Returns per-email attached/skipped/errors lists and triggers a single Xray restart if any target inbound was running.", + "summary": "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 AddInboundClient call. Clients already present on a target are reported under skipped. Explicit email requests return per-email lists. Alternatively submit selection with explicit clientIds or a frozen allMatching scopeToken plus excludedClientIds and the search and group it was frozen under. Scoped requests start a background job and return {jobId}. Poll GET /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay outside the frozen scope. Changes to the frozen membership are rejected before applying changes. Triggers a single Xray restart if any target inbound was running.", "operationId": "post_panel_api_clients_bulkAttach", "requestBody": { "required": true, @@ -11733,7 +11996,11 @@ "items": { "type": "string" }, - "description": "Emails of existing clients to attach." + "description": "Emails of existing clients to attach. Omit when using selection." + }, + "selection": { + "type": "object", + "description": "Either {mode: \"explicit\", clientIds, sourceId?} or {mode: \"allMatching\", scopeToken, excludedClientIds?, search?, group?, sourceId?}." }, "inboundIds": { "type": "array", @@ -11744,7 +12011,6 @@ } }, "required": [ - "emails", "inboundIds" ] }, @@ -11797,6 +12063,58 @@ } } }, + "/panel/api/clients/bulkAttach/{id}": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Poll a scoped attachment job. The result contains counts per target (attached, skipped, errors); an operation failure sets error instead. Completed results are retained for up to 15 minutes in the running panel process.", + "operationId": "get_panel_api_clients_bulkAttach_id", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Job ID returned by the scoped bulkAttach request.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/AttachJobStatus" + } + } + }, + "example": { + "success": true, + "obj": { + "ended": "2025-01-01T00:00:00Z", + "error": "", + "result": null, + "running": false + } + } + } + } + } + } + } + }, "/panel/api/clients/bulkDetach": { "post": { "tags": [ diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 32d2940e5..483eae866 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -1903,6 +1903,140 @@ ], "type": "object" }, + "AttachCandidate": { + "properties": { + "alreadyAttached": { + "example": false, + "type": "boolean" + }, + "comment": { + "example": "Example client", + "type": "string" + }, + "email": { + "example": "alice@example.test", + "type": "string" + }, + "enable": { + "example": true, + "type": "boolean" + }, + "group": { + "example": "staff", + "type": "string" + }, + "id": { + "example": 1, + "type": "integer" + }, + "inScope": { + "example": true, + "type": "boolean" + } + }, + "required": [ + "alreadyAttached", + "comment", + "email", + "enable", + "group", + "id", + "inScope" + ], + "type": "object" + }, + "AttachCandidatePage": { + "properties": { + "eligible": { + "example": 118, + "format": "int64", + "type": "integer" + }, + "groups": { + "example": [ + "staff" + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "items": { + "items": { + "$ref": "#/components/schemas/AttachCandidate" + }, + "type": "array" + }, + "maxId": { + "type": "integer" + }, + "scopeToken": { + "type": "string" + }, + "total": { + "example": 120, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "eligible", + "groups", + "items", + "total" + ], + "type": "object" + }, + "AttachJobStatus": { + "properties": { + "ended": { + "format": "date-time", + "type": "string" + }, + "error": { + "type": "string" + }, + "result": { + "allOf": [ + { + "$ref": "#/components/schemas/AttachSelectionResult" + } + ], + "nullable": true + }, + "running": { + "example": false, + "type": "boolean" + } + }, + "required": [ + "ended", + "running" + ], + "type": "object" + }, + "AttachSelectionResult": { + "properties": { + "attached": { + "example": 9997, + "type": "integer" + }, + "errors": { + "example": 0, + "type": "integer" + }, + "skipped": { + "example": 0, + "type": "integer" + } + }, + "required": [ + "attached", + "errors", + "skipped" + ], + "type": "object" + }, "Blocker": { "description": "Blocker is one unmet requirement.", "properties": { @@ -9479,6 +9613,135 @@ } } }, + "/panel/api/clients/attachCandidates": { + "get": { + "tags": [ + "Clients" + ], + "summary": "List up to 100 clients for the inbound attachment picker. Counts distinguish filtered rows and all eligible clients. A freeze request returns only the eligible count, maximum ID and a scope token covering the eligible IDs that match the given search and group for the chosen source and targets.", + "operationId": "get_panel_api_clients_attachCandidates", + "parameters": [ + { + "name": "sourceId", + "in": "query", + "required": false, + "description": "Restrict candidates to clients on this inbound.", + "schema": { + "type": "integer" + } + }, + { + "name": "inboundIds", + "in": "query", + "required": false, + "description": "Comma-separated target IDs. Required for freeze and if no source ID is specified.", + "schema": { + "type": "string" + } + }, + { + "name": "page", + "in": "query", + "required": false, + "description": "1-indexed page, defaults to 1.", + "schema": { + "type": "integer" + } + }, + { + "name": "search", + "in": "query", + "required": false, + "description": "Match email and either comment (with a source) or group.", + "schema": { + "type": "string" + } + }, + { + "name": "group", + "in": "query", + "required": false, + "description": "Filter by exact group when there is no source.", + "schema": { + "type": "string" + } + }, + { + "name": "freeze", + "in": "query", + "required": false, + "description": "Freeze the eligible IDs matching search and group, independently of page.", + "schema": { + "type": "boolean" + } + }, + { + "name": "scopeSearch", + "in": "query", + "required": false, + "description": "Search a frozen selection was taken under; rows outside it report inScope false.", + "schema": { + "type": "string" + } + }, + { + "name": "scopeGroup", + "in": "query", + "required": false, + "description": "Group a frozen selection was taken under; rows outside it report inScope false.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/AttachCandidatePage" + } + } + }, + "example": { + "success": true, + "obj": { + "eligible": 118, + "groups": [ + "staff" + ], + "items": [ + { + "alreadyAttached": false, + "comment": "Example client", + "email": "alice@example.test", + "enable": true, + "group": "staff", + "id": 1, + "inScope": true + } + ], + "maxId": 0, + "scopeToken": "", + "total": 120 + } + } + } + } + } + } + } + }, "/panel/api/clients/list/paged": { "get": { "tags": [ @@ -11719,7 +11982,7 @@ "tags": [ "Clients" ], - "summary": "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 AddInboundClient call. Clients already present on a target are reported under skipped. Returns per-email attached/skipped/errors lists and triggers a single Xray restart if any target inbound was running.", + "summary": "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 AddInboundClient call. Clients already present on a target are reported under skipped. Explicit email requests return per-email lists. Alternatively submit selection with explicit clientIds or a frozen allMatching scopeToken plus excludedClientIds and the search and group it was frozen under. Scoped requests start a background job and return {jobId}. Poll GET /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay outside the frozen scope. Changes to the frozen membership are rejected before applying changes. Triggers a single Xray restart if any target inbound was running.", "operationId": "post_panel_api_clients_bulkAttach", "requestBody": { "required": true, @@ -11733,7 +11996,11 @@ "items": { "type": "string" }, - "description": "Emails of existing clients to attach." + "description": "Emails of existing clients to attach. Omit when using selection." + }, + "selection": { + "type": "object", + "description": "Either {mode: \"explicit\", clientIds, sourceId?} or {mode: \"allMatching\", scopeToken, excludedClientIds?, search?, group?, sourceId?}." }, "inboundIds": { "type": "array", @@ -11744,7 +12011,6 @@ } }, "required": [ - "emails", "inboundIds" ] }, @@ -11797,6 +12063,58 @@ } } }, + "/panel/api/clients/bulkAttach/{id}": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Poll a scoped attachment job. The result contains counts per target (attached, skipped, errors); an operation failure sets error instead. Completed results are retained for up to 15 minutes in the running panel process.", + "operationId": "get_panel_api_clients_bulkAttach_id", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Job ID returned by the scoped bulkAttach request.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/AttachJobStatus" + } + } + }, + "example": { + "success": true, + "obj": { + "ended": "2025-01-01T00:00:00Z", + "error": "", + "result": null, + "running": false + } + } + } + } + } + } + } + }, "/panel/api/clients/bulkDetach": { "post": { "tags": [ diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index 5139ce603..ce21c190d 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -452,6 +452,46 @@ export const EXAMPLES: Record = { "scope": "admin", "token": "new-token-string" }, + "AttachCandidate": { + "alreadyAttached": false, + "comment": "Example client", + "email": "alice@example.test", + "enable": true, + "group": "staff", + "id": 1, + "inScope": true + }, + "AttachCandidatePage": { + "eligible": 118, + "groups": [ + "staff" + ], + "items": [ + { + "alreadyAttached": false, + "comment": "Example client", + "email": "alice@example.test", + "enable": true, + "group": "staff", + "id": 1, + "inScope": true + } + ], + "maxId": 0, + "scopeToken": "", + "total": 120 + }, + "AttachJobStatus": { + "ended": "2025-01-01T00:00:00Z", + "error": "", + "result": null, + "running": false + }, + "AttachSelectionResult": { + "attached": 9997, + "errors": 0, + "skipped": 0 + }, "Blocker": { "code": "tools", "detail": "awg" diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index 9453db3bb..19fb6bf0b 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -1877,6 +1877,140 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "AttachCandidate": { + "properties": { + "alreadyAttached": { + "example": false, + "type": "boolean" + }, + "comment": { + "example": "Example client", + "type": "string" + }, + "email": { + "example": "alice@example.test", + "type": "string" + }, + "enable": { + "example": true, + "type": "boolean" + }, + "group": { + "example": "staff", + "type": "string" + }, + "id": { + "example": 1, + "type": "integer" + }, + "inScope": { + "example": true, + "type": "boolean" + } + }, + "required": [ + "alreadyAttached", + "comment", + "email", + "enable", + "group", + "id", + "inScope" + ], + "type": "object" + }, + "AttachCandidatePage": { + "properties": { + "eligible": { + "example": 118, + "format": "int64", + "type": "integer" + }, + "groups": { + "example": [ + "staff" + ], + "items": { + "type": "string" + }, + "type": "array" + }, + "items": { + "items": { + "$ref": "#/components/schemas/AttachCandidate" + }, + "type": "array" + }, + "maxId": { + "type": "integer" + }, + "scopeToken": { + "type": "string" + }, + "total": { + "example": 120, + "format": "int64", + "type": "integer" + } + }, + "required": [ + "eligible", + "groups", + "items", + "total" + ], + "type": "object" + }, + "AttachJobStatus": { + "properties": { + "ended": { + "format": "date-time", + "type": "string" + }, + "error": { + "type": "string" + }, + "result": { + "allOf": [ + { + "$ref": "#/components/schemas/AttachSelectionResult" + } + ], + "nullable": true + }, + "running": { + "example": false, + "type": "boolean" + } + }, + "required": [ + "ended", + "running" + ], + "type": "object" + }, + "AttachSelectionResult": { + "properties": { + "attached": { + "example": 9997, + "type": "integer" + }, + "errors": { + "example": 0, + "type": "integer" + }, + "skipped": { + "example": 0, + "type": "integer" + } + }, + "required": [ + "attached", + "errors", + "skipped" + ], + "type": "object" + }, "Blocker": { "description": "Blocker is one unmet requirement.", "properties": { diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index d3702f32b..e49e8ae56 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -447,6 +447,38 @@ export interface ApiTokenView { token?: string; } +export interface AttachCandidate { + alreadyAttached: boolean; + comment: string; + email: string; + enable: boolean; + group: string; + id: number; + inScope: boolean; +} + +export interface AttachCandidatePage { + eligible: number; + groups: string[]; + items: AttachCandidate[]; + maxId?: number; + scopeToken?: string; + total: number; +} + +export interface AttachJobStatus { + ended: string; + error?: string; + result?: AttachSelectionResult | null; + running: boolean; +} + +export interface AttachSelectionResult { + attached: number; + errors: number; + skipped: number; +} + export interface Blocker { code: BlockerCode; detail?: string; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index 3573985b0..38c619155 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -462,6 +462,42 @@ export const ApiTokenViewSchema = z.object({ }); export type ApiTokenView = z.infer; +export const AttachCandidateSchema = z.object({ + alreadyAttached: z.boolean(), + comment: z.string(), + email: z.string(), + enable: z.boolean(), + group: z.string(), + id: z.number().int(), + inScope: z.boolean(), +}); +export type AttachCandidate = z.infer; + +export const AttachCandidatePageSchema = z.object({ + eligible: z.number().int(), + groups: z.array(z.string()), + items: z.array(z.lazy(() => AttachCandidateSchema)), + maxId: z.number().int().optional(), + scopeToken: z.string().optional(), + total: z.number().int(), +}); +export type AttachCandidatePage = z.infer; + +export const AttachJobStatusSchema = z.object({ + ended: z.string(), + error: z.string().optional(), + result: z.lazy(() => AttachSelectionResultSchema).nullable().optional(), + running: z.boolean(), +}); +export type AttachJobStatus = z.infer; + +export const AttachSelectionResultSchema = z.object({ + attached: z.number().int(), + errors: z.number().int(), + skipped: z.number().int(), +}); +export type AttachSelectionResult = z.infer; + export const BlockerSchema = z.object({ code: z.lazy(() => BlockerCodeSchema), detail: z.string().optional(), diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index cc51fe8a4..88748591e 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -1020,6 +1020,71 @@ export const sections: readonly Section[] = [ response: '{\n "success": true,\n "obj": [\n {\n "id": 1,\n "email": "alice@example.com",\n "subId": "abcd1234",\n "uuid": "...",\n "totalGB": 53687091200,\n "expiryTime": 1735689600000,\n "enable": true,\n "reverse": null,\n "inboundIds": [3, 5],\n "traffic": { "up": 1024, "down": 4096, "enable": true }\n }\n ]\n}', }, + { + method: 'GET', + path: '/panel/api/clients/attachCandidates', + summary: + 'List up to 100 clients for the inbound attachment picker. Counts distinguish filtered rows and all eligible clients. A freeze request returns only the eligible count, maximum ID and a scope token covering the eligible IDs that match the given search and group for the chosen source and targets.', + params: [ + { + name: 'sourceId', + in: 'query', + type: 'number', + desc: 'Restrict candidates to clients on this inbound.', + optional: true, + }, + { + name: 'inboundIds', + in: 'query', + type: 'string', + desc: 'Comma-separated target IDs. Required for freeze and if no source ID is specified.', + optional: true, + }, + { + name: 'page', + in: 'query', + type: 'number', + desc: '1-indexed page, defaults to 1.', + optional: true, + }, + { + name: 'search', + in: 'query', + type: 'string', + desc: 'Match email and either comment (with a source) or group.', + optional: true, + }, + { + name: 'group', + in: 'query', + type: 'string', + desc: 'Filter by exact group when there is no source.', + optional: true, + }, + { + name: 'freeze', + in: 'query', + type: 'boolean', + desc: 'Freeze the eligible IDs matching search and group, independently of page.', + optional: true, + }, + { + name: 'scopeSearch', + in: 'query', + type: 'string', + desc: 'Search a frozen selection was taken under; rows outside it report inScope false.', + optional: true, + }, + { + name: 'scopeGroup', + in: 'query', + type: 'string', + desc: 'Group a frozen selection was taken under; rows outside it report inScope false.', + optional: true, + }, + ], + responseSchema: 'AttachCandidatePage', + }, { method: 'GET', path: '/panel/api/clients/list/paged', @@ -1650,13 +1715,21 @@ export const sections: readonly Section[] = [ method: 'POST', path: '/panel/api/clients/bulkAttach', summary: - '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 AddInboundClient call. Clients already present on a target are reported under skipped. Returns per-email attached/skipped/errors lists and triggers a single Xray restart if any target inbound was running.', + '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 AddInboundClient call. Clients already present on a target are reported under skipped. Explicit email requests return per-email lists. Alternatively submit selection with explicit clientIds or a frozen allMatching scopeToken plus excludedClientIds and the search and group it was frozen under. Scoped requests start a background job and return {jobId}. Poll GET /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay outside the frozen scope. Changes to the frozen membership are rejected before applying changes. Triggers a single Xray restart if any target inbound was running.', params: [ { name: 'emails', in: 'body (json)', type: 'string[]', - desc: 'Emails of existing clients to attach.', + desc: 'Emails of existing clients to attach. Omit when using selection.', + optional: true, + }, + { + name: 'selection', + in: 'body (json)', + type: 'object', + desc: 'Either {mode: "explicit", clientIds, sourceId?} or {mode: "allMatching", scopeToken, excludedClientIds?, search?, group?, sourceId?}.', + optional: true, }, { name: 'inboundIds', @@ -1669,6 +1742,21 @@ export const sections: readonly Section[] = [ response: '{\n "success": true,\n "obj": {\n "attached": ["alice", "bob"],\n "skipped": ["bob"],\n "errors": []\n }\n}', }, + { + method: 'GET', + path: '/panel/api/clients/bulkAttach/:id', + summary: + 'Poll a scoped attachment job. The result contains counts per target (attached, skipped, errors); an operation failure sets error instead. Completed results are retained for up to 15 minutes in the running panel process.', + params: [ + { + name: 'id', + in: 'path', + type: 'string', + desc: 'Job ID returned by the scoped bulkAttach request.', + }, + ], + responseSchema: 'AttachJobStatus', + }, { method: 'POST', path: '/panel/api/clients/bulkDetach', diff --git a/frontend/src/pages/inbounds/clients/AttachClientPickerModal.tsx b/frontend/src/pages/inbounds/clients/AttachClientPickerModal.tsx new file mode 100644 index 000000000..e29cd8092 --- /dev/null +++ b/frontend/src/pages/inbounds/clients/AttachClientPickerModal.tsx @@ -0,0 +1,497 @@ +import { useEffect, useRef, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { + Alert, + AutoComplete, + Button, + Input, + Modal, + Pagination, + Select, + Space, + Table, + Tag, + Typography, + message, +} from 'antd'; +import type { ColumnsType } from 'antd/es/table'; + +import { selectTagRender } from '@/components/form'; +import { formatInboundLabel } from '@/lib/inbounds/label'; +import type { DBInbound } from '@/models/dbinbound'; +import { HttpUtil, PromiseUtil } from '@/utils'; +import { isInboundMultiUser } from '../list'; + +const PAGE_SIZE = 100; +const CANDIDATES = '/panel/api/clients/attachCandidates'; + +interface Candidate { + id: number; + email: string; + comment: string; + group: string; + enable: boolean; + alreadyAttached: boolean; + inScope: boolean; +} + +interface CandidatePage { + items: Candidate[]; + total: number; + eligible: number; + groups: string[]; + scopeToken?: string; + maxId?: number; +} + +interface AttachResult { + attached: number; + skipped: number; + errors: number; +} + +interface FrozenSelection { + token: string; + eligible: number; + maxId: number; + search: string; + group: string; +} + +function inFrozenScope(frozen: FrozenSelection, row: Candidate) { + return row.inScope && row.id <= frozen.maxId; +} + +interface AttachClientPickerProps { + inbound: DBInbound; + sourceInbounds?: DBInbound[]; + onClose: () => void; + onAttached?: () => void; +} + +export default function AttachClientPickerModal({ + inbound, + sourceInbounds, + onClose, + onAttached, +}: AttachClientPickerProps) { + const { t } = useTranslation(); + const [messages, holder] = message.useMessage(); + const sourceId = sourceInbounds ? inbound.id : 0; + const [targets, setTargets] = useState(sourceId ? [] : [inbound.id]); + const targetScope = targets.join(','); + const [page, setPage] = useState(1); + const [search, setSearch] = useState(''); + const [group, setGroup] = useState(''); + const [rows, setRows] = useState(); + const [loadError, setLoadError] = useState(''); + const [loading, setLoading] = useState(true); + const [busy, setBusy] = useState<'freeze' | 'submit'>(); + const action = useRef(false); + const [frozen, setFrozen] = useState(); + // Explicitly selected rows, or excluded rows when the scope is frozen. + const [choices, setChoices] = useState(new Map()); + const [exclusionPage, setExclusionPage] = useState(1); + const selected = frozen ? frozen.eligible - choices.size : choices.size; + const scopeSearch = frozen?.search ?? ''; + const scopeGroup = frozen?.group ?? ''; + + useEffect(() => { + let cancelled = false; + const timer = window.setTimeout( + () => { + HttpUtil.get( + CANDIDATES, + { + sourceId, + inboundIds: targetScope, + page, + search, + group, + scopeSearch, + scopeGroup, + }, + { silent: true }, + ) + .then((response) => { + if (cancelled) return; + if (response?.success) { + setRows(response.obj as CandidatePage); + setLoadError(''); + } else { + setRows(undefined); + setLoadError(response?.msg || t('somethingWentWrong')); + } + }) + .finally(() => { + if (!cancelled) setLoading(false); + }); + }, + search || group ? 220 : 0, + ); + return () => { + cancelled = true; + window.clearTimeout(timer); + }; + }, [sourceId, targetScope, page, search, group, scopeSearch, scopeGroup, t]); + + function clear() { + setFrozen(undefined); + setChoices(new Map()); + setExclusionPage(1); + } + + function changeTargets(ids: number[]) { + clear(); + setTargets(ids); + setLoading(true); + setPage(1); + } + + function selectRows(keys: React.Key[]) { + const checked = new Set(keys); + setChoices((current) => { + const next = new Map(current); + for (const row of rows?.items ?? []) { + if (row.alreadyAttached || (frozen && !inFrozenScope(frozen, row))) continue; + if (frozen ? !checked.has(row.id) : checked.has(row.id)) next.set(row.id, row.email); + else next.delete(row.id); + } + return next; + }); + } + + async function selectAll() { + if (action.current || !targets.length) return; + action.current = true; + setBusy('freeze'); + try { + const response = await HttpUtil.get( + CANDIDATES, + { sourceId, inboundIds: targetScope, search, group, freeze: true }, + { silent: true }, + ); + const scope = response?.obj as CandidatePage | undefined; + if (!response?.success || !scope?.scopeToken) { + messages.error(response?.msg || t('somethingWentWrong')); + return; + } + clear(); + setFrozen({ + token: scope.scopeToken, + eligible: scope.eligible, + maxId: scope.maxId ?? 0, + search, + group, + }); + } finally { + action.current = false; + setBusy(undefined); + } + } + + async function submit() { + if (action.current || !targets.length || selected <= 0) return; + action.current = true; + setBusy('submit'); + try { + const selection = frozen + ? { + mode: 'allMatching', + sourceId, + scopeToken: frozen.token, + excludedClientIds: [...choices.keys()], + search: frozen.search, + group: frozen.group, + } + : { mode: 'explicit', sourceId, clientIds: [...choices.keys()] }; + const response = await HttpUtil.post<{ jobId: string }>( + '/panel/api/clients/bulkAttach', + { inboundIds: targets, selection }, + { headers: { 'Content-Type': 'application/json' }, silent: true }, + ); + if (!response?.success || !response.obj?.jobId) { + messages.error(response?.msg || t('somethingWentWrong')); + return; + } + const statusURL = '/panel/api/clients/bulkAttach/' + encodeURIComponent(response.obj.jobId); + let result: AttachResult | undefined; + let failedPolls = 0; + while (!result) { + const status = await HttpUtil.get<{ + running: boolean; + result?: AttachResult; + error?: string; + }>(statusURL, undefined, { silent: true }); + if (!status?.success) { + if (++failedPolls < 3) { + await PromiseUtil.sleep(1000); + continue; + } + messages.error(status?.msg || t('somethingWentWrong')); + return; + } + failedPolls = 0; + if (!status.obj?.running) { + if (!status.obj?.result) { + messages.error(status.obj?.error || t('somethingWentWrong')); + return; + } + result = status.obj.result; + } else { + await PromiseUtil.sleep(1000); + } + } + const { attached, skipped, errors } = result; + if (errors > 0) + messages.warning( + t('pages.inbounds.attachClientsResultMixed', { + attached, + skipped, + errors, + }), + ); + else messages.success(t('pages.inbounds.attachClientsResult', { attached, skipped })); + onAttached?.(); + onClose(); + } finally { + action.current = false; + setBusy(undefined); + } + } + + const columns: ColumnsType = [ + { title: t('pages.inbounds.email'), dataIndex: 'email', ellipsis: true }, + sourceId + ? { title: t('comment'), dataIndex: 'comment', ellipsis: true } + : { title: t('pages.clients.group'), dataIndex: 'group', ellipsis: true }, + { + title: t('enable'), + key: 'status', + render: (_, row) => + row.alreadyAttached ? ( + {t('pages.inbounds.attachExistingStatusAttached')} + ) : row.enable ? ( + {t('enable')} + ) : ( + {t('pages.inbounds.attachClientsStatusDisabled')} + ), + }, + ]; + const label = formatInboundLabel(inbound.tag, inbound.remark); + const targetOptions = sourceInbounds + ?.filter((item) => item.id !== sourceId && isInboundMultiUser(item)) + .map((item) => ({ + value: item.id, + label: formatInboundLabel(item.tag, item.remark), + })); + const lastExclusionPage = Math.max(1, Math.ceil(choices.size / 10)); + const currentExclusionPage = Math.min(exclusionPage, lastExclusionPage); + const exclusions = frozen + ? [...choices].slice((currentExclusionPage - 1) * 10, currentExclusionPage * 10) + : []; + + return ( + { + if (!action.current) onClose(); + }} + onOk={submit} + closable={!busy} + keyboard={!busy} + okText={t('pages.inbounds.attachClients')} + cancelText={t('cancel')} + okButtonProps={{ + loading: busy === 'submit', + disabled: !!busy || loading || !!loadError || !targets.length || selected <= 0, + }} + cancelButtonProps={{ disabled: !!busy }} + > + {holder} + + {t(sourceId ? 'pages.inbounds.attachClientsDesc' : 'pages.inbounds.attachExistingDesc', { + count: rows?.eligible ?? 0, + })} + + + {targetOptions && + (targetOptions.length ? ( + - )} - + ); } diff --git a/frontend/src/pages/inbounds/clients/AttachExistingClientsModal.tsx b/frontend/src/pages/inbounds/clients/AttachExistingClientsModal.tsx index 2de8540af..38385aa68 100644 --- a/frontend/src/pages/inbounds/clients/AttachExistingClientsModal.tsx +++ b/frontend/src/pages/inbounds/clients/AttachExistingClientsModal.tsx @@ -1,11 +1,5 @@ -import { useEffect, useMemo, useState } from 'react'; -import { useTranslation } from 'react-i18next'; -import { Alert, Input, Modal, Select, Space, Spin, Table, Tag, Typography, message } from 'antd'; -import type { ColumnsType } from 'antd/es/table'; - -import { HttpUtil } from '@/utils'; -import { formatInboundLabel } from '@/lib/inbounds/label'; import type { DBInbound } from '@/models/dbinbound'; +import AttachClientPickerModal from './AttachClientPickerModal'; interface AttachExistingClientsModalProps { open: boolean; @@ -14,241 +8,19 @@ interface AttachExistingClientsModalProps { onAttached?: () => void; } -interface BulkAttachResult { - attached?: string[]; - skipped?: string[]; - errors?: string[]; -} - -interface ClientRow { - email: string; - group: string; - enable: boolean; - alreadyAttached: boolean; -} - -interface RawClient { - email?: string; - group?: string; - enable?: boolean; - inboundIds?: number[] | null; -} - export default function AttachExistingClientsModal({ open, target, onClose, onAttached, }: AttachExistingClientsModalProps) { - const { t } = useTranslation(); - const [messageApi, messageContextHolder] = message.useMessage(); - const [loading, setLoading] = useState(false); - const [saving, setSaving] = useState(false); - const [clientRows, setClientRows] = useState([]); - const [selectedEmails, setSelectedEmails] = useState([]); - const [search, setSearch] = useState(''); - const [groupFilter, setGroupFilter] = useState(undefined); - - // Reset during render, not in an effect, so the first frame is already clean. - const openTarget = open ? target : null; - const [syncedTarget, setSyncedTarget] = useState(openTarget); - if (openTarget !== syncedTarget) { - setSyncedTarget(openTarget); - if (openTarget) { - setLoading(true); - setSearch(''); - setGroupFilter(undefined); - } - } - - useEffect(() => { - if (!open || !target) return; - let cancelled = false; - HttpUtil.get('/panel/api/clients/list', undefined, { silent: true }) - .then((msg) => { - if (cancelled) return; - const list = Array.isArray(msg?.obj) ? (msg.obj as RawClient[]) : []; - const rows: ClientRow[] = list - .map((c) => ({ - email: (c?.email || '').trim(), - group: (c?.group || '').trim(), - enable: c?.enable !== false, - alreadyAttached: Array.isArray(c?.inboundIds) && c.inboundIds.includes(target.id), - })) - .filter((r) => r.email); - setClientRows(rows); - setSelectedEmails(rows.filter((r) => !r.alreadyAttached).map((r) => r.email)); - }) - .finally(() => { - if (!cancelled) setLoading(false); - }); - return () => { - cancelled = true; - }; - }, [open, target]); - - const groupOptions = useMemo(() => { - const set = new Set(); - for (const r of clientRows) if (r.group) set.add(r.group); - return [...set].sort((a, b) => a.localeCompare(b)).map((g) => ({ value: g, label: g })); - }, [clientRows]); - - const attachableCount = useMemo( - () => clientRows.filter((r) => !r.alreadyAttached).length, - [clientRows], - ); - - const filteredRows = useMemo(() => { - const q = search.trim().toLowerCase(); - return clientRows.filter((r) => { - if (groupFilter && r.group !== groupFilter) return false; - if (!q) return true; - return r.email.toLowerCase().includes(q) || r.group.toLowerCase().includes(q); - }); - }, [clientRows, search, groupFilter]); - - const columns: ColumnsType = useMemo( - () => [ - { - title: t('pages.inbounds.email'), - dataIndex: 'email', - key: 'email', - ellipsis: true, - }, - { - title: t('pages.clients.group'), - dataIndex: 'group', - key: 'group', - width: 150, - ellipsis: true, - render: (group: string) => - group ? ( - {group} - ) : ( - — - ), - }, - { - title: t('enable'), - key: 'status', - width: 140, - render: (_v, row) => { - if (row.alreadyAttached) - return {t('pages.inbounds.attachExistingStatusAttached')}; - return row.enable ? ( - {t('enable')} - ) : ( - {t('pages.inbounds.attachClientsStatusDisabled')} - ); - }, - }, - ], - [t], - ); - - async function submit() { - if (!target || selectedEmails.length === 0) return; - setSaving(true); - try { - const msg = await HttpUtil.post( - '/panel/api/clients/bulkAttach', - { emails: selectedEmails, inboundIds: [target.id] }, - { headers: { 'Content-Type': 'application/json' } }, - ); - if (!msg?.success) { - messageApi.error(msg?.msg || t('somethingWentWrong')); - return; - } - const result = (msg.obj || {}) as BulkAttachResult; - const attached = result.attached?.length ?? 0; - const skipped = result.skipped?.length ?? 0; - const errors = result.errors?.length ?? 0; - if (errors > 0) { - messageApi.warning( - t('pages.inbounds.attachClientsResultMixed', { attached, skipped, errors }), - ); - } else { - messageApi.success(t('pages.inbounds.attachClientsResult', { attached, skipped })); - } - onAttached?.(); - onClose(); - } finally { - setSaving(false); - } - } - - const noClients = !loading && clientRows.length === 0; - + if (!open || !target) return null; return ( - - {messageContextHolder} - - {t('pages.inbounds.attachExistingDesc', { count: attachableCount })} - - - {noClients ? ( - - ) : ( - - - - - setSearch(e.target.value)} - placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')} - style={{ width: 260 }} - /> - {groupOptions.length > 0 && ( -