mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-09-30 19:22:10 +03:00
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:
@@ -60,6 +60,7 @@ func (a *ClientController) initRouter(g *gin.RouterGroup) {
|
||||
g.POST("/happLink/:id", a.generateHappLink)
|
||||
|
||||
g.POST("/add", a.create)
|
||||
g.POST("/renewalPreview", a.renewalPreview)
|
||||
g.POST("/update/:email", a.update)
|
||||
g.POST("/del/:email", a.delete)
|
||||
g.POST("/:email/attach", a.attach)
|
||||
@@ -101,6 +102,16 @@ func (a *ClientController) list(c *gin.Context) {
|
||||
jsonObj(c, rows, nil)
|
||||
}
|
||||
|
||||
func (a *ClientController) renewalPreview(c *gin.Context) {
|
||||
var request service.ClientRenewalPreviewRequest
|
||||
if err := c.ShouldBindJSON(&request); err != nil {
|
||||
jsonObj(c, nil, err)
|
||||
return
|
||||
}
|
||||
preview, err := a.clientService.PreviewRenewal(request, &a.settingService)
|
||||
jsonObj(c, preview, err)
|
||||
}
|
||||
|
||||
func (a *ClientController) listPaged(c *gin.Context) {
|
||||
var params service.ClientPageParams
|
||||
if err := c.ShouldBindQuery(¶ms); err != nil {
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
func TestClientRenewalPreviewHTTP(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name, zone, expiry, renewAt, validThrough, next string
|
||||
wantError string
|
||||
reset, day, weekday, max, count int
|
||||
periods int
|
||||
canRenew, delayed, invalid bool
|
||||
}{
|
||||
{name: "monthly uses Taipei and preserves legacy precedence", zone: "Asia/Taipei", expiry: "2030-01-01T00:00:00+08:00", renewAt: "2030-01-01T00:00:00+08:00", validThrough: "2029-12-31T23:59:59+08:00", next: "2030-02-01T00:00:00+08:00", reset: 7, day: 1, canRenew: true},
|
||||
{name: "31st clamps in February", zone: "UTC", expiry: "2030-01-31T00:00:00Z", renewAt: "2030-01-31T00:00:00Z", validThrough: "2030-01-30T23:59:59Z", next: "2030-02-28T00:00:00Z", day: 31, canRenew: true},
|
||||
{name: "31st returns after February", zone: "UTC", expiry: "2030-02-28T00:00:00Z", renewAt: "2030-02-28T00:00:00Z", validThrough: "2030-02-27T23:59:59Z", next: "2030-03-31T00:00:00Z", day: 31, canRenew: true},
|
||||
{name: "leap February", zone: "UTC", expiry: "2028-01-31T00:00:00Z", renewAt: "2028-01-31T00:00:00Z", validThrough: "2028-01-30T23:59:59Z", next: "2028-02-29T00:00:00Z", day: 31, canRenew: true},
|
||||
{name: "weekly crosses New York daylight saving", zone: "America/New_York", expiry: "2030-03-10T00:00:00-05:00", renewAt: "2030-03-10T00:00:00-05:00", validThrough: "2030-03-09T23:59:59-05:00", next: "2030-03-17T00:00:00-04:00", weekday: 7, canRenew: true},
|
||||
{name: "interval preserves 168 hours", zone: "America/New_York", expiry: "2030-03-10T00:00:00-05:00", renewAt: "2030-03-10T00:00:00-05:00", validThrough: "2030-03-09T23:59:59-05:00", next: "2030-03-17T01:00:00-04:00", reset: 7, canRenew: true},
|
||||
{name: "inclusive month end charges full month", zone: "UTC", expiry: "2030-01-31T23:59:59Z", renewAt: "2030-02-01T00:00:00Z", validThrough: "2030-01-31T23:59:58Z", next: "2030-03-01T00:00:00Z", day: 1, max: 1, canRenew: true},
|
||||
{name: "inclusive week end charges full week", zone: "UTC", expiry: "2030-01-06T23:59:59Z", renewAt: "2030-01-07T00:00:00Z", validThrough: "2030-01-06T23:59:58Z", next: "2030-01-14T00:00:00Z", weekday: 1, max: 1, canRenew: true},
|
||||
{name: "partial offline catch-up remains expired", zone: "UTC", expiry: "2026-03-01T00:00:00Z", renewAt: "2026-03-01T00:00:00Z", validThrough: "2026-02-28T23:59:59Z", next: "2026-03-08T00:00:00Z", weekday: 7, max: 3, count: 2, periods: 1},
|
||||
{name: "arbitrary initial cutoff is not silently realigned", zone: "UTC", expiry: "2030-01-08T12:00:00Z", renewAt: "2030-01-08T12:00:00Z", validThrough: "2030-01-08T11:59:59Z", next: "2030-01-14T00:00:00Z", weekday: 1, canRenew: true},
|
||||
{name: "cap exhausted", zone: "UTC", expiry: "2030-01-01T00:00:00Z", renewAt: "2030-01-01T00:00:00Z", validThrough: "2029-12-31T23:59:59Z", day: 1, max: 3, count: 3},
|
||||
{name: "unset cutoff only suggests a boundary", zone: "UTC", weekday: 1},
|
||||
{name: "first-use waits for activation", zone: "UTC", expiry: "first-use", weekday: 1, delayed: true},
|
||||
{name: "disabled ignores absolute expiry", zone: "UTC", expiry: "2030-01-01T00:00:00Z"},
|
||||
{name: "invalid weekday", zone: "UTC", weekday: 8, invalid: true, wantError: "client resetWeekday must be between 0 and 7, got: 8\n"},
|
||||
{name: "conflicting weekly and monthly", zone: "UTC", day: 1, weekday: 1, invalid: true, wantError: "client weekly renewal cannot be combined with reset or resetDay\n"},
|
||||
{name: "conflicting weekly and interval", zone: "UTC", reset: 7, weekday: 1, invalid: true, wantError: "client weekly renewal cannot be combined with reset or resetDay\n"},
|
||||
{name: "negative count", zone: "UTC", count: -1, invalid: true, wantError: "renewal preview reset and resetCount must not be negative\n"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if err := database.InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.CloseDB() })
|
||||
db := database.GetDB()
|
||||
if err := db.Create(&model.Setting{Key: "timeLocation", Value: tt.zone}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snapshot := xray.ClientTraffic{Email: "preview-sentinel", ExpiryTime: 1893456000000, ResetCount: 7, Up: 111, Down: 222, Enable: true}
|
||||
if err := db.Create(&snapshot).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := service.ClientRenewalPreviewRequest{Reset: tt.reset, ResetDay: tt.day, ResetWeekday: tt.weekday, ResetMax: tt.max, ResetCount: tt.count}
|
||||
if tt.expiry == "first-use" {
|
||||
request.ExpiryTime = -7 * 86400000
|
||||
} else if tt.expiry != "" {
|
||||
at, err := time.Parse(time.RFC3339, tt.expiry)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request.ExpiryTime = at.UnixMilli()
|
||||
}
|
||||
payload, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
router := gin.New()
|
||||
NewClientController(router.Group("/panel/api/clients"))
|
||||
w := httptest.NewRecorder()
|
||||
r := httptest.NewRequest(http.MethodPost, "/panel/api/clients/renewalPreview", bytes.NewReader(payload))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(w, r)
|
||||
var msg struct {
|
||||
Success bool `json:"success"`
|
||||
Msg string `json:"msg"`
|
||||
Obj service.ClientRenewalPreview `json:"obj"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != http.StatusOK || msg.Success == tt.invalid {
|
||||
t.Fatalf("status/body = %d/%s", w.Code, w.Body.String())
|
||||
}
|
||||
if tt.invalid && msg.Msg != " ("+tt.wantError+")" {
|
||||
t.Fatalf("validation error = %q, want wrapped error %q", msg.Msg, tt.wantError)
|
||||
}
|
||||
if !tt.invalid {
|
||||
got := msg.Obj
|
||||
if got.TimeZone != tt.zone || got.RenewAt != tt.renewAt || got.ValidThrough != tt.validThrough || got.NextExpiry != tt.next || got.CanRenew != tt.canRenew || got.DelayedStart != tt.delayed {
|
||||
t.Fatalf("preview = %+v, want boundary/valid/next %q/%q/%q", got, tt.renewAt, tt.validThrough, tt.next)
|
||||
}
|
||||
wantRenewals := 0
|
||||
if tt.canRenew {
|
||||
wantRenewals = 1
|
||||
}
|
||||
if tt.periods > 0 {
|
||||
wantRenewals = tt.periods
|
||||
}
|
||||
if got.Renewals != wantRenewals {
|
||||
t.Fatalf("periods = %d, want %d", got.Renewals, wantRenewals)
|
||||
}
|
||||
if tt.weekday > 0 || tt.day > 0 {
|
||||
if got.SuggestedExpiryTime <= time.Now().UnixMilli() || got.SuggestedExpiry == "" {
|
||||
t.Fatalf("missing future suggestion: %+v", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
var after xray.ClientTraffic
|
||||
if err := db.Where("email = ?", snapshot.Email).First(&after).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after != snapshot {
|
||||
t.Fatalf("read-only preview mutated traffic: %+v", after)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
package service
|
||||
|
||||
import "time"
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
// nextCalendarRenewal returns the next renewal strictly after from, at midnight
|
||||
// in loc; a missing day clamps to the month's last, so the 31st comes back (#6106).
|
||||
@@ -40,3 +44,94 @@ func calendarDay(year int, month time.Month, day int, loc *time.Location) time.T
|
||||
func daysInMonth(year int, month time.Month) int {
|
||||
return time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC).Day()
|
||||
}
|
||||
|
||||
// Advance by calendar dates, not 168 hours; a repeated midnight must not spend
|
||||
// another weekly allowance on the same local date.
|
||||
func nextWeeklyRenewal(from time.Time, weekday int, loc *time.Location) time.Time {
|
||||
if loc == nil {
|
||||
loc = time.UTC
|
||||
}
|
||||
local := from.In(loc)
|
||||
days := (min(7, max(1, weekday))%7 - int(local.Weekday()) + 7) % 7
|
||||
if days == 0 {
|
||||
days = 7
|
||||
}
|
||||
date := time.Date(local.Year(), local.Month(), local.Day()+days, 0, 0, 0, 0, time.UTC)
|
||||
// A corrupt or unusual zone must not stall the single traffic writer.
|
||||
// Returning from lets the catch-up forward-progress guard fail closed.
|
||||
for range 8 {
|
||||
candidate, exists := localCalendarDateStart(date, loc)
|
||||
if exists && candidate.After(local) {
|
||||
return candidate
|
||||
}
|
||||
date = date.AddDate(0, 0, 7)
|
||||
}
|
||||
return from
|
||||
}
|
||||
|
||||
// Find the first valid instant of a local date: Date can pick a repeated
|
||||
// midnight or normalize a nonexistent midnight into the preceding day.
|
||||
func localCalendarDateStart(date time.Time, loc *time.Location) (time.Time, bool) {
|
||||
localDate := func(at time.Time) time.Time {
|
||||
local := at.In(loc)
|
||||
return time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, time.UTC)
|
||||
}
|
||||
candidate := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, loc)
|
||||
if localDate(candidate).Equal(date) && localDate(candidate.Add(-time.Second)).Before(date) {
|
||||
return candidate, true
|
||||
}
|
||||
low, high := candidate.Unix()-86400, candidate.Unix()+86400
|
||||
for low < high {
|
||||
mid := low + (high-low)/2
|
||||
if localDate(time.Unix(mid, 0)).Before(date) {
|
||||
low = mid + 1
|
||||
} else {
|
||||
high = mid
|
||||
}
|
||||
}
|
||||
start := time.Unix(low, 0).In(loc)
|
||||
return start, localDate(start).Equal(date)
|
||||
}
|
||||
|
||||
func nextClientRenewal(expiry int64, reset, day, weekday int, loc *time.Location) int64 {
|
||||
if day > 0 {
|
||||
return nextCalendarRenewal(time.UnixMilli(expiry), day, loc).UnixMilli()
|
||||
}
|
||||
if weekday > 0 {
|
||||
return nextWeeklyRenewal(time.UnixMilli(expiry), weekday, loc).UnixMilli()
|
||||
}
|
||||
return expiry + int64(reset)*86400000
|
||||
}
|
||||
|
||||
func canonicalRenewalExpiry(expiry int64, reset, day, weekday int, loc *time.Location) int64 {
|
||||
if day > 0 || weekday > 0 {
|
||||
boundary := nextClientRenewal(expiry, reset, day, weekday, loc)
|
||||
if expiry >= boundary-1000 && expiry < boundary {
|
||||
return boundary
|
||||
}
|
||||
}
|
||||
return expiry
|
||||
}
|
||||
|
||||
func catchUpClientRenewal(traffic *xray.ClientTraffic, now int64, loc *time.Location) (int64, int) {
|
||||
if traffic.ResetDay <= 0 && traffic.ResetWeekday <= 0 && traffic.Reset <= 0 {
|
||||
return traffic.ExpiryTime, 0
|
||||
}
|
||||
expiry := canonicalRenewalExpiry(traffic.ExpiryTime, traffic.Reset, traffic.ResetDay, traffic.ResetWeekday, loc)
|
||||
renewals := 0
|
||||
for expiry < now {
|
||||
if traffic.ResetMax > 0 && traffic.ResetCount+renewals >= traffic.ResetMax {
|
||||
break
|
||||
}
|
||||
next := nextClientRenewal(expiry, traffic.Reset, traffic.ResetDay, traffic.ResetWeekday, loc)
|
||||
if next <= expiry {
|
||||
return traffic.ExpiryTime, 0
|
||||
}
|
||||
expiry = next
|
||||
renewals++
|
||||
}
|
||||
if renewals == 0 {
|
||||
return traffic.ExpiryTime, 0
|
||||
}
|
||||
return expiry, renewals
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
func TestWeeklyRenewalSearchFailsClosed(t *testing.T) {
|
||||
// Keep a background clock reader so -race catches global timezone writes.
|
||||
started, stop, done := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
_ = time.Now()
|
||||
close(started)
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
_ = time.Now()
|
||||
}
|
||||
}
|
||||
}()
|
||||
<-started
|
||||
t.Cleanup(func() { close(stop); <-done })
|
||||
|
||||
// Fault injection: a valid TZif with twelve absent Sundays, not a claim
|
||||
// about real IANA zones. Each following Monday repeats, so no Sunday returns.
|
||||
const transitions = 24
|
||||
data := make([]byte, 44+transitions*5+2*6+2)
|
||||
copy(data, "TZif")
|
||||
binary.BigEndian.PutUint32(data[32:36], transitions)
|
||||
binary.BigEndian.PutUint32(data[36:40], 2)
|
||||
binary.BigEndian.PutUint32(data[40:44], 2)
|
||||
from := time.Date(2026, time.March, 1, 0, 0, 0, 0, time.UTC)
|
||||
for week := range 12 {
|
||||
at := from.AddDate(0, 0, (week+1)*7).Unix()
|
||||
for day := range 2 {
|
||||
index := week*2 + day
|
||||
binary.BigEndian.PutUint32(data[44+index*4:48+index*4], uint32(at+int64(day)*86400))
|
||||
data[44+transitions*4+index] = byte(1 - day)
|
||||
}
|
||||
}
|
||||
binary.BigEndian.PutUint32(data[44+transitions*5+6:48+transitions*5+6], 86400)
|
||||
data[len(data)-2] = 'X'
|
||||
loc, err := time.LoadLocationFromTZData("Test/SkippedSundays", data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := nextWeeklyRenewal(from, 7, loc); !got.Equal(from) {
|
||||
t.Fatalf("exhausted weekly search advanced to %s, want unchanged %s", got.Format(time.RFC3339), from.Format(time.RFC3339))
|
||||
}
|
||||
traffic := &xray.ClientTraffic{ExpiryTime: from.UnixMilli(), ResetWeekday: 7, ResetMax: 4, ResetCount: 2, Enable: false, Up: 111, Down: 222}
|
||||
before := *traffic
|
||||
expiry, renewals := catchUpClientRenewal(traffic, from.AddDate(0, 0, 28).UnixMilli(), loc)
|
||||
if expiry != before.ExpiryTime || renewals != 0 || *traffic != before {
|
||||
t.Fatalf("exhausted search changed billing/traffic: expiry=%d renewals=%d traffic=%+v", expiry, renewals, traffic)
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
now int64
|
||||
}{
|
||||
{"initial suggestion exhausted", from.UnixMilli()},
|
||||
{"catch-up exhausted with allowances left", from.AddDate(0, 3, 0).UnixMilli()},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
preview, err := previewClientRenewal(ClientRenewalPreviewRequest{
|
||||
ExpiryTime: before.ExpiryTime, ResetWeekday: 7, ResetMax: 4, ResetCount: 2,
|
||||
}, tt.now, loc)
|
||||
if err == nil || err.Error() != "calendar renewal could not find a future expiry\n" || preview != nil {
|
||||
t.Fatalf("failed search preview/error = %+v/%v, want nil/calendar search error", preview, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNextWeeklyRenewal_RepeatedMidnight(t *testing.T) {
|
||||
loc, err := time.LoadLocation("America/Havana")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tt := range []struct{ expiry, want string }{
|
||||
{"2026-10-25T00:00:00-04:00", "2026-11-01T00:00:00-04:00"},
|
||||
{"2026-11-01T00:00:00-04:00", "2026-11-08T00:00:00-05:00"},
|
||||
{"2026-11-01T00:00:00-05:00", "2026-11-08T00:00:00-05:00"},
|
||||
} {
|
||||
from, err := time.Parse(time.RFC3339, tt.expiry)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := nextWeeklyRenewal(from, 7, loc).Format(time.RFC3339)
|
||||
if got != tt.want {
|
||||
t.Fatalf("next Sunday after %s = %s, want %s", tt.expiry, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextWeeklyRenewal_SkippedDates(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
zone, from, want string
|
||||
weekday int
|
||||
}{
|
||||
{"America/Havana", "2026-03-01T00:00:00-05:00", "2026-03-08T01:00:00-04:00", 7},
|
||||
{"Pacific/Apia", "2011-12-23T00:00:00-10:00", "2012-01-06T00:00:00+14:00", 5},
|
||||
} {
|
||||
t.Run(tt.zone, func(t *testing.T) {
|
||||
loc, err := time.LoadLocation(tt.zone)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
from, err := time.Parse(time.RFC3339, tt.from)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := nextWeeklyRenewal(from, tt.weekday, loc).Format(time.RFC3339)
|
||||
if got != tt.want {
|
||||
t.Fatalf("next weekly cutoff = %s, want %s", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1303,7 +1303,7 @@ func (s *ClientService) BulkCreate(inboundSvc *InboundService, payloads []Client
|
||||
skip(email, verr.Error())
|
||||
continue
|
||||
}
|
||||
if verr := validateClientResetDay(client.ResetDay); verr != nil {
|
||||
if verr := validateClientRenewal(client); verr != nil {
|
||||
skip(email, verr.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -81,6 +81,28 @@ func validateClientResetMax(resetMax int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateClientRenewal(client model.Client) error {
|
||||
if err := validateClientResetDay(client.ResetDay); err != nil {
|
||||
return err
|
||||
}
|
||||
if client.ResetWeekday < 0 || client.ResetWeekday > 7 {
|
||||
return common.NewError("client resetWeekday must be between 0 and 7, got:", client.ResetWeekday)
|
||||
}
|
||||
if client.ResetWeekday > 0 && (client.Reset > 0 || client.ResetDay > 0) {
|
||||
return common.NewError("client weekly renewal cannot be combined with reset or resetDay")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateClientsRenewal(clients []model.Client) error {
|
||||
for _, client := range clients {
|
||||
if err := validateClientRenewal(client); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// normalizeClientTrafficReset stores what the inbound path would store, so the
|
||||
// day never reaches the DB as a 0 that three layers downstream each clamp to 1.
|
||||
func normalizeClientTrafficReset(c *model.Client) {
|
||||
@@ -137,7 +159,7 @@ func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreate
|
||||
if err := validateClientSubID(client.SubID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := validateClientResetDay(client.ResetDay); err != nil {
|
||||
if err := validateClientRenewal(client); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := validateClientResetMax(client.ResetMax); err != nil {
|
||||
@@ -591,7 +613,7 @@ func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model
|
||||
if err := validateClientSubID(updated.SubID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := validateClientResetDay(updated.ResetDay); err != nil {
|
||||
if err := validateClientRenewal(updated); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := validateClientResetMax(updated.ResetMax); err != nil {
|
||||
@@ -756,6 +778,7 @@ func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model
|
||||
"comment": merged.Comment,
|
||||
"reset": merged.Reset,
|
||||
"reset_day": merged.ResetDay,
|
||||
"reset_weekday": merged.ResetWeekday,
|
||||
"reset_max": merged.ResetMax,
|
||||
"traffic_reset": merged.TrafficReset,
|
||||
"traffic_reset_day": merged.TrafficResetDay,
|
||||
|
||||
@@ -329,6 +329,9 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := validateClientsRenewal(clients); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
var settings map[string]any
|
||||
err = json.Unmarshal([]byte(data.Settings), &settings)
|
||||
@@ -659,6 +662,9 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := validateClientsRenewal(clients); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
var settings map[string]any
|
||||
err = json.Unmarshal([]byte(data.Settings), &settings)
|
||||
|
||||
@@ -65,6 +65,7 @@ func applyClientRecordMerge(row *model.ClientRecord, incoming *model.ClientRecor
|
||||
row.Comment = incoming.Comment
|
||||
row.Reset = incoming.Reset
|
||||
row.ResetDay = incoming.ResetDay
|
||||
row.ResetWeekday = incoming.ResetWeekday
|
||||
row.ResetMax = incoming.ResetMax
|
||||
// Guarded like Group and AdTag: a node snapshot rebuilt from settings that
|
||||
// predate the cycle would otherwise silently erase it.
|
||||
@@ -94,6 +95,9 @@ func (s *ClientService) ApplyInboundClientDelta(tx *gorm.DB, inboundId int, chan
|
||||
}
|
||||
|
||||
func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients []model.Client, detachEmails []string, prune bool) error {
|
||||
if err := validateClientsRenewal(clients); err != nil {
|
||||
return err
|
||||
}
|
||||
if tx == nil {
|
||||
tx = database.GetDB()
|
||||
}
|
||||
|
||||
@@ -18,22 +18,23 @@ import (
|
||||
// so the list payload stays compact even when the panel manages thousands
|
||||
// of clients. Modals that need the full record still call /get/:email.
|
||||
type ClientSlim struct {
|
||||
Email string `json:"email" example:"alice@example.com"`
|
||||
SubID string `json:"subId" example:"abcd1234"`
|
||||
Enable bool `json:"enable" example:"true"`
|
||||
TotalGB int64 `json:"totalGB" example:"53687091200"`
|
||||
ExpiryTime int64 `json:"expiryTime" example:"1735689600000"`
|
||||
LimitIP int `json:"limitIp" example:"0"`
|
||||
LimitHwid int `json:"limitHwid" example:"0"`
|
||||
Reset int `json:"reset" example:"0"`
|
||||
ResetDay int `json:"resetDay" example:"0"`
|
||||
ResetMax int `json:"resetMax" example:"0"`
|
||||
Group string `json:"group,omitempty" example:"staff"`
|
||||
Comment string `json:"comment,omitempty" example:"Primary device"`
|
||||
InboundIds []int `json:"inboundIds" example:"[3,5]"`
|
||||
Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
|
||||
CreatedAt int64 `json:"createdAt" example:"1735000000000"`
|
||||
UpdatedAt int64 `json:"updatedAt" example:"1735100000000"`
|
||||
Email string `json:"email" example:"alice@example.com"`
|
||||
SubID string `json:"subId" example:"abcd1234"`
|
||||
Enable bool `json:"enable" example:"true"`
|
||||
TotalGB int64 `json:"totalGB" example:"53687091200"`
|
||||
ExpiryTime int64 `json:"expiryTime" example:"1735689600000"`
|
||||
LimitIP int `json:"limitIp" example:"0"`
|
||||
LimitHwid int `json:"limitHwid" example:"0"`
|
||||
Reset int `json:"reset" example:"0"`
|
||||
ResetDay int `json:"resetDay" example:"0"`
|
||||
ResetWeekday int `json:"resetWeekday" example:"0"`
|
||||
ResetMax int `json:"resetMax" example:"0"`
|
||||
Group string `json:"group,omitempty" example:"staff"`
|
||||
Comment string `json:"comment,omitempty" example:"Primary device"`
|
||||
InboundIds []int `json:"inboundIds" example:"[3,5]"`
|
||||
Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
|
||||
CreatedAt int64 `json:"createdAt" example:"1735000000000"`
|
||||
UpdatedAt int64 `json:"updatedAt" example:"1735100000000"`
|
||||
}
|
||||
|
||||
// ClientPageParams are the query params accepted by /panel/api/clients/list/paged.
|
||||
@@ -246,9 +247,9 @@ func (q clientQuery) applyParams(tx *gorm.DB, params ClientPageParams, onlines [
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(params.AutoRenew)) {
|
||||
case "on":
|
||||
where("(COALESCE(c.reset, 0) > 0 OR COALESCE(c.reset_day, 0) > 0)")
|
||||
where("(COALESCE(c.reset, 0) > 0 OR COALESCE(c.reset_day, 0) > 0 OR COALESCE(c.reset_weekday, 0) > 0)")
|
||||
case "off":
|
||||
where("(COALESCE(c.reset, 0) <= 0 AND COALESCE(c.reset_day, 0) <= 0)")
|
||||
where("(COALESCE(c.reset, 0) <= 0 AND COALESCE(c.reset_day, 0) <= 0 AND COALESCE(c.reset_weekday, 0) <= 0)")
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(params.HasTgID)) {
|
||||
case "yes":
|
||||
@@ -598,22 +599,23 @@ func sqlInt(v int64) string {
|
||||
|
||||
func toClientSlim(c ClientWithAttachments) ClientSlim {
|
||||
return ClientSlim{
|
||||
Email: c.Email,
|
||||
SubID: c.SubID,
|
||||
Enable: c.Enable,
|
||||
TotalGB: c.TotalGB,
|
||||
ExpiryTime: c.ExpiryTime,
|
||||
LimitIP: c.LimitIP,
|
||||
LimitHwid: c.LimitHwid,
|
||||
Reset: c.Reset,
|
||||
ResetDay: c.ResetDay,
|
||||
ResetMax: c.ResetMax,
|
||||
Group: c.Group,
|
||||
Comment: c.Comment,
|
||||
InboundIds: c.InboundIds,
|
||||
Traffic: c.Traffic,
|
||||
CreatedAt: c.CreatedAt,
|
||||
UpdatedAt: c.UpdatedAt,
|
||||
Email: c.Email,
|
||||
SubID: c.SubID,
|
||||
Enable: c.Enable,
|
||||
TotalGB: c.TotalGB,
|
||||
ExpiryTime: c.ExpiryTime,
|
||||
LimitIP: c.LimitIP,
|
||||
LimitHwid: c.LimitHwid,
|
||||
Reset: c.Reset,
|
||||
ResetDay: c.ResetDay,
|
||||
ResetWeekday: c.ResetWeekday,
|
||||
ResetMax: c.ResetMax,
|
||||
Group: c.Group,
|
||||
Comment: c.Comment,
|
||||
InboundIds: c.InboundIds,
|
||||
Traffic: c.Traffic,
|
||||
CreatedAt: c.CreatedAt,
|
||||
UpdatedAt: c.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -115,7 +115,7 @@ func (s *ClientService) ImportClients(inboundSvc *InboundService, items []Client
|
||||
skip(email, verr.Error())
|
||||
continue
|
||||
}
|
||||
if verr := validateClientResetDay(client.ResetDay); verr != nil {
|
||||
if verr := validateClientRenewal(client); verr != nil {
|
||||
skip(email, verr.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
type ClientRenewalPreviewRequest struct {
|
||||
ExpiryTime int64 `json:"expiryTime" example:"1893456000000"`
|
||||
Reset int `json:"reset" example:"0"`
|
||||
ResetDay int `json:"resetDay" example:"1"`
|
||||
ResetWeekday int `json:"resetWeekday" example:"0"`
|
||||
ResetMax int `json:"resetMax" example:"0"`
|
||||
ResetCount int `json:"resetCount" example:"0"`
|
||||
}
|
||||
|
||||
type ClientRenewalPreview struct {
|
||||
TimeZone string `json:"timeZone" example:"UTC"`
|
||||
RenewAt string `json:"renewAt" example:"2030-01-01T00:00:00Z"`
|
||||
ValidThrough string `json:"validThrough" example:"2029-12-31T23:59:59Z"`
|
||||
NextExpiry string `json:"nextExpiry" example:"2030-02-01T00:00:00Z"`
|
||||
SuggestedExpiryTime int64 `json:"suggestedExpiryTime" example:"1893456000000"`
|
||||
SuggestedExpiry string `json:"suggestedExpiry" example:"2030-01-01T00:00:00Z"`
|
||||
Renewals int `json:"renewals" example:"1"`
|
||||
CanRenew bool `json:"canRenew" example:"true"`
|
||||
DelayedStart bool `json:"delayedStart" example:"false"`
|
||||
}
|
||||
|
||||
func (s *ClientService) PreviewRenewal(request ClientRenewalPreviewRequest, settings *SettingService) (*ClientRenewalPreview, error) {
|
||||
client := model.Client{Reset: request.Reset, ResetDay: request.ResetDay, ResetWeekday: request.ResetWeekday}
|
||||
if err := validateClientRenewal(client); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := validateClientResetMax(request.ResetMax); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if request.ResetCount < 0 || request.Reset < 0 {
|
||||
return nil, common.NewError("renewal preview reset and resetCount must not be negative")
|
||||
}
|
||||
loc, err := settings.GetTimeLocation()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return previewClientRenewal(request, time.Now().UnixMilli(), loc)
|
||||
}
|
||||
|
||||
func previewClientRenewal(request ClientRenewalPreviewRequest, now int64, loc *time.Location) (*ClientRenewalPreview, error) {
|
||||
preview := &ClientRenewalPreview{TimeZone: loc.String(), DelayedStart: request.ExpiryTime < 0}
|
||||
if request.ResetDay > 0 || request.ResetWeekday > 0 {
|
||||
preview.SuggestedExpiryTime = nextClientRenewal(now, request.Reset, request.ResetDay, request.ResetWeekday, loc)
|
||||
if preview.SuggestedExpiryTime <= now {
|
||||
return nil, common.NewError("calendar renewal could not find a future expiry")
|
||||
}
|
||||
preview.SuggestedExpiry = time.UnixMilli(preview.SuggestedExpiryTime).In(loc).Format(time.RFC3339)
|
||||
}
|
||||
if request.ExpiryTime <= 0 || (request.Reset <= 0 && request.ResetDay <= 0 && request.ResetWeekday <= 0) {
|
||||
return preview, nil
|
||||
}
|
||||
at := canonicalRenewalExpiry(request.ExpiryTime, request.Reset, request.ResetDay, request.ResetWeekday, loc)
|
||||
preview.RenewAt = time.UnixMilli(at).In(loc).Format(time.RFC3339Nano)
|
||||
// Billing alignment does not rewrite the stored exclusive deadline; the
|
||||
// preview must not promise an extra second before the first renewal.
|
||||
preview.ValidThrough = time.UnixMilli(request.ExpiryTime - 1).In(loc).Format(time.RFC3339)
|
||||
traffic := &xray.ClientTraffic{
|
||||
ExpiryTime: request.ExpiryTime, Reset: request.Reset, ResetDay: request.ResetDay,
|
||||
ResetWeekday: request.ResetWeekday, ResetMax: request.ResetMax, ResetCount: request.ResetCount,
|
||||
}
|
||||
expiry, renewals := catchUpClientRenewal(traffic, max(now, at+1), loc)
|
||||
if renewals == 0 && request.ResetWeekday > 0 && (request.ResetMax == 0 || request.ResetCount < request.ResetMax) {
|
||||
return nil, common.NewError("calendar renewal could not find a future expiry")
|
||||
}
|
||||
preview.Renewals = renewals
|
||||
preview.CanRenew = renewals > 0 && expiry > max(now, at)
|
||||
if renewals > 0 {
|
||||
preview.NextExpiry = time.UnixMilli(expiry).In(loc).Format(time.RFC3339Nano)
|
||||
}
|
||||
return preview, nil
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
func TestClientRenewalWriteValidation(t *testing.T) {
|
||||
for _, operation := range []string{"add inbound", "update inbound", "add inbound client", "update inbound client", "sync inbound", "client delta", "add stat", "update stat", "import stat"} {
|
||||
for _, schedule := range []struct {
|
||||
name string
|
||||
reset, day, weekday int
|
||||
errorMessage string
|
||||
}{
|
||||
{"weekly and interval", 7, 0, 3, "client weekly renewal cannot be combined with reset or resetDay"},
|
||||
{"weekly and monthly", 0, 1, 3, "client weekly renewal cannot be combined with reset or resetDay"},
|
||||
{"invalid weekday", 0, 0, 8, "client resetWeekday must be between 0 and 7, got: 8"},
|
||||
} {
|
||||
t.Run(operation+"/"+schedule.name, func(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
nodeID, fake := setupNodeRuntime(t)
|
||||
svc, inboundSvc := &ClientService{}, &InboundService{}
|
||||
client := model.Client{Email: "renewal-boundary", ID: "11111111-1111-1111-1111-111111111111", SubID: "renewal-boundary-sub", Enable: true, ResetWeekday: 3, ResetMax: 4, ExpiryTime: time.Now().Add(time.Hour).UnixMilli()}
|
||||
inbound := nodeInbound(t, nodeID, 41759, []model.Client{client})
|
||||
if err := inboundSvc.AddClientStat(database.GetDB(), inbound.Id, &client); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
record, err := svc.GetRecordByEmail(nil, client.Email)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
beforeRecord := *record
|
||||
beforeTraffic := readTraffic(t, database.GetDB(), client.Email)
|
||||
beforeSettings := inbound.Settings
|
||||
client.Reset, client.ResetDay, client.ResetWeekday = schedule.reset, schedule.day, schedule.weekday
|
||||
update := *inbound
|
||||
update.Settings = clientsSettings(t, []model.Client{client})
|
||||
switch operation {
|
||||
case "add inbound", "import stat":
|
||||
update.Id, update.Port, update.Tag = 0, 41760, "renewal-boundary-new"
|
||||
if operation == "import stat" {
|
||||
update.Settings = beforeSettings
|
||||
update.ClientStats = []xray.ClientTraffic{{Email: "invalid-import-stat", Reset: schedule.reset, ResetDay: schedule.day, ResetWeekday: schedule.weekday}}
|
||||
}
|
||||
_, _, err = inboundSvc.AddInbound(&update)
|
||||
case "update inbound":
|
||||
_, _, err = inboundSvc.UpdateInbound(&update)
|
||||
case "add inbound client":
|
||||
client.Email = "invalid-new-client"
|
||||
update.Settings = clientsSettings(t, []model.Client{client})
|
||||
_, err = svc.AddInboundClient(inboundSvc, &update)
|
||||
case "update inbound client":
|
||||
_, err = svc.UpdateInboundClient(inboundSvc, &update, client.Email)
|
||||
case "sync inbound":
|
||||
err = svc.SyncInbound(nil, inbound.Id, []model.Client{client})
|
||||
case "client delta":
|
||||
err = svc.ApplyInboundClientDelta(nil, inbound.Id, []model.Client{client}, nil)
|
||||
case "add stat":
|
||||
err = inboundSvc.AddClientStat(database.GetDB(), inbound.Id, &client)
|
||||
case "update stat":
|
||||
err = inboundSvc.UpdateClientStat(database.GetDB(), client.Email, &client)
|
||||
}
|
||||
if err == nil || err.Error() != schedule.errorMessage+"\n" {
|
||||
t.Fatalf("write error = %v, want %q", err, schedule.errorMessage)
|
||||
}
|
||||
var persisted model.Inbound
|
||||
if err := database.GetDB().First(&persisted, inbound.Id).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if persisted.Settings != beforeSettings {
|
||||
t.Fatal("rejected write changed inbound settings")
|
||||
}
|
||||
record, err = svc.GetRecordByEmail(nil, beforeRecord.Email)
|
||||
if err != nil || *record != beforeRecord || readTraffic(t, database.GetDB(), beforeRecord.Email) != beforeTraffic {
|
||||
t.Fatalf("rejected write changed client/traffic: record=%+v error=%v", record, err)
|
||||
}
|
||||
for _, table := range []string{"inbounds", "clients", "client_traffics"} {
|
||||
var count int64
|
||||
if err := database.GetDB().Table(table).Count(&count).Error; err != nil || count != 1 {
|
||||
t.Fatalf("%s count/error = %d/%v, want 1/nil", table, count, err)
|
||||
}
|
||||
}
|
||||
if fake.addInbound.Load() != 0 || fake.updateInbound.Load() != 0 || fake.delInbound.Load() != 0 || fake.addClient.Load() != 0 || fake.updateUser.Load() != 0 {
|
||||
t.Fatal("rejected write dispatched to the runtime")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboundRenewalModesRemainEditable(t *testing.T) {
|
||||
for _, weekly := range []bool{false, true} {
|
||||
name := "legacy monthly with interval"
|
||||
if weekly {
|
||||
name = "weekly"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
nodeID, _ := setupNodeRuntime(t)
|
||||
svc, inboundSvc := &ClientService{}, &InboundService{}
|
||||
client := model.Client{Email: "renewal-editable", ID: "11111111-1111-1111-1111-111111111111", Enable: true, Reset: 7, ResetDay: 1, ResetMax: 4, ExpiryTime: time.Now().Add(time.Hour).UnixMilli()}
|
||||
if weekly {
|
||||
client.Reset, client.ResetDay, client.ResetWeekday = 0, 0, 3
|
||||
}
|
||||
inbound := &model.Inbound{Tag: "renewal-editable", NodeID: &nodeID, Port: 41761, Protocol: model.VLESS, Enable: true, Settings: clientsSettings(t, []model.Client{client})}
|
||||
if _, _, err := inboundSvc.AddInbound(inbound); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := inboundSvc.UpdateInbound(inbound); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
record, err := svc.GetRecordByEmail(nil, client.Email)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
toggle := *record.ToClient()
|
||||
toggle.Enable = false
|
||||
if _, err := svc.Update(inboundSvc, record.Id, toggle, 0); err != nil {
|
||||
t.Fatalf("valid inbound client could not be toggled: %v", err)
|
||||
}
|
||||
record, err = svc.GetRecordByEmail(nil, client.Email)
|
||||
if err != nil || record.Enable || record.Reset != client.Reset || record.ResetDay != client.ResetDay || record.ResetWeekday != client.ResetWeekday || record.ResetMax != 4 {
|
||||
t.Fatalf("valid schedule/toggle not preserved: %+v/%v", record, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
)
|
||||
|
||||
func TestClientWeeklyRenewCRUD(t *testing.T) {
|
||||
setupBulkDB(t)
|
||||
svc, inboundSvc := &ClientService{}, &InboundService{}
|
||||
first := mkInbound(t, 41701, model.VLESS, `{"clients":[]}`)
|
||||
second := mkInbound(t, 41702, model.VLESS, `{"clients":[]}`)
|
||||
client := model.Client{
|
||||
Email: "weekly-crud", ID: "11111111-1111-1111-1111-111111111111", Enable: true,
|
||||
ResetWeekday: 7, ResetMax: 3, ExpiryTime: time.Now().Add(-time.Hour).UnixMilli(),
|
||||
}
|
||||
if _, err := svc.Create(inboundSvc, &ClientCreatePayload{Client: client, InboundIds: []int{first.Id, second.Id}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
record, err := svc.GetRecordByEmail(nil, client.Email)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertSchedule := func(want int) {
|
||||
t.Helper()
|
||||
got, err := svc.GetRecordByEmail(nil, client.Email)
|
||||
if err != nil || got.ResetWeekday != want || got.ToClient().ResetWeekday != want {
|
||||
t.Fatalf("record schedule/error = %+v/%v, want %d", got, err, want)
|
||||
}
|
||||
traffic := readTraffic(t, database.GetDB(), client.Email)
|
||||
if traffic.ResetWeekday != want || traffic.ResetMax != 3 {
|
||||
t.Fatalf("traffic policy = %+v, want weekday %d and cap 3", traffic, want)
|
||||
}
|
||||
for _, id := range []int{first.Id, second.Id} {
|
||||
var inbound model.Inbound
|
||||
if err := database.GetDB().First(&inbound, id).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
clients, err := inboundSvc.GetClients(&inbound)
|
||||
if err != nil || len(clients) != 1 || clients[0].ResetWeekday != want {
|
||||
t.Fatalf("inbound %d schedule/error = %+v/%v, want %d", id, clients, err, want)
|
||||
}
|
||||
}
|
||||
filter := "on"
|
||||
if want == 0 {
|
||||
filter = "off"
|
||||
}
|
||||
page, err := svc.ListPaged(inboundSvc, nil, ClientPageParams{AutoRenew: filter})
|
||||
if err != nil || len(page.Items) != 1 || page.Items[0].ResetWeekday != want {
|
||||
t.Fatalf("renewal filter/projection = %+v/%v, want weekday %d", page, err, want)
|
||||
}
|
||||
}
|
||||
assertSchedule(7)
|
||||
if deleted, _, err := svc.DelDepleted(inboundSvc); err != nil || deleted != 0 {
|
||||
t.Fatalf("expired weekly client was purged: deleted/error = %d/%v", deleted, err)
|
||||
}
|
||||
for _, weekday := range []int{2, 0} {
|
||||
updated := *record.ToClient()
|
||||
updated.ResetWeekday = weekday
|
||||
if _, err := svc.Update(inboundSvc, record.Id, updated, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertSchedule(weekday)
|
||||
}
|
||||
if deleted, _, err := svc.DelDepleted(inboundSvc); err != nil || deleted != 1 {
|
||||
t.Fatalf("non-renewing expired client was not purged: deleted/error = %d/%v", deleted, err)
|
||||
}
|
||||
}
|
||||
@@ -1133,6 +1133,14 @@ func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, boo
|
||||
if err != nil {
|
||||
return inbound, false, err
|
||||
}
|
||||
if err := validateClientsRenewal(clients); err != nil {
|
||||
return inbound, false, err
|
||||
}
|
||||
for _, traffic := range inbound.ClientStats {
|
||||
if err := validateClientRenewal(model.Client{Reset: traffic.Reset, ResetDay: traffic.ResetDay, ResetWeekday: traffic.ResetWeekday}); err != nil {
|
||||
return inbound, false, err
|
||||
}
|
||||
}
|
||||
existEmail, err := s.clientService.checkEmailsExistForClients(s, clients)
|
||||
if err != nil {
|
||||
return inbound, false, err
|
||||
@@ -1702,6 +1710,9 @@ func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound,
|
||||
if err != nil {
|
||||
return inbound, false, err
|
||||
}
|
||||
if err := validateClientsRenewal(clients); err != nil {
|
||||
return inbound, false, err
|
||||
}
|
||||
if inbound.Protocol == model.Hysteria {
|
||||
for _, client := range clients {
|
||||
if client.Auth == "" {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
func TestAutoRenewClients_WeeklyMode(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name, zone string
|
||||
weekday, max, count int
|
||||
inclusive, manual bool
|
||||
}{
|
||||
{name: "UTC Monday catch-up across shared inbounds", zone: "UTC", weekday: 1},
|
||||
{name: "New York Sunday across daylight saving", zone: "America/New_York", weekday: 7},
|
||||
{name: "capped catch-up stays expired", zone: "UTC", weekday: 3, max: 3, count: 2},
|
||||
{name: "inclusive last second spends one allowance", zone: "Asia/Taipei", weekday: 1, max: 1, inclusive: true},
|
||||
{name: "operator-disabled settings stay disabled", zone: "UTC", weekday: 5, manual: true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
setupBulkDB(t)
|
||||
db := database.GetDB()
|
||||
zone := pinPanelZone(t, tt.zone)
|
||||
now := time.Now().In(zone)
|
||||
boundary := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, zone)
|
||||
for int(boundary.Weekday()+6)%7+1 != tt.weekday || !boundary.Before(now) {
|
||||
boundary = boundary.AddDate(0, 0, -1)
|
||||
}
|
||||
past := boundary.AddDate(0, 0, -21)
|
||||
if tt.zone == "America/New_York" {
|
||||
past = time.Date(2026, time.March, 1, 0, 0, 0, 0, zone)
|
||||
}
|
||||
if tt.inclusive {
|
||||
past = boundary.Add(-time.Second)
|
||||
}
|
||||
client := model.Client{
|
||||
Email: "weekly@x", ID: "11111111-1111-1111-1111-111111111111",
|
||||
ResetWeekday: tt.weekday, ResetMax: tt.max, ExpiryTime: past.UnixMilli(),
|
||||
}
|
||||
svc := &InboundService{}
|
||||
for _, port := range []int{30241, 30242} {
|
||||
ib := mkInbound(t, port, model.VLESS, clientsSettings(t, []model.Client{client}))
|
||||
if err := svc.clientService.SyncInbound(nil, ib.Id, []model.Client{client}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
traffic := xray.ClientTraffic{
|
||||
Email: client.Email, ResetWeekday: tt.weekday, ResetMax: tt.max, ResetCount: tt.count,
|
||||
ExpiryTime: past.UnixMilli(), Up: 111, Down: 222, Enable: tt.manual,
|
||||
}
|
||||
if err := db.Create(&traffic).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, steps := past, 0
|
||||
if tt.inclusive {
|
||||
want = boundary
|
||||
}
|
||||
for !want.After(now) && (tt.max == 0 || tt.count+steps < tt.max) {
|
||||
want = want.AddDate(0, 0, 7)
|
||||
steps++
|
||||
}
|
||||
if _, _, err := svc.autoRenewClients(db, newTrafficMutationBatch()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got xray.ClientTraffic
|
||||
if err := db.Where("email = ?", client.Email).First(&got).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.ExpiryTime != want.UnixMilli() || got.ResetCount != tt.count+steps || got.ResetWeekday != tt.weekday {
|
||||
t.Fatalf("expiry/count/weekday = %d/%d/%d, want %d/%d/%d", got.ExpiryTime, got.ResetCount, got.ResetWeekday, want.UnixMilli(), tt.count+steps, tt.weekday)
|
||||
}
|
||||
if want.After(now) {
|
||||
if !got.Enable || got.Up != 0 || got.Down != 0 {
|
||||
t.Fatalf("renewed enable/up/down = %v/%d/%d, want true/0/0", got.Enable, got.Up, got.Down)
|
||||
}
|
||||
} else if got.Enable || got.Up != 111 || got.Down != 222 {
|
||||
t.Fatalf("capped enable/up/down = %v/%d/%d, want false/111/222", got.Enable, got.Up, got.Down)
|
||||
}
|
||||
var record model.ClientRecord
|
||||
if err := db.Where("email = ?", client.Email).First(&record).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if record.ResetWeekday != tt.weekday || record.ExpiryTime != got.ExpiryTime || record.Enable != (want.After(now) && !tt.manual) {
|
||||
t.Fatalf("client record lost weekly schedule or operator enable state: %+v", record)
|
||||
}
|
||||
if _, count, err := svc.autoRenewClients(db, newTrafficMutationBatch()); err != nil || count != 0 {
|
||||
t.Fatalf("repeat tick count/error = %d/%v, want 0/nil", count, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -290,7 +290,7 @@ func applyMasterClientLifecycle(c *model.Client, master *xray.ClientTraffic, cs
|
||||
// nodeClientRenewed reports a node-side auto-renew: an absolute deadline moved
|
||||
// forward, evidenced by a renewal-count bump or a drop below the stored baseline.
|
||||
func nodeClientRenewed(existing *xray.ClientTraffic, cs xray.ClientTraffic, canon, base nodeTrafficCounter) bool {
|
||||
if (cs.Reset <= 0 && cs.ResetDay <= 0) || cs.ExpiryTime <= 0 || existing.ExpiryTime <= 0 {
|
||||
if (cs.Reset <= 0 && cs.ResetDay <= 0 && cs.ResetWeekday <= 0) || cs.ExpiryTime <= 0 || existing.ExpiryTime <= 0 {
|
||||
return false
|
||||
}
|
||||
if cs.ExpiryTime <= existing.ExpiryTime {
|
||||
@@ -952,16 +952,19 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
seedUp, seedDown = canon.Up, canon.Down
|
||||
}
|
||||
row := &xray.ClientTraffic{
|
||||
InboundId: c.Id,
|
||||
Email: cs.Email,
|
||||
Enable: cs.Enable,
|
||||
Total: cs.Total,
|
||||
ExpiryTime: cs.ExpiryTime,
|
||||
Reset: cs.Reset,
|
||||
ResetDay: cs.ResetDay,
|
||||
Up: seedUp,
|
||||
Down: seedDown,
|
||||
LastOnline: cs.LastOnline,
|
||||
InboundId: c.Id,
|
||||
Email: cs.Email,
|
||||
Enable: cs.Enable,
|
||||
Total: cs.Total,
|
||||
ExpiryTime: cs.ExpiryTime,
|
||||
Reset: cs.Reset,
|
||||
ResetDay: cs.ResetDay,
|
||||
ResetWeekday: cs.ResetWeekday,
|
||||
ResetMax: cs.ResetMax,
|
||||
ResetCount: cs.ResetCount,
|
||||
Up: seedUp,
|
||||
Down: seedDown,
|
||||
LastOnline: cs.LastOnline,
|
||||
}
|
||||
if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
|
||||
Create(row).Error; err != nil {
|
||||
@@ -985,7 +988,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
// re-enables from the node.
|
||||
enableChanged := !lifecycleFrozen && existing.Enable && !cs.Enable &&
|
||||
!nodeDisableIsStale(existing, cs, now, deltaUp, deltaDown)
|
||||
metaChanged := !lifecycleFrozen && (existing.Total != cs.Total || existing.Reset != cs.Reset)
|
||||
metaChanged := !lifecycleFrozen && (existing.Total != cs.Total || existing.Reset != cs.Reset || existing.ResetWeekday != cs.ResetWeekday)
|
||||
if enableChanged || metaChanged || expiryChanged {
|
||||
structuralChange = true
|
||||
}
|
||||
@@ -1009,12 +1012,12 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
fmt.Sprintf(
|
||||
`UPDATE client_traffics
|
||||
SET up = ?, down = ?, enable = ?, total = ?,
|
||||
expiry_time = ?, reset = ?, reset_day = ?, reset_count = ?, last_online = %s
|
||||
expiry_time = ?, reset = ?, reset_day = ?, reset_weekday = ?, reset_count = ?, last_online = %s
|
||||
WHERE email = ?`,
|
||||
database.GreatestExpr("last_online", "?"),
|
||||
),
|
||||
canon.Up, canon.Down, cs.Enable, cs.Total,
|
||||
cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetCount,
|
||||
cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.ResetCount,
|
||||
cs.LastOnline, cs.Email,
|
||||
).Error; err != nil {
|
||||
return false, err
|
||||
@@ -1028,6 +1031,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
existing.Total = cs.Total
|
||||
existing.ExpiryTime = cs.ExpiryTime
|
||||
existing.Reset = cs.Reset
|
||||
existing.ResetWeekday = cs.ResetWeekday
|
||||
existing.ResetCount = cs.ResetCount
|
||||
structuralChange = true
|
||||
} else if lifecycleFrozen {
|
||||
@@ -1058,7 +1062,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
`UPDATE client_traffics
|
||||
SET up = %s, down = %s, enable = %s, total = ?,
|
||||
expiry_time = %s,
|
||||
reset = ?, reset_day = ?, last_online = %s
|
||||
reset = ?, reset_day = ?, reset_weekday = ?, last_online = %s
|
||||
WHERE email = ?`,
|
||||
database.ClampedAddExpr("up"),
|
||||
database.ClampedAddExpr("down"),
|
||||
@@ -1069,7 +1073,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
deltaUp, deltaDown,
|
||||
cs.Enable, cs.ExpiryTime, cs.Total, now, deltaUp, deltaDown,
|
||||
cs.Total,
|
||||
cs.ExpiryTime, cs.Reset, cs.ResetDay,
|
||||
cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday,
|
||||
cs.LastOnline, cs.Email,
|
||||
).Error; err != nil {
|
||||
return false, err
|
||||
@@ -1084,6 +1088,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi
|
||||
existing.Down = clampTrafficCounter(existing.Down + deltaDown)
|
||||
existing.Total = cs.Total
|
||||
existing.Reset = cs.Reset
|
||||
existing.ResetWeekday = cs.ResetWeekday
|
||||
}
|
||||
}
|
||||
// A dip plus a lagging longer expiry mimics nodeClientRenewed and would
|
||||
|
||||
@@ -23,7 +23,7 @@ import (
|
||||
|
||||
// A client with a renewal day set auto-renews too, so it must not read as
|
||||
// depleted — otherwise the operator's purge deletes it between cycles (#6239).
|
||||
const depletedClientsClause = "reset = 0 and reset_day = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
|
||||
const depletedClientsClause = "reset = 0 and reset_day = 0 and reset_weekday = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
|
||||
|
||||
func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (needRestart bool, clientsDisabled bool, err error) {
|
||||
var disabledNodeIDs []int
|
||||
@@ -345,7 +345,7 @@ func (s *InboundService) autoRenewClients(tx *gorm.DB, mutationBatch *trafficMut
|
||||
// attached to, so it could be a node inbound even when the client also has
|
||||
// local inbounds. The email-based join through client_inbounds is authoritative.
|
||||
err = tx.Model(xray.ClientTraffic{}).
|
||||
Where("(reset > 0 or reset_day > 0) and expiry_time > 0 and expiry_time <= ?", now).
|
||||
Where("(reset > 0 or reset_day > 0 or reset_weekday > 0) and expiry_time > 0 and expiry_time <= ?", now).
|
||||
// A prepaid plan stops itself: once as many renewals have fired as the
|
||||
// operator allowed, the client is left to expire like any other.
|
||||
Where("reset_max <= 0 or reset_count < reset_max").
|
||||
@@ -447,37 +447,7 @@ func (s *InboundService) autoRenewClients(tx *gorm.DB, mutationBatch *trafficMut
|
||||
}
|
||||
// One allowance per period, not per tick: a client away for three
|
||||
// cycles must not catch up three of them against a prepaid cap.
|
||||
newExpiryTime := traffic.ExpiryTime
|
||||
if traffic.ResetDay <= 0 && traffic.Reset <= 0 {
|
||||
// Unreachable while the selection filter holds: a zero step below
|
||||
// would spin forever on the single traffic writer and hang the panel.
|
||||
continue
|
||||
}
|
||||
at := time.UnixMilli(newExpiryTime)
|
||||
// Inclusive end-of-day expiries share the next billing midnight; snap without
|
||||
// spending an allowance so the first charged step is a full month (#6300).
|
||||
if traffic.ResetDay > 0 {
|
||||
boundary := nextCalendarRenewal(at, traffic.ResetDay, renewLocation)
|
||||
if !at.Before(boundary.Add(-time.Second)) && at.Before(boundary) {
|
||||
at = boundary
|
||||
newExpiryTime = at.UnixMilli()
|
||||
}
|
||||
}
|
||||
renewals := 0
|
||||
for newExpiryTime < now {
|
||||
if traffic.ResetMax > 0 && traffic.ResetCount+renewals >= traffic.ResetMax {
|
||||
break
|
||||
}
|
||||
if traffic.ResetDay > 0 {
|
||||
// Calendar mode: step whole months in the panel's zone, so the
|
||||
// renewal date does not drift the way a fixed 30-day step does.
|
||||
at = nextCalendarRenewal(at, traffic.ResetDay, renewLocation)
|
||||
newExpiryTime = at.UnixMilli()
|
||||
} else {
|
||||
newExpiryTime += (int64(traffic.Reset) * 86400000)
|
||||
}
|
||||
renewals++
|
||||
}
|
||||
newExpiryTime, renewals := catchUpClientRenewal(traffic, now, renewLocation)
|
||||
if renewals > 0 {
|
||||
traffic.ExpiryTime = newExpiryTime
|
||||
traffic.ResetCount += renewals
|
||||
@@ -580,33 +550,41 @@ func (s *InboundService) autoRenewClients(tx *gorm.DB, mutationBatch *trafficMut
|
||||
// happens to reuse an orphaned email still inherits that row's leftover
|
||||
// up/down, since nothing at this call site can tell the two cases apart.
|
||||
func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
|
||||
if err := validateClientRenewal(*client); err != nil {
|
||||
return err
|
||||
}
|
||||
clientTraffic := xray.ClientTraffic{
|
||||
InboundId: inboundId,
|
||||
Email: client.Email,
|
||||
Total: client.TotalGB,
|
||||
ExpiryTime: client.ExpiryTime,
|
||||
Enable: client.Enable,
|
||||
Reset: client.Reset,
|
||||
ResetDay: client.ResetDay,
|
||||
ResetMax: client.ResetMax,
|
||||
InboundId: inboundId,
|
||||
Email: client.Email,
|
||||
Total: client.TotalGB,
|
||||
ExpiryTime: client.ExpiryTime,
|
||||
Enable: client.Enable,
|
||||
Reset: client.Reset,
|
||||
ResetDay: client.ResetDay,
|
||||
ResetWeekday: client.ResetWeekday,
|
||||
ResetMax: client.ResetMax,
|
||||
}
|
||||
return tx.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "email"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"inbound_id", "total", "expiry_time", "enable", "reset", "reset_day", "reset_max"}),
|
||||
DoUpdates: clause.AssignmentColumns([]string{"inbound_id", "total", "expiry_time", "enable", "reset", "reset_day", "reset_weekday", "reset_max"}),
|
||||
}).Create(&clientTraffic).Error
|
||||
}
|
||||
|
||||
func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
|
||||
if err := validateClientRenewal(*client); err != nil {
|
||||
return err
|
||||
}
|
||||
result := tx.Model(xray.ClientTraffic{}).
|
||||
Where("email = ?", email).
|
||||
Updates(map[string]any{
|
||||
"enable": client.Enable,
|
||||
"email": client.Email,
|
||||
"total": client.TotalGB,
|
||||
"expiry_time": client.ExpiryTime,
|
||||
"reset": client.Reset,
|
||||
"reset_day": client.ResetDay,
|
||||
"reset_max": client.ResetMax,
|
||||
"enable": client.Enable,
|
||||
"email": client.Email,
|
||||
"total": client.TotalGB,
|
||||
"expiry_time": client.ExpiryTime,
|
||||
"reset": client.Reset,
|
||||
"reset_day": client.ResetDay,
|
||||
"reset_weekday": client.ResetWeekday,
|
||||
"reset_max": client.ResetMax,
|
||||
})
|
||||
err := result.Error
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
func TestNodeWeeklyRenew_AdoptsNewPeriod(t *testing.T) {
|
||||
db := initTrafficTestDB(t)
|
||||
createNodeInbound(t, db, 1, "n1-weekly", 41011)
|
||||
svc := &InboundService{}
|
||||
first := time.Date(2030, time.January, 7, 0, 0, 0, 0, time.UTC).UnixMilli()
|
||||
second := first + 7*86400000
|
||||
client := model.Client{Email: "node-weekly", ID: "11111111-1111-1111-1111-111111111111", Enable: true, ResetWeekday: 1, ResetMax: 4, ExpiryTime: first}
|
||||
stats := xray.ClientTraffic{Email: client.Email, Enable: true, ResetWeekday: 1, ResetMax: 4, ResetCount: 2, ExpiryTime: first}
|
||||
syncNodeWithSettings(t, svc, 1, "n1-weekly", clientsSettings(t, []model.Client{client}), stats)
|
||||
seeded := readTraffic(t, db, client.Email)
|
||||
if seeded.ResetMax != 4 || seeded.ResetCount != 2 || seeded.ResetWeekday != 1 {
|
||||
t.Fatalf("node adoption lost renewal policy: %+v", seeded)
|
||||
}
|
||||
stats.Up, stats.Down = 500, 100
|
||||
syncNodeWithSettings(t, svc, 1, "n1-weekly", clientsSettings(t, []model.Client{client}), stats)
|
||||
if err := db.Model(&xray.ClientTraffic{}).Where("email = ?", client.Email).Update("enable", false).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.ClientGlobalTraffic{MasterGuid: "other", Email: client.Email, Up: 90}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client.ExpiryTime, stats.ExpiryTime = second, second
|
||||
stats.Up, stats.Down, stats.ResetCount = 0, 0, 3
|
||||
syncNodeWithSettings(t, svc, 1, "n1-weekly", clientsSettings(t, []model.Client{client}), stats)
|
||||
got := readTraffic(t, db, client.Email)
|
||||
if got.ExpiryTime != second || got.ResetCount != 3 || got.ResetMax != 4 || got.ResetWeekday != 1 || !got.Enable || got.Up != 0 || got.Down != 0 {
|
||||
t.Fatalf("node weekly renewal was not adopted: %+v", got)
|
||||
}
|
||||
var count int64
|
||||
if err := db.Model(&model.ClientGlobalTraffic{}).Where("email = ?", client.Email).Count(&count).Error; err != nil || count != 0 {
|
||||
t.Fatalf("stale global traffic count/error = %d/%v, want 0/nil", count, err)
|
||||
}
|
||||
var record model.ClientRecord
|
||||
if err := db.Where("email = ?", client.Email).First(&record).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if record.ResetWeekday != 1 || record.ExpiryTime != second {
|
||||
t.Fatalf("node weekly client record lost schedule: %+v", record)
|
||||
}
|
||||
stats.Up, stats.Down = 20, 8
|
||||
syncNodeWithSettings(t, svc, 1, "n1-weekly", clientsSettings(t, []model.Client{client}), stats)
|
||||
assertUpDown(t, readTraffic(t, db, client.Email), 20, 8, "new weekly period")
|
||||
}
|
||||
@@ -943,6 +943,23 @@
|
||||
},
|
||||
"renewMax": "الحد الأقصى للتجديدات",
|
||||
"renewMaxDesc": "عدد المرات التي يمكن أن يعمل فيها التجديد التلقائي قبل ترك العميل ينتهي. القيمة 0 تعني بلا حد. تعويض عدة فترات فائتة يستهلك تجديدًا واحدًا لكل فترة.",
|
||||
"renewMode": "Auto renewal",
|
||||
"renewModeNone": "Disabled",
|
||||
"renewModeInterval": "Fixed interval (days)",
|
||||
"renewModeWeekly": "Calendar weekly",
|
||||
"renewModeMonthly": "Calendar monthly",
|
||||
"renewWeekday": "Renew on weekday",
|
||||
"renewScheduleDesc": "Calendar renewal uses midnight in the panel timezone and also resets the client's traffic. Keep independent traffic resets disabled unless an additional reset is intended. Monthly day 1 means valid through the preceding month; day 31 is not the same boundary.",
|
||||
"renewPreview": "Renewal preview ({zone})",
|
||||
"renewAt": "Renewal boundary",
|
||||
"renewValidThrough": "Valid through",
|
||||
"renewNextExpiry": "Cutoff after renewal",
|
||||
"renewPeriods": "Periods charged: {count}",
|
||||
"renewUnavailable": "The remaining renewal allowances cannot provide a future cutoff.",
|
||||
"renewFirstUse": "Dates are available after first-use activation. The initial duration is unchanged.",
|
||||
"renewSetExpiry": "Set first cycle cutoff",
|
||||
"renewNeedsExpiry": "An expiry must be set before auto-renewal can run.",
|
||||
"renewPreviewError": "Could not preview renewal dates.",
|
||||
"renewOnDay": "يوم التجديد",
|
||||
"renewOnDayDesc": "يتم التجديد في هذا اليوم من كل شهر ميلادي، عند منتصف الليل بتوقيت اللوحة، بدلاً من كل N يوم. إذا كان الشهر أقصر من اليوم المختار، يتم التجديد في آخر يوم منه. القيمة 0 تُبقي وضع الفاصل اليومي.",
|
||||
"renewsUsed": "التجديدات المستخدمة",
|
||||
|
||||
@@ -943,6 +943,23 @@
|
||||
},
|
||||
"renewMax": "Max renewals",
|
||||
"renewMaxDesc": "How many times auto-renew may fire before the client is left to expire. 0 means no limit. Catching up several missed periods spends one renewal per period.",
|
||||
"renewMode": "Auto renewal",
|
||||
"renewModeNone": "Disabled",
|
||||
"renewModeInterval": "Fixed interval (days)",
|
||||
"renewModeWeekly": "Calendar weekly",
|
||||
"renewModeMonthly": "Calendar monthly",
|
||||
"renewWeekday": "Renew on weekday",
|
||||
"renewScheduleDesc": "Calendar renewal uses midnight in the panel timezone and also resets the client's traffic. Keep independent traffic resets disabled unless an additional reset is intended. Monthly day 1 means valid through the preceding month; day 31 is not the same boundary.",
|
||||
"renewPreview": "Renewal preview ({zone})",
|
||||
"renewAt": "Renewal boundary",
|
||||
"renewValidThrough": "Valid through",
|
||||
"renewNextExpiry": "Cutoff after renewal",
|
||||
"renewPeriods": "Periods charged: {count}",
|
||||
"renewUnavailable": "The remaining renewal allowances cannot provide a future cutoff.",
|
||||
"renewFirstUse": "Dates are available after first-use activation. The initial duration is unchanged.",
|
||||
"renewSetExpiry": "Set first cycle cutoff",
|
||||
"renewNeedsExpiry": "An expiry must be set before auto-renewal can run.",
|
||||
"renewPreviewError": "Could not preview renewal dates.",
|
||||
"renewOnDay": "Renew on day",
|
||||
"renewOnDayDesc": "Renew on this day of every calendar month, at midnight in the panel's time zone, instead of every N days. A month too short for the chosen day renews on its last day. 0 keeps the day-interval mode.",
|
||||
"renewsUsed": "Renewals used",
|
||||
|
||||
@@ -943,6 +943,23 @@
|
||||
},
|
||||
"renewMax": "Renovaciones máximas",
|
||||
"renewMaxDesc": "Cuántas veces puede activarse la renovación automática antes de dejar que el cliente caduque. 0 significa sin límite. Recuperar varios periodos perdidos consume una renovación por periodo.",
|
||||
"renewMode": "Auto renewal",
|
||||
"renewModeNone": "Disabled",
|
||||
"renewModeInterval": "Fixed interval (days)",
|
||||
"renewModeWeekly": "Calendar weekly",
|
||||
"renewModeMonthly": "Calendar monthly",
|
||||
"renewWeekday": "Renew on weekday",
|
||||
"renewScheduleDesc": "Calendar renewal uses midnight in the panel timezone and also resets the client's traffic. Keep independent traffic resets disabled unless an additional reset is intended. Monthly day 1 means valid through the preceding month; day 31 is not the same boundary.",
|
||||
"renewPreview": "Renewal preview ({zone})",
|
||||
"renewAt": "Renewal boundary",
|
||||
"renewValidThrough": "Valid through",
|
||||
"renewNextExpiry": "Cutoff after renewal",
|
||||
"renewPeriods": "Periods charged: {count}",
|
||||
"renewUnavailable": "The remaining renewal allowances cannot provide a future cutoff.",
|
||||
"renewFirstUse": "Dates are available after first-use activation. The initial duration is unchanged.",
|
||||
"renewSetExpiry": "Set first cycle cutoff",
|
||||
"renewNeedsExpiry": "An expiry must be set before auto-renewal can run.",
|
||||
"renewPreviewError": "Could not preview renewal dates.",
|
||||
"renewOnDay": "Renovar el día",
|
||||
"renewOnDayDesc": "Renueva este día de cada mes natural, a medianoche en la zona horaria del panel, en lugar de cada N días. Si el mes es demasiado corto para el día elegido, renueva su último día. 0 mantiene el modo de intervalo en días.",
|
||||
"renewsUsed": "Renovaciones usadas",
|
||||
|
||||
@@ -943,6 +943,23 @@
|
||||
},
|
||||
"renewMax": "حداکثر تعداد تمدید",
|
||||
"renewMaxDesc": "تمدید خودکار حداکثر چند بار اجرا شود پیش از آنکه کلاینت منقضی بماند. مقدار ۰ یعنی بدون محدودیت. جبران چند دورهٔ ازدسترفته، برای هر دوره یک تمدید مصرف میکند.",
|
||||
"renewMode": "Auto renewal",
|
||||
"renewModeNone": "Disabled",
|
||||
"renewModeInterval": "Fixed interval (days)",
|
||||
"renewModeWeekly": "Calendar weekly",
|
||||
"renewModeMonthly": "Calendar monthly",
|
||||
"renewWeekday": "Renew on weekday",
|
||||
"renewScheduleDesc": "Calendar renewal uses midnight in the panel timezone and also resets the client's traffic. Keep independent traffic resets disabled unless an additional reset is intended. Monthly day 1 means valid through the preceding month; day 31 is not the same boundary.",
|
||||
"renewPreview": "Renewal preview ({zone})",
|
||||
"renewAt": "Renewal boundary",
|
||||
"renewValidThrough": "Valid through",
|
||||
"renewNextExpiry": "Cutoff after renewal",
|
||||
"renewPeriods": "Periods charged: {count}",
|
||||
"renewUnavailable": "The remaining renewal allowances cannot provide a future cutoff.",
|
||||
"renewFirstUse": "Dates are available after first-use activation. The initial duration is unchanged.",
|
||||
"renewSetExpiry": "Set first cycle cutoff",
|
||||
"renewNeedsExpiry": "An expiry must be set before auto-renewal can run.",
|
||||
"renewPreviewError": "Could not preview renewal dates.",
|
||||
"renewOnDay": "روز تمدید",
|
||||
"renewOnDayDesc": "در این روز از هر ماه تقویمی، در نیمهشب به وقت پنل تمدید میشود، به جای هر N روز. اگر ماه کوتاهتر از روز انتخابی باشد، در آخرین روز آن ماه تمدید میشود. مقدار ۰ حالت بازهٔ روزانه را حفظ میکند.",
|
||||
"renewsUsed": "تمدیدهای استفادهشده",
|
||||
|
||||
@@ -943,6 +943,23 @@
|
||||
},
|
||||
"renewMax": "Maksimum perpanjangan",
|
||||
"renewMaxDesc": "Berapa kali perpanjangan otomatis boleh berjalan sebelum klien dibiarkan kedaluwarsa. 0 berarti tanpa batas. Mengejar beberapa periode yang terlewat menghabiskan satu perpanjangan per periode.",
|
||||
"renewMode": "Auto renewal",
|
||||
"renewModeNone": "Disabled",
|
||||
"renewModeInterval": "Fixed interval (days)",
|
||||
"renewModeWeekly": "Calendar weekly",
|
||||
"renewModeMonthly": "Calendar monthly",
|
||||
"renewWeekday": "Renew on weekday",
|
||||
"renewScheduleDesc": "Calendar renewal uses midnight in the panel timezone and also resets the client's traffic. Keep independent traffic resets disabled unless an additional reset is intended. Monthly day 1 means valid through the preceding month; day 31 is not the same boundary.",
|
||||
"renewPreview": "Renewal preview ({zone})",
|
||||
"renewAt": "Renewal boundary",
|
||||
"renewValidThrough": "Valid through",
|
||||
"renewNextExpiry": "Cutoff after renewal",
|
||||
"renewPeriods": "Periods charged: {count}",
|
||||
"renewUnavailable": "The remaining renewal allowances cannot provide a future cutoff.",
|
||||
"renewFirstUse": "Dates are available after first-use activation. The initial duration is unchanged.",
|
||||
"renewSetExpiry": "Set first cycle cutoff",
|
||||
"renewNeedsExpiry": "An expiry must be set before auto-renewal can run.",
|
||||
"renewPreviewError": "Could not preview renewal dates.",
|
||||
"renewOnDay": "Perpanjang pada tanggal",
|
||||
"renewOnDayDesc": "Perpanjang pada tanggal ini setiap bulan kalender, pada tengah malam menurut zona waktu panel, alih-alih setiap N hari. Bulan yang terlalu pendek untuk tanggal yang dipilih diperpanjang pada hari terakhirnya. 0 mempertahankan mode interval hari.",
|
||||
"renewsUsed": "Perpanjangan terpakai",
|
||||
|
||||
@@ -943,6 +943,23 @@
|
||||
},
|
||||
"renewMax": "最大更新回数",
|
||||
"renewMaxDesc": "自動更新が実行される最大回数です。これを超えるとクライアントはそのまま失効します。0 は無制限。複数の未処理期間をまとめて処理する場合、1 期間につき 1 回消費します。",
|
||||
"renewMode": "Auto renewal",
|
||||
"renewModeNone": "Disabled",
|
||||
"renewModeInterval": "Fixed interval (days)",
|
||||
"renewModeWeekly": "Calendar weekly",
|
||||
"renewModeMonthly": "Calendar monthly",
|
||||
"renewWeekday": "Renew on weekday",
|
||||
"renewScheduleDesc": "Calendar renewal uses midnight in the panel timezone and also resets the client's traffic. Keep independent traffic resets disabled unless an additional reset is intended. Monthly day 1 means valid through the preceding month; day 31 is not the same boundary.",
|
||||
"renewPreview": "Renewal preview ({zone})",
|
||||
"renewAt": "Renewal boundary",
|
||||
"renewValidThrough": "Valid through",
|
||||
"renewNextExpiry": "Cutoff after renewal",
|
||||
"renewPeriods": "Periods charged: {count}",
|
||||
"renewUnavailable": "The remaining renewal allowances cannot provide a future cutoff.",
|
||||
"renewFirstUse": "Dates are available after first-use activation. The initial duration is unchanged.",
|
||||
"renewSetExpiry": "Set first cycle cutoff",
|
||||
"renewNeedsExpiry": "An expiry must be set before auto-renewal can run.",
|
||||
"renewPreviewError": "Could not preview renewal dates.",
|
||||
"renewOnDay": "更新する日",
|
||||
"renewOnDayDesc": "毎月この日の深夜(パネルのタイムゾーン基準)に更新します。N 日ごとの更新の代わりになります。その日が存在しない月は月末に更新されます。0 で日数間隔モードのままになります。",
|
||||
"renewsUsed": "使用済み更新回数",
|
||||
|
||||
@@ -943,6 +943,23 @@
|
||||
},
|
||||
"renewMax": "Renovações máximas",
|
||||
"renewMaxDesc": "Quantas vezes a renovação automática pode ocorrer antes de o cliente ser deixado a expirar. 0 significa sem limite. Recuperar vários períodos perdidos consome uma renovação por período.",
|
||||
"renewMode": "Auto renewal",
|
||||
"renewModeNone": "Disabled",
|
||||
"renewModeInterval": "Fixed interval (days)",
|
||||
"renewModeWeekly": "Calendar weekly",
|
||||
"renewModeMonthly": "Calendar monthly",
|
||||
"renewWeekday": "Renew on weekday",
|
||||
"renewScheduleDesc": "Calendar renewal uses midnight in the panel timezone and also resets the client's traffic. Keep independent traffic resets disabled unless an additional reset is intended. Monthly day 1 means valid through the preceding month; day 31 is not the same boundary.",
|
||||
"renewPreview": "Renewal preview ({zone})",
|
||||
"renewAt": "Renewal boundary",
|
||||
"renewValidThrough": "Valid through",
|
||||
"renewNextExpiry": "Cutoff after renewal",
|
||||
"renewPeriods": "Periods charged: {count}",
|
||||
"renewUnavailable": "The remaining renewal allowances cannot provide a future cutoff.",
|
||||
"renewFirstUse": "Dates are available after first-use activation. The initial duration is unchanged.",
|
||||
"renewSetExpiry": "Set first cycle cutoff",
|
||||
"renewNeedsExpiry": "An expiry must be set before auto-renewal can run.",
|
||||
"renewPreviewError": "Could not preview renewal dates.",
|
||||
"renewOnDay": "Renovar no dia",
|
||||
"renewOnDayDesc": "Renova neste dia de cada mês do calendário, à meia-noite no fuso horário do painel, em vez de a cada N dias. Se o mês for curto demais para o dia escolhido, renova no último dia dele. 0 mantém o modo de intervalo em dias.",
|
||||
"renewsUsed": "Renovações usadas",
|
||||
|
||||
@@ -943,6 +943,23 @@
|
||||
},
|
||||
"renewMax": "Лимит продлений",
|
||||
"renewMaxDesc": "Сколько раз автопродление может сработать, прежде чем клиент будет оставлен истекать. 0 — без ограничения. Догон нескольких пропущенных периодов расходует по одному продлению на период.",
|
||||
"renewMode": "Auto renewal",
|
||||
"renewModeNone": "Disabled",
|
||||
"renewModeInterval": "Fixed interval (days)",
|
||||
"renewModeWeekly": "Calendar weekly",
|
||||
"renewModeMonthly": "Calendar monthly",
|
||||
"renewWeekday": "Renew on weekday",
|
||||
"renewScheduleDesc": "Calendar renewal uses midnight in the panel timezone and also resets the client's traffic. Keep independent traffic resets disabled unless an additional reset is intended. Monthly day 1 means valid through the preceding month; day 31 is not the same boundary.",
|
||||
"renewPreview": "Renewal preview ({zone})",
|
||||
"renewAt": "Renewal boundary",
|
||||
"renewValidThrough": "Valid through",
|
||||
"renewNextExpiry": "Cutoff after renewal",
|
||||
"renewPeriods": "Periods charged: {count}",
|
||||
"renewUnavailable": "The remaining renewal allowances cannot provide a future cutoff.",
|
||||
"renewFirstUse": "Dates are available after first-use activation. The initial duration is unchanged.",
|
||||
"renewSetExpiry": "Set first cycle cutoff",
|
||||
"renewNeedsExpiry": "An expiry must be set before auto-renewal can run.",
|
||||
"renewPreviewError": "Could not preview renewal dates.",
|
||||
"renewOnDay": "Продлевать числа",
|
||||
"renewOnDayDesc": "Продлевать этого числа каждого месяца, в полночь по часовому поясу панели, вместо интервала в днях. Если в месяце такого числа нет, продление придётся на последний день. 0 — оставить режим интервала.",
|
||||
"renewsUsed": "Продлений израсходовано",
|
||||
|
||||
@@ -943,6 +943,23 @@
|
||||
},
|
||||
"renewMax": "En fazla yenileme",
|
||||
"renewMaxDesc": "İstemcinin süresi dolmaya bırakılmadan önce otomatik yenilemenin kaç kez çalışabileceği. 0 sınırsız demektir. Kaçırılan birden fazla dönemi telafi etmek, dönem başına bir yenileme harcar.",
|
||||
"renewMode": "Auto renewal",
|
||||
"renewModeNone": "Disabled",
|
||||
"renewModeInterval": "Fixed interval (days)",
|
||||
"renewModeWeekly": "Calendar weekly",
|
||||
"renewModeMonthly": "Calendar monthly",
|
||||
"renewWeekday": "Renew on weekday",
|
||||
"renewScheduleDesc": "Calendar renewal uses midnight in the panel timezone and also resets the client's traffic. Keep independent traffic resets disabled unless an additional reset is intended. Monthly day 1 means valid through the preceding month; day 31 is not the same boundary.",
|
||||
"renewPreview": "Renewal preview ({zone})",
|
||||
"renewAt": "Renewal boundary",
|
||||
"renewValidThrough": "Valid through",
|
||||
"renewNextExpiry": "Cutoff after renewal",
|
||||
"renewPeriods": "Periods charged: {count}",
|
||||
"renewUnavailable": "The remaining renewal allowances cannot provide a future cutoff.",
|
||||
"renewFirstUse": "Dates are available after first-use activation. The initial duration is unchanged.",
|
||||
"renewSetExpiry": "Set first cycle cutoff",
|
||||
"renewNeedsExpiry": "An expiry must be set before auto-renewal can run.",
|
||||
"renewPreviewError": "Could not preview renewal dates.",
|
||||
"renewOnDay": "Yenileme günü",
|
||||
"renewOnDayDesc": "Her N günde bir yerine, her takvim ayının bu gününde, panel saat diliminde gece yarısı yeniler. Seçilen gün için kısa olan aylarda ayın son gününde yeniler. 0 gün aralığı modunu korur.",
|
||||
"renewsUsed": "Kullanılan yenileme",
|
||||
|
||||
@@ -943,6 +943,23 @@
|
||||
},
|
||||
"renewMax": "Ліміт подовжень",
|
||||
"renewMaxDesc": "Скільки разів автоподовження може спрацювати, перш ніж клієнта буде залишено спливати. 0 — без обмеження. Надолуження кількох пропущених періодів витрачає по одному подовженню на період.",
|
||||
"renewMode": "Auto renewal",
|
||||
"renewModeNone": "Disabled",
|
||||
"renewModeInterval": "Fixed interval (days)",
|
||||
"renewModeWeekly": "Calendar weekly",
|
||||
"renewModeMonthly": "Calendar monthly",
|
||||
"renewWeekday": "Renew on weekday",
|
||||
"renewScheduleDesc": "Calendar renewal uses midnight in the panel timezone and also resets the client's traffic. Keep independent traffic resets disabled unless an additional reset is intended. Monthly day 1 means valid through the preceding month; day 31 is not the same boundary.",
|
||||
"renewPreview": "Renewal preview ({zone})",
|
||||
"renewAt": "Renewal boundary",
|
||||
"renewValidThrough": "Valid through",
|
||||
"renewNextExpiry": "Cutoff after renewal",
|
||||
"renewPeriods": "Periods charged: {count}",
|
||||
"renewUnavailable": "The remaining renewal allowances cannot provide a future cutoff.",
|
||||
"renewFirstUse": "Dates are available after first-use activation. The initial duration is unchanged.",
|
||||
"renewSetExpiry": "Set first cycle cutoff",
|
||||
"renewNeedsExpiry": "An expiry must be set before auto-renewal can run.",
|
||||
"renewPreviewError": "Could not preview renewal dates.",
|
||||
"renewOnDay": "Подовжувати числа",
|
||||
"renewOnDayDesc": "Подовжувати цього числа кожного місяця, опівночі за часовим поясом панелі, замість інтервалу в днях. Якщо в місяці такого числа немає, подовження припаде на останній день. 0 — залишити режим інтервалу.",
|
||||
"renewsUsed": "Подовжень витрачено",
|
||||
|
||||
@@ -943,6 +943,23 @@
|
||||
},
|
||||
"renewMax": "Số lần gia hạn tối đa",
|
||||
"renewMaxDesc": "Gia hạn tự động được phép chạy bao nhiêu lần trước khi để khách hàng hết hạn. 0 nghĩa là không giới hạn. Bù lại nhiều kỳ đã bỏ lỡ sẽ tiêu tốn một lần gia hạn cho mỗi kỳ.",
|
||||
"renewMode": "Auto renewal",
|
||||
"renewModeNone": "Disabled",
|
||||
"renewModeInterval": "Fixed interval (days)",
|
||||
"renewModeWeekly": "Calendar weekly",
|
||||
"renewModeMonthly": "Calendar monthly",
|
||||
"renewWeekday": "Renew on weekday",
|
||||
"renewScheduleDesc": "Calendar renewal uses midnight in the panel timezone and also resets the client's traffic. Keep independent traffic resets disabled unless an additional reset is intended. Monthly day 1 means valid through the preceding month; day 31 is not the same boundary.",
|
||||
"renewPreview": "Renewal preview ({zone})",
|
||||
"renewAt": "Renewal boundary",
|
||||
"renewValidThrough": "Valid through",
|
||||
"renewNextExpiry": "Cutoff after renewal",
|
||||
"renewPeriods": "Periods charged: {count}",
|
||||
"renewUnavailable": "The remaining renewal allowances cannot provide a future cutoff.",
|
||||
"renewFirstUse": "Dates are available after first-use activation. The initial duration is unchanged.",
|
||||
"renewSetExpiry": "Set first cycle cutoff",
|
||||
"renewNeedsExpiry": "An expiry must be set before auto-renewal can run.",
|
||||
"renewPreviewError": "Could not preview renewal dates.",
|
||||
"renewOnDay": "Gia hạn vào ngày",
|
||||
"renewOnDayDesc": "Gia hạn vào ngày này của mỗi tháng dương lịch, lúc nửa đêm theo múi giờ của bảng điều khiển, thay vì mỗi N ngày. Tháng không có ngày đã chọn sẽ gia hạn vào ngày cuối cùng của tháng. 0 giữ nguyên chế độ khoảng cách theo ngày.",
|
||||
"renewsUsed": "Số lần gia hạn đã dùng",
|
||||
|
||||
@@ -943,6 +943,23 @@
|
||||
},
|
||||
"renewMax": "最大续期次数",
|
||||
"renewMaxDesc": "自动续期最多可触发的次数,达到后客户端将自然到期。填 0 表示不限制。补齐多个错过的周期时,每个周期消耗一次续期。",
|
||||
"renewMode": "自动续期模式",
|
||||
"renewModeNone": "不续期",
|
||||
"renewModeInterval": "固定间隔(天)",
|
||||
"renewModeWeekly": "日历周",
|
||||
"renewModeMonthly": "日历月",
|
||||
"renewWeekday": "每周续期日",
|
||||
"renewScheduleDesc": "日历续期按面板时区的午夜执行,并重置客户端流量。若不需要额外重置,请关闭独立的流量重置。每月 1 日续期表示有效至上个月末;每月 31 日不是同一边界。",
|
||||
"renewPreview": "续期预览({zone})",
|
||||
"renewAt": "续期边界",
|
||||
"renewValidThrough": "本期有效至",
|
||||
"renewNextExpiry": "续期后的截止时间",
|
||||
"renewPeriods": "计入续期次数:{count}",
|
||||
"renewUnavailable": "剩余续期次数不足以提供未来的截止时间。",
|
||||
"renewFirstUse": "首次使用激活后才能确定日期,首次使用后的初始时长保持不变。",
|
||||
"renewSetExpiry": "设置首个周期截止时间",
|
||||
"renewNeedsExpiry": "需要先设置到期时间,自动续期才会执行。",
|
||||
"renewPreviewError": "无法预览续期日期。",
|
||||
"renewOnDay": "按日期续期",
|
||||
"renewOnDayDesc": "每个自然月的这一天午夜(按面板时区)续期,而不是每 N 天续期一次。若当月没有该日期,则在当月最后一天续期。填 0 保持按天间隔模式。",
|
||||
"renewsUsed": "已用续期次数",
|
||||
|
||||
@@ -943,6 +943,23 @@
|
||||
},
|
||||
"renewMax": "最大續期次數",
|
||||
"renewMaxDesc": "自動續期最多可觸發的次數,達到後用戶端將自然到期。填 0 表示不限制。補齊多個錯過的週期時,每個週期消耗一次續期。",
|
||||
"renewMode": "自動續期模式",
|
||||
"renewModeNone": "不續期",
|
||||
"renewModeInterval": "固定間隔(天)",
|
||||
"renewModeWeekly": "日曆週",
|
||||
"renewModeMonthly": "日曆月",
|
||||
"renewWeekday": "每週續期日",
|
||||
"renewScheduleDesc": "日曆續期按面板時區的午夜執行,並重置客戶端流量。若不需要額外重置,請關閉獨立的流量重置。每月 1 日續期表示有效至上個月末;每月 31 日不是同一邊界。",
|
||||
"renewPreview": "續期預覽({zone})",
|
||||
"renewAt": "續期邊界",
|
||||
"renewValidThrough": "本期有效至",
|
||||
"renewNextExpiry": "續期後的截止時間",
|
||||
"renewPeriods": "計入續期次數:{count}",
|
||||
"renewUnavailable": "剩餘續期次數不足以提供未來的截止時間。",
|
||||
"renewFirstUse": "首次使用啟用後才能確定日期,首次使用後的初始時長保持不變。",
|
||||
"renewSetExpiry": "設定首個週期截止時間",
|
||||
"renewNeedsExpiry": "需要先設定到期時間,自動續期才會執行。",
|
||||
"renewPreviewError": "無法預覽續期日期。",
|
||||
"renewOnDay": "按日期續期",
|
||||
"renewOnDayDesc": "每個自然月的這一天午夜(依面板時區)續期,而不是每 N 天續期一次。若當月沒有該日期,則在當月最後一天續期。填 0 保持按天間隔模式。",
|
||||
"renewsUsed": "已用續期次數",
|
||||
|
||||
Reference in New Issue
Block a user