mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 16:34:52 +03:00
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.
This commit is contained in:
+434
-19
@@ -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": [
|
||||
|
||||
@@ -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(),
|
||||
);
|
||||
}
|
||||
@@ -509,7 +509,22 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"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<string, unknown> = {
|
||||
"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"
|
||||
},
|
||||
|
||||
@@ -2094,6 +2094,10 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"$ref": "#/components/schemas/BulkAdjustReport"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"skippedCount": {
|
||||
"example": 0,
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -2101,6 +2105,43 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
],
|
||||
"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<string, unknown> = {
|
||||
],
|
||||
"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": {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<typeof BulkAdjustResultSchema>;
|
||||
|
||||
export const BulkDeleteReportSchema = z.object({
|
||||
email: z.string(),
|
||||
reason: z.string(),
|
||||
});
|
||||
export type BulkDeleteReport = z.infer<typeof BulkDeleteReportSchema>;
|
||||
|
||||
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<typeof BulkDeleteResultSchema>;
|
||||
|
||||
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<typeof GeodataTokenIssueSchema>;
|
||||
|
||||
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<typeof GroupClientPageSchema>;
|
||||
|
||||
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<typeof GroupClientRowSchema>;
|
||||
|
||||
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<typeof GroupClientSelectionSchema>;
|
||||
|
||||
export const HappLinkResultSchema = z.object({
|
||||
encryptedLink: z.string(),
|
||||
});
|
||||
|
||||
@@ -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<Msg<BulkDeleteResult>> => {
|
||||
mutationFn: async (
|
||||
payload: ({ emails: string[] } | GroupBulkScope) & { keepTraffic?: boolean },
|
||||
): Promise<Msg<BulkDeleteResult>> => {
|
||||
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<Msg<BulkAdjustResult>> => {
|
||||
mutationFn: async (
|
||||
payload: ({ emails: string[] } | GroupBulkScope) & {
|
||||
addDays: number;
|
||||
addBytes: number;
|
||||
flow?: string;
|
||||
limitHwid?: number | null;
|
||||
adTag?: string;
|
||||
externalLinks?: ExternalLinkInput[];
|
||||
},
|
||||
): Promise<Msg<BulkAdjustResult>> => {
|
||||
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<BulkDeleteResult>);
|
||||
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],
|
||||
);
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<Row[]>(() => {
|
||||
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}
|
||||
<Modal
|
||||
open={open}
|
||||
title={t('pages.clients.subLinksTitle', { count: rows.length })}
|
||||
title={t('pages.clients.subLinksTitle', { count: total })}
|
||||
width={780}
|
||||
footer={
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
||||
@@ -158,18 +206,19 @@ export default function SubLinksModal({
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<Button
|
||||
icon={<CopyOutlined aria-hidden />}
|
||||
disabled={rows.length === 0}
|
||||
onClick={() =>
|
||||
copy(allText, t('pages.clients.subLinksCopiedAll', { count: rows.length }))
|
||||
}
|
||||
disabled={!total}
|
||||
loading={copying}
|
||||
onClick={copyAll}
|
||||
>
|
||||
{t('pages.clients.subLinksCopyAll')}
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<DownloadOutlined aria-hidden />}
|
||||
disabled={rows.length === 0}
|
||||
onClick={download}
|
||||
disabled={!total}
|
||||
href={exportPath}
|
||||
download={exportPath ? 'sub-links.txt' : undefined}
|
||||
onClick={exportPath ? undefined : download}
|
||||
>
|
||||
{t('download')}
|
||||
</Button>
|
||||
@@ -187,7 +236,7 @@ export default function SubLinksModal({
|
||||
style={{ marginBottom: 12 }}
|
||||
/>
|
||||
)}
|
||||
{enabled && rows.length === 0 && (
|
||||
{enabled && !total && !groupPage.isFetching && !groupPage.isError && (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
@@ -195,12 +244,26 @@ export default function SubLinksModal({
|
||||
style={{ marginBottom: 12 }}
|
||||
/>
|
||||
)}
|
||||
{rows.length > 0 && (
|
||||
{groupPage.isError && (
|
||||
<Alert showIcon type="error" title={groupPage.error.message || t('somethingWentWrong')} />
|
||||
)}
|
||||
{enabled && (total > 0 || groupPage.isFetching) && (
|
||||
<Table<Row>
|
||||
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 }}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -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<string[]>([]);
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
const rows = useMemo<ClientRow[]>(
|
||||
() =>
|
||||
(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<ClientRow> = 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 ? (
|
||||
<Tag color="geekblue">{g}</Tag>
|
||||
) : (
|
||||
<Typography.Text type="secondary">—</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('enable'),
|
||||
dataIndex: 'enable',
|
||||
key: 'enable',
|
||||
width: 90,
|
||||
render: (enabled: boolean) =>
|
||||
enabled ? (
|
||||
<Tag color="success">{t('enable')}</Tag>
|
||||
) : (
|
||||
<Tag>{t('pages.inbounds.attachClientsStatusDisabled')}</Tag>
|
||||
),
|
||||
},
|
||||
],
|
||||
[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 (
|
||||
<Modal
|
||||
open={open}
|
||||
onCancel={onClose}
|
||||
onOk={submit}
|
||||
okButtonProps={{ disabled: selectedEmails.length === 0, loading: saving }}
|
||||
okText={t('add')}
|
||||
cancelText={t('cancel')}
|
||||
title={t('pages.groups.addToGroupTitle', { name: groupName ?? '' })}
|
||||
width={720}
|
||||
>
|
||||
{messageContextHolder}
|
||||
<Typography.Paragraph type="secondary">
|
||||
{t('pages.groups.addToGroupDesc')}
|
||||
</Typography.Paragraph>
|
||||
|
||||
<Space orientation="vertical" size="small" style={{ width: '100%' }}>
|
||||
<Space style={{ width: '100%', justifyContent: 'space-between' }} wrap>
|
||||
<Input.Search
|
||||
allowClear
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
|
||||
aria-label={t('pages.inbounds.attachClientsSearchPlaceholder')}
|
||||
style={{ maxWidth: 320 }}
|
||||
/>
|
||||
<Typography.Text type="secondary">
|
||||
{t('pages.inbounds.attachClientsSelectedCount', {
|
||||
selected: selectedEmails.length,
|
||||
total: rows.length,
|
||||
})}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
{rows.length === 0 ? (
|
||||
<Alert type="info" showIcon title={t('pages.groups.addToGroupEmpty')} />
|
||||
) : (
|
||||
<Table<ClientRow>
|
||||
size="small"
|
||||
rowKey="email"
|
||||
columns={columns}
|
||||
dataSource={filteredRows}
|
||||
pagination={false}
|
||||
scroll={{ y: 320 }}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedEmails,
|
||||
onChange: (keys) => setSelectedEmails(keys as string[]),
|
||||
preserveSelectedRowKeys: true,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Space>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -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<number>());
|
||||
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<GroupClientRow> = [
|
||||
{ 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 ? <Tag color="geekblue">{label}</Tag> : '—'),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
title: t('enable'),
|
||||
dataIndex: 'enable',
|
||||
width: 100,
|
||||
render: (enabled: boolean) => (
|
||||
<Tag color={enabled ? 'success' : undefined}>
|
||||
{t(enabled ? 'enable' : 'pages.inbounds.attachClientsStatusDisabled')}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open
|
||||
onCancel={() => {
|
||||
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}
|
||||
<Typography.Paragraph type="secondary">
|
||||
{t(add ? 'pages.groups.addToGroupDesc' : 'pages.groups.removeFromGroupDesc')}
|
||||
</Typography.Paragraph>
|
||||
<Space orientation="vertical" size="small" style={{ width: '100%' }}>
|
||||
<Input.Search
|
||||
allowClear
|
||||
disabled={!!busy}
|
||||
value={search}
|
||||
onChange={(event) => {
|
||||
setSearch(event.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
maxLength={256}
|
||||
placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
|
||||
aria-label={t('pages.inbounds.attachClientsSearchPlaceholder')}
|
||||
style={{ maxWidth: 320 }}
|
||||
/>
|
||||
<Space wrap>
|
||||
<Button
|
||||
size="small"
|
||||
disabled={!!busy || loading || !visible.length}
|
||||
onClick={() => selectVisible(visible.map((row) => row.id))}
|
||||
>
|
||||
{t('pages.inbounds.attachSelectPage')}
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
disabled={!!busy || loading || !query.data?.total}
|
||||
loading={busy === 'freeze'}
|
||||
aria-pressed={!!frozen}
|
||||
onClick={selectAll}
|
||||
>
|
||||
{t('pages.groups.selectAllMatching')}
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
disabled={!!busy || (!choices.size && !frozen)}
|
||||
onClick={clearSelection}
|
||||
>
|
||||
{t('pages.inbounds.attachClearSelection')}
|
||||
</Button>
|
||||
{frozen && choices.size > 0 && (
|
||||
<Button size="small" disabled={!!busy} onClick={() => setChoices(new Set())}>
|
||||
{t('pages.inbounds.attachClearExclusions')}
|
||||
</Button>
|
||||
)}
|
||||
<Typography.Text role="status" type="secondary">
|
||||
{t('pages.inbounds.attachClientsSelectedCount', {
|
||||
selected,
|
||||
total: frozen?.count ?? query.data?.total ?? 0,
|
||||
})}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
{query.isError && (
|
||||
<Alert showIcon type="error" title={query.error.message || t('somethingWentWrong')} />
|
||||
)}
|
||||
{!loading && !query.isError && !search && query.data?.total === 0 && (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
title={t(add ? 'pages.groups.addToGroupEmpty' : 'pages.groups.removeFromGroupEmpty')}
|
||||
/>
|
||||
)}
|
||||
<Table<GroupClientRow>
|
||||
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),
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -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<string[]>([]);
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
const rows = useMemo<ClientRow[]>(
|
||||
() =>
|
||||
(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<ClientRow> = 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 ? (
|
||||
<Tag color="success">{t('enable')}</Tag>
|
||||
) : (
|
||||
<Tag>{t('pages.inbounds.attachClientsStatusDisabled')}</Tag>
|
||||
),
|
||||
},
|
||||
],
|
||||
[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 (
|
||||
<Modal
|
||||
open={open}
|
||||
onCancel={onClose}
|
||||
onOk={submit}
|
||||
okButtonProps={{ danger: true, disabled: selectedEmails.length === 0, loading: saving }}
|
||||
okText={t('remove')}
|
||||
cancelText={t('cancel')}
|
||||
title={t('pages.groups.removeFromGroupTitle', { name: groupName ?? '' })}
|
||||
width={680}
|
||||
>
|
||||
{messageContextHolder}
|
||||
<Typography.Paragraph type="secondary">
|
||||
{t('pages.groups.removeFromGroupDesc')}
|
||||
</Typography.Paragraph>
|
||||
|
||||
<Space orientation="vertical" size="small" style={{ width: '100%' }}>
|
||||
<Space style={{ width: '100%', justifyContent: 'space-between' }} wrap>
|
||||
<Input.Search
|
||||
allowClear
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
|
||||
aria-label={t('pages.inbounds.attachClientsSearchPlaceholder')}
|
||||
style={{ maxWidth: 320 }}
|
||||
/>
|
||||
<Typography.Text type="secondary">
|
||||
{t('pages.inbounds.attachClientsSelectedCount', {
|
||||
selected: selectedEmails.length,
|
||||
total: rows.length,
|
||||
})}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
<Table<ClientRow>
|
||||
size="small"
|
||||
rowKey="email"
|
||||
columns={columns}
|
||||
dataSource={filteredRows}
|
||||
pagination={false}
|
||||
scroll={{ y: 280 }}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedEmails,
|
||||
onChange: (keys) => setSelectedEmails(keys as string[]),
|
||||
preserveSelectedRowKeys: true,
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -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<string, unknown> }[] = [];
|
||||
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 (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/panel/groups']}>
|
||||
<ThemeProvider>
|
||||
<Button onClick={() => setInboundOpen(true)}>Group the source inbound</Button>
|
||||
<GroupsPage />
|
||||
<AddClientsToGroupModal
|
||||
open={inboundOpen}
|
||||
inboundId={7}
|
||||
count={groupCount}
|
||||
onClose={() => setInboundOpen(false)}
|
||||
/>
|
||||
</ThemeProvider>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function response(obj: unknown) {
|
||||
return Promise.resolve(Response.json({ success: true, msg: '', obj }));
|
||||
}
|
||||
|
||||
const meta = {
|
||||
title: 'Pages/Groups/Client management',
|
||||
component: GroupsPage,
|
||||
render: () => <GroupFixture />,
|
||||
} satisfies Meta<typeof GroupsPage>;
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
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<string, unknown>)
|
||||
: 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<typeof within>, 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' });
|
||||
},
|
||||
};
|
||||
@@ -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<GroupSummary[]> {
|
||||
return validated.obj ?? [];
|
||||
}
|
||||
|
||||
async function fetchEmailsForGroup(name: string): Promise<string[]> {
|
||||
const msg = await HttpUtil.get<string[]>(
|
||||
`/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<string[]>([]);
|
||||
const [adjustScope, setAdjustScope] = useState<(GroupBulkScope & { count: number }) | null>(null);
|
||||
const scopeRequest = useRef(0);
|
||||
const [groupForAction, setGroupForAction] = useState<GroupSummary | null>(null);
|
||||
|
||||
const allClientsQuery = useQuery<ClientRecord[]>({
|
||||
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() {
|
||||
/>
|
||||
</LazyMount>
|
||||
|
||||
<LazyMount when={subLinksOpen}>
|
||||
<SubLinksModal
|
||||
open={subLinksOpen}
|
||||
emails={groupEmails}
|
||||
clients={allClients}
|
||||
subSettings={subSettings}
|
||||
onOpenChange={setSubLinksOpen}
|
||||
/>
|
||||
</LazyMount>
|
||||
{subLinksOpen && groupForAction && (
|
||||
<LazyMount when={subLinksOpen}>
|
||||
<SubLinksModal
|
||||
key={groupForAction.name}
|
||||
open
|
||||
group={groupForAction.name}
|
||||
subSettings={subSettings}
|
||||
onOpenChange={setSubLinksOpen}
|
||||
/>
|
||||
</LazyMount>
|
||||
)}
|
||||
|
||||
<LazyMount when={adjustOpen}>
|
||||
<ClientBulkAdjustModal
|
||||
open={adjustOpen}
|
||||
count={groupEmails.length}
|
||||
onOpenChange={setAdjustOpen}
|
||||
onSubmit={async (addDays, addBytes, flow, limitHwid, adTag) => {
|
||||
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 && (
|
||||
<LazyMount when={adjustOpen}>
|
||||
<ClientBulkAdjustModal
|
||||
open
|
||||
count={adjustScope.count}
|
||||
onOpenChange={setAdjustOpen}
|
||||
onSubmit={async (addDays, addBytes, flow, limitHwid, adTag, externalLinks) => {
|
||||
const { group, scopeToken } = adjustScope;
|
||||
const msg = await bulkAdjust(
|
||||
{ group, scopeToken },
|
||||
addDays,
|
||||
addBytes,
|
||||
flow,
|
||||
limitHwid,
|
||||
adTag,
|
||||
externalLinks,
|
||||
);
|
||||
return obj;
|
||||
}
|
||||
return null;
|
||||
}}
|
||||
/>
|
||||
</LazyMount>
|
||||
if (!msg?.success || !msg.obj) return null;
|
||||
messageApi.success(
|
||||
t('pages.groups.adjustSuccess', { count: msg.obj.adjusted, name: group }),
|
||||
);
|
||||
return msg.obj;
|
||||
}}
|
||||
/>
|
||||
</LazyMount>
|
||||
)}
|
||||
|
||||
<LazyMount when={addClientsOpen}>
|
||||
<GroupAddClientsModal
|
||||
open={addClientsOpen}
|
||||
groupName={groupForAction?.name ?? null}
|
||||
candidates={allClients.filter((c) => 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;
|
||||
}}
|
||||
/>
|
||||
</LazyMount>
|
||||
|
||||
<LazyMount when={removeClientsOpen}>
|
||||
<GroupRemoveClientsModal
|
||||
open={removeClientsOpen}
|
||||
groupName={groupForAction?.name ?? null}
|
||||
members={allClients.filter((c) => 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;
|
||||
}}
|
||||
/>
|
||||
</LazyMount>
|
||||
{(addClientsOpen || removeClientsOpen) && groupForAction && (
|
||||
<LazyMount when={addClientsOpen || removeClientsOpen}>
|
||||
<GroupClientsModal
|
||||
key={(addClientsOpen ? 'add:' : 'remove:') + groupForAction.name}
|
||||
mode={addClientsOpen ? 'add' : 'remove'}
|
||||
group={groupForAction.name}
|
||||
onClose={() => {
|
||||
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;
|
||||
}}
|
||||
/>
|
||||
</LazyMount>
|
||||
)}
|
||||
</Layout>
|
||||
</ConfigProvider>
|
||||
);
|
||||
|
||||
@@ -173,7 +173,7 @@ export default function InboundsPage() {
|
||||
const [detachSource, setDetachSource] = useState<DBInbound | null>(null);
|
||||
|
||||
const [groupOpen, setGroupOpen] = useState(false);
|
||||
const [groupSource, setGroupSource] = useState<DBInbound | null>(null);
|
||||
const [groupSourceID, setGroupSourceID] = useState<number | null>(null);
|
||||
|
||||
const [cloneOpen, setCloneOpen] = useState(false);
|
||||
const [cloneSource, setCloneSource] = useState<DBInbound | null>(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}
|
||||
/>
|
||||
</LazyMount>
|
||||
<LazyMount when={groupOpen}>
|
||||
<AddClientsToGroupModal
|
||||
open={groupOpen}
|
||||
onClose={() => setGroupOpen(false)}
|
||||
onAdded={refresh}
|
||||
source={groupSource}
|
||||
/>
|
||||
</LazyMount>
|
||||
{groupSourceID !== null && (
|
||||
<LazyMount when={groupOpen}>
|
||||
<AddClientsToGroupModal
|
||||
open={groupOpen}
|
||||
onClose={() => setGroupOpen(false)}
|
||||
onAdded={refresh}
|
||||
inboundId={groupSourceID}
|
||||
count={clientCount[groupSourceID]?.clients ?? 0}
|
||||
/>
|
||||
</LazyMount>
|
||||
)}
|
||||
<LazyMount when={cloneOpen}>
|
||||
<CloneInboundModal
|
||||
open={cloneOpen}
|
||||
|
||||
@@ -1,64 +1,60 @@
|
||||
import { lazy, useEffect, useMemo, useState } from 'react';
|
||||
import { lazy } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
import { keys } from '@/api/queryKeys';
|
||||
import { GroupSummaryListSchema } from '@/schemas/client';
|
||||
import { HttpUtil } from '@/utils';
|
||||
import { coerceInboundJsonField, type DBInbound } from '@/models/dbinbound';
|
||||
import { parseMsg } from '@/utils/zodValidate';
|
||||
|
||||
const BulkAddToGroupModal = lazy(() => 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<string[]>([]);
|
||||
|
||||
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 (
|
||||
<BulkAddToGroupModal
|
||||
open={open}
|
||||
count={emails.length}
|
||||
groups={groups}
|
||||
onOpenChange={(o) => {
|
||||
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 };
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -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(),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user