2022-05-08 17:20:04 +01:00
|
|
|
import enum
|
2024-12-06 16:08:48 +00:00
|
|
|
from datetime import datetime, timezone
|
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
from sqlalchemy.orm import Mapped, mapped_column
|
2022-05-08 17:20:04 +01:00
|
|
|
|
2022-06-17 14:02:10 +01:00
|
|
|
from app.brm.brn import BRN
|
2022-05-08 17:20:04 +01:00
|
|
|
from app.extensions import db
|
|
|
|
from app.models import AbstractConfiguration, AbstractResource
|
2024-12-06 18:02:59 +00:00
|
|
|
from app.models.types import AwareDateTime
|
2022-05-08 17:20:04 +01:00
|
|
|
|
|
|
|
|
|
|
|
class AutomationState(enum.Enum):
|
|
|
|
IDLE = 0
|
|
|
|
RUNNING = 1
|
|
|
|
ERROR = 3
|
|
|
|
|
|
|
|
|
|
|
|
class Automation(AbstractConfiguration):
|
2024-12-06 16:08:48 +00:00
|
|
|
short_name: Mapped[str]
|
|
|
|
state: Mapped[AutomationState] = mapped_column(default=AutomationState.IDLE)
|
|
|
|
enabled: Mapped[bool]
|
2024-12-06 18:02:59 +00:00
|
|
|
last_run: Mapped[Optional[datetime]] = mapped_column(AwareDateTime())
|
|
|
|
next_run: Mapped[Optional[datetime]] = mapped_column(AwareDateTime())
|
2024-12-06 16:08:48 +00:00
|
|
|
next_is_full: Mapped[bool]
|
2022-05-08 17:20:04 +01:00
|
|
|
|
|
|
|
logs = db.relationship("AutomationLogs", back_populates="automation")
|
|
|
|
|
2022-06-17 14:02:10 +01:00
|
|
|
@property
|
|
|
|
def brn(self) -> BRN:
|
|
|
|
return BRN(
|
|
|
|
group_id=0,
|
|
|
|
product="core",
|
|
|
|
provider="",
|
|
|
|
resource_type="automation",
|
2024-12-06 18:15:47 +00:00
|
|
|
resource_id=self.short_name,
|
2022-06-17 14:02:10 +01:00
|
|
|
)
|
|
|
|
|
2022-05-16 11:44:03 +01:00
|
|
|
def kick(self) -> None:
|
2022-05-08 17:20:04 +01:00
|
|
|
self.enabled = True
|
2024-12-06 16:08:48 +00:00
|
|
|
self.next_run = datetime.now(tz=timezone.utc)
|
|
|
|
self.updated = datetime.now(tz=timezone.utc)
|
2022-05-08 17:20:04 +01:00
|
|
|
|
|
|
|
|
|
|
|
class AutomationLogs(AbstractResource):
|
2024-12-06 16:08:48 +00:00
|
|
|
automation_id: Mapped[int] = mapped_column(db.ForeignKey("automation.id"))
|
|
|
|
logs: Mapped[str]
|
2022-05-08 17:20:04 +01:00
|
|
|
|
|
|
|
automation = db.relationship("Automation", back_populates="logs")
|
2022-06-17 14:02:10 +01:00
|
|
|
|
|
|
|
@property
|
|
|
|
def brn(self) -> BRN:
|
|
|
|
return BRN(
|
|
|
|
group_id=0,
|
|
|
|
product="core",
|
|
|
|
provider="",
|
|
|
|
resource_type="automationlog",
|
2024-12-06 18:15:47 +00:00
|
|
|
resource_id=str(self.id),
|
2022-06-17 14:02:10 +01:00
|
|
|
)
|