mbs-panel/settings.py

104 lines
3.3 KiB
Python
Raw Normal View History

feat: plan prices, payment toggles and HWID limit now editable live from the admin panel, no restart Closes the last "still .env-only" gap from the backlog (tariffs/HWID) and fixes a real bug found while building it: payment provider credentials and enabled-flags were frozen in api.py's process at import time, so a Platega secret rotation via the settings UI would leave api.py verifying inbound webhooks against the OLD secret until a manual `mbs restart` — while bot.py (which does get restarted on save) already had the new one. Same class of staleness affected HWID_LIMIT_ENABLED/HWID_FALLBACK_LIMIT and plan prices, neither of which had any settings UI at all before this. New `settings.py` module: get_plans()/get_plans_by_code() (live prices, falls back to config.py defaults), get_payment_settings(), get_hwid_settings(), yookassa_credentials()/platega_credentials(), set_plan_prices() — all backed by a new batched legal.read_env_vars() (one file read for N keys instead of N reads) and legal.update_env_var() (moved out of api.py's private _update_env_var, which is now a one-line delegate to avoid duplicating the same env-file-rewrite logic in two places). api.py and bot.py no longer import PLANS/PLANS_BY_CODE/PAYMENTS_ENABLED/ HWID_LIMIT_ENABLED/HWID_FALLBACK_LIMIT from config as frozen constants — every read goes through settings.py instead. payments.py no longer imports YOOKASSA_*/PLATEGA_* from config either; every provider call (create/check payment, verify webhook signature) reads live credentials at call time. Every call site inside a loop hoists the live lookup before the loop first (same N+1 discipline as the rest of tonight), so this doesn't regress get_subscription's hot path — one settings.get_hwid_settings() call per request, same as before. New routes: GET/POST /admin/api/payments/plan-settings (per-plan prices + a payments_enabled master toggle — there was previously no way to turn payment collection back off without deleting provider credentials), GET/POST /admin/api/hwid-settings. Both validate input strictly (prices: non-negative int; HWID limit: 1-1000) and reject the whole request instead of partially applying on bad input. admin.html: new "Тарифы" section in Платежи (price inputs rendered from the live plan list + payments toggle) and "Лимит устройств (HWID)" in Настройки, both using the existing .check checkbox / plain-input styling (no native <select>, per the earlier white-popup complaint). Removed the now-incorrect "выполни mbs restart" copy from the YooKassa/Platega settings hints and save-result messages, and added a doc-block for HWID (never had one) plus extended the Платежи doc-block to mention live-apply. Also dropped a dead `import links` in bot.py caught by pyflakes while verifying this. Verification: api.py/bot.py still can't be imported on this Windows machine (no prebuilt pydantic-core wheel for Python 3.14, confirmed again by a fresh pip attempt — same wall as every prior session), so relied on what's actually exercisable: py_compile + pyflakes (zero undefined names) across every module including api.py/bot.py, a real runtime test against an isolated .env fixture covering live price/toggle/HWID reads with zero reimport, write-idempotency (no duplicate .env lines on repeated saves), and the concrete bug this fixes end to end — computed an HMAC signature against an old Platega secret, rotated the secret via update_env_var (the same call the settings route makes), confirmed the old signature is now rejected and a new one computed against the rotated secret verifies, all in the same process with no reimport. Also ran the new CI step's exact heredoc locally byte-for-byte before adding it to ci.yml. GitHub Actions still won't trigger for this account (still under abuse-review, ticket open >2 days) so this is the same substitute-for-CI rigor used all night. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 23:27:06 +05:00
import config
import legal
PRICE_ENV_KEYS = {"7d": "PRICE_7D", "1m": "PRICE_1M", "3m": "PRICE_3M", "6m": "PRICE_6M", "1y": "PRICE_1Y"}
def _bool(raw: str, default: bool) -> bool:
if raw is None or raw == "":
return default
return raw.strip().lower() == "true"
def _positive_int(raw: str, default: int) -> int:
if raw and raw.strip().lstrip("-").isdigit():
parsed = int(raw)
if parsed >= 0:
return parsed
return default
def get_plans() -> list:
raw = legal.read_env_vars(list(PRICE_ENV_KEYS.values()))
plans = []
for p in config.PLANS:
env_key = PRICE_ENV_KEYS[p["code"]]
plans.append({
"code": p["code"],
"label": p["label"],
"days": p["days"],
"price": _positive_int(raw.get(env_key), p["price"]),
})
return plans
def get_plans_by_code() -> dict:
return {p["code"]: p for p in get_plans()}
def set_plan_prices(prices: dict):
for code, price in prices.items():
if code in PRICE_ENV_KEYS:
legal.update_env_var(PRICE_ENV_KEYS[code], str(int(price)))
def get_payment_settings() -> dict:
raw = legal.read_env_vars(["PAYMENTS_ENABLED", "YOOKASSA_ENABLED", "PLATEGA_ENABLED"])
return {
"payments_enabled": _bool(raw.get("PAYMENTS_ENABLED"), config.PAYMENTS_ENABLED),
"yookassa_enabled": _bool(raw.get("YOOKASSA_ENABLED"), config.YOOKASSA_ENABLED),
"platega_enabled": _bool(raw.get("PLATEGA_ENABLED"), config.PLATEGA_ENABLED),
}
def yookassa_credentials():
raw = legal.read_env_vars(["YOOKASSA_SHOP_ID", "YOOKASSA_SECRET_KEY"])
return (
raw.get("YOOKASSA_SHOP_ID") or config.YOOKASSA_SHOP_ID,
raw.get("YOOKASSA_SECRET_KEY") or config.YOOKASSA_SECRET_KEY,
)
def platega_credentials():
raw = legal.read_env_vars(["PLATEGA_MERCHANT_ID", "PLATEGA_SECRET"])
return (
raw.get("PLATEGA_MERCHANT_ID") or config.PLATEGA_MERCHANT_ID,
raw.get("PLATEGA_SECRET") or config.PLATEGA_SECRET,
)
feat: custom brand name everywhere + a working client-facing site out of the box User ask, paraphrased: install it, get help wiring up payments, and immediately have a ready site under your own name — not "MBS Panel" plastered everywhere and a bunch of manual follow-up. Two things were actually broken/missing, found by tracing every surface a real customer or the operator would see: 1. "MBS Panel" was hardcoded in ~20 places (bot messages, subscription page, admin panel splash/title/sidebar, legal pages, 2FA issuer, install.sh) with zero way to change it short of editing source. New BRAND_NAME config value (config.py default "MBS Panel", so this is 100% backward compatible for existing installs) wired through everywhere via the same live-settings pattern from the last commit (settings.get_brand_name(), no restart needed anywhere it's used). New Настройки → «Название» section in the admin panel to change it. 2. site/index.html and site/cabinet.html — a fully-built landing page + personal-cabinet template, already in the repo — were never actually served by anything. Not mounted by FastAPI, not deployed by install.sh, not linked from anywhere. Pure dead weight: a repo that looked like it shipped a client site but didn't. Now legal.py gets a render_site_page() (same {{TOKEN}} substitution + HTML-escaping as the existing offer/privacy renderer, new tokens: BRAND_NAME, SITE_DOMAIN, SUB_DOMAIN, BOT_USERNAME) and GET "/" serves the branded landing page on any host that isn't PANEL_DOMAIN (in practice: SUB_DOMAIN, which nginx already routes to this backend — zero install.sh/nginx/certbot changes needed, so this is live on every existing install without an upgrade step beyond `mbs update`). GET /cabinet.html serves the cabinet. Landing page's pricing section now fetches real, live prices from a new public GET /api/plans instead of showing static duration labels with no numbers. Also fixed along the way, same staleness-bug class as the payments/HWID fix last commit, found by grepping for every remaining frozen `from config import ...` in api.py: BOT_TOKEN/BOT_USERNAME were still frozen constants in api.py (mbs-api never restarts itself). Concretely this meant: changing the bot via Настройки → Telegram-бот would leave _tg_send_message (payment-received notifications) silently trying the OLD token, admin_get_bot_settings showing the OLD username right after a successful save, and gift-code links pointing at the OLD bot — all until a manual mbs restart, same shape as the Platega-secret bug fixed last commit. Added settings.bot_credentials(), wired it through every call site (hoisted out of loops where relevant, same N+1 discipline as always), removed the now-stale "выполни mbs restart" copy from the bot settings hint. legal.py's own BOT_USERNAME import was frozen too (used by the /offer and /privacy {{BOT_USERNAME}} token) — switched to reading it live in-module (no settings.py import from legal.py, would've been circular since settings.py already imports legal.py for the env reader). install.sh: new interactive prompt for the brand name (default "MBS Panel", so hitting enter reproduces today's behavior exactly), written to .env, echoed in the final summary along with the now-live site URL. Verification: same story as always — api.py/bot.py still can't import locally (no pydantic-core wheel for Python 3.14 on this machine). py_compile + pyflakes clean across the whole repo. Real runtime test against an isolated .env fixture: brand name and bot-credential live reads (no reimport), render_site_page() token substitution correctness on the actual site/index.html and site/cabinet.html files including an XSS check (brand name containing <script> comes out HTML-escaped), and a regression check that adding the BRAND_NAME token to the existing legal.render() didn't break offer.html/privacy.html. Extracted SUB_PAGE_TEMPLATE/SUB_PAGE_EXPIRED_TEMPLATE via ast from api.py (can't import the module, but can pull the string constants) and ran the real .format() calls against them to catch any brace-escaping mistake in the new {brand_name} placeholder — CSS braces in those templates are already double-escaped for .format(), easy to get wrong. Extracted and node --check'd admin.html's whole inline script, div-tag-balance check on the full file. install.sh's new prompt+heredoc snippet run standalone with piped stdin (both a brand name with spaces and an empty/default input), round-tripped the resulting .env back through the real env-parsing logic. Extended the existing CI "app wiring" step (which does import api/bot for real on Linux) with branding assertions calling the actual route functions directly (api.root(), api.public_plans(), api.public_branding()) — ran every part of that step's new logic that doesn't need api.py locally first, to catch what's catchable before trusting the rest to CI once the account's abuse-review lifts. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 23:52:54 +05:00
def get_brand_name() -> str:
raw = legal.read_env_var("BRAND_NAME", "")
return raw.strip() if raw.strip() else config.BRAND_NAME
def bot_credentials():
raw = legal.read_env_vars(["BOT_TOKEN", "BOT_USERNAME"])
return (
raw.get("BOT_TOKEN") or config.BOT_TOKEN,
raw.get("BOT_USERNAME") or config.BOT_USERNAME,
)
feat: plan prices, payment toggles and HWID limit now editable live from the admin panel, no restart Closes the last "still .env-only" gap from the backlog (tariffs/HWID) and fixes a real bug found while building it: payment provider credentials and enabled-flags were frozen in api.py's process at import time, so a Platega secret rotation via the settings UI would leave api.py verifying inbound webhooks against the OLD secret until a manual `mbs restart` — while bot.py (which does get restarted on save) already had the new one. Same class of staleness affected HWID_LIMIT_ENABLED/HWID_FALLBACK_LIMIT and plan prices, neither of which had any settings UI at all before this. New `settings.py` module: get_plans()/get_plans_by_code() (live prices, falls back to config.py defaults), get_payment_settings(), get_hwid_settings(), yookassa_credentials()/platega_credentials(), set_plan_prices() — all backed by a new batched legal.read_env_vars() (one file read for N keys instead of N reads) and legal.update_env_var() (moved out of api.py's private _update_env_var, which is now a one-line delegate to avoid duplicating the same env-file-rewrite logic in two places). api.py and bot.py no longer import PLANS/PLANS_BY_CODE/PAYMENTS_ENABLED/ HWID_LIMIT_ENABLED/HWID_FALLBACK_LIMIT from config as frozen constants — every read goes through settings.py instead. payments.py no longer imports YOOKASSA_*/PLATEGA_* from config either; every provider call (create/check payment, verify webhook signature) reads live credentials at call time. Every call site inside a loop hoists the live lookup before the loop first (same N+1 discipline as the rest of tonight), so this doesn't regress get_subscription's hot path — one settings.get_hwid_settings() call per request, same as before. New routes: GET/POST /admin/api/payments/plan-settings (per-plan prices + a payments_enabled master toggle — there was previously no way to turn payment collection back off without deleting provider credentials), GET/POST /admin/api/hwid-settings. Both validate input strictly (prices: non-negative int; HWID limit: 1-1000) and reject the whole request instead of partially applying on bad input. admin.html: new "Тарифы" section in Платежи (price inputs rendered from the live plan list + payments toggle) and "Лимит устройств (HWID)" in Настройки, both using the existing .check checkbox / plain-input styling (no native <select>, per the earlier white-popup complaint). Removed the now-incorrect "выполни mbs restart" copy from the YooKassa/Platega settings hints and save-result messages, and added a doc-block for HWID (never had one) plus extended the Платежи doc-block to mention live-apply. Also dropped a dead `import links` in bot.py caught by pyflakes while verifying this. Verification: api.py/bot.py still can't be imported on this Windows machine (no prebuilt pydantic-core wheel for Python 3.14, confirmed again by a fresh pip attempt — same wall as every prior session), so relied on what's actually exercisable: py_compile + pyflakes (zero undefined names) across every module including api.py/bot.py, a real runtime test against an isolated .env fixture covering live price/toggle/HWID reads with zero reimport, write-idempotency (no duplicate .env lines on repeated saves), and the concrete bug this fixes end to end — computed an HMAC signature against an old Platega secret, rotated the secret via update_env_var (the same call the settings route makes), confirmed the old signature is now rejected and a new one computed against the rotated secret verifies, all in the same process with no reimport. Also ran the new CI step's exact heredoc locally byte-for-byte before adding it to ci.yml. GitHub Actions still won't trigger for this account (still under abuse-review, ticket open >2 days) so this is the same substitute-for-CI rigor used all night. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 23:27:06 +05:00
def get_hwid_settings() -> dict:
raw = legal.read_env_vars(["HWID_LIMIT_ENABLED", "HWID_FALLBACK_LIMIT"])
limit = _positive_int(raw.get("HWID_FALLBACK_LIMIT"), config.HWID_FALLBACK_LIMIT)
return {
"enabled": _bool(raw.get("HWID_LIMIT_ENABLED"), config.HWID_LIMIT_ENABLED),
"fallback_limit": limit if limit > 0 else config.HWID_FALLBACK_LIMIT,
}
feat: two-sided referral program Each user gets a short ref_code (backfilled lazily for pre-existing accounts too) and a shareable t.me/<bot>?start=ref_<code> link, new "Пригласить друга" menu item shows it plus how many referrals actually converted and any bonus days waiting to be applied. Reward fires once, on the referred user's first subscription of any kind (free, gift, or paid) — not on signup, so an unconverted click never pays out. Both sides get REFERRAL_BONUS_DAYS (config.py/.env, default 3): the referrer's day count comes from settings.py's live-read pattern, same as prices/HWID, so it's tunable without a restart even before a panel UI exists for it. Bonus extends an active subscription directly if the recipient has one, otherwise accumulates in bonus_days_pending and gets folded into whichever subscription they create next (redeemed automatically inside create_subscription, one choke point regardless of which of bot.py's several call sites created it — free trial, gift code, paid, or admin grant). Guards: no self-referral, referrer must exist, first-touch attribution only (a second ?start=ref_ link never overwrites it), and only takes for genuinely new accounts (no existing subscriptions) — attaching a referrer to an already-active user was never the intent. Tested two ways, matching this repo's usual db.py-can-be-imported- standalone / bot.py-needs-a-workaround split: 16 checks against a real isolated sqlite db for the db.py logic (attribution, both reward paths, double-reward guard, pending-bonus fold-in), then 9 more through an actual `import bot` — aiogram/fastapi now have Python 3.14 wheels so this imported for real rather than needing AST-extraction, modulo one old blocker (xray_manager still imports the Unix-only fcntl for its file lock) worked around with a tiny fake fcntl module in sys.modules, same spirit as the fcntl shim already used elsewhere in this project's history. Real start_deeplink and cb_referral calls, get_me() mocked to avoid a live Telegram API call. Not done: admin-panel UI toggle for REFERRAL_ENABLED/REFERRAL_BONUS_DAYS (currently .env-only, like several other business tunables were before they got a settings-page treatment) and a docs-tab writeup — happy to add both if wanted, scoped this pass to the mechanic itself. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-26 22:29:15 +05:00
def get_referral_settings() -> dict:
raw = legal.read_env_vars(["REFERRAL_ENABLED", "REFERRAL_BONUS_DAYS"])
days = _positive_int(raw.get("REFERRAL_BONUS_DAYS"), config.REFERRAL_BONUS_DAYS)
return {
"enabled": _bool(raw.get("REFERRAL_ENABLED"), config.REFERRAL_ENABLED),
"bonus_days": days if days > 0 else config.REFERRAL_BONUS_DAYS,
}
def set_referral_settings(enabled: bool, bonus_days: int):
legal.update_env_var("REFERRAL_ENABLED", "true" if enabled else "false")
legal.update_env_var("REFERRAL_BONUS_DAYS", str(int(bonus_days)))