feat(clients): cap how many times a client may auto-renew (#6238)

* feat(clients): cap how many times a client may auto-renew

Auto-renew today runs forever: a prepaid or fixed-term client keeps being
handed new periods until an operator remembers to switch it off. There is no
way to say "renew this three times, then let it lapse".

Add a per-client maximum. Zero keeps today's behaviour, so nothing changes for
anyone who does not set one. When the count is reached the client is simply
left to expire, like any client without auto-renew.

Catching up several missed periods spends one allowance per period. A client
that was away for three cycles must not receive three of them free of the cap,
and the catch-up stops at the last period the cap paid for rather than jumping
to the present.

* fix(clients): persist the auto-renew cap and stop the capped churn

resetMax lived only in the inbound settings JSON and client_traffics, so
every path that rebuilds a client from the clients table wrote it back as
zero. The edit dialog showed 0 for a capped client, and saving an
unrelated comment change lifted the cap; an attach or a traffic reset did
the same with no operator action at all.

Adds reset_max to ClientRecord and threads it through ToRecord, ToClient,
applyClientRecordMerge, the record update map and ClientSlim, so the cap
survives the round trip.

When the cap truncates a catch-up the client is still expired, but the
renewal side effects fired anyway: counters were zeroed for periods it
can never use, and it was enabled and pushed to xray only for
disableInvalidClients to undo both in the same transaction. Those are now
skipped when the new expiry has not reached the present.

Also makes any non-positive resetMax mean unlimited instead of silently
meaning "never renew again", rejects a negative one at the service layer,
surfaces renewals used against allowed in the client info modal so the
operator can see what to raise, adds the field to the bulk-add modal,
translates the labels in all 13 locales, and drops the stray
internal/web/dist/.gitkeep build stub.

* fix(clients): let the renewal cap be changed after creation

ClientService.Update writes the record columns directly only for a client
with no inbounds. The normal path goes through SyncInbound and
applyClientRecordMerge, which this change had not extended, so raising a
cap from 3 to 6 — the natural action when a customer buys another block
of periods — updated the inbound settings JSON while clients.reset_max
kept the old value and the renewal query kept enforcing it.

The existing test did not catch it: it asserted the cap survived an
unrelated edit, and it survived precisely because nothing on that path
ever wrote it. TestClientEditChangesTheRenewalCap raises the cap and then
lifts it entirely; removing the record write turns it red.

* chore: drop the accidentally committed dist build stub

internal/web/dist/.gitkeep is what make dist-stub creates locally. Committing
it changes fresh-clone behaviour for everyone: today a bare go build fails
loudly on //go:embed all:dist, which is the documented signal to run the stub
target; with the file present the build succeeds and the panel serves an empty
dist instead.

---------

Co-authored-by: n0ctal <n0ctal@users.noreply.github.com>
This commit is contained in:
n0ctal
2026-08-18 14:53:11 +05:00
committed by GitHub
parent 6a674c7f0c
commit e940f30bb8
29 changed files with 508 additions and 27 deletions
+4 -1
View File
@@ -869,7 +869,10 @@
"delOrphans": "تم حذف {count} عميل غير مرتبط",
"imported": "تم استيراد {count} عميل",
"importedMixed": "{ok} تم استيرادهم، {failed} تم تخطيهم"
}
},
"renewMax": "الحد الأقصى للتجديدات",
"renewMaxDesc": "عدد المرات التي يمكن أن يعمل فيها التجديد التلقائي قبل ترك العميل ينتهي. القيمة 0 تعني بلا حد. تعويض عدة فترات فائتة يستهلك تجديدًا واحدًا لكل فترة.",
"renewsUsed": "التجديدات المستخدمة"
},
"groups": {
"name": "الاسم",
+4 -1
View File
@@ -869,7 +869,10 @@
"delOrphans": "{count} unattached clients deleted",
"imported": "{count} clients imported",
"importedMixed": "{ok} imported, {failed} skipped"
}
},
"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.",
"renewsUsed": "Renewals used"
},
"groups": {
"name": "Name",
+4 -1
View File
@@ -869,7 +869,10 @@
"delOrphans": "{count} clientes sin entrante eliminados",
"imported": "{count} clientes importados",
"importedMixed": "{ok} importados, {failed} omitidos"
}
},
"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.",
"renewsUsed": "Renovaciones usadas"
},
"groups": {
"name": "Nombre",
+4 -1
View File
@@ -869,7 +869,10 @@
"delOrphans": "{count} کلاینت بدون اینباند حذف شد",
"imported": "{count} کلاینت وارد شد",
"importedMixed": "{ok} وارد شد، {failed} رد شد"
}
},
"renewMax": "حداکثر تعداد تمدید",
"renewMaxDesc": "تمدید خودکار حداکثر چند بار اجرا شود پیش از آنکه کلاینت منقضی بماند. مقدار ۰ یعنی بدون محدودیت. جبران چند دورهٔ ازدست‌رفته، برای هر دوره یک تمدید مصرف می‌کند.",
"renewsUsed": "تمدیدهای استفاده‌شده"
},
"groups": {
"name": "نام",
+4 -1
View File
@@ -869,7 +869,10 @@
"delOrphans": "{count} klien tanpa inbound dihapus",
"imported": "{count} klien diimpor",
"importedMixed": "{ok} diimpor, {failed} dilewati"
}
},
"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.",
"renewsUsed": "Perpanjangan terpakai"
},
"groups": {
"name": "Nama",
+4 -1
View File
@@ -869,7 +869,10 @@
"delOrphans": "未アタッチの {count} 件のクライアントを削除しました",
"imported": "{count} 件のクライアントをインポートしました",
"importedMixed": "{ok} 件インポート、{failed} 件スキップ"
}
},
"renewMax": "最大更新回数",
"renewMaxDesc": "自動更新が実行される最大回数です。これを超えるとクライアントはそのまま失効します。0 は無制限。複数の未処理期間をまとめて処理する場合、1 期間につき 1 回消費します。",
"renewsUsed": "使用済み更新回数"
},
"groups": {
"name": "名前",
+4 -1
View File
@@ -869,7 +869,10 @@
"delOrphans": "{count} clientes sem inbound excluídos",
"imported": "{count} clientes importados",
"importedMixed": "{ok} importados, {failed} ignorados"
}
},
"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.",
"renewsUsed": "Renovações usadas"
},
"groups": {
"name": "Nome",
+4 -1
View File
@@ -869,7 +869,10 @@
"delOrphans": "Удалено клиентов без входящего: {count}",
"imported": "Импортировано клиентов: {count}",
"importedMixed": "Импортировано: {ok}, пропущено: {failed}"
}
},
"renewMax": "Лимит продлений",
"renewMaxDesc": "Сколько раз автопродление может сработать, прежде чем клиент будет оставлен истекать. 0 — без ограничения. Догон нескольких пропущенных периодов расходует по одному продлению на период.",
"renewsUsed": "Продлений израсходовано"
},
"groups": {
"name": "Имя",
+4 -1
View File
@@ -869,7 +869,10 @@
"delOrphans": "{count} bağsız kullanıcı silindi",
"imported": "{count} kullanıcı içe aktarıldı",
"importedMixed": "{ok} içe aktarıldı, {failed} atlandı"
}
},
"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.",
"renewsUsed": "Kullanılan yenileme"
},
"groups": {
"name": "İsim",
+4 -1
View File
@@ -869,7 +869,10 @@
"delOrphans": "Видалено клієнтів без вхідного: {count}",
"imported": "Імпортовано клієнтів: {count}",
"importedMixed": "Імпортовано: {ok}, пропущено: {failed}"
}
},
"renewMax": "Ліміт подовжень",
"renewMaxDesc": "Скільки разів автоподовження може спрацювати, перш ніж клієнта буде залишено спливати. 0 — без обмеження. Надолуження кількох пропущених періодів витрачає по одному подовженню на період.",
"renewsUsed": "Подовжень витрачено"
},
"groups": {
"name": "Назва",
+4 -1
View File
@@ -869,7 +869,10 @@
"delOrphans": "Đã xóa {count} khách hàng không gắn inbound",
"imported": "Đã nhập {count} khách hàng",
"importedMixed": "Đã nhập {ok}, bỏ qua {failed}"
}
},
"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ỳ.",
"renewsUsed": "Số lần gia hạn đã dùng"
},
"groups": {
"name": "Tên",
+4 -1
View File
@@ -869,7 +869,10 @@
"delOrphans": "已删除 {count} 个未关联的客户端",
"imported": "已导入 {count} 个客户端",
"importedMixed": "已导入 {ok} 个,跳过 {failed} 个"
}
},
"renewMax": "最大续期次数",
"renewMaxDesc": "自动续期最多可触发的次数,达到后客户端将自然到期。填 0 表示不限制。补齐多个错过的周期时,每个周期消耗一次续期。",
"renewsUsed": "已用续期次数"
},
"groups": {
"name": "名称",
+4 -1
View File
@@ -869,7 +869,10 @@
"delOrphans": "已刪除 {count} 個未關聯的客戶端",
"imported": "已匯入 {count} 個客戶端",
"importedMixed": "已匯入 {ok} 個,跳過 {failed} 個"
}
},
"renewMax": "最大續期次數",
"renewMaxDesc": "自動續期最多可觸發的次數,達到後用戶端將自然到期。填 0 表示不限制。補齊多個錯過的週期時,每個週期消耗一次續期。",
"renewsUsed": "已用續期次數"
},
"groups": {
"name": "名稱",