feat: Add Processing Opex functionality

- Introduced OpexValidationError for handling validation errors in processing opex calculations.
- Implemented ProjectProcessingOpexRepository and ScenarioProcessingOpexRepository for managing project and scenario-level processing opex snapshots.
- Enhanced UnitOfWork to include repositories for processing opex.
- Updated sidebar navigation and scenario detail templates to include links to the new Processing Opex Planner.
- Created a new template for the Processing Opex Planner with form handling for input components and parameters.
- Developed integration tests for processing opex calculations, covering HTML and JSON flows, including validation for currency mismatches and unsupported frequencies.
- Added unit tests for the calculation logic, ensuring correct handling of various scenarios and edge cases.
This commit is contained in:
2025-11-13 09:26:57 +01:00
parent 1240b08740
commit 1feae7ff85
16 changed files with 1931 additions and 11 deletions

View File

@@ -29,6 +29,10 @@ from .simulation_parameter import SimulationParameter
from .user import Role, User, UserRole, password_context
from .profitability_snapshot import ProjectProfitability, ScenarioProfitability
from .capex_snapshot import ProjectCapexSnapshot, ScenarioCapexSnapshot
from .processing_opex_snapshot import (
ProjectProcessingOpexSnapshot,
ScenarioProcessingOpexSnapshot,
)
__all__ = [
"FinancialCategory",
@@ -37,12 +41,14 @@ __all__ = [
"Project",
"ProjectProfitability",
"ProjectCapexSnapshot",
"ProjectProcessingOpexSnapshot",
"PricingSettings",
"PricingMetalSettings",
"PricingImpuritySettings",
"Scenario",
"ScenarioProfitability",
"ScenarioCapexSnapshot",
"ScenarioProcessingOpexSnapshot",
"ScenarioStatus",
"DistributionType",
"SimulationParameter",

View File

@@ -0,0 +1,109 @@
from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING
from sqlalchemy import JSON, Boolean, DateTime, ForeignKey, Integer, Numeric, String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.sql import func
from config.database import Base
if TYPE_CHECKING: # pragma: no cover
from .project import Project
from .scenario import Scenario
from .user import User
class ProjectProcessingOpexSnapshot(Base):
"""Snapshot of recurring processing opex metrics at the project level."""
__tablename__ = "project_processing_opex_snapshots"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
project_id: Mapped[int] = mapped_column(
ForeignKey("projects.id", ondelete="CASCADE"), nullable=False, index=True
)
created_by_id: Mapped[int | None] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True
)
calculation_source: Mapped[str | None] = mapped_column(String(64), nullable=True)
calculated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
currency_code: Mapped[str | None] = mapped_column(String(3), nullable=True)
overall_annual: Mapped[float | None] = mapped_column(Numeric(18, 2), nullable=True)
escalated_total: Mapped[float | None] = mapped_column(Numeric(18, 2), nullable=True)
annual_average: Mapped[float | None] = mapped_column(Numeric(18, 2), nullable=True)
evaluation_horizon_years: Mapped[int | None] = mapped_column(Integer, nullable=True)
escalation_pct: Mapped[float | None] = mapped_column(Numeric(12, 6), nullable=True)
apply_escalation: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
component_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
payload: Mapped[dict | None] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now()
)
project: Mapped[Project] = relationship(
"Project", back_populates="processing_opex_snapshots"
)
created_by: Mapped[User | None] = relationship("User")
def __repr__(self) -> str: # pragma: no cover
return (
"ProjectProcessingOpexSnapshot(id={id!r}, project_id={project_id!r}, overall_annual={overall_annual!r})".format(
id=self.id,
project_id=self.project_id,
overall_annual=self.overall_annual,
)
)
class ScenarioProcessingOpexSnapshot(Base):
"""Snapshot of processing opex metrics for an individual scenario."""
__tablename__ = "scenario_processing_opex_snapshots"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
scenario_id: Mapped[int] = mapped_column(
ForeignKey("scenarios.id", ondelete="CASCADE"), nullable=False, index=True
)
created_by_id: Mapped[int | None] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True
)
calculation_source: Mapped[str | None] = mapped_column(String(64), nullable=True)
calculated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
currency_code: Mapped[str | None] = mapped_column(String(3), nullable=True)
overall_annual: Mapped[float | None] = mapped_column(Numeric(18, 2), nullable=True)
escalated_total: Mapped[float | None] = mapped_column(Numeric(18, 2), nullable=True)
annual_average: Mapped[float | None] = mapped_column(Numeric(18, 2), nullable=True)
evaluation_horizon_years: Mapped[int | None] = mapped_column(Integer, nullable=True)
escalation_pct: Mapped[float | None] = mapped_column(Numeric(12, 6), nullable=True)
apply_escalation: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
component_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
payload: Mapped[dict | None] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now(), onupdate=func.now()
)
scenario: Mapped[Scenario] = relationship(
"Scenario", back_populates="processing_opex_snapshots"
)
created_by: Mapped[User | None] = relationship("User")
def __repr__(self) -> str: # pragma: no cover
return (
"ScenarioProcessingOpexSnapshot(id={id!r}, scenario_id={scenario_id!r}, overall_annual={overall_annual!r})".format(
id=self.id,
scenario_id=self.scenario_id,
overall_annual=self.overall_annual,
)
)

View File

@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, List
from .enums import MiningOperationType, sql_enum
from .profitability_snapshot import ProjectProfitability
from .capex_snapshot import ProjectCapexSnapshot
from .processing_opex_snapshot import ProjectProcessingOpexSnapshot
from sqlalchemy import DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
@@ -67,6 +68,13 @@ class Project(Base):
order_by=lambda: ProjectCapexSnapshot.calculated_at.desc(),
passive_deletes=True,
)
processing_opex_snapshots: Mapped[List["ProjectProcessingOpexSnapshot"]] = relationship(
"ProjectProcessingOpexSnapshot",
back_populates="project",
cascade="all, delete-orphan",
order_by=lambda: ProjectProcessingOpexSnapshot.calculated_at.desc(),
passive_deletes=True,
)
@property
def latest_profitability(self) -> "ProjectProfitability | None":
@@ -84,5 +92,13 @@ class Project(Base):
return None
return self.capex_snapshots[0]
@property
def latest_processing_opex(self) -> "ProjectProcessingOpexSnapshot | None":
"""Return the most recent processing opex snapshot, if any."""
if not self.processing_opex_snapshots:
return None
return self.processing_opex_snapshots[0]
def __repr__(self) -> str: # pragma: no cover - helpful for debugging
return f"Project(id={self.id!r}, name={self.name!r})"

View File

@@ -21,6 +21,7 @@ from services.currency import normalise_currency
from .enums import ResourceType, ScenarioStatus, sql_enum
from .profitability_snapshot import ScenarioProfitability
from .capex_snapshot import ScenarioCapexSnapshot
from .processing_opex_snapshot import ScenarioProcessingOpexSnapshot
if TYPE_CHECKING: # pragma: no cover
from .financial_input import FinancialInput
@@ -91,6 +92,13 @@ class Scenario(Base):
order_by=lambda: ScenarioCapexSnapshot.calculated_at.desc(),
passive_deletes=True,
)
processing_opex_snapshots: Mapped[List["ScenarioProcessingOpexSnapshot"]] = relationship(
"ScenarioProcessingOpexSnapshot",
back_populates="scenario",
cascade="all, delete-orphan",
order_by=lambda: ScenarioProcessingOpexSnapshot.calculated_at.desc(),
passive_deletes=True,
)
@validates("currency")
def _normalise_currency(self, key: str, value: str | None) -> str | None:
@@ -115,3 +123,11 @@ class Scenario(Base):
if not self.capex_snapshots:
return None
return self.capex_snapshots[0]
@property
def latest_processing_opex(self) -> "ScenarioProcessingOpexSnapshot | None":
"""Return the most recent processing opex snapshot for this scenario."""
if not self.processing_opex_snapshots:
return None
return self.processing_opex_snapshots[0]