Harden resource cost evidence contract

This commit is contained in:
tegwick 2026-08-11 10:25:03 +02:00
parent 080f756fff
commit 00343307fd
22 changed files with 1623 additions and 130 deletions

View file

@ -35,12 +35,14 @@ class ServiceCostLine:
def build_service_cost_report(
lines: Iterable[ServiceCostLine],
) -> dict:
by_service: dict[str, dict] = {}
totals_by_month: dict[str, float] = defaultdict(float)
by_attribution: dict[tuple[str, str], dict] = {}
by_service: dict[tuple[str, str, str], dict] = {}
totals_by_period_currency: dict[tuple[str, str], float] = defaultdict(float)
by_attribution: dict[tuple[str, str, str], dict] = {}
unattributed: dict[tuple[str, str], dict] = {}
for line in lines:
service_key = (line.service_id, line.environment, line.currency)
bucket = by_service.setdefault(
line.service_id,
service_key,
{
"service_id": line.service_id,
"environment": line.environment,
@ -52,8 +54,12 @@ def build_service_cost_report(
month_total = bucket["months"].get(line.period_month, 0.0) + line.amount
bucket["months"][line.period_month] = month_total
bucket["total"] += line.amount
totals_by_month[line.period_month] += line.amount
key = (line.cost_attribution_key or "unattributed", line.currency)
totals_by_period_currency[(line.period_month, line.currency)] += line.amount
key = (
line.cost_attribution_key or "unattributed",
line.environment,
line.currency,
)
attribution = by_attribution.setdefault(
key,
{
@ -61,6 +67,7 @@ def build_service_cost_report(
"client_id": line.client_id,
"application_id": line.application_id,
"app_instance_id": line.app_instance_id,
"environment": line.environment,
"currency": line.currency,
"months": {},
"total": 0.0,
@ -70,6 +77,21 @@ def build_service_cost_report(
attribution["months"].get(line.period_month, 0.0) + line.amount
)
attribution["total"] += line.amount
if line.cost_attribution_key is None:
residual_key = (line.environment, line.currency)
residual = unattributed.setdefault(
residual_key,
{
"environment": line.environment,
"currency": line.currency,
"months": {},
"total": 0.0,
},
)
residual["months"][line.period_month] = (
residual["months"].get(line.period_month, 0.0) + line.amount
)
residual["total"] += line.amount
services = sorted(by_service.values(), key=lambda item: item["total"], reverse=True)
return {
"source_hub": "fin-hub",
@ -79,5 +101,11 @@ def build_service_cost_report(
"attributions": sorted(
by_attribution.values(), key=lambda item: item["total"], reverse=True
),
"totals_by_month": dict(sorted(totals_by_month.items())),
"unattributed": sorted(
unattributed.values(), key=lambda item: (item["currency"], item["environment"])
),
"totals_by_period_currency": [
{"period_month": period, "currency": currency, "total": total}
for (period, currency), total in sorted(totals_by_period_currency.items())
],
}