File size: 7,941 Bytes
89af3b2
 
 
 
 
 
 
 
 
 
f462120
89af3b2
 
 
816fa8a
89af3b2
 
 
 
 
 
 
 
816fa8a
 
89af3b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
 
 
 
 
 
 
89af3b2
dec006b
89af3b2
 
 
 
 
 
 
dec006b
89af3b2
 
816fa8a
 
 
 
 
 
 
 
dec006b
 
89af3b2
 
 
f462120
 
 
 
 
8133df9
f462120
8133df9
89af3b2
 
dec006b
 
816fa8a
 
 
 
 
 
 
 
 
 
89af3b2
816fa8a
 
 
89af3b2
 
 
 
 
 
 
 
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
"""C5 notifications enter the recipient's durable Assistant conversation."""
import copy
import logging
import re
import threading
from urllib.parse import urlencode

import ai_enrich
import assistant_log
import ping_doors
from core import account_rows, alerts


CUTOVER_KEY = "assistant_notice_cutover"
INBOX_KEYS = ("type", "request_id", "sender", "target", "text", "actions", "state")
_LOCK = threading.RLock()
_LOG = logging.getLogger(__name__)


def _target(item):
    if isinstance(item.get("target"), dict):
        return copy.deepcopy(item["target"])
    topic, key = str(item.get("topic") or ""), str(item.get("alertId") or "")
    if topic == "inbox":
        return None  # A C6 target arrives as a dict above. A question may have none.
    view = str(item.get("viewId") or "")
    if topic == "automation" and key:
        return {"module": "automation", "id": key, "tab": "runs"}
    if topic == "share" and key:
        if key not in {"customer_data", "product_data"} and not re.fullmatch(r"ut_[A-Za-z0-9_]+", key):
            return None
        view = str(item.get("rowId") or "")
        return {"module": "database", "id": key, **({"tab": view} if view else {})}
    database = {"customer": "customer_data", "product": "product_data"}.get(topic)
    if topic.startswith("ut_"):
        database = topic
    return {"module": "database", "id": database,
            **({"tab": view} if view else {})} if database else None


def _link(target):
    if not target:
        return ""
    module, ident = target.get("module"), target.get("id")
    if module == "database":
        params = {"database": ident}
        if target.get("tab"):
            params["view"] = target["tab"]
        return "#/data?" + urlencode(params)
    if module == "automation":
        params = {"agent": ident}
        if target.get("tab"):
            params["tab"] = target["tab"]
        return "#/automation?" + urlencode(params)
    if isinstance(module, str) and module.startswith("ut_"):
        return "#/data?" + urlencode({"database": module, "record": ident})
    return ""


def _inbox_link(target):
    """The deep link of a C6 target `{kind, key, label}`, or "" when it has no address."""
    if not isinstance(target, dict):
        return ""
    kind, key = target.get("kind"), str(target.get("key") or "")
    pair = re.split(r"[/:]", key, maxsplit=1)
    if not key:
        return ""
    if kind == "database":
        return "#/data?" + urlencode({"database": key})
    if kind == "view":
        if len(pair) == 2 and all(pair):
            return "#/data?" + urlencode({"database": pair[0], "view": pair[1]})
        return "#/data?" + urlencode({"view": key})
    if kind == "sheet":
        return "#/sheet?" + urlencode({"wb": key})
    if kind == "app" and len(pair) == 2 and all(pair):
        # An app opens inside its database: `#/app?database=<db>&application=<id>`.
        return "#/app?" + urlencode({"database": pair[0], "application": pair[1]})
    return ""


def _inbox_payload(inbox, subject, body):
    """Exactly the C6 keys, plus title, body, link and source for the external door."""
    payload = {key: copy.deepcopy(inbox.get(key)) for key in INBOX_KEYS}
    sender = payload.get("sender")
    if isinstance(sender, dict):
        sender["name"] = ai_enrich.no_dashes(" ".join(str(sender.get("name") or "").split()))
    payload.update(title=subject, body=body, link=_inbox_link(payload.get("target")),
                   source="inbox")
    return payload


def _inside_window(rt, username):
    """True when the recipient has a WhatsApp phone inside the 24-hour window."""
    try:
        import telnyx_whatsapp
        from core import users
        record = dict(users._tenant_accounts(assistant_log._tenant_of(rt))).get(username)
        whatsapp = record.get("whatsapp") if isinstance(record, dict) else None
        phone = whatsapp.get("phone") if isinstance(whatsapp, dict) else None
        return bool(phone) and bool(telnyx_whatsapp.within_window(phone))
    except Exception as exc:                                             # noqa: BLE001
        _LOG.warning("WhatsApp window was not read: %s", type(exc).__name__)
        return False


def _internal_only(rt, item):
    """Bulk alerts and retired Once outcomes have only internal destinations."""
    if item.get("kind") == "alert":
        return True
    if item.get("topic") == "automation" and not item.get("rowId") and item.get("alertId"):
        import automation_engine
        row = (rt.get(automation_engine.STORE_KEY) or {}).get(str(item["alertId"])) or {}
        status = row.get("status") or {}
        completion = f"{status.get('state')}: {status.get('lastSummary') or ''}"[:300]
        return bool(row.get("retiredOnceAt")) and item.get("label") == completion
    return False


def post(rt, username, item):
    """Append one notice, perform cutover once, and fan out eligible deliveries."""
    if item.get("topic") == "ticket":
        return None  # Ticket pings already enter through ping_doors.deliver_new.
    # Validate the tenant and recipient before cutover changes their store.
    assistant_log._hash(rt, username)
    subject = ai_enrich.no_dashes(item.get("alertLabel") or item.get("label") or "Notice")
    body = ai_enrich.no_dashes(item.get("label") or "")
    source = str(item.get("topic") or "alert")
    fallback = {"automation": "Automation", "share": "A teammate"}.get(source, "Alerts")
    sender = ai_enrich.no_dashes(item.get("actor") or fallback)
    target = _target(item)
    inbox = item.get("inbox") if isinstance(item.get("inbox"), dict) else None
    if inbox is not None:
        payload = _inbox_payload(inbox, subject, body)
    else:
        payload = {"title": subject, "subject": subject, "body": body, "sender": sender,
                   "target": target, "link": _link(target), "source": source,
                   "notificationId": item.get("id"), "alertId": item.get("alertId"),
                   "viewId": item.get("viewId"), "rowId": item.get("rowId")}
        if item.get("kind") == "alert":
            payload.update(kind="alert", count=item.get("count"), label=body)
    turn = {"role": "system", "door": "wake", "kind": "notice", "text": body,
            "payload": payload, "at": item.get("at") or alerts._now_iso()}
    with _LOCK:
        row_mode = bool(account_rows.records_backend(rt))
        cutover_key = CUTOVER_KEY + ':' + str(username).encode('utf-8').hex() if row_mode else CUTOVER_KEY
        if not (rt.get(cutover_key) or {}).get("purged"):
            if not row_mode:
                def purge(data):
                    return {}
                rt.update(alerts.NOTIFICATIONS_KEY, purge, flush="sync")
            rt.update(cutover_key, lambda _data: {"version": 2 if row_mode else 1, "purged": True}, flush="sync")
        turn_id = assistant_log.append(rt, username, turn)
    turn["id"] = turn_id
    if _internal_only(rt, item):
        return turn_id
    if getattr(rt, "preview_only", False):
        rt.deferred_notices.append({"username": username, "turn": copy.deepcopy(turn),
                                    "inside_window_only": inbox is not None})
        return turn_id
    deliver_external(rt, username, turn, inside_window_only=inbox is not None)
    return turn_id


def deliver_external(rt, username, turn, *, inside_window_only=False):
    """Deliver an already committed notice, including a notice held by an Assistant preview."""
    external = getattr(ping_doors, "notify_external", None)
    if inside_window_only and not _inside_window(rt, username):
        # R108(l): an agent message reaches WhatsApp only inside the window, never as a template.
        external = None
    if callable(external):
        try:
            external(rt, username, copy.deepcopy(turn))
        except Exception as exc:
            _LOG.warning("External notice was not delivered: %s", type(exc).__name__)


alerts.set_sink(post)