M8-T12: scope energy contracts

This commit is contained in:
2026-08-23 21:22:06 +02:00
parent a9458394f2
commit b812d5ac46
13 changed files with 533 additions and 47 deletions
+16 -6
View File
@@ -46,7 +46,9 @@ from app.schemas.energy_contract import (
from app.services.auth import AuthenticatedSession
from app.services import timezone as _tz_mod
from app.services.contracts import (
CONTRACT_KIND_SCOPES,
ContractVersionError,
ContractScopeError,
activate_contract,
add_version,
create_contract,
@@ -98,6 +100,7 @@ def _contract_detail(db: Session, contract) -> ContractDetailResponse:
id=contract.id,
name=contract.name,
kind=contract.kind,
scope=contract.scope,
active=contract.active,
currency=contract.currency,
created_at=contract.created_at,
@@ -163,16 +166,22 @@ def get_profiles(
@router.get("/contracts", response_model=ContractListResponse)
def list_energy_contracts(
scope: str = "electricity",
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> ContractListResponse:
"""List all energy contracts with their active status.
Returns a flat list (no embedded version history); use
Scope defaults to ``electricity`` for old clients. Returns a flat list (no embedded version history); use
GET /api/energy/contracts/{id} to fetch the full version history for a
specific contract.
"""
contracts = list_contracts(db)
if scope not in set(CONTRACT_KIND_SCOPES.values()):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Unknown energy contract scope: {scope!r}",
)
contracts = list_contracts(db, scope=scope)
items = [ContractResponse.model_validate(c) for c in contracts]
return ContractListResponse(items=items, total=len(items))
@@ -208,10 +217,11 @@ def create_energy_contract(
name=body.name,
kind=body.kind,
currency=body.currency,
scope=body.scope,
values=body.values,
effective_from=effective_from,
)
except (ProfileNotFoundError, ProfileValidationError) as exc:
except (ProfileNotFoundError, ProfileValidationError, ContractScopeError) as exc:
_raise_422_for_profile_error(exc)
db.commit()
@@ -256,11 +266,11 @@ def patch_energy_contract(
"""Partially update a contract: rename or change activation status.
- ``name``: updates the human-readable label.
- ``active=true``: activates this contract (all others are deactivated).
- ``active=true``: activates this contract (same-scope contracts are deactivated).
- ``active=false``: deactivates this contract (no effect on others).
At most one contract may be active at any time; the service layer enforces
mutual exclusion.
At most one contract may be active per scope; the service layer enforces
scope-local mutual exclusion.
"""
contract = _get_contract_or_404(db, contract_id)