This commit is contained in:
2026-04-22 18:34:13 +03:00
parent 3992121397
commit ce7a1f70b2
60 changed files with 10243 additions and 3443 deletions

1
app/db/__init__.py Normal file
View File

@@ -0,0 +1 @@
"""Database package."""

11
app/db/base.py Normal file
View File

@@ -0,0 +1,11 @@
from datetime import datetime, timezone
from sqlalchemy.orm import DeclarativeBase
def utcnow() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
class Base(DeclarativeBase):
"""Base class for ORM models."""

238
app/db/models.py Normal file
View File

@@ -0,0 +1,238 @@
from datetime import datetime
from sqlalchemy import BigInteger, Boolean, DateTime, Float, ForeignKey, Index, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column
from app.db.base import Base, utcnow
class TelegramUser(Base):
__tablename__ = "telegram_users"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
telegram_id: Mapped[int] = mapped_column(BigInteger, nullable=False, unique=True, index=True)
username: Mapped[str | None] = mapped_column(String(64), nullable=True)
first_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
last_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
language_code: Mapped[str | None] = mapped_column(String(16), nullable=True)
is_admin: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
is_blocked: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
last_seen_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow, onupdate=utcnow)
class RemnawaveUser(Base):
__tablename__ = "remnawave_users"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
owner_telegram_user_id: Mapped[int | None] = mapped_column(
ForeignKey("telegram_users.id", ondelete="SET NULL"),
nullable=True,
index=True,
)
rw_uuid: Mapped[str] = mapped_column(String(36), nullable=False, unique=True, index=True)
rw_id: Mapped[int] = mapped_column(BigInteger, nullable=False, unique=True)
short_uuid: Mapped[str] = mapped_column(String(48), nullable=False, unique=True, index=True)
username: Mapped[str] = mapped_column(String(36), nullable=False, unique=True, index=True)
status: Mapped[str] = mapped_column(String(16), nullable=False)
traffic_limit_bytes: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
used_traffic_bytes: Mapped[float] = mapped_column(Float(asdecimal=False), nullable=False, default=0.0)
lifetime_used_traffic_bytes: Mapped[float] = mapped_column(Float(asdecimal=False), nullable=False, default=0.0)
expire_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
telegram_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True, index=True)
email: Mapped[str | None] = mapped_column(String(320), nullable=True, index=True)
description: Mapped[str | None] = mapped_column(Text, nullable=True)
tag: Mapped[str | None] = mapped_column(String(16), nullable=True, index=True)
hwid_device_limit: Mapped[int | None] = mapped_column(Integer, nullable=True)
external_squad_uuid: Mapped[str | None] = mapped_column(String(36), nullable=True)
trojan_password: Mapped[str] = mapped_column(String(64), nullable=False)
vless_uuid: Mapped[str] = mapped_column(String(36), nullable=False)
ss_password: Mapped[str] = mapped_column(String(64), nullable=False)
last_triggered_threshold: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
sub_revoked_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
sub_last_user_agent: Mapped[str | None] = mapped_column(String(512), nullable=True)
sub_last_opened_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
last_traffic_reset_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
subscription_url: Mapped[str] = mapped_column(Text, nullable=False)
online_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
first_connected_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
last_connected_node_uuid: Mapped[str | None] = mapped_column(String(36), nullable=True)
remote_created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
remote_updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
synced_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow)
class InternalSquad(Base):
__tablename__ = "internal_squads"
uuid: Mapped[str] = mapped_column(String(36), primary_key=True)
name: Mapped[str] = mapped_column(String(255), nullable=False)
synced_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow)
class RemnawaveUserInternalSquad(Base):
__tablename__ = "remnawave_user_internal_squads"
user_id: Mapped[int] = mapped_column(
ForeignKey("remnawave_users.id", ondelete="CASCADE"),
primary_key=True,
)
squad_uuid: Mapped[str] = mapped_column(
ForeignKey("internal_squads.uuid", ondelete="CASCADE"),
primary_key=True,
)
class SubscriptionRequestLog(Base):
__tablename__ = "subscription_request_logs"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
remote_id: Mapped[int] = mapped_column(BigInteger, nullable=False, unique=True, index=True)
user_uuid: Mapped[str] = mapped_column(
ForeignKey("remnawave_users.rw_uuid", ondelete="CASCADE"),
nullable=False,
index=True,
)
request_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
request_ip: Mapped[str | None] = mapped_column(String(45), nullable=True)
user_agent: Mapped[str | None] = mapped_column(Text, nullable=True)
synced_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow)
class SupportTicket(Base):
__tablename__ = "support_tickets"
__table_args__ = (
Index(
"ix_support_tickets_chat_message",
"support_chat_id",
"support_message_id",
unique=True,
),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
public_id: Mapped[str] = mapped_column(String(32), nullable=False, unique=True, index=True)
telegram_id: Mapped[int] = mapped_column(BigInteger, nullable=False, index=True)
username: Mapped[str | None] = mapped_column(String(64), nullable=True)
display_name: Mapped[str] = mapped_column(String(255), nullable=False)
user_message: Mapped[str] = mapped_column(Text, nullable=False)
support_chat_id: Mapped[int] = mapped_column(BigInteger, nullable=False, index=True)
support_thread_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
support_message_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default="OPEN")
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow, onupdate=utcnow)
class ReferralInvite(Base):
__tablename__ = "referral_invites"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
inviter_telegram_id: Mapped[int] = mapped_column(BigInteger, nullable=False, index=True)
invited_telegram_id: Mapped[int] = mapped_column(BigInteger, nullable=False, unique=True, index=True)
invited_username: Mapped[str | None] = mapped_column(String(64), nullable=True)
invited_display_name: Mapped[str] = mapped_column(String(255), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow)
class ReferralCode(Base):
__tablename__ = "referral_codes"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
telegram_id: Mapped[int] = mapped_column(BigInteger, nullable=False, unique=True, index=True)
code: Mapped[str] = mapped_column(String(32), nullable=False, unique=True, index=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow, onupdate=utcnow)
class ReferralBonus(Base):
__tablename__ = "referral_bonuses"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
inviter_telegram_id: Mapped[int] = mapped_column(BigInteger, nullable=False, index=True)
invited_telegram_id: Mapped[int] = mapped_column(BigInteger, nullable=False, index=True)
source_order_uuid: Mapped[str] = mapped_column(String(36), nullable=False, unique=True, index=True)
bonus_days: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
status: Mapped[str] = mapped_column(String(16), nullable=False, default="PENDING", index=True)
applied_to_user_uuid: Mapped[str | None] = mapped_column(String(36), nullable=True, index=True)
applied_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow, onupdate=utcnow)
class BotSetting(Base):
__tablename__ = "bot_settings"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
key: Mapped[str] = mapped_column(String(64), nullable=False, unique=True, index=True)
value: Mapped[str] = mapped_column(Text, nullable=False, default="")
updated_by_telegram_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True, index=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow, onupdate=utcnow)
class SubscriptionNotification(Base):
__tablename__ = "subscription_notifications"
__table_args__ = (
Index(
"ix_sub_notif_unique",
"remnawave_user_id",
"notification_type",
"expire_at_snapshot",
unique=True,
),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
remnawave_user_id: Mapped[int] = mapped_column(
ForeignKey("remnawave_users.id", ondelete="CASCADE"),
nullable=False,
index=True,
)
telegram_id: Mapped[int] = mapped_column(BigInteger, nullable=False, index=True)
notification_type: Mapped[str] = mapped_column(String(32), nullable=False)
expire_at_snapshot: Mapped[datetime] = mapped_column(DateTime, nullable=False)
sent_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow)
class PaymentOrder(Base):
__tablename__ = "payment_orders"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
order_uuid: Mapped[str] = mapped_column(String(36), nullable=False, unique=True, index=True)
telegram_user_id: Mapped[int] = mapped_column(
ForeignKey("telegram_users.id", ondelete="CASCADE"),
nullable=False,
index=True,
)
telegram_id: Mapped[int] = mapped_column(BigInteger, nullable=False, index=True)
plan_code: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
plan_title: Mapped[str] = mapped_column(String(255), nullable=False)
plan_duration_days: Mapped[int] = mapped_column(Integer, nullable=False)
traffic_limit_bytes: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
traffic_limit_strategy: Mapped[str] = mapped_column(String(32), nullable=False, default="NO_RESET")
amount_stars: Mapped[int] = mapped_column(Integer, nullable=False)
currency: Mapped[str] = mapped_column(String(8), nullable=False, default="XTR")
status: Mapped[str] = mapped_column(String(32), nullable=False, default="PENDING", index=True)
invoice_payload: Mapped[str] = mapped_column(String(128), nullable=False, unique=True, index=True)
provision_username: Mapped[str] = mapped_column(String(36), nullable=False, index=True)
remnawave_user_uuid: Mapped[str | None] = mapped_column(String(36), nullable=True, index=True)
subscription_url: Mapped[str | None] = mapped_column(Text, nullable=True)
telegram_payment_charge_id: Mapped[str | None] = mapped_column(String(255), nullable=True, unique=True)
provider_payment_charge_id: Mapped[str | None] = mapped_column(String(255), nullable=True)
error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
paid_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
fulfilled_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow)
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=utcnow, onupdate=utcnow)

152
app/db/session.py Normal file
View File

@@ -0,0 +1,152 @@
import logging
from sqlalchemy import text
from sqlalchemy.ext.asyncio import (
AsyncConnection,
AsyncEngine,
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from app.db.base import Base
from app.db import models as _models # noqa: F401
logger = logging.getLogger(__name__)
PAYMENT_ORDERS_TABLE_NAME = "payment_orders"
PAYMENT_ORDERS_PROVISION_USERNAME_COLUMN = "provision_username"
PAYMENT_ORDERS_PROVISION_USERNAME_INDEX = "ix_payment_orders_provision_username"
def create_engine_and_session_factory(
database_url: str,
*,
echo: bool = False,
) -> tuple[AsyncEngine, async_sessionmaker[AsyncSession]]:
engine = create_async_engine(
database_url,
echo=echo,
pool_pre_ping=True,
pool_recycle=3600,
)
session_factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
return engine, session_factory
def _quote_mysql_identifier(identifier: str) -> str:
return f"`{identifier.replace('`', '``')}`"
async def _get_mysql_single_column_indexes(
connection: AsyncConnection,
*,
table_name: str,
column_name: str,
non_unique: int,
) -> list[str]:
result = await connection.execute(
text(
"""
SELECT index_name
FROM information_schema.statistics
WHERE table_schema = DATABASE()
AND table_name = :table_name
GROUP BY index_name, non_unique
HAVING non_unique = :non_unique
AND COUNT(*) = 1
AND MAX(CASE WHEN column_name = :column_name THEN 1 ELSE 0 END) = 1
"""
),
{
"table_name": table_name,
"column_name": column_name,
"non_unique": non_unique,
},
)
return [row[0] for row in result]
async def _normalize_payment_order_provision_username_index(
connection: AsyncConnection,
) -> None:
if connection.dialect.name != "mysql":
return
unique_index_names = await _get_mysql_single_column_indexes(
connection,
table_name=PAYMENT_ORDERS_TABLE_NAME,
column_name=PAYMENT_ORDERS_PROVISION_USERNAME_COLUMN,
non_unique=0,
)
quoted_table_name = _quote_mysql_identifier(PAYMENT_ORDERS_TABLE_NAME)
for index_name in unique_index_names:
logger.info(
"Dropping stale UNIQUE index %s on %s.%s",
index_name,
PAYMENT_ORDERS_TABLE_NAME,
PAYMENT_ORDERS_PROVISION_USERNAME_COLUMN,
)
await connection.execute(
text(
"DROP INDEX "
f"{_quote_mysql_identifier(index_name)} "
f"ON {quoted_table_name}"
)
)
non_unique_index_names = await _get_mysql_single_column_indexes(
connection,
table_name=PAYMENT_ORDERS_TABLE_NAME,
column_name=PAYMENT_ORDERS_PROVISION_USERNAME_COLUMN,
non_unique=1,
)
if non_unique_index_names:
return
logger.info(
"Creating non-unique index %s on %s.%s",
PAYMENT_ORDERS_PROVISION_USERNAME_INDEX,
PAYMENT_ORDERS_TABLE_NAME,
PAYMENT_ORDERS_PROVISION_USERNAME_COLUMN,
)
await connection.execute(
text(
"CREATE INDEX "
f"{_quote_mysql_identifier(PAYMENT_ORDERS_PROVISION_USERNAME_INDEX)} "
f"ON {quoted_table_name} "
f"({_quote_mysql_identifier(PAYMENT_ORDERS_PROVISION_USERNAME_COLUMN)})"
)
)
async def ensure_database_exists(
server_url: str,
database_name: str,
*,
echo: bool = False,
) -> None:
engine = create_async_engine(
server_url,
echo=echo,
pool_pre_ping=True,
pool_recycle=3600,
)
try:
async with engine.begin() as connection:
await connection.execute(
text(
"CREATE DATABASE IF NOT EXISTS "
f"{_quote_mysql_identifier(database_name)} "
"CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
)
)
finally:
await engine.dispose()
async def init_db(engine: AsyncEngine) -> None:
async with engine.begin() as connection:
await connection.run_sync(Base.metadata.create_all)
await _normalize_payment_order_provision_username_index(connection)