client_renewal_preview_test.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. package controller
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "net/http"
  6. "net/http/httptest"
  7. "path/filepath"
  8. "testing"
  9. "time"
  10. "github.com/gin-gonic/gin"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  13. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  14. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  15. )
  16. func TestClientRenewalPreviewHTTP(t *testing.T) {
  17. for _, tt := range []struct {
  18. name, zone, expiry, renewAt, validThrough, next string
  19. wantError string
  20. reset, day, weekday, max, count int
  21. periods int
  22. canRenew, delayed, invalid bool
  23. }{
  24. {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},
  25. {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},
  26. {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},
  27. {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},
  28. {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},
  29. {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},
  30. {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},
  31. {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},
  32. {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},
  33. {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},
  34. {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},
  35. {name: "unset cutoff only suggests a boundary", zone: "UTC", weekday: 1},
  36. {name: "first-use waits for activation", zone: "UTC", expiry: "first-use", weekday: 1, delayed: true},
  37. {name: "disabled ignores absolute expiry", zone: "UTC", expiry: "2030-01-01T00:00:00Z"},
  38. {name: "invalid weekday", zone: "UTC", weekday: 8, invalid: true, wantError: "client resetWeekday must be between 0 and 7, got: 8\n"},
  39. {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"},
  40. {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"},
  41. {name: "negative count", zone: "UTC", count: -1, invalid: true, wantError: "renewal preview reset and resetCount must not be negative\n"},
  42. } {
  43. t.Run(tt.name, func(t *testing.T) {
  44. if err := database.InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
  45. t.Fatal(err)
  46. }
  47. t.Cleanup(func() { _ = database.CloseDB() })
  48. db := database.GetDB()
  49. if err := db.Create(&model.Setting{Key: "timeLocation", Value: tt.zone}).Error; err != nil {
  50. t.Fatal(err)
  51. }
  52. snapshot := xray.ClientTraffic{Email: "preview-sentinel", ExpiryTime: 1893456000000, ResetCount: 7, Up: 111, Down: 222, Enable: true}
  53. if err := db.Create(&snapshot).Error; err != nil {
  54. t.Fatal(err)
  55. }
  56. request := service.ClientRenewalPreviewRequest{Reset: tt.reset, ResetDay: tt.day, ResetWeekday: tt.weekday, ResetMax: tt.max, ResetCount: tt.count}
  57. if tt.expiry == "first-use" {
  58. request.ExpiryTime = -7 * 86400000
  59. } else if tt.expiry != "" {
  60. at, err := time.Parse(time.RFC3339, tt.expiry)
  61. if err != nil {
  62. t.Fatal(err)
  63. }
  64. request.ExpiryTime = at.UnixMilli()
  65. }
  66. payload, err := json.Marshal(request)
  67. if err != nil {
  68. t.Fatal(err)
  69. }
  70. router := gin.New()
  71. NewClientController(router.Group("/panel/api/clients"))
  72. w := httptest.NewRecorder()
  73. r := httptest.NewRequest(http.MethodPost, "/panel/api/clients/renewalPreview", bytes.NewReader(payload))
  74. r.Header.Set("Content-Type", "application/json")
  75. router.ServeHTTP(w, r)
  76. var msg struct {
  77. Success bool `json:"success"`
  78. Msg string `json:"msg"`
  79. Obj service.ClientRenewalPreview `json:"obj"`
  80. }
  81. if err := json.Unmarshal(w.Body.Bytes(), &msg); err != nil {
  82. t.Fatal(err)
  83. }
  84. if w.Code != http.StatusOK || msg.Success == tt.invalid {
  85. t.Fatalf("status/body = %d/%s", w.Code, w.Body.String())
  86. }
  87. if tt.invalid && msg.Msg != " ("+tt.wantError+")" {
  88. t.Fatalf("validation error = %q, want wrapped error %q", msg.Msg, tt.wantError)
  89. }
  90. if !tt.invalid {
  91. got := msg.Obj
  92. 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 {
  93. t.Fatalf("preview = %+v, want boundary/valid/next %q/%q/%q", got, tt.renewAt, tt.validThrough, tt.next)
  94. }
  95. wantRenewals := 0
  96. if tt.canRenew {
  97. wantRenewals = 1
  98. }
  99. if tt.periods > 0 {
  100. wantRenewals = tt.periods
  101. }
  102. if got.Renewals != wantRenewals {
  103. t.Fatalf("periods = %d, want %d", got.Renewals, wantRenewals)
  104. }
  105. if tt.weekday > 0 || tt.day > 0 {
  106. if got.SuggestedExpiryTime <= time.Now().UnixMilli() || got.SuggestedExpiry == "" {
  107. t.Fatalf("missing future suggestion: %+v", got)
  108. }
  109. }
  110. }
  111. var after xray.ClientTraffic
  112. if err := db.Where("email = ?", snapshot.Email).First(&after).Error; err != nil {
  113. t.Fatal(err)
  114. }
  115. if after != snapshot {
  116. t.Fatalf("read-only preview mutated traffic: %+v", after)
  117. }
  118. })
  119. }
  120. }