41 lines
1.5 KiB
Python
41 lines
1.5 KiB
Python
import secrets
|
|
import string
|
|
from typing import TYPE_CHECKING
|
|
|
|
from sqlalchemy import BIGINT, INTEGER, REAL, TEXT, VARCHAR, ForeignKey
|
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
|
|
from db.base import Base
|
|
|
|
if TYPE_CHECKING:
|
|
from db.models import Order, Session, Subscription
|
|
|
|
|
|
def generate_ref_code(length: int = 8):
|
|
alphabet = string.ascii_letters + string.digits
|
|
return "".join(secrets.choice(alphabet) for _ in range(length))
|
|
|
|
|
|
class User(Base):
|
|
__tablename__ = "users"
|
|
|
|
id: Mapped[int] = mapped_column(
|
|
INTEGER, unique=True, autoincrement=True, nullable=False, primary_key=True
|
|
)
|
|
username: Mapped[str] = mapped_column(TEXT, unique=True, nullable=True)
|
|
hashed_password: Mapped[str] = mapped_column(VARCHAR(255), nullable=True)
|
|
telegram_id: Mapped[int] = mapped_column(BIGINT, unique=True, nullable=True)
|
|
referal_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=True)
|
|
referal_code: Mapped[str] = mapped_column(
|
|
TEXT, nullable=False, unique=True, default=generate_ref_code
|
|
)
|
|
|
|
balance: Mapped[float] = mapped_column(REAL, nullable=False, default=0)
|
|
|
|
orders: Mapped[list["Order"]] = relationship("Order", back_populates="user", lazy="selectin")
|
|
subscription: Mapped["Subscription"] = relationship(
|
|
"Subscription", back_populates="user", lazy="selectin"
|
|
)
|
|
sessions: Mapped[list["Session"]] = relationship(back_populates="user", lazy="selectin")
|
|
referal: Mapped["User | None"] = relationship("User", remote_side=[id], lazy="selectin")
|