accounts.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from __future__ import annotations
  2. from sqlalchemy import select, func
  3. from flexmeasures.data import db
  4. from flexmeasures.data.models.audit_log import AuditLog
  5. from flexmeasures.data.models.user import Account, AccountRole
  6. from flexmeasures.data.models.generic_assets import GenericAsset
  7. def get_accounts(
  8. role_name: str | None = None,
  9. ) -> list[Account]:
  10. """Return a list of Account objects.
  11. The role_name parameter allows to filter by role.
  12. """
  13. if role_name is not None:
  14. role = db.session.execute(
  15. select(AccountRole).filter_by(name=role_name)
  16. ).scalar_one_or_none()
  17. if role:
  18. accounts = db.session.scalars(
  19. select(Account).filter(Account.account_roles.contains(role))
  20. ).all()
  21. else:
  22. return []
  23. else:
  24. accounts = db.session.scalars(select(Account)).all()
  25. return accounts
  26. def get_number_of_assets_in_account(account_id: int) -> int:
  27. """Get the number of assets in an account."""
  28. number_of_assets_in_account = db.session.scalar(
  29. select(func.count()).select_from(GenericAsset).filter_by(account_id=account_id)
  30. )
  31. return number_of_assets_in_account
  32. def get_account_roles(account_id: int) -> list[AccountRole]:
  33. account = db.session.get(Account, account_id)
  34. if account is None:
  35. return []
  36. return account.account_roles
  37. def get_audit_log_records(account: Account) -> list[AuditLog]:
  38. """
  39. Get history of account actions
  40. """
  41. audit_log_records = (
  42. db.session.query(AuditLog).filter_by(affected_account_id=account.id).all()
  43. )
  44. return audit_log_records