brewman/brewman/brewman/models/client.py

56 lines
1.8 KiB
Python

from __future__ import annotations
import random
import string
import uuid
from datetime import UTC, datetime
from sqlalchemy import Boolean, DateTime, Integer, Unicode, Uuid, desc
from sqlalchemy.orm import Mapped, Session, mapped_column, relationship
from ..db.base_class import reg
from .login_history import LoginHistory
@reg.mapped_as_dataclass(unsafe_hash=True)
class Client:
__tablename__ = "clients"
id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, insert_default=uuid.uuid4)
code: Mapped[int] = mapped_column(Integer, unique=True, nullable=False)
name: Mapped[str] = mapped_column(Unicode, unique=True, nullable=False)
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False)
otp: Mapped[int | None] = mapped_column(Integer, nullable=True)
creation_date: Mapped[datetime] = mapped_column(DateTime(), nullable=False)
login_history: Mapped[list[LoginHistory]] = relationship(
"LoginHistory", order_by=desc(LoginHistory.date), back_populates="client"
)
def __init__(
self,
code: int,
name: str,
enabled: bool,
otp: int | None,
creation_date: datetime | None = None,
id_: uuid.UUID | None = None,
) -> None:
self.code = code
self.name = name
self.enabled = enabled
self.otp = otp
self.creation_date = datetime.now(UTC).replace(tzinfo=None) if creation_date is None else creation_date
if id_ is not None:
self.id = id_
@classmethod
def create(cls, db: Session) -> Client:
client_code = random.randint(1000, 9999)
otp = random.randint(1000, 9999)
name = "".join(random.choice(string.ascii_uppercase + string.digits) for x in range(6))
client = Client(client_code, name, False, otp)
db.add(client)
return client