File size: 12,109 Bytes
cfa8541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2aa446
 
 
 
cfa8541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
"""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)