Spaces:
Paused
Paused
Deploy Loopable
Browse files- app.py +13 -13
- modules/digest.py +224 -224
- modules/sales.py +18 -4
app.py
CHANGED
|
@@ -346,7 +346,7 @@ h1,h2,h3,h4,h5{ font-family:__FONT__; color:var(--navy); letter-spacing:-.012em;
|
|
| 346 |
.kpi{ background:#fff; border:1px solid var(--line); border-radius:var(--rad);
|
| 347 |
padding:14px 16px 12px; height:100%; display:flex; flex-direction:column; gap:3px;
|
| 348 |
transition:box-shadow var(--t-base) var(--ease), border-color var(--t-base) var(--ease); }
|
| 349 |
-
.kpi-lab{ font-size:.
|
| 350 |
color:var(--muted); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
| 351 |
.kpi-val{ font-weight:600; color:var(--navy); font-size:1.7rem; letter-spacing:-.02em;
|
| 352 |
line-height:1.08; }
|
|
@@ -359,8 +359,8 @@ h1,h2,h3,h4,h5{ font-family:__FONT__; color:var(--navy); letter-spacing:-.012em;
|
|
| 359 |
background:#fff; border:1px solid var(--line); border-radius:var(--rad);
|
| 360 |
padding:14px 16px 12px; height:100%;
|
| 361 |
}
|
| 362 |
-
[data-testid="stMetricLabel"] p{ font-size:.
|
| 363 |
-
|
| 364 |
[data-testid="stMetricValue"]{ font-weight:600; color:var(--navy); font-size:1.7rem;
|
| 365 |
letter-spacing:-.02em; line-height:1.08; }
|
| 366 |
[data-testid="stMetricValue"] > div{ overflow:visible; }
|
|
@@ -464,8 +464,8 @@ section[data-testid="stSidebar"][aria-expanded="true"] [data-testid="stSidebarHe
|
|
| 464 |
/* group micro-labels (benchmark: 10-11px upper, letterspaced, AIR BEFORE each group). The label's
|
| 465 |
element container collapses to ~3px in Streamlit's flex column (text overflowed onto the widget
|
| 466 |
below) — pin a real min-height on the container so the rhythm is honest. */
|
| 467 |
-
.side-lab{ display:block; font-size:
|
| 468 |
-
|
| 469 |
margin:0 0 2px; }
|
| 470 |
[data-testid="stSidebar"] [data-testid="stElementContainer"]:has(.side-lab){
|
| 471 |
min-height:18px; margin-top:14px; }
|
|
@@ -813,8 +813,8 @@ section[data-testid="stSidebar"][aria-expanded="false"] .st-key-navrail{ padding
|
|
| 813 |
margin-left:auto !important; margin-right:auto !important;
|
| 814 |
border-radius:var(--lp-r-lg); box-shadow:0 18px 48px rgba(20,24,40,.22); }
|
| 815 |
/* the dialog's LEFT RAIL — the reference's grouped nav, at our two-section scale */
|
| 816 |
-
.dlg-rail-cap{ font-size:var(--lp-fs-
|
| 817 |
-
|
| 818 |
[data-testid="stDialog"] [class*="st-key-dlgsec_"] button{
|
| 819 |
justify-content:flex-start !important; text-align:left; min-height:32px; height:32px;
|
| 820 |
padding:0 10px; border:none !important; box-shadow:none !important; background:transparent;
|
|
@@ -991,8 +991,8 @@ section[data-testid="stMain"] [data-testid="stChatInput"] textarea{ font-size:.9
|
|
| 991 |
hr{ border-color:var(--line); margin:1rem 0; }
|
| 992 |
|
| 993 |
/* data-health severity badges + check cards */
|
| 994 |
-
.sev{ display:inline-block; padding:2px 10px; border-radius:999px; font-size:.
|
| 995 |
-
font-weight:700;
|
| 996 |
.sev-high{ background:#FBE9E7; color:#B42318; }
|
| 997 |
.sev-medium{ background:#FBF1DE; color:#9A6700; }
|
| 998 |
.sev-low{ background:var(--lp-blue-t); color:#2F5FA8; }
|
|
@@ -1026,7 +1026,7 @@ div[data-testid="stDialog"] .kpi-val{ font-size:1.38rem; white-space:nowrap; }
|
|
| 1026 |
[data-testid="stButton"] button[kind="tertiary"] p{
|
| 1027 |
width:100%; text-align:left!important; justify-content:flex-start!important; margin:0;
|
| 1028 |
font-weight:500; font-size:.88rem; }
|
| 1029 |
-
.lh{ color:var(--muted); font-size:.
|
| 1030 |
.rowv{ font-size:.86rem; color:var(--ink); padding-top:.16rem; }
|
| 1031 |
.rowt{ font-weight:700; color:var(--navy); font-size:.83rem; border-bottom:2px solid #E3E8EF;
|
| 1032 |
padding:1px 0 4px; }
|
|
@@ -1126,8 +1126,8 @@ div[data-testid="stDialog"] .kpi-val{ font-size:1.38rem; white-space:nowrap; }
|
|
| 1126 |
div[class*="st-key-lhwrap_"] button[kind="tertiary"],
|
| 1127 |
div[class*="st-key-lhwrap_"] button[kind="tertiary"] > div,
|
| 1128 |
div[class*="st-key-lhwrap_"] button[kind="tertiary"] p{
|
| 1129 |
-
color:var(--muted)!important; font-size:.
|
| 1130 |
-
|
| 1131 |
div[class*="st-key-lhwrap_"] button[kind="tertiary"]:hover,
|
| 1132 |
div[class*="st-key-lhwrap_"] button[kind="tertiary"]:hover p{
|
| 1133 |
color:var(--navy)!important; text-decoration:none!important; }
|
|
@@ -2582,7 +2582,7 @@ def _health_card(c, scope_label):
|
|
| 2582 |
with st.container(border=True):
|
| 2583 |
a, bcol = st.columns([6, 2])
|
| 2584 |
with a:
|
| 2585 |
-
st.markdown(f"<span class='sev sev-{c['severity']}'>{c['severity']}</span> "
|
| 2586 |
f"<span class='hc-title'>{c['title']}</span>", unsafe_allow_html=True)
|
| 2587 |
st.markdown(f"<span class='hc-fix'>{c['fix']}</span> "
|
| 2588 |
f"<span class='hc-sub'>· {scope_label}</span>", unsafe_allow_html=True)
|
|
|
|
| 346 |
.kpi{ background:#fff; border:1px solid var(--line); border-radius:var(--rad);
|
| 347 |
padding:14px 16px 12px; height:100%; display:flex; flex-direction:column; gap:3px;
|
| 348 |
transition:box-shadow var(--t-base) var(--ease), border-color var(--t-base) var(--ease); }
|
| 349 |
+
.kpi-lab{ font-size:.72rem; font-weight:600;
|
| 350 |
color:var(--muted); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
| 351 |
.kpi-val{ font-weight:600; color:var(--navy); font-size:1.7rem; letter-spacing:-.02em;
|
| 352 |
line-height:1.08; }
|
|
|
|
| 359 |
background:#fff; border:1px solid var(--line); border-radius:var(--rad);
|
| 360 |
padding:14px 16px 12px; height:100%;
|
| 361 |
}
|
| 362 |
+
[data-testid="stMetricLabel"] p{ font-size:.72rem!important; font-weight:600;
|
| 363 |
+
color:var(--muted); }
|
| 364 |
[data-testid="stMetricValue"]{ font-weight:600; color:var(--navy); font-size:1.7rem;
|
| 365 |
letter-spacing:-.02em; line-height:1.08; }
|
| 366 |
[data-testid="stMetricValue"] > div{ overflow:visible; }
|
|
|
|
| 464 |
/* group micro-labels (benchmark: 10-11px upper, letterspaced, AIR BEFORE each group). The label's
|
| 465 |
element container collapses to ~3px in Streamlit's flex column (text overflowed onto the widget
|
| 466 |
below) — pin a real min-height on the container so the rhythm is honest. */
|
| 467 |
+
.side-lab{ display:block; font-size:12px; font-weight:600;
|
| 468 |
+
color:#8792A2; line-height:1.3; padding-left:2px;
|
| 469 |
margin:0 0 2px; }
|
| 470 |
[data-testid="stSidebar"] [data-testid="stElementContainer"]:has(.side-lab){
|
| 471 |
min-height:18px; margin-top:14px; }
|
|
|
|
| 813 |
margin-left:auto !important; margin-right:auto !important;
|
| 814 |
border-radius:var(--lp-r-lg); box-shadow:0 18px 48px rgba(20,24,40,.22); }
|
| 815 |
/* the dialog's LEFT RAIL — the reference's grouped nav, at our two-section scale */
|
| 816 |
+
.dlg-rail-cap{ font-size:var(--lp-fs-2xs); font-weight:600;
|
| 817 |
+
color:var(--lp-muted); padding:2px 2px 8px; }
|
| 818 |
[data-testid="stDialog"] [class*="st-key-dlgsec_"] button{
|
| 819 |
justify-content:flex-start !important; text-align:left; min-height:32px; height:32px;
|
| 820 |
padding:0 10px; border:none !important; box-shadow:none !important; background:transparent;
|
|
|
|
| 991 |
hr{ border-color:var(--line); margin:1rem 0; }
|
| 992 |
|
| 993 |
/* data-health severity badges + check cards */
|
| 994 |
+
.sev{ display:inline-block; padding:2px 10px; border-radius:999px; font-size:.72rem;
|
| 995 |
+
font-weight:700; vertical-align:middle; }
|
| 996 |
.sev-high{ background:#FBE9E7; color:#B42318; }
|
| 997 |
.sev-medium{ background:#FBF1DE; color:#9A6700; }
|
| 998 |
.sev-low{ background:var(--lp-blue-t); color:#2F5FA8; }
|
|
|
|
| 1026 |
[data-testid="stButton"] button[kind="tertiary"] p{
|
| 1027 |
width:100%; text-align:left!important; justify-content:flex-start!important; margin:0;
|
| 1028 |
font-weight:500; font-size:.88rem; }
|
| 1029 |
+
.lh{ color:var(--muted); font-size:.74rem; font-weight:700; }
|
| 1030 |
.rowv{ font-size:.86rem; color:var(--ink); padding-top:.16rem; }
|
| 1031 |
.rowt{ font-weight:700; color:var(--navy); font-size:.83rem; border-bottom:2px solid #E3E8EF;
|
| 1032 |
padding:1px 0 4px; }
|
|
|
|
| 1126 |
div[class*="st-key-lhwrap_"] button[kind="tertiary"],
|
| 1127 |
div[class*="st-key-lhwrap_"] button[kind="tertiary"] > div,
|
| 1128 |
div[class*="st-key-lhwrap_"] button[kind="tertiary"] p{
|
| 1129 |
+
color:var(--muted)!important; font-size:.74rem!important; font-weight:700!important;
|
| 1130 |
+
line-height:1.1; }
|
| 1131 |
div[class*="st-key-lhwrap_"] button[kind="tertiary"]:hover,
|
| 1132 |
div[class*="st-key-lhwrap_"] button[kind="tertiary"]:hover p{
|
| 1133 |
color:var(--navy)!important; text-decoration:none!important; }
|
|
|
|
| 2582 |
with st.container(border=True):
|
| 2583 |
a, bcol = st.columns([6, 2])
|
| 2584 |
with a:
|
| 2585 |
+
st.markdown(f"<span class='sev sev-{c['severity']}'>{str(c['severity']).title()}</span> "
|
| 2586 |
f"<span class='hc-title'>{c['title']}</span>", unsafe_allow_html=True)
|
| 2587 |
st.markdown(f"<span class='hc-fix'>{c['fix']}</span> "
|
| 2588 |
f"<span class='hc-sub'>· {scope_label}</span>", unsafe_allow_html=True)
|
modules/digest.py
CHANGED
|
@@ -1,224 +1,224 @@
|
|
| 1 |
-
"""Daily agent digest — "Your book this morning": one email per user, their queue only.
|
| 2 |
-
|
| 3 |
-
Delivery reuses the ONE sanctioned Odoo write path (modules/collections_send.py: mail.mail
|
| 4 |
-
create through the Office 365 relay) including its SAFE_MODE allow-list — while the guardrail
|
| 5 |
-
is ON no digest can leave the allow-list. Content rules (adoption canon, engagement-adoption
|
| 6 |
-
brief): ≤10 lines, only non-empty sections, every line deep-links back to the exact row
|
| 7 |
-
(?src=digest), and the email is SKIPPED entirely when there is nothing to act on — silence
|
| 8 |
-
keeps opens high. Internal mail: no model/res_id (these must NOT land in customer chatter).
|
| 9 |
-
|
| 10 |
-
Scheduling: app.py starts one daemon ticker (in the cache_resource singleton) that calls
|
| 11 |
-
run_due() every few minutes; run_due sends at most once per (weekday, user) after
|
| 12 |
-
DIGEST_UTC_HOUR (default 11:00 UTC = 7am ET in summer), idempotent across Space restarts via
|
| 13 |
-
the store key 'digest_log' (empty-skips are logged too, so a quiet day isn't rebuilt all day).
|
| 14 |
-
|
| 15 |
-
BU isolation carries into email: a single-BU user's digest is scoped to that BU's team_id.
|
| 16 |
-
"""
|
| 17 |
-
import os
|
| 18 |
-
import html as _html
|
| 19 |
-
import datetime as dt
|
| 20 |
-
|
| 21 |
-
import core.store as store
|
| 22 |
-
import core.users as users
|
| 23 |
-
import core.links as links
|
| 24 |
-
import modules.collections_send as cs
|
| 25 |
-
import modules.customer_data as md # call-list / win-back queues (ex-myday, ex-customer_list)
|
| 26 |
-
import modules.tasks as tasks
|
| 27 |
-
import modules.customers as cust
|
| 28 |
-
|
| 29 |
-
KEY = 'digest_log'
|
| 30 |
-
UTC_HOUR = int(os.environ.get('DIGEST_UTC_HOUR', '11'))
|
| 31 |
-
WEEKDAYS_ONLY = os.environ.get('DIGEST_WEEKDAYS_ONLY', '1').strip().lower() \
|
| 32 |
-
not in ('0', 'false', 'no', '')
|
| 33 |
-
ENABLED = os.environ.get('DIGEST_ENABLED', '1').strip().lower() not in ('0', 'false', 'no', '')
|
| 34 |
-
|
| 35 |
-
_NAVY, _GOLD, _MUTED = '#5B8FD9', '#D9A93A', '#6B7280'
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
def _team_for(user):
|
| 39 |
-
"""Single-BU users get a digest scoped to that BU — isolation carries into email."""
|
| 40 |
-
bus = (user or {}).get('bus', 'all')
|
| 41 |
-
if isinstance(bus, (list, tuple)) and len(bus) == 1:
|
| 42 |
-
return bus[0]
|
| 43 |
-
return None
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
def _m(x):
|
| 47 |
-
try:
|
| 48 |
-
return f"${float(x):,.0f}"
|
| 49 |
-
except (TypeError, ValueError):
|
| 50 |
-
return '—'
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
def _line(text, href, meta=''):
|
| 54 |
-
t = _html.escape(str(text))
|
| 55 |
-
m = f" <span style='color:{_MUTED}'>{_html.escape(str(meta))}</span>" if meta else ''
|
| 56 |
-
return (f"<tr><td style='padding:6px 0;border-bottom:1px solid #ECEFF3;font-size:14px'>"
|
| 57 |
-
f"<a href='{href}' style='color:{_NAVY};text-decoration:none;font-weight:600'>{t}</a>"
|
| 58 |
-
f"{m}</td></tr>")
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
def _sec(title):
|
| 62 |
-
return (f"<tr><td style='padding:14px 0 4px;font-size:
|
| 63 |
-
f"
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
def build(user, t=None):
|
| 67 |
-
"""(subject, html, n_actionable) for one user. n_actionable == 0 → skip the send."""
|
| 68 |
-
t = t or dt.date.today()
|
| 69 |
-
uname = user.get('username', '')
|
| 70 |
-
agent = user.get('agent')
|
| 71 |
-
team_id = _team_for(user)
|
| 72 |
-
pids = md.agent_pids(agent)
|
| 73 |
-
|
| 74 |
-
today = t.isoformat()
|
| 75 |
-
my = [x for x in tasks.for_owner(uname)] if store.available() else []
|
| 76 |
-
due = [x for x in my if (x.get('due') or '9999-12-31') <= today]
|
| 77 |
-
q = md.queues(agent, team_id, limit=25)
|
| 78 |
-
calls, risk = q['calls'][:5], q['risk'][:3]
|
| 79 |
-
|
| 80 |
-
# yesterday's orders for the book (one read_group; skip silently on a transport error —
|
| 81 |
-
# the digest must never fail because one section couldn't be pulled)
|
| 82 |
-
yday = (t - dt.timedelta(days=1)).isoformat()
|
| 83 |
-
y_rev = y_orders = 0
|
| 84 |
-
try:
|
| 85 |
-
rev_map = cust._cust_rev(yday, yday, team_id, pids)
|
| 86 |
-
y_rev = sum(v.get('rev', 0.0) for v in rev_map.values())
|
| 87 |
-
y_orders = sum(v.get('orders', 0) for v in rev_map.values())
|
| 88 |
-
except Exception:
|
| 89 |
-
pass
|
| 90 |
-
|
| 91 |
-
n = len(due) + len(calls) + len(risk)
|
| 92 |
-
if n == 0 and y_orders == 0:
|
| 93 |
-
return None, None, 0
|
| 94 |
-
|
| 95 |
-
rows = []
|
| 96 |
-
if due:
|
| 97 |
-
rows.append(_sec(f'Tasks due ({len(due)})'))
|
| 98 |
-
for x in due[:5]:
|
| 99 |
-
ent = x.get('entity') or {}
|
| 100 |
-
href = links.deeplink('customer_data', src='digest')
|
| 101 |
-
if ent.get('kind') and ent.get('id') is not None:
|
| 102 |
-
href = links.deeplink('customer_data', ent['kind'], ent['id'], src='digest')
|
| 103 |
-
meta = f"due {x.get('due') or '—'}"
|
| 104 |
-
rows.append(_line(x.get('title', 'Task'), href, meta))
|
| 105 |
-
if calls:
|
| 106 |
-
rows.append(_sec('Call today — overdue vs their own cadence'))
|
| 107 |
-
for r in calls:
|
| 108 |
-
href = links.deeplink('customer_data', 'customer', r['pid'], src='digest')
|
| 109 |
-
meta = (f"{int(r.get('overdue_days') or 0)}d past cycle · "
|
| 110 |
-
f"est. missed {_m(r.get('est_missed'))}")
|
| 111 |
-
rows.append(_line(r.get('customer', '?'), href, meta))
|
| 112 |
-
if risk:
|
| 113 |
-
rows.append(_sec('Win-back — down vs last year'))
|
| 114 |
-
for r in risk:
|
| 115 |
-
href = links.deeplink('customer_data', 'customer', r['pid'], src='digest')
|
| 116 |
-
meta = f"{_m(r.get('at_risk'))} at risk · {r.get('status', '')}"
|
| 117 |
-
rows.append(_line(r.get('customer', '?'), href, meta))
|
| 118 |
-
if y_orders:
|
| 119 |
-
rows.append(_sec('Yesterday'))
|
| 120 |
-
rows.append(_line(f"{y_orders} orders · {_m(y_rev)}",
|
| 121 |
-
links.deeplink('sales', src='digest')))
|
| 122 |
-
|
| 123 |
-
scope = f"{agent}'s book" if agent else 'the whole book'
|
| 124 |
-
list_url = links.deeplink('customer_data', src='digest')
|
| 125 |
-
html_body = f"""
|
| 126 |
-
<div style='font-family:Calibri,Arial,sans-serif;color:#1A2332;max-width:600px;margin:0 auto'>
|
| 127 |
-
<div style='border-top:3px solid {_GOLD};padding:16px 0 4px'>
|
| 128 |
-
<div style='font-size:18px;font-weight:700;color:{_NAVY}'>Your book this morning</div>
|
| 129 |
-
<div style='font-size:12px;color:{_MUTED}'>{t.strftime('%A, %B %d')} · {scope}</div>
|
| 130 |
-
</div>
|
| 131 |
-
<table style='width:100%;border-collapse:collapse'>{''.join(rows)}</table>
|
| 132 |
-
<div style='padding:16px 0;font-size:13px'>
|
| 133 |
-
<a href='{list_url}' style='color:{_NAVY};font-weight:700'>Open your Customer List →</a>
|
| 134 |
-
</div>
|
| 135 |
-
<div style='font-size:11px;color:{_MUTED};border-top:1px solid #ECEFF3;padding-top:8px'>
|
| 136 |
-
Internal daily digest from Loopable.
|
| 137 |
-
Sent only on days with something to act on.
|
| 138 |
-
</div>
|
| 139 |
-
</div>"""
|
| 140 |
-
subject = f"Your book this morning — {n} to act on · {t.strftime('%b %d')}"
|
| 141 |
-
return subject, html_body, n
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
def send_one(user, odoo=None, override_to=None):
|
| 145 |
-
"""Build + queue one digest. Returns a short result string (never raises past itself)."""
|
| 146 |
-
to = override_to or user.get('email')
|
| 147 |
-
if not to:
|
| 148 |
-
return 'no-email'
|
| 149 |
-
subject, body, n = build(user)
|
| 150 |
-
if n == 0:
|
| 151 |
-
return 'empty-skip'
|
| 152 |
-
if not cs.safe_recipient_ok(to):
|
| 153 |
-
return 'safe-mode-blocked'
|
| 154 |
-
odoo = odoo or cs.Odoo()
|
| 155 |
-
mid = odoo.queue_mail({
|
| 156 |
-
'subject': subject, 'body_html': body,
|
| 157 |
-
'email_to': to, 'email_from': cs.SENDER_DISPLAY, 'reply_to': cs.REPLY_TO,
|
| 158 |
-
'mail_server_id': cs.ROYAL_MAIL_SERVER_ID, 'author_id': cs.ROYAL_AUTHOR_ID,
|
| 159 |
-
'state': 'outgoing', 'auto_delete': False,
|
| 160 |
-
# This Odoo runs the custom rt_multi_dba module whose mail-create hook browses
|
| 161 |
-
# env[mail.model].browse(mail.res_id) — a mail WITHOUT model/res_id crashes with
|
| 162 |
-
# KeyError: False (verified 2026-07-05). Anchor internal mail on the house partner
|
| 163 |
-
# (Royal Imports, cs.ROYAL_AUTHOR_ID) so nothing lands in a CUSTOMER's chatter.
|
| 164 |
-
'model': 'res.partner', 'res_id': cs.ROYAL_AUTHOR_ID,
|
| 165 |
-
})
|
| 166 |
-
return f'queued:{mid}'
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
def run_due(force_user=None, override_to=None):
|
| 170 |
-
"""The ticker entry point. Normal path: after UTC_HOUR on weekdays, send each active
|
| 171 |
-
emailed user their digest at most once per day (dedup via digest_log, including
|
| 172 |
-
empty-skips). force_user bypasses the schedule/dedup (the 'Send my digest now' button)
|
| 173 |
-
but NEVER the SAFE_MODE guardrail; forced sends are not logged (the 7am run still runs)."""
|
| 174 |
-
if not store.available():
|
| 175 |
-
return {}
|
| 176 |
-
now = dt.datetime.utcnow()
|
| 177 |
-
today = now.date().isoformat()
|
| 178 |
-
if force_user is None:
|
| 179 |
-
if not ENABLED:
|
| 180 |
-
return {}
|
| 181 |
-
if WEEKDAYS_ONLY and now.weekday() >= 5:
|
| 182 |
-
return {}
|
| 183 |
-
if now.hour < UTC_HOUR:
|
| 184 |
-
return {}
|
| 185 |
-
try:
|
| 186 |
-
reg = users.registry()
|
| 187 |
-
except Exception:
|
| 188 |
-
return {}
|
| 189 |
-
already = (store.get(KEY) or {}).get(today, {}) if force_user is None else {}
|
| 190 |
-
results = {}
|
| 191 |
-
odoo = None
|
| 192 |
-
for un, u in sorted(reg.items()):
|
| 193 |
-
if force_user is not None and un != force_user:
|
| 194 |
-
continue
|
| 195 |
-
if not u.get('active', True) or not u.get('email'):
|
| 196 |
-
continue
|
| 197 |
-
if force_user is None and un in already:
|
| 198 |
-
continue
|
| 199 |
-
pub = users._public(un, u)
|
| 200 |
-
try:
|
| 201 |
-
if odoo is None:
|
| 202 |
-
odoo = cs.Odoo()
|
| 203 |
-
results[un] = send_one(pub, odoo, override_to=override_to)
|
| 204 |
-
except cs.SafeModeBlocked:
|
| 205 |
-
results[un] = 'safe-mode-blocked'
|
| 206 |
-
except Exception as e:
|
| 207 |
-
results[un] = f'error:{str(e)[:80]}'
|
| 208 |
-
if force_user is None and results:
|
| 209 |
-
stamp = now.strftime('%H:%M')
|
| 210 |
-
|
| 211 |
-
def _rec(d):
|
| 212 |
-
day = d.setdefault(today, {})
|
| 213 |
-
for un, r in results.items():
|
| 214 |
-
day[un] = {'at': stamp, 'result': r}
|
| 215 |
-
return d
|
| 216 |
-
try:
|
| 217 |
-
store.update(KEY, _rec)
|
| 218 |
-
except Exception:
|
| 219 |
-
pass
|
| 220 |
-
return results
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
def today_log():
|
| 224 |
-
return (store.get(KEY) or {}).get(dt.date.today().isoformat(), {})
|
|
|
|
| 1 |
+
"""Daily agent digest — "Your book this morning": one email per user, their queue only.
|
| 2 |
+
|
| 3 |
+
Delivery reuses the ONE sanctioned Odoo write path (modules/collections_send.py: mail.mail
|
| 4 |
+
create through the Office 365 relay) including its SAFE_MODE allow-list — while the guardrail
|
| 5 |
+
is ON no digest can leave the allow-list. Content rules (adoption canon, engagement-adoption
|
| 6 |
+
brief): ≤10 lines, only non-empty sections, every line deep-links back to the exact row
|
| 7 |
+
(?src=digest), and the email is SKIPPED entirely when there is nothing to act on — silence
|
| 8 |
+
keeps opens high. Internal mail: no model/res_id (these must NOT land in customer chatter).
|
| 9 |
+
|
| 10 |
+
Scheduling: app.py starts one daemon ticker (in the cache_resource singleton) that calls
|
| 11 |
+
run_due() every few minutes; run_due sends at most once per (weekday, user) after
|
| 12 |
+
DIGEST_UTC_HOUR (default 11:00 UTC = 7am ET in summer), idempotent across Space restarts via
|
| 13 |
+
the store key 'digest_log' (empty-skips are logged too, so a quiet day isn't rebuilt all day).
|
| 14 |
+
|
| 15 |
+
BU isolation carries into email: a single-BU user's digest is scoped to that BU's team_id.
|
| 16 |
+
"""
|
| 17 |
+
import os
|
| 18 |
+
import html as _html
|
| 19 |
+
import datetime as dt
|
| 20 |
+
|
| 21 |
+
import core.store as store
|
| 22 |
+
import core.users as users
|
| 23 |
+
import core.links as links
|
| 24 |
+
import modules.collections_send as cs
|
| 25 |
+
import modules.customer_data as md # call-list / win-back queues (ex-myday, ex-customer_list)
|
| 26 |
+
import modules.tasks as tasks
|
| 27 |
+
import modules.customers as cust
|
| 28 |
+
|
| 29 |
+
KEY = 'digest_log'
|
| 30 |
+
UTC_HOUR = int(os.environ.get('DIGEST_UTC_HOUR', '11'))
|
| 31 |
+
WEEKDAYS_ONLY = os.environ.get('DIGEST_WEEKDAYS_ONLY', '1').strip().lower() \
|
| 32 |
+
not in ('0', 'false', 'no', '')
|
| 33 |
+
ENABLED = os.environ.get('DIGEST_ENABLED', '1').strip().lower() not in ('0', 'false', 'no', '')
|
| 34 |
+
|
| 35 |
+
_NAVY, _GOLD, _MUTED = '#5B8FD9', '#D9A93A', '#6B7280'
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _team_for(user):
|
| 39 |
+
"""Single-BU users get a digest scoped to that BU — isolation carries into email."""
|
| 40 |
+
bus = (user or {}).get('bus', 'all')
|
| 41 |
+
if isinstance(bus, (list, tuple)) and len(bus) == 1:
|
| 42 |
+
return bus[0]
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _m(x):
|
| 47 |
+
try:
|
| 48 |
+
return f"${float(x):,.0f}"
|
| 49 |
+
except (TypeError, ValueError):
|
| 50 |
+
return '—'
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _line(text, href, meta=''):
|
| 54 |
+
t = _html.escape(str(text))
|
| 55 |
+
m = f" <span style='color:{_MUTED}'>{_html.escape(str(meta))}</span>" if meta else ''
|
| 56 |
+
return (f"<tr><td style='padding:6px 0;border-bottom:1px solid #ECEFF3;font-size:14px'>"
|
| 57 |
+
f"<a href='{href}' style='color:{_NAVY};text-decoration:none;font-weight:600'>{t}</a>"
|
| 58 |
+
f"{m}</td></tr>")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _sec(title):
|
| 62 |
+
return (f"<tr><td style='padding:14px 0 4px;font-size:12.5px;font-weight:700;"
|
| 63 |
+
f"color:{_MUTED}'>{_html.escape(title)}</td></tr>")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def build(user, t=None):
|
| 67 |
+
"""(subject, html, n_actionable) for one user. n_actionable == 0 → skip the send."""
|
| 68 |
+
t = t or dt.date.today()
|
| 69 |
+
uname = user.get('username', '')
|
| 70 |
+
agent = user.get('agent')
|
| 71 |
+
team_id = _team_for(user)
|
| 72 |
+
pids = md.agent_pids(agent)
|
| 73 |
+
|
| 74 |
+
today = t.isoformat()
|
| 75 |
+
my = [x for x in tasks.for_owner(uname)] if store.available() else []
|
| 76 |
+
due = [x for x in my if (x.get('due') or '9999-12-31') <= today]
|
| 77 |
+
q = md.queues(agent, team_id, limit=25)
|
| 78 |
+
calls, risk = q['calls'][:5], q['risk'][:3]
|
| 79 |
+
|
| 80 |
+
# yesterday's orders for the book (one read_group; skip silently on a transport error —
|
| 81 |
+
# the digest must never fail because one section couldn't be pulled)
|
| 82 |
+
yday = (t - dt.timedelta(days=1)).isoformat()
|
| 83 |
+
y_rev = y_orders = 0
|
| 84 |
+
try:
|
| 85 |
+
rev_map = cust._cust_rev(yday, yday, team_id, pids)
|
| 86 |
+
y_rev = sum(v.get('rev', 0.0) for v in rev_map.values())
|
| 87 |
+
y_orders = sum(v.get('orders', 0) for v in rev_map.values())
|
| 88 |
+
except Exception:
|
| 89 |
+
pass
|
| 90 |
+
|
| 91 |
+
n = len(due) + len(calls) + len(risk)
|
| 92 |
+
if n == 0 and y_orders == 0:
|
| 93 |
+
return None, None, 0
|
| 94 |
+
|
| 95 |
+
rows = []
|
| 96 |
+
if due:
|
| 97 |
+
rows.append(_sec(f'Tasks due ({len(due)})'))
|
| 98 |
+
for x in due[:5]:
|
| 99 |
+
ent = x.get('entity') or {}
|
| 100 |
+
href = links.deeplink('customer_data', src='digest')
|
| 101 |
+
if ent.get('kind') and ent.get('id') is not None:
|
| 102 |
+
href = links.deeplink('customer_data', ent['kind'], ent['id'], src='digest')
|
| 103 |
+
meta = f"due {x.get('due') or '—'}"
|
| 104 |
+
rows.append(_line(x.get('title', 'Task'), href, meta))
|
| 105 |
+
if calls:
|
| 106 |
+
rows.append(_sec('Call today — overdue vs their own cadence'))
|
| 107 |
+
for r in calls:
|
| 108 |
+
href = links.deeplink('customer_data', 'customer', r['pid'], src='digest')
|
| 109 |
+
meta = (f"{int(r.get('overdue_days') or 0)}d past cycle · "
|
| 110 |
+
f"est. missed {_m(r.get('est_missed'))}")
|
| 111 |
+
rows.append(_line(r.get('customer', '?'), href, meta))
|
| 112 |
+
if risk:
|
| 113 |
+
rows.append(_sec('Win-back — down vs last year'))
|
| 114 |
+
for r in risk:
|
| 115 |
+
href = links.deeplink('customer_data', 'customer', r['pid'], src='digest')
|
| 116 |
+
meta = f"{_m(r.get('at_risk'))} at risk · {r.get('status', '')}"
|
| 117 |
+
rows.append(_line(r.get('customer', '?'), href, meta))
|
| 118 |
+
if y_orders:
|
| 119 |
+
rows.append(_sec('Yesterday'))
|
| 120 |
+
rows.append(_line(f"{y_orders} orders · {_m(y_rev)}",
|
| 121 |
+
links.deeplink('sales', src='digest')))
|
| 122 |
+
|
| 123 |
+
scope = f"{agent}'s book" if agent else 'the whole book'
|
| 124 |
+
list_url = links.deeplink('customer_data', src='digest')
|
| 125 |
+
html_body = f"""
|
| 126 |
+
<div style='font-family:Calibri,Arial,sans-serif;color:#1A2332;max-width:600px;margin:0 auto'>
|
| 127 |
+
<div style='border-top:3px solid {_GOLD};padding:16px 0 4px'>
|
| 128 |
+
<div style='font-size:18px;font-weight:700;color:{_NAVY}'>Your book this morning</div>
|
| 129 |
+
<div style='font-size:12px;color:{_MUTED}'>{t.strftime('%A, %B %d')} · {scope}</div>
|
| 130 |
+
</div>
|
| 131 |
+
<table style='width:100%;border-collapse:collapse'>{''.join(rows)}</table>
|
| 132 |
+
<div style='padding:16px 0;font-size:13px'>
|
| 133 |
+
<a href='{list_url}' style='color:{_NAVY};font-weight:700'>Open your Customer List →</a>
|
| 134 |
+
</div>
|
| 135 |
+
<div style='font-size:11px;color:{_MUTED};border-top:1px solid #ECEFF3;padding-top:8px'>
|
| 136 |
+
Internal daily digest from Loopable.
|
| 137 |
+
Sent only on days with something to act on.
|
| 138 |
+
</div>
|
| 139 |
+
</div>"""
|
| 140 |
+
subject = f"Your book this morning — {n} to act on · {t.strftime('%b %d')}"
|
| 141 |
+
return subject, html_body, n
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def send_one(user, odoo=None, override_to=None):
|
| 145 |
+
"""Build + queue one digest. Returns a short result string (never raises past itself)."""
|
| 146 |
+
to = override_to or user.get('email')
|
| 147 |
+
if not to:
|
| 148 |
+
return 'no-email'
|
| 149 |
+
subject, body, n = build(user)
|
| 150 |
+
if n == 0:
|
| 151 |
+
return 'empty-skip'
|
| 152 |
+
if not cs.safe_recipient_ok(to):
|
| 153 |
+
return 'safe-mode-blocked'
|
| 154 |
+
odoo = odoo or cs.Odoo()
|
| 155 |
+
mid = odoo.queue_mail({
|
| 156 |
+
'subject': subject, 'body_html': body,
|
| 157 |
+
'email_to': to, 'email_from': cs.SENDER_DISPLAY, 'reply_to': cs.REPLY_TO,
|
| 158 |
+
'mail_server_id': cs.ROYAL_MAIL_SERVER_ID, 'author_id': cs.ROYAL_AUTHOR_ID,
|
| 159 |
+
'state': 'outgoing', 'auto_delete': False,
|
| 160 |
+
# This Odoo runs the custom rt_multi_dba module whose mail-create hook browses
|
| 161 |
+
# env[mail.model].browse(mail.res_id) — a mail WITHOUT model/res_id crashes with
|
| 162 |
+
# KeyError: False (verified 2026-07-05). Anchor internal mail on the house partner
|
| 163 |
+
# (Royal Imports, cs.ROYAL_AUTHOR_ID) so nothing lands in a CUSTOMER's chatter.
|
| 164 |
+
'model': 'res.partner', 'res_id': cs.ROYAL_AUTHOR_ID,
|
| 165 |
+
})
|
| 166 |
+
return f'queued:{mid}'
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def run_due(force_user=None, override_to=None):
|
| 170 |
+
"""The ticker entry point. Normal path: after UTC_HOUR on weekdays, send each active
|
| 171 |
+
emailed user their digest at most once per day (dedup via digest_log, including
|
| 172 |
+
empty-skips). force_user bypasses the schedule/dedup (the 'Send my digest now' button)
|
| 173 |
+
but NEVER the SAFE_MODE guardrail; forced sends are not logged (the 7am run still runs)."""
|
| 174 |
+
if not store.available():
|
| 175 |
+
return {}
|
| 176 |
+
now = dt.datetime.utcnow()
|
| 177 |
+
today = now.date().isoformat()
|
| 178 |
+
if force_user is None:
|
| 179 |
+
if not ENABLED:
|
| 180 |
+
return {}
|
| 181 |
+
if WEEKDAYS_ONLY and now.weekday() >= 5:
|
| 182 |
+
return {}
|
| 183 |
+
if now.hour < UTC_HOUR:
|
| 184 |
+
return {}
|
| 185 |
+
try:
|
| 186 |
+
reg = users.registry()
|
| 187 |
+
except Exception:
|
| 188 |
+
return {}
|
| 189 |
+
already = (store.get(KEY) or {}).get(today, {}) if force_user is None else {}
|
| 190 |
+
results = {}
|
| 191 |
+
odoo = None
|
| 192 |
+
for un, u in sorted(reg.items()):
|
| 193 |
+
if force_user is not None and un != force_user:
|
| 194 |
+
continue
|
| 195 |
+
if not u.get('active', True) or not u.get('email'):
|
| 196 |
+
continue
|
| 197 |
+
if force_user is None and un in already:
|
| 198 |
+
continue
|
| 199 |
+
pub = users._public(un, u)
|
| 200 |
+
try:
|
| 201 |
+
if odoo is None:
|
| 202 |
+
odoo = cs.Odoo()
|
| 203 |
+
results[un] = send_one(pub, odoo, override_to=override_to)
|
| 204 |
+
except cs.SafeModeBlocked:
|
| 205 |
+
results[un] = 'safe-mode-blocked'
|
| 206 |
+
except Exception as e:
|
| 207 |
+
results[un] = f'error:{str(e)[:80]}'
|
| 208 |
+
if force_user is None and results:
|
| 209 |
+
stamp = now.strftime('%H:%M')
|
| 210 |
+
|
| 211 |
+
def _rec(d):
|
| 212 |
+
day = d.setdefault(today, {})
|
| 213 |
+
for un, r in results.items():
|
| 214 |
+
day[un] = {'at': stamp, 'result': r}
|
| 215 |
+
return d
|
| 216 |
+
try:
|
| 217 |
+
store.update(KEY, _rec)
|
| 218 |
+
except Exception:
|
| 219 |
+
pass
|
| 220 |
+
return results
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def today_log():
|
| 224 |
+
return (store.get(KEY) or {}).get(dt.date.today().isoformat(), {})
|
modules/sales.py
CHANGED
|
@@ -724,13 +724,27 @@ def validate(t=None, team_id=None):
|
|
| 724 |
'gap': round(cust_sum - order_rev, 2),
|
| 725 |
'ok': abs(cust_sum - order_rev) <= 1.0})
|
| 726 |
|
| 727 |
-
# 4. Σ(category revenue) == line-level total (YTD)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 728 |
cat_sum = sum(c['revenue'] for c in by_category(t, limit=10**9, team_id=team_id))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 729 |
checks.append({
|
| 730 |
'check': 'YTD revenue: Σ(category) == line-level total',
|
| 731 |
-
'a': round(cat_sum, 2), 'b': round(
|
| 732 |
-
'gap': round(cat_sum -
|
| 733 |
-
'ok': abs(cat_sum -
|
| 734 |
|
| 735 |
# 6. Cadence: Σ(frequency-bucket customers) == total LTM customers
|
| 736 |
cad = cadence(t, team_id=team_id)
|
|
|
|
| 724 |
'gap': round(cust_sum - order_rev, 2),
|
| 725 |
'ok': abs(cust_sum - order_rev) <= 1.0})
|
| 726 |
|
| 727 |
+
# 4. Σ(category revenue) == line-level total (YTD) — SAME-SOURCE on purpose (wave-14 debt
|
| 728 |
+
# sweep). `by_category` reads the DATASTORE mirror when USE_STORE while `line_rev` above is
|
| 729 |
+
# LIVE Odoo, so this check used to compare two sources and went red on a pending sync
|
| 730 |
+
# (a stable +2,499.90 measured twice 75s apart, 2026-08-02 — the same mixed-source
|
| 731 |
+
# signature as the wave-13 ±$8.5k triple, which healed on resync). The decomposition's
|
| 732 |
+
# claim — every line lands in exactly one category, none lost, none doubled — must be
|
| 733 |
+
# judged against the SAME rows the decomposition consumed; order-vs-line freshness is
|
| 734 |
+
# check 1's job, on one source.
|
| 735 |
cat_sum = sum(c['revenue'] for c in by_category(t, limit=10**9, team_id=team_id))
|
| 736 |
+
cat_line_total = line_rev
|
| 737 |
+
if USE_STORE:
|
| 738 |
+
try:
|
| 739 |
+
cat_line_total = sum((amt or 0.0) for _pid, amt in
|
| 740 |
+
_line_rev_by_product_store(yf, yt, team_id))
|
| 741 |
+
except Exception:
|
| 742 |
+
pass
|
| 743 |
checks.append({
|
| 744 |
'check': 'YTD revenue: Σ(category) == line-level total',
|
| 745 |
+
'a': round(cat_sum, 2), 'b': round(cat_line_total, 2),
|
| 746 |
+
'gap': round(cat_sum - cat_line_total, 2),
|
| 747 |
+
'ok': abs(cat_sum - cat_line_total) <= 1.0})
|
| 748 |
|
| 749 |
# 6. Cadence: Σ(frequency-bucket customers) == total LTM customers
|
| 750 |
cad = cadence(t, team_id=team_id)
|