File size: 28,711 Bytes
dec006b
 
 
8133df9
dec006b
 
8133df9
 
dec006b
 
 
8133df9
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
dec006b
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
8729c1d
 
 
 
 
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
dec006b
 
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
dec006b
 
 
 
 
 
8133df9
dec006b
 
 
 
 
 
 
8133df9
 
 
dec006b
8133df9
 
dec006b
8133df9
 
dec006b
 
 
 
 
 
 
 
8133df9
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
8133df9
 
 
 
dec006b
8133df9
dec006b
 
 
 
 
8133df9
dec006b
 
 
8133df9
 
 
 
dec006b
 
 
 
 
 
 
 
8133df9
 
dec006b
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
dec006b
8133df9
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
 
dec006b
 
 
8133df9
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
 
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
"""Read standard metrics only after source access and independent reconciliation pass."""

import calendar
import contextlib
import copy
import datetime as dt
import hashlib
import json
import math
import re

from core import external_tools, live_limiter, perm_scope, periods
import deps


_KEYS = ("booked", "shipped", "invoiced", "collected", "margin")
_BASES = ("states", "channel_excludes", "date_basis", "cost_basis")
_DATABASE_KEYS = {
    "sale_order": "ORDERS_KEY",
    "sale_order_line": "ORDER_LINES_KEY",
    "stock_picking": "PICKINGS_KEY",
    "purchase_order_line": "PURCHASE_LINES_KEY",
    "purchase_order": "PURCHASE_ORDERS_KEY",
    "stock_move": "STOCK_MOVES_KEY",
    "account_move": "INVOICES_KEY",
    "account_move_line": "GL_LINES_KEY",
    "account_payment": "PAYMENTS_KEY",
}
WINDOW_SCHEMA = {
    "type": "object",
    "description": "Inclusive dates. calendar_month requires one complete calendar month. "
                   "date_range accepts any ordered pair of dates. No window is inferred.",
    "properties": {
        "name": {"type": "string", "enum": ["calendar_month", "date_range"]},
        **{key: {"type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"}
           for key in ("date_from", "date_to")},
    },
    "required": ["name", "date_from", "date_to"],
    "additionalProperties": False,
    "examples": [{"name": "calendar_month", "date_from": "2026-09-01", "date_to": "2026-09-30"}],
}
#: `get` only. The prior window and its rule come from `core.periods.yoy_window`, the one YoY rule.
COMPARE_SCHEMA = {"type": "string", "enum": ["yoy"],
                  "description": "Also return the same metric for the prior year window, validated the same way."}


class _Unavailable(Exception):
    """The requested metric has no proven value within this caller's access."""


class _WarningsUnavailable(Exception):
    """Required warnings have no independent proof within this metric scope."""


class _LimitRefused(_Unavailable):
    """The live limiter refused the cross-check and no validated value exists for this key."""

    def __init__(self, refusal):
        super().__init__(refusal.message)
        self.refusal = refusal


#: The store document holding the last validated value per metric, window and caller scope.
LAST_VALIDATED_KEY = "metric_last_validated"
#: The newest entries kept. An evicted key is refused until it validates again (rule 8).
LAST_VALIDATED_ENTRIES = 2000
_UNAVAILABLE = ("This metric has no validated value within your current access and window. "
                "Ask an Administrator to check source availability and metric access, or choose another window.")
_LIMITED = ("This window has no validated value yet, and the live call limit is reached. "
            "Retry after the live call limit resets.")
_WINDOW_INVALID = ("The dates do not form a valid named window. Use real ISO dates in order, "
                   "and a complete calendar month for calendar_month.")
_WARNINGS_LIMITED = "Warnings were not checked because the live call limit is reached."


def _limiter_store(session):
    """The tenant store the limiter and the cache share, or None for a runtime without one."""
    runtime = session.runtime
    if all(callable(getattr(runtime, name, None)) for name in ("get", "revision", "update")):
        return runtime
    return None


def _live_admission(session, caller):
    """Admit one live cross-check through the tenant limiter. Raises `LiveLimitRefused`."""
    store = _limiter_store(session)
    if store is None:
        return contextlib.nullcontext()
    return live_limiter.scoped_admit(store, caller=caller)


def _walls(session, databases):
    """A digest of the caller's row and field walls on each database the metric reads."""
    user, runtime = session.user, session.runtime
    read = user.get if callable(getattr(user, "get", None)) else (lambda _name: None)
    claims = getattr(session, "claims", None) or {}
    parts = {"bus": read("bus"), "external_databases": claims.get("external_databases"), "databases": {}}
    for database in sorted(set(databases)):
        access = perm_scope.min_access([user], database, st=runtime)
        parts["databases"][database] = {
            "grant": (read("perms") or {}).get(database),
            "readable": bool(access.get("readable")),
            "hidden": sorted(str(field) for field in (access.get("hidden") or ())),
            "filter": (perm_scope.assistant_entry(user, database) or {}).get("filter"),
            "pool": list(perm_scope.derive_pool_scope(user, database)),
            "wall": bool(perm_scope.wall_declared(user, database, st=runtime)),
        }
    return hashlib.sha256(json.dumps(parts, sort_keys=True, default=str).encode("utf-8")).hexdigest()


def _cache_key(session, key, window, walls, *, customer_id=None, team_id=None):
    """The last-validated key for one tenant, metric, window, narrowing and caller scope."""
    parts = {"tenant": session.tenant, "metric": key,
             "window": [window["date_from"], window["date_to"]],
             "customer_id": customer_id, "team_id": team_id, "walls": walls}
    return hashlib.sha256(json.dumps(parts, sort_keys=True, default=str).encode("utf-8")).hexdigest()


def _read_last_validated(session, cache):
    """The cached `{value, as_of}` for this key, or None."""
    store = _limiter_store(session)
    if store is None or not cache:
        return None
    try:
        document = store.get(LAST_VALIDATED_KEY, fresh=True) or {}
        entry = (document.get("entries") or {}).get(cache)
    except Exception:
        return None
    return copy.deepcopy(entry) if isinstance(entry, dict) else None


def _remember(session, cache, value, as_of):
    """Store a value that passed `validate_metric`. A failed write never fails the read."""
    store = _limiter_store(session)
    if store is None or not cache:
        return
    at = live_limiter._now()

    def _put(document):
        document = document if isinstance(document, dict) else {}
        entries = document.get("entries") if isinstance(document.get("entries"), dict) else {}
        entries[cache] = {"value": value, "as_of": as_of, "at": at}
        if len(entries) > LAST_VALIDATED_ENTRIES:
            newest = sorted(entries, key=lambda name: entries[name].get("at") or 0)[-LAST_VALIDATED_ENTRIES:]
            entries = {name: entries[name] for name in newest}
        document["entries"] = entries
        return document

    try:
        store.update(LAST_VALIDATED_KEY, _put)
    except Exception:
        return


def _last_validated(session, definition, cache, refusal):
    """Serve the newest validated value for this exact key with its as-of time, or refuse (rule 8)."""
    entry = _read_last_validated(session, cache)
    if not entry or not _number(entry.get("value")) or not isinstance(entry.get("as_of"), str):
        raise _LimitRefused(refusal)
    return {**definition, "value": entry["value"], "as_of": entry["as_of"],
            "served": "last_validated", "limit_refusal": refusal.as_dict(),
            "warnings": None, "warning_status": "unavailable",
            "warning_refusal": {"code": "metric_warnings_unavailable", "message": _WARNINGS_LIMITED}}


def _refused_row(key, exc):
    """A refused metric as a list row that names its cause."""
    if isinstance(exc, _LimitRefused):
        return {"key": key, **exc.refusal.as_dict()}
    return {"key": key, "code": "metric_unavailable", "cause": "unavailable", "message": _UNAVAILABLE}


def _arguments(ctx, args, action):
    """Validate direct calls with the same schema used by the group dispatcher."""
    if not isinstance(ctx, external_tools.ToolContext):
        raise deps.err(403, "tool_context_required", "Use the authenticated metrics tool.")
    external_tools.validate_arguments(args, GROUP["actions"][action]["schema"])
    return _window(args["window"])


def _window(window):
    """Validate an explicit date window without inferring any missing boundary."""
    try:
        start = dt.date.fromisoformat(window["date_from"])
        end = dt.date.fromisoformat(window["date_to"])
        if start > end:
            raise ValueError
        if window["name"] == "calendar_month" and (
                start.day != 1 or end.year != start.year or end.month != start.month
                or end.day != calendar.monthrange(start.year, start.month)[1]):
            raise ValueError
    except ValueError:
        raise deps.err(400, "metric_window_invalid", _WINDOW_INVALID) from None
    return copy.deepcopy(window)


def _compare_grain(window):
    """The window's YoY grain. One day is day and seven days is week (weekday aligned). A complete
    month, a complete quarter and 1 January to a later date in that year are month, quarter and ytd.
    Any other range has no grain. Those last four keep calendar dates."""
    start = dt.date.fromisoformat(window["date_from"])
    end = dt.date.fromisoformat(window["date_to"])
    days = (end - start).days + 1
    if days == 1:
        return "day"
    if days == 7:
        return "week"

    def month_end(year, month):
        return dt.date(year, month, calendar.monthrange(year, month)[1])

    if start.day == 1 and end == month_end(start.year, start.month):
        return "month"
    if start.day == 1 and start.month in (1, 4, 7, 10) and end == month_end(start.year, start.month + 2):
        return "quarter"
    if (start.month, start.day) == (1, 1) and end.year == start.year:
        return "ytd"
    return None


def _prior_window(window, grain):
    """The prior year window and its rule text, from the one server rule."""
    prior_from, prior_to, rule = periods.yoy_window(window["date_from"], window["date_to"], grain)
    if grain == "month":
        # A complete month compares the complete prior month: February 2025 reaches 2024-02-29.
        end = dt.date.fromisoformat(prior_to)
        prior_to = dt.date(end.year, end.month, calendar.monthrange(end.year, end.month)[1]).isoformat()
    return _window({**window, "date_from": prior_from, "date_to": prior_to}), rule


def _source(session):
    """Bind both reads to the authenticated tenant's runtime and source."""
    runtime = session.runtime
    if runtime.key != session.tenant:
        raise _Unavailable
    runtime.assert_datastore_matches()
    source = runtime.odoo_source()
    if source is None:
        raise _Unavailable
    return source


def _database(table):
    """Require a registered serving database for the metric's own fact table."""
    import odoo_relational
    import routes_odoo_tables

    attribute = _DATABASE_KEYS.get(table)
    database = getattr(odoo_relational, attribute, None) if attribute else None
    spec = routes_odoo_tables._sources().get(database) if database else None
    if not spec:
        raise _Unavailable
    identity = spec.get("id", "")
    alias = identity.split(".")[0] if "." in identity else None
    if ((spec.get("tables") or {}).get(alias) if alias else spec.get("table")) != table:
        raise _Unavailable
    if table == "stock_picking" and (spec.get("from_sql") or spec.get("tables")):
        raise _Unavailable
    # A grant to a filtered database cannot authorize raw rows outside its intrinsic scope.
    predicate = re.sub(r"\s+", "", spec.get("where") or "").lower()
    allowed = {"", "true"}
    if table in {"sale_order", "sale_order_line"}:
        allowed.add("so.statein('sale','done')andso.partner_idisnotnull")
    if table in {"purchase_order", "purchase_order_line"}:
        allowed.add("po.statein('purchase','done')")
    if table == "account_move":
        allowed.add("state='posted'andmove_typein('out_invoice','out_refund')andpartner_idisnotnull")
    if predicate not in allowed:
        raise _Unavailable
    return database, spec


def _admit(ctx, database, spec, source_fields):
    """Reuse the credential and canonical database readers before computing a scalar."""
    session = ctx.session
    ctx.describe_database(database)
    snapshot = deps.assistant_read_scope(session, database, mode="schema")
    if (snapshot.get("database") != database or not snapshot.get("permission_scope_applied")
            or snapshot.get("source_kind") != "mirror_user_table" or not snapshot.get("fields")):
        raise _Unavailable
    visible = {field["key"] for field in snapshot["fields"]}
    identity = spec["id"]
    alias = identity.split(".")[0] if "." in identity else None
    for item in source_fields:
        if isinstance(item, tuple):
            table, field = item
            aliases = [key for key, value in spec.get("tables", {}).items() if value == table]
        else:
            field, aliases = item, [alias]
        bindings = {key for key, value in spec.get("cols", {}).items()
                    if any(value[0].strip() == (prefix + "." if prefix else "") + field
                           for prefix in aliases)}
        if not bindings.intersection(visible):
            raise _Unavailable
    user, runtime = session.user, session.runtime
    access = perm_scope.min_access([user], database, st=runtime)
    # The independent source validator cannot reproduce arbitrary record or field walls.
    if (not access["readable"] or access["hidden"] or not perm_scope.may_metrics(user, database)
            or perm_scope.wall_declared(user, database, st=runtime)
            or (perm_scope.assistant_entry(user, database) or {}).get("filter")
            or any(value is not None for value in perm_scope.derive_pool_scope(user, database))):
        raise _Unavailable


def _definition(key, row):
    """Project only the standard contract instead of legacy topic or tenant prose."""
    for name in ("states", "channel_excludes"):
        value = row.get(name)
        if not isinstance(value, list) or not value or any(
                not isinstance(item, str) or not item for item in value):
            raise _Unavailable
    for name in ("date_basis", "cost_basis"):
        if not isinstance(row.get(name), str) or not row[name]:
            raise _Unavailable
    if not row.get("standard") or not row.get("validate"):
        raise _Unavailable
    return {"key": key, **{name: copy.deepcopy(row[name]) for name in _BASES}}


def _number(value):
    """Accept finite JSON numbers without treating booleans as values."""
    return type(value) in (int, float) and math.isfinite(value)


def _warning_observation(ctx, key, window, **scope):
    """Admit each warning source before reading its mirror or independent source."""
    from harness import semantic

    try:
        if key not in {"booked", "margin"}:
            raise _WarningsUnavailable
        _admit(ctx, *_database("sale_order_line"),
               ("purchase_price", "margin", "order_partner_id", "order_id",
                ("sale_order", "date_order"), ("sale_order", "state"), ("sale_order", "team_name")))
        _admit(ctx, *_database("stock_picking"),
               ("state", "scheduled_date", "picking_type_code", "sale_id", "partner_id"))
        _admit(ctx, *_database("purchase_order_line"),
               ("qty_received", "product_qty", "date_planned", "sale_line_id", "order_id",
                ("purchase_order", "state")))
        with _live_admission(ctx.session, "metrics.warnings"):
            observed = semantic.sales_warnings(key, window["date_from"], window["date_to"],
                                                runtime=ctx.session.runtime, user=ctx.session.user, **scope)
        validation = observed["validation"]
        counts = validation["ours"]
        if (validation.get("ok") is not True or counts != validation.get("independent")
                or set(counts) != {"zero_cost", "negative_margin", "overdue_delivery", "purchase_shortfall"}
                or any(type(count) is not int or count < 0 for count in counts.values())
                or observed["warnings"] != [{"code": code, "count": count}
                                            for code, count in counts.items() if count]):
            raise _WarningsUnavailable
        return {"warnings": observed["warnings"], "warning_status": "verified",
                "warning_validation": validation,
                "warnings_as_of": observed["as_of"]}
    except live_limiter.LiveLimitRefused as refusal:
        return {"warnings": None, "warning_status": "unavailable",
                "warning_refusal": {"code": "metric_warnings_unavailable", "message": _WARNINGS_LIMITED,
                                    "limit": refusal.as_dict()}}
    except Exception:
        return {"warnings": None, "warning_status": "unavailable",
                "warning_refusal": {"code": "metric_warnings_unavailable",
                                    "message": "Warnings have no independent proof within this metric scope."}}


def _observe(ctx, key, window, *, customer_id=None, team_id=None, warnings=True):
    """Return the mirror value checked against live source data for this exact window."""
    from harness import semantic

    row = semantic.metric_catalog().get(key)
    if not row:
        raise _Unavailable
    definition = _definition(key, row)
    session = ctx.session
    source = _source(session)
    with semantic.tenant_context(session.runtime), source._bound():
        table = semantic.topics()[row["topic"]]["store"]["table"]
        databases = [_database(table)]
        _admit(ctx, *databases[0], (row["field"],))
        if key == "shipped":
            databases.append(_database("sale_order_line"))
            _admit(ctx, *databases[-1], ("price_subtotal", "product_uom_qty"))
        kwargs = {"runtime": ctx.session.runtime, "user": ctx.session.user}
        scope = {name: value for name, value in (("customer_id", customer_id), ("team_id", team_id))
                 if value is not None}
        kwargs.update(scope)
        if customer_id is not None:
            customer_field = "order_partner_id" if key in {"booked", "margin"} else "partner_id"
            _admit(ctx, *_database(table), (customer_field,))
        dates = (window["date_from"], window["date_to"])
        cache = None
        if _limiter_store(session) is not None:
            cache = _cache_key(session, key, window, _walls(session, [name for name, _spec in databases]),
                               customer_id=customer_id, team_id=team_id)
        # The limiter admits before the live cross-check. A refusal serves the cached value or refuses.
        try:
            admission = _live_admission(session, "metrics." + key)
            with admission:
                value = semantic.metric(key, *dates, **kwargs)
                checked = semantic.validate_metric(key, *dates, **kwargs)
        except live_limiter.LiveLimitRefused as refusal:
            return _last_validated(session, definition, cache, refusal)
        if (checked.get("ok") is not True or checked.get("state") == "unproven"
                or not _number(value) or not _number(checked.get("ours"))
                or value != checked["ours"] or not _number(checked.get("independent"))):
            raise _Unavailable
        as_of = live_limiter.iso_utc(live_limiter._now())
        _remember(session, cache, value, as_of)
        if not warnings:
            return {**definition, "value": value, "as_of": as_of}
        warnings = _warning_observation(ctx, key, window, **scope)
    return {**definition, "value": value, "as_of": as_of, **warnings}


def list_metrics(ctx, args):
    """List standard metrics that validate within your access for the requested window."""
    window = _arguments(ctx, args, "list")
    rows, refused = [], []
    for key in _KEYS:
        try:
            rows.append(_observe(ctx, key, window))
        except Exception as exc:
            # A refused metric is listed with its cause, never dropped (rule 1). It carries no value.
            refused.append(_refused_row(key, exc))
    return {"window": window, "metrics": rows, "refused_metrics": refused}


def get(ctx, args):
    """Read one validated metric value for a named window. Plain sales means invoiced."""
    window = _arguments(ctx, args, "get")
    key = "invoiced" if args["key"] in ("sales", "invoiced_sales") else args["key"]
    try:
        observed = _observe(ctx, key, window, customer_id=args.get("customer_id"), team_id=args.get("team_id"))
    except _LimitRefused as exc:
        raise deps.err(409, "metric_unavailable", _LIMITED, details=exc.refusal.as_dict()) from None
    except Exception:
        raise deps.err(409, "metric_unavailable", _UNAVAILABLE) from None
    result = {**observed, "window": window,
              **{name: args[name] for name in ("customer_id", "team_id") if name in args}}
    if args.get("compare") == "yoy":
        result.update(_compare(ctx, key, window, args))
    return result


def _compare(ctx, key, window, args):
    """The prior year value under its own cache key and limiter admission (rule 8). A prior window
    that does not validate carries no value and names its cause."""
    grain = _compare_grain(window)
    prior, rule = _prior_window(window, grain)
    try:
        observed = _observe(ctx, key, prior, customer_id=args.get("customer_id"),
                            team_id=args.get("team_id"), warnings=False)
    except Exception as exc:
        refusal = {name: value for name, value in _refused_row(key, exc).items() if name != "key"}
        report = {"value": None, "refusal": refusal}
    else:
        report = {name: observed[name] for name in ("value", "as_of", "served", "limit_refusal")
                  if name in observed}
    return {"compare": "yoy", "compare_rule": rule, "compare_grain": grain,
            "prior": {"window": prior, **report}}


def explain_customer(ctx, args):
    """Explain a named customer's invoiced change over two explicit periods."""
    from harness import semantic

    window = _arguments(ctx, args, "explain_customer")
    previous = _window(args["previous_window"])
    if previous["date_to"] >= window["date_from"]:
        raise deps.err(400, "metric_window_invalid", "The previous window must end before the current window starts.")
    try:
        source = _source(ctx.session)
        with semantic.tenant_context(ctx.session.runtime), source._bound():
            definition = _definition("invoiced", semantic.metric_catalog()["invoiced"])
            _admit(ctx, *_database("account_move"),
                   ("partner_id", "partner_name", "invoice_date", "amount_untaxed_signed", "amount_untaxed", "move_type"))
            _admit(ctx, *_database("account_move_line"),
                   ("partner_id", "move_id", "display_type", "price_subtotal", "quantity", "product_name", "product_uom_name"))
            with _live_admission(ctx.session, "metrics.explain_customer"):
                result = semantic.explain_customer(args["customer"], previous, window,
                                                   customer_id=args.get("customer_id"),
                                                   runtime=ctx.session.runtime, user=ctx.session.user)
            warnings = _warning_observation(ctx, "invoiced", window, customer_id=result.get("customer_id"))
    except live_limiter.LiveLimitRefused as refusal:
        raise deps.err(409, "customer_explanation_unavailable",
                       "The live call limit is reached. Try again later.", details=refusal.as_dict()) from None
    except Exception:
        raise deps.err(409, "customer_explanation_unavailable",
                       "This customer has no validated invoice explanation within your current access and periods.") from None
    return {**definition, **result, **warnings}


def _explanation_action():
    """Declare the read-only customer explanation with an optional disambiguating id."""
    return {"read": True, "destructive": False, "confirm": False,
            "schema": {"type": "object", "description": explain_customer.__doc__,
                       "properties": {"customer": {"type": "string", "minLength": 1, "maxLength": 300,
                                                   "description": "Exact customer name. No other customers are included."},
                                      "customer_id": {"type": "integer", "minimum": 1,
                                                      "description": "Permitted partner_id for an ambiguous customer name."},
                                      "previous_window": copy.deepcopy(WINDOW_SCHEMA),
                                      "window": copy.deepcopy(WINDOW_SCHEMA)},
                       "required": ["customer", "previous_window", "window"], "additionalProperties": False},
            "handler": explain_customer}


def _action(handler, *, get_value=False):
    properties = {"window": copy.deepcopy(WINDOW_SCHEMA)}
    required = ["window"]
    if get_value:
        properties["key"] = {"type": "string", "enum": [*_KEYS, "sales", "invoiced_sales"]}
        required.append("key")
        properties["customer_id"] = {"type": "integer", "minimum": 1,
                                     "description": "Exact permitted customer id. Related customers are not included."}
        properties["team_id"] = {"type": "integer", "minimum": 1,
                                 "description": "Narrow to one configured business unit when the metric supports it."}
        properties["compare"] = copy.deepcopy(COMPARE_SCHEMA)
    return {
        "read": True, "destructive": False, "confirm": False,
        "schema": {"type": "object", "description": handler.__doc__,
                   "properties": properties, "required": required, "additionalProperties": False},
        "handler": handler,
    }


GROUP = {
    "name": "metrics", "title": "Metrics",
    "guide": "Read the five standard metrics: booked, shipped, invoiced, collected and margin. "
             "Plain sales resolves to invoiced. All actions are read only. "
             "All actions require window with name, date_from and date_to. "
             "Use name calendar_month for a complete calendar month or date_range for inclusive dates. "
             "Dates use ISO format. The window schema includes an example. "
             "List returns only metrics whose current mirror values reconcile with the independent source "
             "for that same window. List names each other metric under refused_metrics with its cause. "
             "Get requires key and returns that validated number with as_of. "
             "When the live call limit is reached, a metric serves its last validated value for the same "
             "window and access with its as_of, served last_validated and limit_refusal. "
             "A window never validated is refused with the limit cause and next allowed time. "
             "Each result declares states, channel_excludes, date_basis and cost_basis. "
             "Verified warnings carry stable codes and line or transfer counts with warning_status verified. "
             "Get accepts customer_id and team_id for exact narrowing. No customer scope expands to related customers. "
             "Get accepts compare yoy and adds prior with the prior window and its validated value, "
             "compare_grain and compare_rule. A one day or seven day window compares the same weekday "
             "364 days back. A month, quarter, year to date or other range compares the same calendar dates. "
             "A prior window that does not validate returns value null with its refusal and cause. "
             "Unavailable warnings return warnings null, warning_status unavailable and an explicit warning_refusal. "
             "A warning refusal preserves the independently validated metric or customer explanation. "
             "Invoice warning costs and fulfilment links are unavailable until independently observed. "
             "A missing source or database mapping makes the metric unavailable. "
             "Record, field, customer and business unit limits that cannot be reconciled refuse the metric. "
             "Explain_customer requires an exact customer name and previous_window before window. "
             "Use customer_id to disambiguate a name. It returns six drivers ranked by revenue lost. "
             "The ordered invoice count, lines per invoice, product mix, units per line and realized price bridge "
             "sums to the invoiced change in cents. Margin has zero revenue attribution and is unavailable "
             "without verified historical cost. Invoice lines include charges without products. "
             "Missing history returns no history only after source reconciliation.",
    "actions": {"list": _action(list_metrics), "get": _action(get, get_value=True),
                "explain_customer": _explanation_action()},
}