runloopable / platform /modules /finance_spine.py
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
8133df9 verified
Raw History Blame Contribute Delete
12.1 kB
"""Canonical Finance fact, proof, freshness, lineage, and drill plane.
Applications name facts from this module; they never copy numbers into an application store.
Interactive values come only from the tenant mirror through ``harness.semantic``. Independent
reconciliation reads live Odoo only when the caller explicitly requests it.
"""
from copy import deepcopy
_COMMON = {
"source": {"observation": "tenant_mirror", "proof": "odoo_read_only"},
"drillThrough": {"kind": "source_records"},
}
FINANCE_FACTS = {
"ar_outstanding": {
"label": "AR outstanding", "topic": "receivables", "metric": "ar_outstanding",
"format": "usd", "scope": "hq_consolidated", "sourceEntities": ["account_move"],
"reconciliationMethod": "ar_outstanding",
},
"ap_outstanding": {
"label": "AP outstanding", "topic": "odoo_bills", "metric": "ap_outstanding",
"format": "usd", "scope": "hq_consolidated", "sourceEntities": ["account_move"],
"reconciliationMethod": "ap_outstanding",
},
"invoiced_sales": {
"label": "Invoiced sales", "topic": "customer_invoices", "metric": "invoiced_sales",
"format": "usd", "scope": "hq_consolidated", "sourceEntities": ["account_move"],
"reconciliationMethod": "invoiced_sales",
},
"revenue": {
"label": "Wholesale revenue", "topic": "sales_lines", "metric": "revenue",
"format": "usd", "scope": "business_unit", "sourceEntities": ["sale_order_line", "sale_order"],
"reconciliationMethod": "order_level_revenue",
},
"opex": {
"label": "Operating expense", "topic": "gl_lines", "metric": "opex",
"format": "usd", "scope": "hq_consolidated", "sourceEntities": ["account_move_line"],
"reconciliationMethod": "gl_opex",
},
"commission_accrued": {
"label": "Commission accrued", "topic": "commission_lines", "metric": "commission_accrued",
"format": "usd", "scope": "business_unit", "sourceEntities": ["account_invoice_line_agent", "account_move_line", "sale_order"],
"reconciliationMethod": "commission_accrued",
},
"stock_in": {
"label": "Stock moved in", "topic": "stock_moves", "metric": "stock_in",
"format": "int", "scope": "all_channel_inventory", "sourceEntities": ["stock_move", "stock_location"],
"reconciliationMethod": "stock_movement_in", "scalarAvailable": False, "drillMeasures": [],
"requiredGrain": "product_code",
},
"stock_out": {
"label": "Stock moved out", "topic": "stock_moves", "metric": "stock_out",
"format": "int", "scope": "all_channel_inventory", "sourceEntities": ["stock_move", "stock_location"],
"reconciliationMethod": "stock_movement_out", "scalarAvailable": False, "drillMeasures": [],
"requiredGrain": "product_code",
},
"stock_net": {
"label": "Stock moved net", "topic": "stock_moves", "metric": "stock_net",
"format": "int", "scope": "all_channel_inventory", "sourceEntities": ["stock_move", "stock_location"],
"reconciliationMethod": "stock_movement_net", "drillMeasures": [],
"scalarAvailable": False, "requiredGrain": "product_code",
},
}
def fact_spec(key):
"""Return the governed descriptor for a Finance fact."""
if key not in FINANCE_FACTS:
raise KeyError(key)
item = {"key": key, **_COMMON, **FINANCE_FACTS[key]}
item["lineage"] = {
"topic": item["topic"], "metric": item["metric"],
"sourceEntities": list(item["sourceEntities"]),
}
item["drillThrough"] = {
**item["drillThrough"],
"href": f"/api/v1/finance/facts/{key}/records",
}
item["freshness"] = {"state": "not_observed", "sources": list(item["sourceEntities"])}
item["reconciliation"] = {
"state": "not_checked", "method": item["reconciliationMethod"],
"href": f"/api/v1/finance/facts/{key}/reconciliation",
}
return deepcopy(item)
def fact_specs(keys=None):
return [fact_spec(key) for key in (FINANCE_FACTS if keys is None else keys)]
def effective_team_id(spec, requested_team_id):
"""Apply the declared scope. Company and stock facts cannot wear a BU label."""
if requested_team_id is not None:
import core.odoo as O
if requested_team_id not in O.active_team_ids():
raise ValueError("Finance business-unit scope must be one of the tenant's sales teams")
if spec["scope"] == "business_unit":
return requested_team_id
if spec["scope"] == "hq_consolidated" and requested_team_id is not None:
raise PermissionError("A business-unit-scoped account cannot read consolidated Finance facts")
# Inventory is one physical, all-channel warehouse basis. It is intentionally not allocated
# to Fisch or Royal; a pinned user receives the same company stock rows with no BU label.
return None
def freshness(cursor, entities):
"""Describe mirror readiness from its own sync ledger; never synthesize an as-of time."""
try:
rows = cursor.execute(
"SELECT entity, phase, cursor_wd, updated_at FROM _sync_state WHERE entity IN ("
+ ",".join("?" for _ in entities) + ")", list(entities)).fetchall()
except Exception:
return {"state": "missing", "asOf": None, "sources": []}
found = {str(row[0]): row for row in rows}
sources = []
for entity in entities:
row = found.get(entity)
sources.append({"entity": entity, "state": str(row[1]) if row else "missing",
"asOf": (row[2] or row[3]) if row else None})
phases = {src["state"] for src in sources}
if sources and phases == {"live"}:
state = "ready"
elif "running" in phases or "pending" in phases:
state = "warming"
else:
state = "missing"
stamps = [src["asOf"] for src in sources if src["asOf"]]
return {"state": state, "asOf": min(stamps) if stamps else None, "sources": sources}
def observe(key, cursor, *, date_from=None, date_to=None, team_id=None):
"""Read one governed fact from the canonical mirror and attach its proof metadata."""
from harness import semantic
spec = fact_spec(key)
sync = freshness(cursor, spec["sourceEntities"])
spec["freshness"] = sync
if sync["state"] != "ready":
return {**spec, "state": sync["state"], "value": None}
if spec.get("scalarAvailable") is False:
return {**spec, "state": "requires_sku", "value": None,
"message": "Movement quantities use mixed units and are available at SKU grain."}
try:
scoped_team_id = effective_team_id(spec, team_id)
except PermissionError:
return {**spec, "state": "restricted", "value": None,
"message": "This fact is available only to consolidated Finance viewers."}
except ValueError as exc:
return {**spec, "state": "unavailable", "value": None, "message": str(exc)}
try:
result = semantic.store_query(
spec["topic"], [spec["metric"]], date_from=date_from, date_to=date_to,
team_id=scoped_team_id, limit=1)
rows = result.get("rows") or []
if not rows or rows[0].get(spec["metric"]) is None:
return {**spec, "state": "missing", "value": None}
return {**spec, "state": "ready", "value": rows[0][spec["metric"]]}
except Exception as exc:
return {**spec, "state": "unavailable", "value": None,
"message": _safe_message(exc)}
def source_records(key, *, date_from=None, date_to=None, team_id=None, limit=100, offset=0):
"""Return source-grain records plus whole-scope counts/totals from the same governed topic."""
from harness import semantic
spec = fact_spec(key)
measures = (spec.get("drillMeasures") if "drillMeasures" in spec
else [spec["metric"]])
payload = semantic.store_rows(
spec["topic"], date_from=date_from, date_to=date_to,
team_id=effective_team_id(spec, team_id), limit=limit, offset=offset,
aggregates=measures)
return {"fact": spec, **payload}
def reconcile(key, *, date_from=None, date_to=None, team_id=None):
"""Run the declared independent, read-only Odoo proof on explicit request."""
from harness import semantic
spec = fact_spec(key)
try:
result = semantic.validate_metric(
spec["metric"], date_from=date_from, date_to=date_to,
team_id=effective_team_id(spec, team_id))
return {"state": "passed" if result.get("ok") else "failed", **result}
except Exception as exc:
return {"state": "unavailable", "message": _safe_message(exc)}
def _safe_message(exc):
text = str(exc).lower()
if "sync" in text or "store" in text or "table" in text:
return "The tenant mirror is still warming."
return "The fact is temporarily unavailable."
def _store_value(topic, metric, date_from, date_to, team_id=None):
from harness import semantic
rows = semantic.store_query(topic, [metric], date_from=date_from, date_to=date_to,
team_id=team_id, limit=1).get("rows") or []
return (rows[0].get(metric) if rows else None) or 0
def _date_domain(field, date_from, date_to):
dom = []
if date_from:
dom.append((field, ">=", date_from))
if date_to:
dom.append((field, "<=", date_to))
return dom
def _v_commission_accrued(date_from, date_to, team_id):
import core.odoo as O
ours = _store_value("commission_lines", "commission_accrued", date_from, date_to, team_id)
dom = _date_domain("invoice_date", date_from, date_to)
if team_id:
dom.append(("object_id.sale_line_ids.order_id.team_id", "=", team_id))
return ours, O.sum_field("account.invoice.line.agent", dom, "amount")
def _v_invoiced_sales(date_from, date_to, team_id):
import core.odoo as O
ours = _store_value("customer_invoices", "invoiced_sales", date_from, date_to)
dom = [("state", "=", "posted"), ("move_type", "=", "out_invoice")]
dom += _date_domain("invoice_date", date_from, date_to)
return ours, O.sum_field("account.move", dom, "amount_untaxed_signed")
def _stock_live(date_from, date_to, inbound):
import core.odoo as O
dom = [("state", "=", "done")]
dom += _date_domain("date", date_from, date_to)
if inbound:
dom += [("location_dest_id.usage", "=", "internal"),
("location_id.usage", "!=", "internal")]
else:
dom += [("location_id.usage", "=", "internal"),
("location_dest_id.usage", "!=", "internal")]
return O.sum_field("stock.move", dom, "quantity_done")
def _v_stock_in(date_from, date_to, team_id):
return _store_value("stock_moves", "stock_in", date_from, date_to), _stock_live(date_from, date_to, True)
def _v_stock_out(date_from, date_to, team_id):
return _store_value("stock_moves", "stock_out", date_from, date_to), _stock_live(date_from, date_to, False)
def _v_stock_net(date_from, date_to, team_id):
return (_store_value("stock_moves", "stock_net", date_from, date_to),
_stock_live(date_from, date_to, True) - _stock_live(date_from, date_to, False))
def _v_ap_outstanding(date_from, date_to, team_id):
import core.odoo as O
ours = _store_value("odoo_bills", "ap_outstanding", date_from, date_to)
dom = [("state", "=", "posted"), ("move_type", "in", ["in_invoice", "in_refund"])]
dom += _date_domain("invoice_date", date_from, date_to)
return ours, -O.sum_field("account.move", dom, "amount_residual_signed")
FINANCE_VALIDATORS = {
"commission_accrued": _v_commission_accrued,
"invoiced_sales": _v_invoiced_sales,
"stock_movement_in": _v_stock_in,
"stock_movement_out": _v_stock_out,
"stock_movement_net": _v_stock_net,
"ap_outstanding": _v_ap_outstanding,
}
def register_semantic_validators():
"""Compatibility adapter until the out-of-fence semantic registry imports this module."""
from harness import semantic
semantic._VALIDATORS.update(FINANCE_VALIDATORS)
return tuple(FINANCE_VALIDATORS)