diff --git a/brewman/brewman/models/account.py b/brewman/brewman/models/account.py index c16698c9..42bf6335 100644 --- a/brewman/brewman/models/account.py +++ b/brewman/brewman/models/account.py @@ -1,3 +1,5 @@ +import uuid + from typing import TYPE_CHECKING from sqlalchemy.orm import Mapped, relationship @@ -18,6 +20,30 @@ class Account(AccountBase): "Product", primaryjoin="Account.id==Product.account_id", back_populates="account" ) + def __init__( + self, + name: str, + type_id: int, + is_starred: bool, + is_active: bool, + is_reconcilable: bool, + cost_centre_id: uuid.UUID, + code: int | None = None, + id_: uuid.UUID | None = None, + is_fixture: bool = False, + ) -> None: + if code is not None: + self.code = code + self.name = name + self.type_id = type_id + self.is_starred = is_starred + self.is_active = is_active + self.is_reconcilable = is_reconcilable + self.cost_centre_id = cost_centre_id + if id_ is not None: + self.id = id_ + self.is_fixture = is_fixture + def can_delete(self, advanced_delete: bool) -> tuple[bool, str]: if len(self.products) > 0: return False, "Account has products" diff --git a/brewman/brewman/models/account_base.py b/brewman/brewman/models/account_base.py index 19fa31ce..2baf0ef6 100644 --- a/brewman/brewman/models/account_base.py +++ b/brewman/brewman/models/account_base.py @@ -70,13 +70,6 @@ class AccountBase: self.id = id_ self.is_fixture = is_fixture - def create(self, db: Session) -> "AccountBase": - self.code = db.execute( - select(func.coalesce(func.max(AccountBase.code), 0) + 1).where(AccountBase.type_id == self.type_id) - ).scalar_one() - db.add(self) - return self - def can_delete(self, advanced_delete: bool) -> tuple[bool, str]: if self.is_fixture: return False, f"{self.name} is a fixture and cannot be edited or deleted." diff --git a/brewman/brewman/routers/account.py b/brewman/brewman/routers/account.py index 0ed1c2bb..eb4076bd 100644 --- a/brewman/brewman/routers/account.py +++ b/brewman/brewman/routers/account.py @@ -35,15 +35,14 @@ def save( with SessionFuture() as db: item = Account( name=data.name, + code=Account.get_code(data.type_, db), type_id=data.type_, is_starred=data.is_starred, is_active=data.is_active, is_reconcilable=data.is_reconcilable, cost_centre_id=data.cost_centre.id_, ) - item.code = db.execute( - select(func.coalesce(func.max(Account.code), 0) + 1).where(Account.type_id == item.type_id) - ).scalar_one() + db.add(item) db.commit() except SQLAlchemyError as e: