Guest state: provisioned-but-not-set-up reads 'invited', never 'active'

A guest invitation provisions immediately, but the Cloudron account is not
ACCEPTED until the guest clicks the setup link (inviteAccepted=false, no
username) — until then they cannot log in, so no surface may read them as
active. guest_invite_pending() derives it from the same Cloudron signal the
overview's activated flag uses; unseen-record (users fetch failed) is never
pending, so the state falls back instead of asserting what the data does
not show.

/admin/overview: guest rows report state='invited' with an 'awaiting
setup' reason (invite date named when the ledger has it); /broker/guests
trail entries carry state='invited' the same way, status stays the ledger
record of record. Display/state semantics only — access rules, the $2 cap
and the expiry box are unchanged.

Tests: new test_guest_invited_state.py (derivation, overview flip,
fetch-failure fallback, member rows untouched, trail state);
test_guest_requests.py gains the trail invited/accepted assertions and a
constructible-but-loud fake client so the stubbed users fetch runs.
This commit is contained in:
Inferencebot committed 2026-11-08 20:40:23 +00:00
1 parent f592e5b7b5
commit 88ca8bfe18
3 files changed
+414 -10

No files matched your search

+80 -9
View File
@@ -4681,14 +4681,16 @@ async def admin_overview(request: Request):
"account_type, oc_email, guest_expires_at FROM members ORDER BY email"
).fetchall()
# Guest inviter/expiry from the guests ledger (latest row per recipient) —
# the abuse-protection context the panel shows on the guest pill.
# the abuse-protection context the panel shows on the guest pill, plus the
# invite date for the invited (awaiting setup) reason line.
guest_info: dict[str, dict] = {}
try:
for r in conn.execute(
"SELECT recipient_email, inviter_email, guest_expires_at, status "
"SELECT recipient_email, inviter_email, guest_expires_at, status, created_at "
"FROM guests WHERE id IN (SELECT MAX(id) FROM guests GROUP BY recipient_email)"
).fetchall():
guest_info[r[0]] = {"inviter": r[1], "expires": r[2], "status": r[3]}
guest_info[r[0]] = {"inviter": r[1], "expires": r[2], "status": r[3],
"sent": r[4]}
except Exception as e:
logger.warning("admin overview: guests ledger read failed: %s", e)
conn.close()
@@ -4777,6 +4779,20 @@ async def admin_overview(request: Request):
spend,
)
mstate, mstate_reason = member_membership_state(email, bool(active))
if ((acct_type or "member") == "guest" and active
and guest_invite_pending(user_id, usernames, invite_accepted)):
# A provisioned-but-NOT-set-up guest: the invitation is out but the
# guest has not accepted it (inviteAccepted false / no username), so
# they cannot log in yet. Reads as 'invited' — never 'active' —
# until acceptance flips it. Display/state semantics only: access
# rules, the $2 cap and the expiry box are unchanged (an unaccepted
# guest cannot reach anything anyway — the setup link is the only
# door in).
sent = (guest_info.get(email) or {}).get("sent")
mstate = "invited"
mstate_reason = (f"awaiting setup — invite sent {str(sent)[:10]}, "
"not yet accepted" if sent else
"awaiting setup — invitation not yet accepted")
entry = {
"email": email,
"all_time_spend": round(member_all_time, 2),
@@ -6055,7 +6071,11 @@ async def broker_guest_list(request: Request):
REJECTED requests from the trial-approval period (kept for history;
nothing new is ever decided) plus every row in the guests ledger
with what became of it (active, converted, expired, depleted,
cancelled by recipient).
cancelled by recipient). Each guest entry also carries `state` —
'invited' while the guest has not accepted their Cloudron invite
(provisioned but awaiting setup, cannot log in yet), else the
ledger status; consumers should render `state` and fall back to
`status` only when it is absent (older payloads).
"""
email = _verify_broker_secret(request)
conn = get_db()
@@ -6065,8 +6085,10 @@ async def broker_guest_list(request: Request):
(email,),
).fetchall()
sent = conn.execute(
"SELECT recipient_email, created_at, status "
"FROM guests WHERE inviter_email = ? ORDER BY id DESC",
"SELECT g.recipient_email, g.created_at, g.status, "
"m.cloudron_user_id, m.active, m.account_type "
"FROM guests g LEFT JOIN members m ON m.email = g.recipient_email "
"WHERE g.inviter_email = ? ORDER BY g.id DESC",
(email,),
).fetchall()
window = f"-{int(GUEST_PER_INVITER_DAYS)} days"
@@ -6077,6 +6099,24 @@ async def broker_guest_list(request: Request):
).fetchone()[0]
conn.close()
# Invite acceptance per trail guest — the same Cloudron signal the admin
# overview uses (username + inviteAccepted). Fetched once, fail-soft: when
# the fetch fails the invited state is simply not claimed and the trail
# keeps showing the ledger status.
usernames: dict[str, str] = {}
invite_accepted: dict[str, bool] = {}
try:
async with httpx.AsyncClient(timeout=15.0) as client:
users = await cloudron_fetch_all_users(client)
if users is not None:
for u in users:
uid = u.get("id")
if u.get("username"):
usernames[uid] = u["username"]
invite_accepted[uid] = bool(u.get("inviteAccepted"))
except Exception as e:
logger.warning("broker guests: cloudron users fetch failed: %s", e)
eligible = last_sent is None
next_eligible_at = None
if not eligible:
@@ -6094,9 +6134,18 @@ async def broker_guest_list(request: Request):
"name": rname, "created_at": created, "decided_at": decided,
"status": status, "note": note,
})
for recipient, created, status in sent:
trail.append({"kind": "guest", "recipient": recipient,
"created_at": created, "status": status})
for recipient, created, status, user_id, g_active, g_type in sent:
entry = {"kind": "guest", "recipient": recipient,
"created_at": created, "status": status}
if ((g_type or "member") == "guest" and g_active
and guest_invite_pending(user_id, usernames, invite_accepted)):
# Provisioned but the invite is not accepted yet — display as
# 'invited', never 'active' (the guest cannot log in until they
# accept; the ledger status stays the trail's record of record).
entry["state"] = "invited"
else:
entry["state"] = status
trail.append(entry)
trail.sort(key=lambda t: t.get("decided_at") or t["created_at"] or "", reverse=True)
return {
"eligible": eligible,
@@ -6511,6 +6560,28 @@ def member_membership_state(email: str, active: bool) -> tuple[str, str]:
return "active", ""
def guest_invite_pending(user_id, usernames: dict, invite_accepted: dict) -> bool:
"""True when a guest's Cloudron invite is OUT but NOT yet accepted.
The provisioned-but-not-set-up state: the Cloudron account exists (the
invitation email with the setup link went out) but the guest has not
clicked it — inviteAccepted is false and no username is chosen, so they
cannot log in yet. Derived the same way the overview's `activated` flag
is (username and inviteAccepted move in lockstep for invite-created
accounts); NOT accepted = inviteAccepted false AND no username.
Only a SEEN user record can be pending: when the Cloudron users fetch
failed (or the user is unknown to it) the evidence is absent, and the
caller must fall back to the membership state rather than claim
'invited' — never assert a state the data does not show.
"""
if not user_id:
return False
if user_id not in invite_accepted and user_id not in usernames:
return False
return not (invite_accepted.get(user_id, False) or bool(usernames.get(user_id)))
def _parse_oc_dt(value):
"""Parse an Open Collective ISO timestamp ('…Z') into an aware datetime."""