brewman/brewman/brewman/models/journal.py

76 lines
2.5 KiB
Python

import uuid
from decimal import Decimal
from typing import TYPE_CHECKING, Optional
from sqlalchemy import Column, ForeignKey, Integer, Numeric
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import Mapped, relationship
from .meta import Base
if TYPE_CHECKING:
# if the target of the relationship is in another module
# that cannot normally be imported at runtime
from .account import AccountBase
from .cost_centre import CostCentre
from .employee_benefit import EmployeeBenefit
from .incentive import Incentive
from .voucher import Voucher
class Journal(Base):
__tablename__ = "journals"
id: uuid.UUID = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
debit: int = Column("debit", Integer, nullable=False)
amount: Decimal = Column("amount", Numeric(precision=15, scale=2), nullable=False)
voucher_id: uuid.UUID = Column(
"voucher_id",
UUID(as_uuid=True),
ForeignKey("vouchers.id"),
nullable=False,
index=True,
)
account_id: uuid.UUID = Column("account_id", UUID(as_uuid=True), ForeignKey("accounts.id"), nullable=False)
cost_centre_id: uuid.UUID = Column(
"cost_centre_id",
UUID(as_uuid=True),
ForeignKey("cost_centres.id"),
nullable=False,
)
voucher: Mapped["Voucher"] = relationship("Voucher", back_populates="journals")
account: Mapped["AccountBase"] = relationship("AccountBase", back_populates="journals")
cost_centre: Mapped["CostCentre"] = relationship("CostCentre", back_populates="journals")
employee_benefit: Mapped["EmployeeBenefit"] = relationship("EmployeeBenefit", back_populates="journal")
incentive: Mapped["Incentive"] = relationship("Incentive", back_populates="journal")
@hybrid_property
def _signed_amount(self) -> Decimal:
return self.debit * self.amount
@_signed_amount.expression
def signed_amount(cls) -> Decimal:
return cls.debit * cls.amount
def __init__(
self,
debit: int,
amount: Decimal,
account_id: uuid.UUID,
cost_centre_id: uuid.UUID,
voucher_id: Optional[uuid.UUID] = None,
id_: Optional[uuid.UUID] = None,
) -> None:
if id_ is not None:
self.id = id_
self.debit = debit
self.amount = amount
if voucher_id is not None:
self.voucher_id = voucher_id
self.account_id = account_id
self.cost_centre_id = cost_centre_id