feat: add traffic limit rules and user traffic statistics

This commit is contained in:
EUForest
2026-03-14 17:59:27 +08:00
parent eac7b27f60
commit f8fbf5529f
23 changed files with 823 additions and 50 deletions
@@ -182,5 +182,19 @@
"validationFailed": "Validation failed",
"totalNodeGroups": "Total Node Groups",
"invalidRange": "Minimum traffic must be less than maximum traffic",
"rangeConflict": "Traffic range conflicts with node group \"{{name}}\" (range: {{min}} - {{max}} GB)"
"rangeConflict": "Traffic range conflicts with node group \"{{name}}\" (range: {{min}} - {{max}} GB)",
"isExpiredGroup": "Expired Node Group",
"isExpiredGroupDescription": "Allow expired users to use limited nodes",
"expiredDaysLimit": "Expired Days Limit",
"expiredDaysLimitDescription": "Number of days after expiration that users can still access nodes",
"maxTrafficGBExpired": "Max Traffic for Expired Users (GB)",
"maxTrafficGBExpiredDescription": "Maximum traffic allowed for expired users (0 = unlimited)",
"speedLimit": "Speed Limit (KB/s)",
"speedLimitDescription": "Speed limit for users in this node group (0 = unlimited)",
"expiredGroup": "Expired Only",
"expiredSettings": "Expired Settings",
"days": "days",
"expiredGroupExists": "System already has an expired node group: {{name}}",
"nodeGroupUsedBySubscribe": "This node group is used as default node group in subscription products, cannot set as expired group",
"expiredGroupForCalculationDescription": "Expired-only node groups cannot participate in group calculation"
}
@@ -74,6 +74,17 @@
"showOriginalPriceDescription": "When enabled, the subscription card will display both the original price and the discounted price to help users understand the discount amount",
"speedLimit": "Speed Limit ",
"traffic": "Traffic",
"trafficLimit": "Traffic Limit",
"trafficLimitRules": "Traffic Limit Rules",
"trafficLimitDescription": "Configure traffic-based speed limit rules. When traffic usage reaches the specified amount, the speed will be limited.",
"addTrafficLimitRule": "Add Traffic Limit Rule",
"statType": "Statistics Type",
"selectStatType": "Select type...",
"statTypeHour": "Hour",
"statTypeDay": "Day",
"statValue": "Time Value",
"trafficUsage": "Traffic Usage (GB)",
"speedLimitKb": "Speed Limit (kb)",
"unitPrice": "Unit Price",
"unitTime": "Unit Time",
"unlimitedInventory": "Unlimited (enter -1)",
@@ -182,6 +182,20 @@
"validationFailed": "验证失败",
"totalNodeGroups": "总节点组数",
"invalidRange": "最小流量必须小于最大流量",
"rangeConflict": "流量区间与节点组 \"{{name}}\" 冲突(区间:{{min}} - {{max}} GB"
"rangeConflict": "流量区间与节点组 \"{{name}}\" 冲突(区间:{{min}} - {{max}} GB",
"isExpiredGroup": "过期节点组",
"isExpiredGroupDescription": "允许过期用户使用受限节点",
"expiredDaysLimit": "过期天数限制",
"expiredDaysLimitDescription": "用户订阅过期后仍可访问节点的天数",
"maxTrafficGBExpired": "过期用户最大流量 (GB)",
"maxTrafficGBExpiredDescription": "过期用户允许使用的最大流量(0 = 不限制)",
"speedLimit": "限速 (KB/s)",
"speedLimitDescription": "该节点组用户的速度限制(0 = 不限制)",
"expiredGroup": "过期专用",
"expiredSettings": "过期设置",
"days": "天",
"expiredGroupExists": "系统中已存在过期节点组:{{name}}",
"nodeGroupUsedBySubscribe": "该节点组已被订阅商品设置为默认节点组,不能设为过期节点组",
"expiredGroupForCalculationDescription": "过期专用节点组不能参与分组计算"
}
@@ -74,6 +74,17 @@
"showOriginalPriceDescription": "开启后,在订阅卡片上将会显示原价和折后价,帮助用户了解优惠幅度",
"speedLimit": "速度限制",
"traffic": "流量",
"trafficLimit": "按量限速",
"trafficLimitRules": "按量限速规则",
"trafficLimitDescription": "配置基于流量的限速规则。当流量使用达到指定量时,将进行限速。",
"addTrafficLimitRule": "添加限速规则",
"statType": "统计类型",
"selectStatType": "选择类型...",
"statTypeHour": "小时",
"statTypeDay": "天",
"statValue": "时间值",
"trafficUsage": "使用流量(GB",
"speedLimitKb": "限速(kb",
"unitPrice": "单价",
"unitTime": "时间单位",
"unlimitedInventory": "无限制(输入 -1",
+201 -42
View File
@@ -40,6 +40,10 @@ const NodeGroupForm = forwardRef<
description: "",
sort: 0,
for_calculation: true,
is_expired_group: false,
expired_days_limit: 7,
max_traffic_gb_expired: 0,
speed_limit: 0,
min_traffic_gb: 0,
max_traffic_gb: 0,
});
@@ -53,6 +57,10 @@ const NodeGroupForm = forwardRef<
description: initialValues.description || "",
sort: initialValues.sort ?? 0,
for_calculation: initialValues.for_calculation ?? true,
is_expired_group: initialValues.is_expired_group ?? false,
expired_days_limit: initialValues.expired_days_limit ?? 7,
max_traffic_gb_expired: initialValues.max_traffic_gb_expired ?? 0,
speed_limit: initialValues.speed_limit ?? 0,
min_traffic_gb: initialValues.min_traffic_gb ?? 0,
max_traffic_gb: initialValues.max_traffic_gb ?? 0,
});
@@ -62,6 +70,10 @@ const NodeGroupForm = forwardRef<
description: "",
sort: 0,
for_calculation: true,
is_expired_group: false,
expired_days_limit: 7,
max_traffic_gb_expired: 0,
speed_limit: 0,
min_traffic_gb: 0,
max_traffic_gb: 0,
});
@@ -118,16 +130,69 @@ const NodeGroupForm = forwardRef<
return "";
};
// 检测过期节点组冲突
const checkExpiredGroupConflict = async (isExpiredGroup: boolean): Promise<string> => {
if (!isExpiredGroup) {
return "";
}
// 检查是否已存在其他过期节点组
const existingExpiredGroup = allNodeGroups.find(
(group) => group.is_expired_group && group.id !== currentGroupId
);
if (existingExpiredGroup) {
return t("expiredGroupExists", `System already has an expired node group: ${existingExpiredGroup.name}`);
}
// 检查当前节点组是否被订阅商品使用
if (currentGroupId) {
try {
const { getSubscribeList } = await import("@workspace/ui/services/admin/subscribe");
const { data } = await getSubscribeList({
page: 1,
size: 1,
node_group_id: currentGroupId
});
if (data.data && data.data.total > 0) {
return t("nodeGroupUsedBySubscribe", "This node group is used as default node group in subscription products, cannot set as expired group");
}
} catch (error) {
console.error("Failed to check subscribe usage:", error);
}
}
return "";
};
// 检查是否存在其他过期节点组(用于隐藏开关)
const hasOtherExpiredGroup = allNodeGroups.some(
(group) => group.is_expired_group && group.id !== currentGroupId
);
// 当前是否是过期节点组(编辑模式下)
const isCurrentExpiredGroup = initialValues?.is_expired_group ?? false;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
// 检测流量区间冲突
const conflict = checkTrafficRangeConflict(values.min_traffic_gb, values.max_traffic_gb);
if (conflict) {
setConflictError(conflict);
// 检测过期节点组冲突
const expiredGroupConflict = await checkExpiredGroupConflict(values.is_expired_group);
if (expiredGroupConflict) {
setConflictError(expiredGroupConflict);
return;
}
// 仅在非过期节点组时检测流量区间冲突
if (!values.is_expired_group) {
const conflict = checkTrafficRangeConflict(values.min_traffic_gb, values.max_traffic_gb);
if (conflict) {
setConflictError(conflict);
return;
}
}
setSubmitting(true);
const success = await onSubmit(values);
setSubmitting(false);
@@ -139,6 +204,10 @@ const NodeGroupForm = forwardRef<
description: "",
sort: 0,
for_calculation: true,
is_expired_group: false,
expired_days_limit: 7,
max_traffic_gb_expired: 0,
speed_limit: 0,
min_traffic_gb: 0,
max_traffic_gb: 0,
});
@@ -207,69 +276,159 @@ const NodeGroupForm = forwardRef<
{t("forCalculation", "For Calculation")}
</Label>
<p className="text-sm text-muted-foreground">
{t("forCalculationDescription", "Whether this node group participates in grouping calculation")}
{values.is_expired_group
? t("expiredGroupForCalculationDescription", "Expired-only node groups cannot participate in group calculation")
: t("forCalculationDescription", "Whether this node group participates in grouping calculation")}
</p>
</div>
<Switch
id="for_calculation"
checked={values.for_calculation}
disabled={values.is_expired_group}
onCheckedChange={(checked) =>
setValues({ ...values, for_calculation: checked })
}
/>
</div>
<div className="space-y-2">
{/* 仅在没有其他过期节点组或当前就是过期节点组时显示 */}
{(!hasOtherExpiredGroup || isCurrentExpiredGroup) && (
<div className="flex items-center justify-between">
<Label>{t("trafficRangeGB", "Traffic Range (GB)")}</Label>
<div className="space-y-0.5">
<Label htmlFor="is_expired_group">
{t("isExpiredGroup", "Expired Node Group")}
</Label>
<p className="text-sm text-muted-foreground">
{t("isExpiredGroupDescription", "Allow expired users to use limited nodes")}
</p>
</div>
<Switch
id="is_expired_group"
checked={values.is_expired_group}
onCheckedChange={async (checked) => {
setValues({
...values,
is_expired_group: checked,
for_calculation: checked ? false : values.for_calculation,
min_traffic_gb: checked ? 0 : values.min_traffic_gb,
max_traffic_gb: checked ? 0 : values.max_traffic_gb,
});
// 实时检测过期节点组冲突
const conflict = await checkExpiredGroupConflict(checked);
setConflictError(conflict);
}}
/>
</div>
<p className="text-sm text-muted-foreground">
{t("trafficRangeDescription", "Users with traffic >= Min and < Max will be assigned to this node group")}
</p>
<div className="grid grid-cols-2 gap-4">
)}
{values.is_expired_group && (
<>
<div className="space-y-2">
<Label htmlFor="min_traffic_gb">{t("minTrafficGB", "Min Traffic (GB)")}</Label>
<Label htmlFor="expired_days_limit">
{t("expiredDaysLimit", "Expired Days Limit")}
</Label>
<p className="text-sm text-muted-foreground">
{t("expiredDaysLimitDescription", "Number of days after expiration that users can still access nodes")}
</p>
<Input
id="min_traffic_gb"
id="expired_days_limit"
type="number"
min={0}
step={1}
value={values.min_traffic_gb}
onChange={(e) => {
const newValue = parseFloat(e.target.value) || 0;
setValues({ ...values, min_traffic_gb: newValue });
// 实时检测冲突
const conflict = checkTrafficRangeConflict(newValue, values.max_traffic_gb);
setConflictError(conflict);
}}
min={1}
value={values.expired_days_limit}
onChange={(e) =>
setValues({ ...values, expired_days_limit: parseInt(e.target.value) || 7 })
}
/>
</div>
<div className="space-y-2">
<Label htmlFor="max_traffic_gb">{t("maxTrafficGB", "Max Traffic (GB)")}</Label>
<Label htmlFor="max_traffic_gb_expired">
{t("maxTrafficGBExpired", "Max Traffic for Expired Users (GB)")}
</Label>
<p className="text-sm text-muted-foreground">
{t("maxTrafficGBExpiredDescription", "Maximum traffic allowed for expired users (0 = unlimited)")}
</p>
<Input
id="max_traffic_gb"
id="max_traffic_gb_expired"
type="number"
min={0}
step={1}
value={values.max_traffic_gb}
onChange={(e) => {
const newValue = parseFloat(e.target.value) || 0;
setValues({ ...values, max_traffic_gb: newValue });
// 实时检测冲突
const conflict = checkTrafficRangeConflict(values.min_traffic_gb, newValue);
setConflictError(conflict);
}}
value={values.max_traffic_gb_expired}
onChange={(e) =>
setValues({ ...values, max_traffic_gb_expired: parseInt(e.target.value) || 0 })
}
/>
</div>
</div>
{/* 显示冲突错误 */}
{conflictError && (
<div className="flex items-center gap-2 rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive">
<AlertCircle className="h-4 w-4 flex-shrink-0" />
<span>{conflictError}</span>
<div className="space-y-2">
<Label htmlFor="speed_limit">
{t("speedLimit", "Speed Limit (KB/s)")}
</Label>
<Input
id="speed_limit"
type="number"
min={0}
value={values.speed_limit}
onChange={(e) =>
setValues({ ...values, speed_limit: parseInt(e.target.value) || 0 })
}
/>
</div>
)}
</div>
</>
)}
{!values.is_expired_group && (
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label>{t("trafficRangeGB", "Traffic Range (GB)")}</Label>
</div>
<p className="text-sm text-muted-foreground">
{t("trafficRangeDescription", "Users with traffic >= Min and < Max will be assigned to this node group")}
</p>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="min_traffic_gb">{t("minTrafficGB", "Min Traffic (GB)")}</Label>
<Input
id="min_traffic_gb"
type="number"
min={0}
step={1}
value={values.min_traffic_gb}
onChange={(e) => {
const newValue = parseFloat(e.target.value) || 0;
setValues({ ...values, min_traffic_gb: newValue });
// 实时检测冲突
const conflict = checkTrafficRangeConflict(newValue, values.max_traffic_gb);
setConflictError(conflict);
}}
/>
</div>
<div className="space-y-2">
<Label htmlFor="max_traffic_gb">{t("maxTrafficGB", "Max Traffic (GB)")}</Label>
<Input
id="max_traffic_gb"
type="number"
min={0}
step={1}
value={values.max_traffic_gb}
onChange={(e) => {
const newValue = parseFloat(e.target.value) || 0;
setValues({ ...values, max_traffic_gb: newValue });
// 实时检测冲突
const conflict = checkTrafficRangeConflict(values.min_traffic_gb, newValue);
setConflictError(conflict);
}}
/>
</div>
</div>
{/* 显示冲突错误 */}
{conflictError && (
<div className="flex items-center gap-2 rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm text-destructive">
<AlertCircle className="h-4 w-4 flex-shrink-0" />
<span>{conflictError}</span>
</div>
)}
</div>
)}
<div className="flex justify-end gap-2">
<button
+13 -1
View File
@@ -77,6 +77,19 @@ export default function NodeGroups() {
id: "name",
accessorKey: "name",
header: t("name", "Name"),
cell: ({ row }: { row: any }) => {
const isExpiredGroup = row.original.is_expired_group;
return (
<div className="flex items-center gap-2">
<span>{row.getValue("name")}</span>
{isExpiredGroup && (
<Badge variant="destructive">
{t("expiredGroup", "Expired")}
</Badge>
)}
</div>
);
},
},
{
id: "description",
@@ -99,7 +112,6 @@ export default function NodeGroups() {
},
{
id: "traffic_range",
accessorKey: "traffic_range",
header: t("trafficRange", "Traffic Range (GB)"),
cell: ({ row }: { row: any }) => {
const min = row.original.min_traffic_gb;
@@ -84,6 +84,7 @@ const defaultValues = {
renewal_reset: false,
show_original_price: false,
deduction_mode: "auto",
traffic_limit: [],
};
export default function SubscribeForm<T extends Record<string, any>>({
@@ -129,6 +130,16 @@ export default function SubscribeForm<T extends Record<string, any>>({
reset_cycle: z.number().optional(),
renewal_reset: z.boolean().optional(),
show_original_price: z.boolean().optional(),
traffic_limit: z
.array(
z.object({
stat_type: z.string(),
stat_value: z.number().int(),
traffic_usage: z.number(),
speed_limit: z.number(),
})
)
.optional(),
});
const form = useForm<z.infer<typeof formSchema>>({
@@ -283,12 +294,14 @@ export default function SubscribeForm<T extends Record<string, any>>({
const tagGroups = getAllAvailableTags();
// Fetch node groups
// Fetch node groups (exclude expired groups)
const { data: nodeGroupsData } = useQuery({
queryKey: ["nodeGroups"],
queryFn: async () => {
const { data } = await getNodeGroupList({ page: 1, size: 1000 });
return data.data?.list || [];
const allGroups = data.data?.list || [];
// Filter out expired node groups
return allGroups.filter((group) => !group.is_expired_group);
},
});
@@ -344,7 +357,7 @@ export default function SubscribeForm<T extends Record<string, any>>({
<Form {...form}>
<form className="pt-4" onSubmit={form.handleSubmit(handleSubmit)}>
<Tabs className="w-full" defaultValue="basic">
<TabsList className="mb-6 grid w-full grid-cols-3">
<TabsList className="mb-6 grid w-full grid-cols-4">
<TabsTrigger
className="flex items-center gap-2"
value="basic"
@@ -366,6 +379,13 @@ export default function SubscribeForm<T extends Record<string, any>>({
<Server className="h-4 w-4" />
{t("form.nodes")}
</TabsTrigger>
<TabsTrigger
className="flex items-center gap-2"
value="traffic-limit"
>
<Icon className="h-4 w-4" icon="uil:tachometer-fast" />
{t("form.trafficLimit")}
</TabsTrigger>
</TabsList>
<TabsContent className="space-y-4" value="basic">
@@ -1396,6 +1416,91 @@ export default function SubscribeForm<T extends Record<string, any>>({
)}
</div>
</TabsContent>
{/* Traffic Limit Tab */}
<TabsContent className="space-y-4" value="traffic-limit">
<div className="space-y-4">
<FormField
control={form.control}
name="traffic_limit"
render={({ field }) => (
<FormItem>
<FormLabel>{t("form.trafficLimitRules", "Traffic Limit Rules")}</FormLabel>
<FormControl>
<ArrayInput
value={field.value && field.value.length > 0 ? field.value : [{ stat_type: "day" }]}
onChange={field.onChange}
fields={[
{
name: "stat_type",
type: "select",
placeholder: t("form.statType", "Statistics Type"),
value: "day",
options: [
{ label: t("form.statTypeHour", "Hour"), value: "hour" },
{ label: t("form.statTypeDay", "Day"), value: "day" },
],
},
{
name: "stat_value",
type: "number",
placeholder: t("form.statValue", "Time Value"),
min: 1,
onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === '.' || e.key === ',') {
e.preventDefault();
}
},
formatOutput: (value: string | number) => {
const num = Number(value);
return isNaN(num) ? 0 : Math.floor(num);
},
},
{
name: "traffic_usage",
type: "number",
placeholder: t("form.trafficUsage", "Traffic Usage (GB)"),
min: 0,
onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === '.' || e.key === ',') {
e.preventDefault();
}
},
formatOutput: (value: string | number) => {
const num = Number(value);
return isNaN(num) ? 0 : Math.floor(num);
},
},
{
name: "speed_limit",
type: "number",
placeholder: t("form.speedLimitKb", "Speed Limit (kb)"),
min: 0,
onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === '.' || e.key === ',') {
e.preventDefault();
}
},
formatOutput: (value: string | number) => {
const num = Number(value);
return isNaN(num) ? 0 : Math.floor(num);
},
},
]}
/>
</FormControl>
<FormDescription>
{t(
"form.trafficLimitDescription",
"Configure traffic-based speed limit rules. When traffic usage reaches the specified amount, the speed will be limited."
)}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</div>
</TabsContent>
</Tabs>
</form>
</Form>
@@ -31,12 +31,14 @@ export default function SubscribeTable() {
const ref = useRef<ProTableActions>(null);
const { fetchSubscribes } = useSubscribe();
// Fetch node groups for filtering
// Fetch node groups for filtering (exclude expired groups)
const { data: nodeGroupsData } = useQuery({
queryKey: ["nodeGroups"],
queryFn: async () => {
const { data } = await getNodeGroupList({ page: 1, size: 1000 });
return data.data?.list || [];
const allGroups = data.data?.list || [];
// Filter out expired node groups
return allGroups.filter((group) => !group.is_expired_group);
},
});