feat(clients): add calendar weekly renewal and schedule previews (#6524)

* feat(clients): add calendar weekly renewal and schedule previews

Expose fixed-day, calendar-weekly, calendar-monthly, and disabled renewal
through one shared selector in individual and bulk client forms. Store the
weekly weekday separately (Monday 1 through Sunday 7) and use panel-local
calendar dates rather than a fixed 168-hour duration. Resolve skipped or
repeated midnights to the first valid instant of the selected date, and skip
an entirely nonexistent calendar date rather than changing the weekday.

Reuse the existing renewal writer and share its boundary alignment and
per-period catch-up calculation with an authenticated, read-only preview.
Keep monthly precedence for legacy records, fixed-day interval semantics,
maximum renewal allowances, first-use durations, and operator-disabled
settings unchanged. Selecting a mode does not rewrite an existing cutoff;
an unset calendar cutoff requires an explicit action to choose the first.
The last-valid-second preview uses the stored exclusive expiry, even when
the billing calculation aligns a legacy last-second cutoff up to midnight.

Carry weekly schedules through client persistence, paging, enable toggles,
inbound settings, and node traffic reconciliation. Migrate missing or nullable
weekday columns to disabled by default without altering existing limits, and
include the new isolated-schema PostgreSQL regression in the live CI gate.

Regenerate API contracts and reference documentation, add lifecycle and form
regressions, and document timezone, quota-reset, and upgrade considerations.
All participating nodes must be upgraded before weekly mode is enabled;
older binaries ignore the new field. Independent periodic traffic resets and
the optional month-end subscription-header display are not changed.

* fix(clients): validate renewal schedules across inbound write paths

Reject conflicting weekly/interval/monthly schedules and out-of-range
weekdays on inbound creation and edits, legacy one-client apply paths,
record/link synchronization, and traffic metadata writes. Validate imported
traffic snapshots as well, before any inbound or client is persisted, so
an inbound API cannot create a client that the clients page cannot toggle.

Merge a weekly-related schedule as one timestamp-selected tuple rather
than filling its zero fields from another renewal mode. Preserve empty
migration snapshots and the existing non-weekly monthly/interval merge
semantics. Renewal caps, counters, credentials, and deadlines are unchanged.

Add regressions for nine write paths, unchanged records and runtime calls
after rejection, valid inbound clients remaining editable, and duplicate
record merges between individually valid renewal modes.

* docs(clients): clarify depleted-client deletion risks on downgrade

Explain in English and Chinese that older versions not only stop weekly
renewal: their depleted-client cleanup can delete a weekly-only client once
its expiry or quota is exhausted. This is conditional on cleanup, not an
automatic deletion caused by downgrade itself.

Recommend backing up and converting weekly schedules to a mode supported
by every participating version before rollback, and avoiding cleanup while
mixed versions or unconverted clients remain. Merely disabling weekly
renewal does not restore the old binary's missing purge protection.

* fix(clients): bound weekly renewal date searches

Limit the search for a valid weekly calendar date to eight candidates so
an unusual timezone cannot monopolize the single traffic writer. Exhaustion
returns the original instant, allowing the existing catch-up forward-progress
guard to stop without advancing expiry, consuming an allowance, resetting
traffic, or falling back to a fixed-duration schedule that can drift.

Reject a non-future calendar suggestion in the read-only preview instead of
offering an immediately expired initial cutoff. Also report failed weekly
catch-up as a search error when allowances remain, not as cap exhaustion.
Existing preview errors use the form's current warning; no API schema or
locale changes are needed.

Exercise exhaustion with a synthetic valid TZif containing twelve skipped
Sundays. This fault-injection case was red without the bound; it is not a
claim that a production IANA timezone was observed hanging. Keep the Havana
and Apia regressions for real skipped/repeated midnights and absent dates.

* fix(tests): isolate weekly renewal preview timezone

Stop the weekly search regression from replacing process-global time.Local.
CI caught that assignment and its cleanup racing with background timer reads
through time.Now, even though the top-level tests do not use t.Parallel.

Pass the timezone and current instant into the unchanged preview calculation.
The public service still validates the request and resolves the panel timezone;
API responses, renewal accounting, and persisted client data are unchanged.

Use fixed dates for both suggestion and catch-up exhaustion, removing the
test's dependency on today's date and its unnecessary database setup. Keep a
bounded-lifetime background clock reader to expose future global-timezone
mutations under the existing race gate rather than disabling that check.

* ci: retrigger PR checks

Create an empty commit to request a fresh pull-request CI run after release dependency downloads failed with network errors.

No source, dependency, or workflow changes are included. Retry the existing checks without bypassing them.

* ci: retry PR checks and record deferred download hardening

Request another CI run after the amd64 release job compiled successfully but failed during dependency fetching with exit code 4 (network failure).

Record possible follow-up improvements for the Linux release fetch helper:
- Print each download URL and destination, and preserve error details.
- Reuse the existing curl configuration with up to five retries; add connection and per-attempt timeouts and a bounded retry window.
- Download to a temporary file and promote it to the final filename only after a successful, non-empty transfer. Keep the job failing if downloads ultimately fail.
- Validate successful downloads, recovery after a temporary failure, and correct failure after persistent errors before shipping such a change.

These improvements are intentionally deferred, not implemented or tested by this commit. This commit is empty: renewal logic, dependencies, workflow configuration, check requirements, and TLS verification remain unchanged.

---------

Co-authored-by: JacktheRanger <219502738+JacktheRanger@users.noreply.github.com>
This commit is contained in:
Jack
2026-09-27 04:59:23 +08:00
committed by GitHub
parent 5e15120cec
commit 9672249edb
58 changed files with 2712 additions and 197 deletions
+25
View File
@@ -371,6 +371,7 @@ export const EXAMPLES: Record<string, unknown> = {
"reset": 0,
"resetDay": 0,
"resetMax": 0,
"resetWeekday": 0,
"reverse": null,
"secret": "ee1234567890abcdef1234567890abcd7777772e636c6f7564666c6172652e636f6d",
"security": "",
@@ -410,6 +411,7 @@ export const EXAMPLES: Record<string, unknown> = {
"reset": 0,
"resetDay": 0,
"resetMax": 0,
"resetWeekday": 0,
"subId": "abcd1234",
"totalGB": 53687091200,
"traffic": null,
@@ -459,6 +461,7 @@ export const EXAMPLES: Record<string, unknown> = {
"reset": 0,
"resetDay": 0,
"resetMax": 0,
"resetWeekday": 0,
"reverse": null,
"secret": "",
"security": "",
@@ -470,6 +473,25 @@ export const EXAMPLES: Record<string, unknown> = {
"updatedAt": 0,
"uuid": ""
},
"ClientRenewalPreview": {
"canRenew": true,
"delayedStart": false,
"nextExpiry": "2030-02-01T00:00:00Z",
"renewAt": "2030-01-01T00:00:00Z",
"renewals": 1,
"suggestedExpiry": "2030-01-01T00:00:00Z",
"suggestedExpiryTime": 1893456000000,
"timeZone": "UTC",
"validThrough": "2029-12-31T23:59:59Z"
},
"ClientRenewalPreviewRequest": {
"expiryTime": 1893456000000,
"reset": 0,
"resetCount": 0,
"resetDay": 1,
"resetMax": 0,
"resetWeekday": 0
},
"ClientReverse": {
"tag": ""
},
@@ -489,6 +511,7 @@ export const EXAMPLES: Record<string, unknown> = {
"reset": 0,
"resetDay": 0,
"resetMax": 0,
"resetWeekday": 0,
"subId": "abcd1234",
"totalGB": 53687091200,
"traffic": null,
@@ -507,6 +530,7 @@ export const EXAMPLES: Record<string, unknown> = {
"resetCount": 0,
"resetDay": 0,
"resetMax": 0,
"resetWeekday": 0,
"subId": "i7tvdpeffi0hvvf1",
"total": 10737418240,
"up": 1048576,
@@ -704,6 +728,7 @@ export const EXAMPLES: Record<string, unknown> = {
"resetCount": 0,
"resetDay": 0,
"resetMax": 0,
"resetWeekday": 0,
"subId": "i7tvdpeffi0hvvf1",
"total": 10737418240,
"up": 1048576,
+113 -2
View File
@@ -1505,13 +1505,17 @@ export const SCHEMAS: Record<string, unknown> = {
"type": "integer"
},
"resetDay": {
"description": "Calendar renewal day 1-31, 0 = interval mode",
"description": "Calendar renewal day 1-31, 0 disables monthly renewal",
"type": "integer"
},
"resetMax": {
"description": "Max auto-renew count, 0 = unlimited",
"type": "integer"
},
"resetWeekday": {
"description": "Calendar weekday 1-7 (Mon-Sun), 0 disables weekly renewal",
"type": "integer"
},
"reverse": {
"allOf": [
{
@@ -1574,6 +1578,7 @@ export const SCHEMAS: Record<string, unknown> = {
"reset",
"resetDay",
"resetMax",
"resetWeekday",
"security",
"subId",
"tgId",
@@ -1725,6 +1730,9 @@ export const SCHEMAS: Record<string, unknown> = {
"resetMax": {
"type": "integer"
},
"resetWeekday": {
"type": "integer"
},
"reverse": {},
"secret": {
"type": "string"
@@ -1780,6 +1788,7 @@ export const SCHEMAS: Record<string, unknown> = {
"reset",
"resetDay",
"resetMax",
"resetWeekday",
"reverse",
"secret",
"security",
@@ -1793,6 +1802,97 @@ export const SCHEMAS: Record<string, unknown> = {
],
"type": "object"
},
"ClientRenewalPreview": {
"properties": {
"canRenew": {
"example": true,
"type": "boolean"
},
"delayedStart": {
"example": false,
"type": "boolean"
},
"nextExpiry": {
"example": "2030-02-01T00:00:00Z",
"type": "string"
},
"renewAt": {
"example": "2030-01-01T00:00:00Z",
"type": "string"
},
"renewals": {
"example": 1,
"type": "integer"
},
"suggestedExpiry": {
"example": "2030-01-01T00:00:00Z",
"type": "string"
},
"suggestedExpiryTime": {
"example": 1893456000000,
"format": "int64",
"type": "integer"
},
"timeZone": {
"example": "UTC",
"type": "string"
},
"validThrough": {
"example": "2029-12-31T23:59:59Z",
"type": "string"
}
},
"required": [
"canRenew",
"delayedStart",
"nextExpiry",
"renewAt",
"renewals",
"suggestedExpiry",
"suggestedExpiryTime",
"timeZone",
"validThrough"
],
"type": "object"
},
"ClientRenewalPreviewRequest": {
"properties": {
"expiryTime": {
"example": 1893456000000,
"format": "int64",
"type": "integer"
},
"reset": {
"example": 0,
"type": "integer"
},
"resetCount": {
"example": 0,
"type": "integer"
},
"resetDay": {
"example": 1,
"type": "integer"
},
"resetMax": {
"example": 0,
"type": "integer"
},
"resetWeekday": {
"example": 0,
"type": "integer"
}
},
"required": [
"expiryTime",
"reset",
"resetCount",
"resetDay",
"resetMax",
"resetWeekday"
],
"type": "object"
},
"ClientReverse": {
"properties": {
"tag": {
@@ -1863,6 +1963,10 @@ export const SCHEMAS: Record<string, unknown> = {
"example": 0,
"type": "integer"
},
"resetWeekday": {
"example": 0,
"type": "integer"
},
"subId": {
"example": "abcd1234",
"type": "string"
@@ -1897,6 +2001,7 @@ export const SCHEMAS: Record<string, unknown> = {
"reset",
"resetDay",
"resetMax",
"resetWeekday",
"subId",
"totalGB",
"updatedAt"
@@ -1952,7 +2057,7 @@ export const SCHEMAS: Record<string, unknown> = {
"type": "integer"
},
"resetDay": {
"description": "ResetDay renews on that day of each calendar month instead of every\nReset days; 0 keeps the interval behaviour.",
"description": "ResetDay renews on that day of each calendar month instead of every\nReset days; 0 disables monthly renewal.",
"example": 0,
"type": "integer"
},
@@ -1961,6 +2066,11 @@ export const SCHEMAS: Record<string, unknown> = {
"example": 0,
"type": "integer"
},
"resetWeekday": {
"description": "ResetWeekday renews weekly at panel-local midnight: 1 Monday through 7 Sunday.",
"example": 0,
"type": "integer"
},
"subId": {
"example": "i7tvdpeffi0hvvf1",
"type": "string"
@@ -1993,6 +2103,7 @@ export const SCHEMAS: Record<string, unknown> = {
"resetCount",
"resetDay",
"resetMax",
"resetWeekday",
"subId",
"total",
"up",
+25
View File
@@ -367,6 +367,7 @@ export interface Client {
reset: number;
resetDay: number;
resetMax: number;
resetWeekday: number;
reverse?: ClientReverse | null;
secret?: string;
security: string;
@@ -418,6 +419,7 @@ export interface ClientRecord {
reset: number;
resetDay: number;
resetMax: number;
resetWeekday: number;
reverse: unknown;
secret: string;
security: string;
@@ -430,6 +432,27 @@ export interface ClientRecord {
uuid: string;
}
export interface ClientRenewalPreview {
canRenew: boolean;
delayedStart: boolean;
nextExpiry: string;
renewAt: string;
renewals: number;
suggestedExpiry: string;
suggestedExpiryTime: number;
timeZone: string;
validThrough: string;
}
export interface ClientRenewalPreviewRequest {
expiryTime: number;
reset: number;
resetCount: number;
resetDay: number;
resetMax: number;
resetWeekday: number;
}
export interface ClientReverse {
tag: string;
}
@@ -447,6 +470,7 @@ export interface ClientSlim {
reset: number;
resetDay: number;
resetMax: number;
resetWeekday: number;
subId: string;
totalGB: number;
traffic?: ClientTraffic | null;
@@ -466,6 +490,7 @@ export interface ClientTraffic {
resetCount: number;
resetDay: number;
resetMax: number;
resetWeekday: number;
subId: string;
total: number;
up: number;
+27
View File
@@ -388,6 +388,7 @@ export const ClientSchema = z.object({
reset: z.number().int(),
resetDay: z.number().int(),
resetMax: z.number().int(),
resetWeekday: z.number().int(),
reverse: z.lazy(() => ClientReverseSchema).nullable().optional(),
secret: z.string().optional(),
security: z.string(),
@@ -442,6 +443,7 @@ export const ClientRecordSchema = z.object({
reset: z.number().int(),
resetDay: z.number().int(),
resetMax: z.number().int(),
resetWeekday: z.number().int(),
reverse: z.unknown(),
secret: z.string(),
security: z.string(),
@@ -455,6 +457,29 @@ export const ClientRecordSchema = z.object({
});
export type ClientRecord = z.infer<typeof ClientRecordSchema>;
export const ClientRenewalPreviewSchema = z.object({
canRenew: z.boolean(),
delayedStart: z.boolean(),
nextExpiry: z.string(),
renewAt: z.string(),
renewals: z.number().int(),
suggestedExpiry: z.string(),
suggestedExpiryTime: z.number().int(),
timeZone: z.string(),
validThrough: z.string(),
});
export type ClientRenewalPreview = z.infer<typeof ClientRenewalPreviewSchema>;
export const ClientRenewalPreviewRequestSchema = z.object({
expiryTime: z.number().int(),
reset: z.number().int(),
resetCount: z.number().int(),
resetDay: z.number().int(),
resetMax: z.number().int(),
resetWeekday: z.number().int(),
});
export type ClientRenewalPreviewRequest = z.infer<typeof ClientRenewalPreviewRequestSchema>;
export const ClientReverseSchema = z.object({
tag: z.string(),
});
@@ -473,6 +498,7 @@ export const ClientSlimSchema = z.object({
reset: z.number().int(),
resetDay: z.number().int(),
resetMax: z.number().int(),
resetWeekday: z.number().int(),
subId: z.string(),
totalGB: z.number().int(),
traffic: z.lazy(() => ClientTrafficSchema).nullable().optional(),
@@ -493,6 +519,7 @@ export const ClientTrafficSchema = z.object({
resetCount: z.number().int(),
resetDay: z.number().int(),
resetMax: z.number().int(),
resetWeekday: z.number().int(),
subId: z.string(),
total: z.number().int(),
up: z.number().int(),
+1
View File
@@ -696,6 +696,7 @@ export function useClients(options: UseClientsOptions = {}) {
tgId: Number(base.tgId) || 0,
reset: Number(base.reset) || 0,
resetDay: Number(base.resetDay) || 0,
resetWeekday: Number(base.resetWeekday) || 0,
resetMax: Number(base.resetMax) || 0,
trafficReset: base.trafficReset || 'never',
trafficResetDay: Number(base.trafficResetDay) || 1,
+46
View File
@@ -1169,6 +1169,52 @@ export const sections: readonly Section[] = [
body: '{\n "client": {\n "email": "alice@example.com",\n "totalGB": 53687091200,\n "expiryTime": 1735689600000,\n "tgId": 0,\n "limitIp": 0,\n "limitHwid": 0,\n "enable": true\n },\n "inboundIds": [3, 5]\n}',
response: '{\n "success": true,\n "msg": "Client added"\n}',
},
{
method: 'POST',
path: '/panel/api/clients/renewalPreview',
summary: 'Preview client auto-renewal dates without saving or resetting anything.',
description:
'Uses the same calendar and catch-up calculation as auto-renew in the panel timezone. resetWeekday is 1 (Monday) to 7 (Sunday), 0 disables weekly mode; it cannot be combined with positive reset or resetDay. Existing resetDay takes precedence over reset. With expiryTime=0, calendar modes suggest a first cutoff but do not activate renewal. Negative expiryTime waits for first-use activation. resetMax and resetCount simulate the existing per-period allowance limit; the preview is informational and does not reserve an allowance or guarantee node availability.',
params: [
{
name: 'expiryTime',
in: 'body (json)',
type: 'integer',
desc: 'Current cutoff in Unix milliseconds; 0 unlimited, negative first-use duration.',
},
{
name: 'reset',
in: 'body (json)',
type: 'integer',
desc: 'Fixed interval in days; 0 disabled.',
},
{
name: 'resetDay',
in: 'body (json)',
type: 'integer',
desc: 'Monthly calendar day 1-31; 0 disabled.',
},
{
name: 'resetWeekday',
in: 'body (json)',
type: 'integer',
desc: 'Weekly calendar day 1-7 (Monday-Sunday); 0 disabled.',
},
{
name: 'resetMax',
in: 'body (json)',
type: 'integer',
desc: 'Maximum renewals; 0 unlimited.',
},
{
name: 'resetCount',
in: 'body (json)',
type: 'integer',
desc: 'Renewals already consumed; defaults to 0.',
},
],
responseSchema: 'ClientRenewalPreview',
},
{
method: 'POST',
path: '/panel/api/clients/update/:email',
@@ -25,6 +25,7 @@ import { DateTimePicker, SelectAllClearButtons } from '@/components/form';
import { FormField } from '@/components/form/rhf';
import { useClients, type InboundOption } from '@/hooks/useClients';
import { useFail2banStatusQuery, getLimitIpNotice } from '@/api/queries/useFail2banStatusQuery';
import ClientRenewalFields from './ClientRenewalFields';
import { ClientBulkAddFormSchema, type ClientBulkAddFormValues } from '@/schemas/client';
const FLOW_OPTIONS = Object.values(TLS_FLOW_CONTROL);
@@ -57,6 +58,7 @@ const EMPTY: ClientBulkAddFormValues = {
expiryTime: 0,
reset: 0,
resetDay: 0,
resetWeekday: 0,
resetMax: 0,
trafficReset: 'never' as const,
trafficResetDay: 1,
@@ -215,6 +217,7 @@ export default function ClientBulkAddModal({
expiryTime: current.expiryTime,
reset: Number(current.reset) || 0,
resetDay: Number(current.resetDay) || 0,
resetWeekday: Number(current.resetWeekday) || 0,
resetMax: Number(current.resetMax) || 0,
trafficReset: current.trafficReset || 'never',
trafficResetDay: Number(current.trafficResetDay) || 1,
@@ -437,32 +440,13 @@ export default function ClientBulkAddModal({
</Form.Item>
)}
<FormField
name="reset"
label={t('pages.clients.renew')}
tooltip={t('pages.clients.renewDesc')}
transform={{ output: (v) => Number(v) || 0 }}
>
<InputNumber min={0} />
</FormField>
<FormField
name="resetDay"
label={t('pages.clients.renewOnDay')}
tooltip={t('pages.clients.renewOnDayDesc')}
transform={{ output: (v) => Number(v) || 0 }}
>
<InputNumber min={0} max={31} />
</FormField>
<FormField
name="resetMax"
label={t('pages.clients.renewMax')}
tooltip={t('pages.clients.renewMaxDesc')}
transform={{ output: (v) => Number(v) || 0 }}
>
<InputNumber min={0} />
</FormField>
<ClientRenewalFields
active={open}
delayedStart={delayedStart}
expiryTime={expiryTime}
bulk
setExpiry={(expiry) => methods.setValue('expiryTime', expiry)}
/>
<FormField name="trafficReset" label={t('pages.inbounds.periodicTrafficResetTitle')}>
<Select
+16 -29
View File
@@ -48,6 +48,7 @@ import type {
ExternalLinkInput,
} from '@/hooks/useClients';
import { useFail2banStatusQuery, getLimitIpNotice } from '@/api/queries/useFail2banStatusQuery';
import ClientRenewalFields from './ClientRenewalFields';
import { ClientFormSchema, ClientCreateFormSchema, type ClientFormValues } from '@/schemas/client';
import './ClientFormModal.css';
@@ -155,6 +156,7 @@ const EMPTY: Values = {
delayedDays: 0,
reset: 0,
resetDay: 0,
resetWeekday: 0,
resetMax: 0,
trafficReset: 'never' as const,
trafficResetDay: 1,
@@ -259,6 +261,7 @@ export default function ClientFormModal({
const methods = useForm<Values>({ defaultValues: EMPTY });
const inboundIds = useWatch({ control: methods.control, name: 'inboundIds' });
const delayedStart = useWatch({ control: methods.control, name: 'delayedStart' });
const delayedDays = useWatch({ control: methods.control, name: 'delayedDays' });
const expiryDate = useWatch({ control: methods.control, name: 'expiryDate' });
const enable = useWatch({ control: methods.control, name: 'enable' });
const flow = useWatch({ control: methods.control, name: 'flow' });
@@ -366,6 +369,7 @@ export default function ClientFormModal({
totalGB: bytesToGB(client.totalGB || 0),
reset: Number(client.reset) || 0,
resetDay: Number(client.resetDay) || 0,
resetWeekday: Number(client.resetWeekday) || 0,
resetMax: Number(client.resetMax) || 0,
trafficReset: (client.trafficReset as ClientFormValues['trafficReset']) || 'never',
trafficResetDay: Number(client.trafficResetDay) || 1,
@@ -663,6 +667,7 @@ export default function ClientFormModal({
delayedDays: values.delayedDays,
reset: values.reset,
resetDay: values.resetDay,
resetWeekday: values.resetWeekday,
resetMax: values.resetMax,
trafficReset: values.trafficReset,
trafficResetDay: values.trafficResetDay,
@@ -696,6 +701,7 @@ export default function ClientFormModal({
expiryTime,
reset: Number(values.reset) || 0,
resetDay: Number(values.resetDay) || 0,
resetWeekday: Number(values.resetWeekday) || 0,
resetMax: Number(values.resetMax) || 0,
trafficReset: values.trafficReset || 'never',
trafficResetDay: Number(values.trafficResetDay) || 1,
@@ -985,35 +991,16 @@ export default function ClientFormModal({
/>
</Form.Item>
</Col>
<Col xs={12} md={6}>
<FormField
name="reset"
label={t('pages.clients.renewDays')}
tooltip={t('pages.clients.renewDesc')}
transform={{ output: (v) => Number(v) || 0 }}
>
<InputNumber min={0} style={{ width: '100%' }} />
</FormField>
</Col>
<Col xs={12} md={6}>
<FormField
name="resetDay"
label={t('pages.clients.renewOnDay')}
tooltip={t('pages.clients.renewOnDayDesc')}
transform={{ output: (v) => Number(v) || 0 }}
>
<InputNumber min={0} max={31} style={{ width: '100%' }} />
</FormField>
</Col>
<Col xs={12} md={6}>
<FormField
name="resetMax"
label={t('pages.clients.renewMax')}
tooltip={t('pages.clients.renewMaxDesc')}
transform={{ output: (v) => Number(v) || 0 }}
>
<InputNumber min={0} style={{ width: '100%' }} />
</FormField>
<Col xs={24}>
<ClientRenewalFields
active={open}
delayedStart={delayedStart}
expiryTime={
delayedStart ? -86400000 * (delayedDays || 0) : expiryDate || 0
}
resetCount={client?.traffic?.resetCount || 0}
setExpiry={(expiry) => methods.setValue('expiryDate', expiry)}
/>
</Col>
<Col xs={12} md={6}>
<FormField
@@ -0,0 +1,197 @@
import { useEffect, useId, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useFormContext, useWatch } from 'react-hook-form';
import { useQuery } from '@tanstack/react-query';
import { Button, Form, InputNumber, Select, Space, Typography } from 'antd';
import { FormField } from '@/components/form/rhf';
import { ClientRenewalPreviewSchema } from '@/generated/zod';
import { HttpUtil } from '@/utils';
import type { ClientFormValues } from '@/schemas/client';
type RenewalFields = Pick<ClientFormValues, 'reset' | 'resetDay' | 'resetWeekday' | 'resetMax'>;
type RenewalMode = 'none' | 'interval' | 'weekly' | 'monthly';
export default function ClientRenewalFields({
active,
expiryTime,
resetCount = 0,
bulk = false,
delayedStart = false,
setExpiry,
}: {
active: boolean;
expiryTime: number;
resetCount?: number;
bulk?: boolean;
delayedStart?: boolean;
setExpiry: (expiry: number) => void;
}) {
const { t, i18n } = useTranslation();
const formId = useId();
const modeId = 'client-renewal-mode-' + formId;
const { control, setValue } = useFormContext<RenewalFields>();
const [reset, resetDay, resetWeekday, resetMax] = useWatch({
control,
name: ['reset', 'resetDay', 'resetWeekday', 'resetMax'],
});
const mode: RenewalMode =
resetDay > 0 ? 'monthly' : resetWeekday > 0 ? 'weekly' : reset > 0 ? 'interval' : 'none';
const request = useMemo(
() => ({
expiryTime,
reset: reset || 0,
resetDay: resetDay || 0,
resetWeekday: resetWeekday || 0,
resetMax: resetMax || 0,
resetCount,
}),
[expiryTime, reset, resetDay, resetWeekday, resetMax, resetCount],
);
const [debounced, setDebounced] = useState(request);
useEffect(() => {
const timer = setTimeout(() => setDebounced(request), 250);
return () => clearTimeout(timer);
}, [request]);
const query = useQuery({
queryKey: ['clients', 'renewalPreview', debounced],
enabled: active && mode !== 'none' && request === debounced,
retry: false,
queryFn: async () => {
const msg = await HttpUtil.post('/panel/api/clients/renewalPreview', debounced, {
headers: { 'Content-Type': 'application/json' },
silent: true,
});
if (!msg?.success) throw new Error(msg?.msg || 'Renewal preview failed');
return ClientRenewalPreviewSchema.parse(msg.obj);
},
});
const preview = request === debounced ? query.data : undefined;
const weekdayFormatter = new Intl.DateTimeFormat(i18n.language, {
weekday: 'long',
timeZone: 'UTC',
});
function changeMode(next: RenewalMode) {
setValue('reset', next === 'interval' ? Math.max(1, reset || 0) : 0);
setValue('resetDay', next === 'monthly' ? Math.max(1, resetDay || 0) : 0);
setValue('resetWeekday', next === 'weekly' ? Math.max(1, resetWeekday || 0) : 0);
}
return (
<>
<Form.Item label={t('pages.clients.renewMode')} htmlFor={modeId}>
<Select
id={modeId}
value={mode}
onChange={changeMode}
options={[
{ value: 'none', label: t('pages.clients.renewModeNone') },
{ value: 'interval', label: t('pages.clients.renewModeInterval') },
{ value: 'weekly', label: t('pages.clients.renewModeWeekly') },
{ value: 'monthly', label: t('pages.clients.renewModeMonthly') },
]}
/>
</Form.Item>
{mode === 'interval' && (
<FormField
name="reset"
label={bulk ? t('pages.clients.renew') : t('pages.clients.renewDays')}
tooltip={t('pages.clients.renewDesc')}
transform={{ output: (v) => Number(v) || 1 }}
>
<InputNumber id={'client-renewal-interval-' + formId} min={1} style={{ width: '100%' }} />
</FormField>
)}
{mode === 'monthly' && (
<FormField
name="resetDay"
label={t('pages.clients.renewOnDay')}
tooltip={t('pages.clients.renewOnDayDesc')}
transform={{ output: (v) => Number(v) || 1 }}
>
<InputNumber
id={'client-renewal-day-' + formId}
min={1}
max={31}
style={{ width: '100%' }}
/>
</FormField>
)}
{mode === 'weekly' && (
<FormField name="resetWeekday" label={t('pages.clients.renewWeekday')}>
<Select
id={'client-renewal-weekday-' + formId}
options={Array.from({ length: 7 }, (_, i) => ({
value: i + 1,
label: weekdayFormatter.format(new Date(Date.UTC(2026, 0, i + 5))),
}))}
/>
</FormField>
)}
{mode !== 'none' && (
<>
<FormField
name="resetMax"
label={t('pages.clients.renewMax')}
tooltip={t('pages.clients.renewMaxDesc')}
transform={{ output: (v) => Number(v) || 0 }}
>
<InputNumber min={0} style={{ width: '100%' }} />
</FormField>
<Typography.Paragraph type="secondary">
{t('pages.clients.renewScheduleDesc')}
</Typography.Paragraph>
{query.isError && request === debounced && (
<Typography.Paragraph type="warning">
{t('pages.clients.renewPreviewError')}
</Typography.Paragraph>
)}
{preview && (
<Space orientation="vertical" size={4} style={{ marginBottom: 16 }}>
<Typography.Text>
{t('pages.clients.renewPreview', { zone: preview.timeZone })}
</Typography.Text>
{delayedStart || preview.delayedStart ? (
<Typography.Text type="secondary">
{t('pages.clients.renewFirstUse')}
</Typography.Text>
) : expiryTime === 0 ? (
<>
<Typography.Text type="warning">
{t('pages.clients.renewNeedsExpiry')}
</Typography.Text>
{preview.suggestedExpiryTime > 0 && (
<Button onClick={() => setExpiry(preview.suggestedExpiryTime)}>
{t('pages.clients.renewSetExpiry')}: {preview.suggestedExpiry}
</Button>
)}
</>
) : (
<>
<Typography.Text>
{t('pages.clients.renewAt')}: {preview.renewAt}
</Typography.Text>
<Typography.Text>
{t('pages.clients.renewValidThrough')}: {preview.validThrough}
</Typography.Text>
{preview.nextExpiry && (
<Typography.Text>
{t('pages.clients.renewNextExpiry')}: {preview.nextExpiry}
</Typography.Text>
)}
<Typography.Text>
{t('pages.clients.renewPeriods', { count: preview.renewals })}
</Typography.Text>
{!preview.canRenew && (
<Typography.Text type="warning">
{t('pages.clients.renewUnavailable')}
</Typography.Text>
)}
</>
)}
</Space>
)}
</>
)}
</>
);
}
+3
View File
@@ -41,6 +41,7 @@ export const ClientRecordSchema = z
enable: z.boolean().optional(),
reset: z.number().optional(),
resetDay: z.number().optional(),
resetWeekday: z.number().optional(),
resetMax: z.number().optional(),
trafficReset: z.string().optional(),
trafficResetDay: z.number().optional(),
@@ -328,6 +329,7 @@ export const ClientFormSchema = z.object({
delayedDays: z.number().int().min(0),
reset: z.number().int().min(0),
resetDay: z.number().int().min(0).max(31),
resetWeekday: z.number().int().min(0).max(7),
resetMax: z.number().int().min(0),
trafficReset: z.enum(['never', 'hourly', 'daily', 'weekly', 'monthly']),
trafficResetDay: z.number().int().min(1).max(31),
@@ -392,6 +394,7 @@ export const ClientBulkAddFormSchema = z.object({
expiryTime: z.number(),
reset: z.number().int().min(0),
resetDay: z.number().int().min(0).max(31),
resetWeekday: z.number().int().min(0).max(7),
resetMax: z.number().int().min(0),
trafficReset: z.enum(['never', 'hourly', 'daily', 'weekly', 'monthly']).optional(),
trafficResetDay: z.number().int().min(1).max(31).optional(),
@@ -0,0 +1,113 @@
import { expect, it, vi } from 'vitest';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import ClientBulkAddModal from '@/pages/clients/ClientBulkAddModal';
import { HttpUtil, Msg } from '@/utils';
import { chooseSelectOption, renderWithProviders } from './test-utils';
const { bulkCreate } = vi.hoisted(() => ({ bulkCreate: vi.fn() }));
vi.mock('@/hooks/useClients', () => ({ useClients: () => ({ bulkCreate }) }));
it('keeps bulk renewal disabled by default and requires explicit cutoff selection without changing first-use duration', async () => {
bulkCreate.mockResolvedValue(new Msg(true, '', { created: 1, skipped: [] }));
const post = vi.spyOn(HttpUtil, 'post').mockImplementation(async (url, body) => {
if (url !== '/panel/api/clients/renewalPreview')
return new Msg(true, '', { datepicker: 'gregorian' });
const request = body as { expiryTime: number };
return new Msg(true, '', {
timeZone: 'Asia/Taipei',
renewAt: '',
validThrough: '',
nextExpiry: '',
suggestedExpiryTime: 1893427200000,
suggestedExpiry: '2030-01-01T00:00:00+08:00',
renewals: 0,
canRenew: false,
delayedStart: request.expiryTime < 0,
});
});
async function submit() {
const button = document.querySelector('.ant-modal-footer .ant-btn-primary');
if (!button) throw new Error('Create button missing');
await waitFor(() => expect(button.classList.contains('ant-btn-loading')).toBe(false));
fireEvent.click(button);
}
try {
renderWithProviders(
<ClientBulkAddModal
open
inbounds={[{ id: 1, protocol: 'vless', tag: 'calendar' }]}
onOpenChange={() => {}}
/>,
);
fireEvent.click(screen.getByRole('button', { name: 'Select all' }));
const mode = screen.getByLabelText('Auto renewal');
expect(mode.closest('.ant-select')?.textContent).toContain('Disabled');
expect(post.mock.calls.some(([url]) => url === '/panel/api/clients/renewalPreview')).toBe(
false,
);
await submit();
await waitFor(() =>
expect(bulkCreate).toHaveBeenCalledWith([
expect.objectContaining({
client: expect.objectContaining({
reset: 0,
resetDay: 0,
resetWeekday: 0,
expiryTime: 0,
}),
}),
]),
);
chooseSelectOption(mode.id, 'Calendar weekly');
await waitFor(() => expect(document.body.textContent).toContain('An expiry must be set'));
await submit();
await waitFor(() =>
expect(bulkCreate).toHaveBeenLastCalledWith([
expect.objectContaining({
client: expect.objectContaining({
reset: 0,
resetDay: 0,
resetWeekday: 1,
expiryTime: 0,
}),
}),
]),
);
fireEvent.click(screen.getByRole('button', { name: /Set first cycle cutoff/ }));
await submit();
await waitFor(() =>
expect(bulkCreate).toHaveBeenLastCalledWith([
expect.objectContaining({
client: expect.objectContaining({ resetWeekday: 1, expiryTime: 1893427200000 }),
}),
]),
);
const label = Array.from(document.querySelectorAll('.ant-form-item-label label')).find(
(el) => el.textContent === 'Start After First Use',
);
const toggle = label?.closest('.ant-form-item')?.querySelector('[role="switch"]');
if (!toggle) throw new Error('First-use switch missing');
fireEvent.click(toggle);
const daysLabel = Array.from(document.querySelectorAll('.ant-form-item-label label')).find(
(el) => el.textContent === 'Duration (days)',
);
const daysInput = daysLabel?.closest('.ant-form-item')?.querySelector('input');
if (!daysInput) throw new Error('First-use days input missing');
fireEvent.change(daysInput, { target: { value: '7' } });
await waitFor(() =>
expect(document.body.textContent).toContain('Dates are available after first-use activation'),
);
expect(screen.queryByRole('button', { name: /Set first cycle cutoff/ })).toBeNull();
await submit();
await waitFor(() =>
expect(bulkCreate).toHaveBeenLastCalledWith([
expect.objectContaining({
client: expect.objectContaining({ resetWeekday: 1, expiryTime: -604800000 }),
}),
]),
);
} finally {
post.mockRestore();
}
});
@@ -0,0 +1,109 @@
import { expect, it, vi } from 'vitest';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import ClientFormModal from '@/pages/clients/ClientFormModal';
import { HttpUtil, Msg } from '@/utils';
import { chooseSelectOption, renderWithProviders } from './test-utils';
it('preserves monthly clients, previews backend dates, and saves exclusive weekly or disabled modes', async () => {
const post = vi.spyOn(HttpUtil, 'post').mockResolvedValue(
new Msg(true, '', {
timeZone: 'Asia/Taipei',
renewAt: '2030-01-01T00:00:00+08:00',
validThrough: '2029-12-31T23:59:59+08:00',
nextExpiry: '2030-02-01T00:00:00+08:00',
suggestedExpiryTime: 1893427200000,
suggestedExpiry: '2030-01-01T00:00:00+08:00',
renewals: 1,
canRenew: true,
delayedStart: false,
}),
);
const save = vi.fn().mockResolvedValue(new Msg(true, '', null));
async function submit() {
const button = document.querySelector('.ant-modal-footer .ant-btn-primary');
if (!button) throw new Error('Save button missing');
await waitFor(() => expect(button.classList.contains('ant-btn-loading')).toBe(false));
fireEvent.click(button);
}
try {
renderWithProviders(
<ClientFormModal
open
mode="edit"
client={{
email: 'monthly@example.com',
uuid: '11111111-1111-1111-1111-111111111111',
subId: 'calendar-sub',
enable: true,
expiryTime: 1893427200000,
resetDay: 1,
reset: 7,
resetMax: 3,
traffic: { resetCount: 2 },
}}
attachedIds={[1]}
inbounds={[{ id: 1, protocol: 'vless', tag: 'calendar' }]}
save={save}
onOpenChange={() => {}}
/>,
);
const mode = screen.getByLabelText('Auto renewal');
expect(mode.closest('.ant-select')?.textContent).toContain('Calendar monthly');
await waitFor(() => expect(document.body.textContent).toContain('2029-12-31T23:59:59+08:00'));
expect(post).toHaveBeenCalledWith(
'/panel/api/clients/renewalPreview',
expect.objectContaining({ resetMax: 3, resetCount: 2 }),
expect.anything(),
);
await submit();
await waitFor(() =>
expect(save).toHaveBeenCalledWith(
expect.objectContaining({
reset: 7,
resetDay: 1,
resetWeekday: 0,
expiryTime: 1893427200000,
}),
expect.anything(),
),
);
chooseSelectOption(mode.id, 'Calendar weekly');
const weekday = screen.getByLabelText('Renew on weekday');
chooseSelectOption(weekday.id, 'Sunday');
await waitFor(() =>
expect(post).toHaveBeenCalledWith(
'/panel/api/clients/renewalPreview',
expect.objectContaining({ reset: 0, resetDay: 0, resetWeekday: 7 }),
expect.anything(),
),
);
await submit();
await waitFor(() =>
expect(save).toHaveBeenCalledWith(
expect.objectContaining({
reset: 0,
resetDay: 0,
resetWeekday: 7,
expiryTime: 1893427200000,
}),
expect.anything(),
),
);
chooseSelectOption(mode.id, 'Disabled');
await submit();
await waitFor(() =>
expect(save).toHaveBeenCalledWith(
expect.objectContaining({
reset: 0,
resetDay: 0,
resetWeekday: 0,
expiryTime: 1893427200000,
}),
expect.anything(),
),
);
} finally {
post.mockRestore();
}
});
@@ -18,7 +18,16 @@ describe('client enable toggle', () => {
const email = 'scheduled@example.com';
vi.spyOn(HttpUtil, 'get').mockResolvedValue(
new Msg(true, '', {
client: { email, enable: !enable, trafficReset: 'monthly', trafficResetDay: 15 },
client: {
email,
enable: !enable,
trafficReset: 'monthly',
trafficResetDay: 15,
reset: 0,
resetDay: 0,
resetWeekday: 7,
resetMax: 3,
},
inboundIds: [],
}),
);
@@ -44,7 +53,16 @@ describe('client enable toggle', () => {
expect(HttpUtil.get).toHaveBeenCalledWith('/panel/api/clients/get/scheduled%40example.com');
expect(post).toHaveBeenCalledWith(
'/panel/api/clients/update/scheduled%40example.com',
expect.objectContaining({ email, enable, trafficReset: 'monthly', trafficResetDay: 15 }),
expect.objectContaining({
email,
enable,
trafficReset: 'monthly',
trafficResetDay: 15,
reset: 0,
resetDay: 0,
resetWeekday: 7,
resetMax: 3,
}),
{ headers: { 'Content-Type': 'application/json' } },
);
},