"""core/alerts.py — "tell me when a record ENTERS this view" (wave 20, owner item 25). THE OWNER'S SHAPE, verbatim: *"a user click a view and click 'Create alert'. This way when a Record gets into that Filter's criteria, a user gets notified in that module … Read/Unread like an inbox type of thing so they can confirm whether they have seen the Record that got filtered in."* An alert remembers a View's matched set and delivers one counted notification per run. An entrant is a pid that matches now and did not last time. That definition is what makes the module trustworthy rather than noisy: * a record already in the view when the alert is created is NOT news. The first evaluation SEEDS the set silently (`seed=True`); without that, creating an alert on a 400-row view would announce 400 "new" records, and the user would turn the feature off in one click; * a record that leaves and comes back IS news again — it re-entered the criteria, which is the event the owner described; * a record that merely CHANGES while staying in the view is not an entrant. "Still matching" is not an event. (An on-change alert is a different feature with a different noise budget; it is NOT smuggled in here under the same name.) ⚠ **WHY THE MATCHED SET IS STORED AND NOT RECOMPUTED FROM HISTORY.** There is no row-level audit log to diff against — `store` holds current state, and Odoo is read-only. The remembered set IS the history, so it is written on every evaluation, in the same transaction that queues the notifications. Losing that write while keeping the notifications would re-announce the same records forever. ⚠ **WHAT AN UNANSWERABLE LEAF ACTUALLY DOES HERE — CHECKED, NOT ASSUMED.** `harness.filter_eval`'s `EvalCtx` is explicit that each of its four members "absent, the condition matches NOTHING rather than everything" — the engine NARROWS on an unresolved measure/cohort/rank set rather than widening. So the failure mode is not a false alert; it is a **missed** one, and a missed entrant is re-detected on the next evaluation because `matched` only ever records what genuinely matched. That is the safe direction, and it is why `partial` is a caller-supplied flag rather than something inferred in here: the caller (`routes_alerts`) is the only layer that knows whether it could BUILD a complete context. When it says so, `evaluate()` records the attempt and changes nothing — updating `matched` from a narrowed evaluation would drop rows out of the remembered set and then re-announce every one of them as an "entrant" on the next complete pass. That is the real hazard: not a phantom alert, but a storm of stale ones. ⚠ **EVERY STAMP CARRIES A UTC OFFSET** (DEBT D-18). A browser can only render a timestamp relatively if it can subtract it from `now`, and a naive container-local stamp is unsubtractable — it renders VERBATIM or, worse, silently as the reader's own zone. `_now_iso()` is the one place that is decided. """ import datetime as _dt import logging as _logging from urllib.parse import urlencode import core.store as store from core import account_rows #: Alert DEFINITIONS, per tenant: {alert_id: {...}}. Separate from the notifications bucket so a #: busy inbox never rewrites the definitions (and a definition edit never rewrites the inbox). ALERTS_KEY = 'alerts' #: Legacy inbox document, replaced by recipient-scoped notification rows on PostgreSQL. NOTIFICATIONS_KEY = 'alert_notifications' #: Keep 200 per recipient when possible, dropping only the oldest read notifications. MAX_NOTIFICATIONS = account_rows.NOTIFICATION_TARGET _SINK = None _LOG = _logging.getLogger(__name__) def set_sink(fn): """Register the optional notification sink without importing an application layer.""" if fn is not None and not callable(fn): raise ValueError('A notification sink must be callable.') global _SINK _SINK = fn def _publish(owner, item, st): if _SINK is not None: try: _SINK(_st(st), owner, item) except Exception as exc: # A failed notice must not roll back its producer or suppress the compatibility row. _LOG.warning('Assistant notice was not delivered: %s', type(exc).__name__) def _now_iso(): """UTC, WITH the offset — `2026-08-05T09:41:07.123456+00:00`. See the module note (D-18).""" from core import write_execution return write_execution.utcnow().isoformat() def _st(st): return st if st is not None else store def list_alerts(user=None, st=None, is_admin=False): """Alert definitions this user may see: their own. Admins see all (they support them).""" try: recs = _st(st).get(ALERTS_KEY) or {} except Exception: return [] out = [] for aid, rec in recs.items(): if not isinstance(rec, dict): continue if user and not is_admin and str(rec.get('owner') or '') != str(user): continue out.append({**rec, 'id': str(aid)}) return sorted(out, key=lambda r: str(r.get('createdAt') or '')) def create(alert_id, *, view_id, topic, owner, label='', st=None): """Register an alert on a view. Returns the record. The view is stored BY ID, never by a copy of its filter tree. An alert whose criteria were snapshotted at creation would silently stop matching the view the moment its owner edited it — and the user's mental model is "alert me on THIS VIEW", not "on this view as it was in August". """ rec = {'id': str(alert_id), 'viewId': str(view_id), 'topic': str(topic), 'owner': str(owner), 'label': str(label or '')[:160], 'createdAt': _now_iso(), 'matched': [], 'seeded': False, 'lastRunAt': None, 'lastError': None} def _apply(data): data[str(alert_id)] = rec return data _st(st).update(ALERTS_KEY, _apply, flush='sync') return rec def drop_topic(topic, st=None): """Delete every alert DEFINITION on a topic (wave 21, item 6a / C3 — a deleted database's alerts die with it; an alert on a view that no longer exists can only ever error). Notifications already delivered are left in inboxes: they are history, and history is the one thing a delete must not rewrite.""" t = str(topic or '') if not t: return def _apply(data): for aid in [k for k, r in (data or {}).items() if isinstance(r, dict) and str(r.get('topic') or '') == t]: data.pop(aid, None) return data _st(st).update(ALERTS_KEY, _apply, flush='async') def delete(alert_id, st=None): def _apply(data): data.pop(str(alert_id), None) return data _st(st).update(ALERTS_KEY, _apply, flush='sync') return True def evaluate(alert_id, matching_pids, *, labels=None, partial=False, st=None): """Fold a fresh evaluation of one alert's view into its state; queue any NEW entrants. `matching_pids` is what the view matches NOW — the caller owns running the filter, because only it knows the topic's rows and the reader's scope. `partial` says the evaluation could not answer every leaf; see the module note on why that suppresses everything. Returns `{'new': [...], 'seeded': bool}` or `{'skipped': 'partial'|'missing'}`. """ now_set = {str(p) for p in (matching_pids or ())} outcome = {} def _apply(data): rec = data.get(str(alert_id)) if not isinstance(rec, dict): outcome['skipped'] = 'missing' return data if partial: # Record the ATTEMPT (so "last checked" is honest) but change nothing else. Writing # `matched` here would bake a widened set in as truth, and the next COMPLETE # evaluation would then report every genuinely-absent row as an entrant. rec['lastRunAt'] = _now_iso() rec['lastError'] = ('the view could not be fully evaluated (a filter leaf was ' 'unanswerable); no alert was raised') outcome['skipped'] = 'partial' data[str(alert_id)] = rec return data prior = {str(p) for p in (rec.get('matched') or ())} seeding = not rec.get('seeded') entrants = [] if seeding else sorted(now_set - prior, key=lambda s: (len(s), s)) rec['matched'] = sorted(now_set, key=lambda s: (len(s), s)) rec['seeded'] = True rec['lastRunAt'] = _now_iso() rec['lastError'] = None data[str(alert_id)] = rec outcome['new'] = entrants outcome['seeded'] = seeding outcome['_rec'] = rec return data _st(st).update(ALERTS_KEY, _apply, flush='sync') if outcome.get('skipped'): return {'skipped': outcome['skipped']} rec = outcome.pop('_rec', {}) or {} if outcome.get('new'): _queue(rec, outcome['new'], labels or {}, st=st) return outcome def _queue(rec, pids, labels, st=None): """Append one counted delivery per filter run to both internal destinations.""" if not pids: return at = _now_iso() topic = str(rec.get('topic') or '') database = {'customer': 'customer_data', 'product': 'product_data'}.get(topic, topic) view = str(rec.get('viewId') or '') count = len(pids) item = {'id': f"{rec.get('id')}:{at}", 'alertId': str(rec.get('id')), 'viewId': str(rec.get('viewId')), 'topic': topic, 'rowId': '', 'kind': 'alert', 'count': count, 'label': f"{count} {'record' if count == 1 else 'records'} entered this View", 'target': {'module': 'database', 'id': database, 'tab': view}, 'link': '#/data?' + urlencode({'database': database, 'view': view}), 'alertLabel': str(rec.get('label') or ''), 'at': at, 'read': False} owner = str(rec.get('owner') or '') # The sink's first-post cutover must finish before the new bell row is appended. _publish(owner, item, st) if account_rows.records_backend(_st(st)): _notification_write(st, lambda: _append_notification_rows([(owner, False, item, {})], st=st), 1) return def _apply(data): inbox = list(data.get(owner) or []) inbox.append(item) if len(inbox) > MAX_NOTIFICATIONS: # Drop READ entries oldest-first; keep every unread one. A cap that dropped unread # notifications would silently lose exactly the records the user has not confirmed — # the one thing this module promises not to do. unread = [n for n in inbox if not n.get('read')] read = [n for n in inbox if n.get('read')] keep_read = read[max(0, len(unread) + len(read) - MAX_NOTIFICATIONS):] inbox = sorted(unread + keep_read, key=lambda n: str(n.get('at') or '')) data[owner] = inbox return data _notification_write(st, lambda: _st(st).update(NOTIFICATIONS_KEY, _apply, flush='async'), 1) def notify(owner, label, *, topic='automation', key='', row_id='', detail='', actor='', st=None, replace=False, target=None, inbox=None): """⭐ WAVE 23 (C6) — put ONE notification in a named user's inbox, for a producer that is not a view-alert evaluation. The automation engine needs the bell to ring when records arrive at a review gate, and that is not an alert over a view: there is no filter tree, no `matched` set, no entrant diff. It reached for `_queue` directly during the wave, which would have made a private function a cross-module contract — so this is the public door instead, and `_queue` stays the internal half of `evaluate()`. The inbox shape is UNCHANGED, deliberately: `AlertsPane` reads one list, and a second row shape would mean a client that must branch on where a notification came from. `alertId` carries the producer's key so a click-through can route (W23-W5). ⭐⭐ W33-T28 (`ASK C-14`) — `actor` IS THE ONLY THING THAT KNOWS WHO. Owner item: *"the Inbox reads like email"*, and a verifier reading the carried wave-32 surface found the SENDER position occupied by `kindLabel(n.kind)` — the literals "Alert" / "Automation" / "Shared with you", i.e. a CATEGORY where mail puts a who — with no sender field anywhere on the wire, in the model or in the markup. An alert and an automation have no person behind them and are honestly named by their machine; **a SHARE has a real person, and only the PRODUCER knows their name.** By the time the read path sees the row that fact is gone, so it has to be carried at write time. ⛔ ADDITIVE, AND THAT IS THE WHOLE DESIGN. No existing caller changes, no stored row changes shape, and every reader already tolerates the key's absence — so an inbox written before this line reads exactly as it did. The alternative C rejected is worth recording because it is the tempting one: recovering the name by REGEXING the body prose (`" shared this with you"`). A sender parsed out of a sentence breaks the first time the sentence is reworded, and it breaks SILENTLY, in the header — [[one-question-two-normalizers]] with the second normaliser being English. ⚠ Blank is a legitimate value and means *"no person did this"*, NOT "unknown". The client falls back BY KIND rather than to an empty From column, so an automation never borrows a human's name. `inbox` (S72-T27) is an agent message's C6 payload. It rides to the sink only and never enters the compatibility row or the returned item. """ items = notify_many([{'owner': owner, 'label': label, 'topic': topic, 'key': key, 'row_id': row_id, 'detail': detail, 'actor': actor, 'replace': replace, 'target': target, 'inbox': inbox}], st=st) return items[0] if items else None def _notification_write(st, write, count): """Count refused notices under their tenant and clear the loss after a successful write.""" from core import audit target = _st(st) tenant = getattr(target, 'key', None) or getattr(target, 'tenant_slug', None) if tenant is None and target is store: tenant = getattr(store._d(), 'tenant_slug', None) or 'royal-imports' tenant = tenant or 'unknown' try: result = write() except Exception as exc: audit.note_loss(tenant, NOTIFICATIONS_KEY, exc, count) raise audit.note_ok(tenant, NOTIFICATIONS_KEY) return result def notify_many(entries, st=None): """Queue a producer's notifications in one write, preserving the existing inbox wire. Replacement is opt-in and scoped to one owner's (topic, alertId). Ticket assignments keep the assignment count in the row label and the ticket title in an additive detail cell. """ queued = [] for entry in entries: owner = str(entry.get('owner') or '').strip() label = entry.get('label') if not owner or not label: continue topic, key = str(entry.get('topic', 'automation')), str(entry.get('key') or '') row_id, detail = str(entry.get('row_id') or ''), str(entry.get('detail') or '') at = _now_iso() replace = bool(entry.get('replace')) item = {'id': f"{key or topic}:{row_id or 'n'}:{at}", 'alertId': key, 'viewId': '', 'topic': topic, 'rowId': row_id, 'label': str(detail or label), 'alertLabel': str(label), 'at': at, 'read': False, 'actor': str(entry.get('actor') or '')} if topic == 'ticket' and replace: # Subject (`alertLabel`) says who assigned it; the preview (`label`) names the ticket. item['detail'] = detail if isinstance(entry.get('target'), dict): item['target'] = dict(entry['target']) sink_extra = {'inbox': dict(entry['inbox'])} if isinstance(entry.get('inbox'), dict) else {} queued.append((owner, replace, item, sink_extra)) if not queued: return [] # Cutover drops old unread rows before this batch writes fresh compatibility rows. for owner, _replace, item, sink_extra in queued: _publish(owner, {**item, **sink_extra}, st) if account_rows.records_backend(_st(st)): _notification_write(st, lambda: _append_notification_rows(queued, st=st), len(queued)) return [item for _owner, _replace, item, _extra in queued] def _apply(data): owners = set() for owner, replace, item, _extra in queued: box = list(data.get(owner) or []) if replace: box = [n for n in box if (n.get('topic'), n.get('alertId')) != (item['topic'], item['alertId'])] box.append(dict(item)) data[owner] = box owners.add(owner) for owner in owners: box = data[owner] if len(box) > MAX_NOTIFICATIONS: unread = [n for n in box if not n.get('read')] read = [n for n in box if n.get('read')] keep_read = read[max(0, len(unread) + len(read) - MAX_NOTIFICATIONS):] box = sorted(unread + keep_read, key=lambda n: str(n.get('at') or '')) data[owner] = box return data _notification_write(st, lambda: _st(st).update(NOTIFICATIONS_KEY, _apply, flush='async'), len(queued)) return [item for _owner, _replace, item, _extra in queued] def _trim_notifications(items): return account_rows.retain_notifications(items) def _append_notification_rows(queued, *, st): for owner in sorted({entry[0] for entry in queued}): def append(items, owner=owner): for recipient, replace, item, _extra in queued: if recipient != owner: continue if replace: items = [n for n in items if (n.get('topic'), n.get('alertId')) != (item['topic'], item['alertId'])] items.append(dict(item)) return _trim_notifications(items) account_rows.update_notifications(owner, append, st=_st(st)) def notification_items(user, st=None): """Return only the recipient's notices without falling back after a row-store failure.""" st = _st(st) if account_rows.records_backend(st): return account_rows.notification_items(str(user), st=st) reader = getattr(st, 'get_entry', None) if callable(reader): return reader(NOTIFICATIONS_KEY, str(user)) or [] return (st.get(NOTIFICATIONS_KEY) or {}).get(str(user)) or [] def mark_read(user, ids, st=None): """Mark allowed notification ids read without changing another recipient's inbox.""" ids = set(ids) def mark(items): for item in items: if isinstance(item, dict) and item.get('id') in ids: item['read'] = True return _trim_notifications(items) st = _st(st) if account_rows.records_backend(st): return account_rows.update_notifications(str(user), mark, st=st) def apply(data): data[str(user)] = mark(data.get(str(user)) or []) return data return st.update(NOTIFICATIONS_KEY, apply, flush='sync') def inbox(user, st=None, limit=100): """`{'unread': int, 'items': [...]}` — newest first, for the badge and the pane.""" try: items = list(notification_items(user, st=st)) except Exception: return {'unread': 0, 'items': []} items = [n for n in items if isinstance(n, dict)] items.sort(key=lambda n: str(n.get('at') or ''), reverse=True) return {'unread': sum(1 for n in items if not n.get('read')), 'items': items[:max(0, limit)]} def after_write(topic_key, st=None, runner=None): """The write-path HOOK: re-evaluate every alert whose view belongs to `topic_key`. ⚠ CALLED FROM A WRITE PATH, SO IT MUST NOT RAISE AND MUST NOT BLOCK ON A FULL POOL BUILD. A failed alert evaluation must never fail the edit that triggered it — the user typed into a cell; whether an alert fires is not their problem. `runner` is injected by the caller (`routes_alerts` passes one that can resolve the topic's rows for the alert's owner), so this module never reaches for a pool itself and stays unit-testable with a fake. """ if runner is None: return {'evaluated': 0} n = 0 for rec in list_alerts(st=st): if str(rec.get('topic')) != str(topic_key): continue try: runner(rec) n += 1 except Exception: # noqa: BLE001 — see the docstring continue return {'evaluated': n}