50 lines
2.4 KiB
Python
50 lines
2.4 KiB
Python
from datetime import datetime, date
|
|
from decimal import Decimal
|
|
from sqlalchemy import String, Boolean, Numeric, ForeignKey, Date, DateTime, UniqueConstraint, func
|
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|
from app.database import Base
|
|
|
|
|
|
class Currency(Base):
|
|
__tablename__ = "currencies"
|
|
|
|
id: Mapped[int] = mapped_column(primary_key=True)
|
|
code: Mapped[str] = mapped_column(String(3), unique=True, nullable=False) # ISO 4217
|
|
name: Mapped[str] = mapped_column(String(100), nullable=False)
|
|
symbol: Mapped[str | None] = mapped_column(String(10))
|
|
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
|
|
exchange_rates_from: Mapped[list["ExchangeRate"]] = relationship(
|
|
"ExchangeRate", foreign_keys="ExchangeRate.currency_from_id", back_populates="currency_from"
|
|
)
|
|
exchange_rates_to: Mapped[list["ExchangeRate"]] = relationship(
|
|
"ExchangeRate", foreign_keys="ExchangeRate.currency_to_id", back_populates="currency_to"
|
|
)
|
|
accounts: Mapped[list] = relationship("Account", back_populates="currency")
|
|
operations: Mapped[list] = relationship("Operation", back_populates="currency")
|
|
budgets: Mapped[list] = relationship("Budget", back_populates="currency")
|
|
calendar_events: Mapped[list] = relationship("CalendarEvent", back_populates="currency")
|
|
|
|
|
|
class ExchangeRate(Base):
|
|
__tablename__ = "exchange_rates"
|
|
__table_args__ = (
|
|
UniqueConstraint("currency_from_id", "currency_to_id", "rate_date", name="uq_exchange_rate_day"),
|
|
)
|
|
|
|
id: Mapped[int] = mapped_column(primary_key=True)
|
|
currency_from_id: Mapped[int] = mapped_column(ForeignKey("currencies.id"), nullable=False)
|
|
currency_to_id: Mapped[int] = mapped_column(ForeignKey("currencies.id"), nullable=False)
|
|
rate: Mapped[Decimal] = mapped_column(Numeric(20, 6), nullable=False)
|
|
rate_date: Mapped[date] = mapped_column(Date, nullable=False)
|
|
source: Mapped[str | None] = mapped_column(String(100))
|
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
|
|
currency_from: Mapped["Currency"] = relationship(
|
|
"Currency", foreign_keys=[currency_from_id], back_populates="exchange_rates_from"
|
|
)
|
|
currency_to: Mapped["Currency"] = relationship(
|
|
"Currency", foreign_keys=[currency_to_id], back_populates="exchange_rates_to"
|
|
)
|