Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b3de608170 | ||
|
|
f1ba9d7313 |
No files matched your search
@@ -31,5 +31,5 @@
|
||||
"manifestVersion": 2,
|
||||
"website": "https://inference.coop",
|
||||
"contactEmail": "info@inference.coop",
|
||||
"dockerImage": "registry.inference.coop/code/member-portal:20261123-db0c09e"
|
||||
"dockerImage": "registry.inference.coop/code/member-portal:20261123-419b1f4"
|
||||
}
|
||||
+241
-8
@@ -1035,6 +1035,116 @@ def _verify_admin_token(request: Request) -> None:
|
||||
raise HTTPException(403, "Forbidden")
|
||||
|
||||
|
||||
def _backfill_membership_events(conn: sqlite3.Connection) -> None:
|
||||
"""Give every already-inactive member a deactivation row (once).
|
||||
|
||||
The portal kept inactive members only as members.active = 0, so the two
|
||||
members who lapsed before this table existed had no event record. This
|
||||
backfill derives the best available reason from the allowance/reminder
|
||||
trail and inserts ONE deactivated row per member. occurred_at stays NULL:
|
||||
the exact lapse date is not recorded anywhere, and inventing one would make
|
||||
the log lie. The portal_state marker keeps it to one pass.
|
||||
"""
|
||||
try:
|
||||
done = conn.execute(
|
||||
"SELECT value FROM portal_state WHERE key = 'membership_events_backfill_v1'"
|
||||
).fetchone()
|
||||
if done:
|
||||
return
|
||||
tables = {r[0] for r in conn.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table'"
|
||||
).fetchall()}
|
||||
rows = conn.execute(
|
||||
"SELECT email, COALESCE(account_type, 'member'), welcome_sent_at "
|
||||
"FROM members WHERE active = 0"
|
||||
).fetchall()
|
||||
for email, acct_type, welcome_sent_at in rows:
|
||||
# Guests have their own ledger and are not members; never backfill
|
||||
# a guest into the member log.
|
||||
if (acct_type or "member") == "guest":
|
||||
continue
|
||||
if conn.execute(
|
||||
"SELECT 1 FROM membership_events "
|
||||
"WHERE email = ? AND event = 'deactivated' LIMIT 1",
|
||||
(email,),
|
||||
).fetchone():
|
||||
continue
|
||||
latest = reminded = None
|
||||
if "allowance_log" in tables:
|
||||
latest = conn.execute(
|
||||
"SELECT decision, evidence, decided_at FROM allowance_log "
|
||||
"WHERE email = ? ORDER BY decided_at DESC, id DESC LIMIT 1",
|
||||
(email,),
|
||||
).fetchone()
|
||||
if "payment_reminders" in tables:
|
||||
reminded = conn.execute(
|
||||
"SELECT sent_at FROM payment_reminders WHERE email = ? "
|
||||
"ORDER BY sent_at DESC LIMIT 1",
|
||||
(email,),
|
||||
).fetchone()
|
||||
if latest:
|
||||
decision, evidence, decided_at = latest
|
||||
reason = (
|
||||
f"Membership lapsed; last allowance decision '{decision}' "
|
||||
f"({str(decided_at or '')[:10] or 'undated'}): {evidence or 'no evidence recorded'}"
|
||||
)
|
||||
detail = "Backfilled from allowance_log; exact deactivation date unknown."
|
||||
elif reminded:
|
||||
reason = (
|
||||
"Membership lapsed after a payment reminder sent "
|
||||
f"{str(reminded[0] or '')[:10]}; no later renewal recorded."
|
||||
)
|
||||
detail = "Backfilled from payment_reminders; exact deactivation date unknown."
|
||||
else:
|
||||
reason = (
|
||||
"Membership lapsed; no allowance or reminder trail was recorded"
|
||||
+ (f" (provisioned {str(welcome_sent_at)[:10]})" if welcome_sent_at else "")
|
||||
+ "."
|
||||
)
|
||||
detail = "Backfilled from the inactive members row; cause and date unknown."
|
||||
conn.execute(
|
||||
"INSERT INTO membership_events "
|
||||
"(email, account_type, event, reason, source, occurred_at, detail) "
|
||||
"VALUES (?, ?, 'deactivated', ?, 'backfill', NULL, ?)",
|
||||
(email, acct_type or "member", reason, detail),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO portal_state (key, value) "
|
||||
"VALUES ('membership_events_backfill_v1', datetime('now'))"
|
||||
)
|
||||
except sqlite3.OperationalError as e:
|
||||
# A fresh/partial database may not yet have the trail tables. Leave the
|
||||
# marker unset so a later pass retries once they exist.
|
||||
logger.warning("membership events backfill skipped: %s", e)
|
||||
|
||||
|
||||
def record_membership_event(
|
||||
conn: sqlite3.Connection,
|
||||
email: str,
|
||||
event: str,
|
||||
reason: str = "",
|
||||
source: str = "",
|
||||
account_type: str = "member",
|
||||
occurred_at: str | None = None,
|
||||
detail: str = "",
|
||||
) -> None:
|
||||
"""Append one membership transition to the durable log."""
|
||||
conn.execute(
|
||||
"INSERT INTO membership_events "
|
||||
"(email, account_type, event, reason, source, occurred_at, detail) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
(
|
||||
email,
|
||||
account_type or "member",
|
||||
event,
|
||||
reason or "",
|
||||
source or "",
|
||||
occurred_at or datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S"),
|
||||
detail or "",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def get_db() -> sqlite3.Connection:
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.execute(
|
||||
@@ -1046,6 +1156,29 @@ def get_db() -> sqlite3.Connection:
|
||||
"active INTEGER DEFAULT 1"
|
||||
")"
|
||||
)
|
||||
# Membership events — the durable answer to "who was a member, and what
|
||||
# happened to them". The members row keeps only the CURRENT flag (active
|
||||
# 1/0); without this table a lapse left no record of WHEN or WHY, so a
|
||||
# former member was indistinguishable from one who never paid. Every
|
||||
# deactivation/reactivation transition writes one row; backfilled rows
|
||||
# carry occurred_at NULL because the exact historical date is unknown.
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS membership_events ("
|
||||
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
|
||||
"email TEXT NOT NULL, "
|
||||
"account_type TEXT NOT NULL DEFAULT 'member', "
|
||||
"event TEXT NOT NULL, "
|
||||
"reason TEXT NOT NULL DEFAULT '', "
|
||||
"source TEXT NOT NULL DEFAULT '', "
|
||||
"occurred_at TEXT, "
|
||||
"recorded_at TEXT NOT NULL DEFAULT (datetime('now')), "
|
||||
"detail TEXT NOT NULL DEFAULT ''"
|
||||
")"
|
||||
)
|
||||
conn.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_membership_events_email "
|
||||
"ON membership_events(email, id)"
|
||||
)
|
||||
# Daily metrics snapshot, written by /app/code/metrics_snapshot.py from the
|
||||
# scheduler and read by the admin panel + dashboard. Cumulative columns
|
||||
# (members_*, newsletter_subs, matrix_space_members) are counts AS OF that
|
||||
@@ -1368,6 +1501,10 @@ def get_db() -> sqlite3.Connection:
|
||||
# CRITICAL log if PORTAL_KEK is unset — see the inline key-encryption module.
|
||||
migrate_plaintext_keys(conn)
|
||||
|
||||
# One-time backfill for members who lapsed before the events table existed.
|
||||
# Runs after portal_state exists; the marker inside keeps it to one pass.
|
||||
_backfill_membership_events(conn)
|
||||
|
||||
# Commit the DML above — ALTER TABLE auto-commits, but the UPDATEs open an
|
||||
# implicit transaction that would otherwise roll back when get_db() closes.
|
||||
conn.commit()
|
||||
@@ -2818,6 +2955,12 @@ def store_member(email: str, key_token: str, cloudron_user_id: str, slug: str =
|
||||
row = conn.execute("SELECT slug FROM members WHERE email = ?", (email,)).fetchone()
|
||||
if row and row[0]:
|
||||
slug = row[0]
|
||||
# Reactivation is a transition worth keeping: a former member who returns
|
||||
# gets active=1 here, and the log must show that alongside the lapse.
|
||||
prior = conn.execute(
|
||||
"SELECT active, COALESCE(account_type, 'member') FROM members WHERE email = ?",
|
||||
(email,),
|
||||
).fetchone()
|
||||
# account_type: None (every normal path) preserves whatever the row holds —
|
||||
# re-provisioning a guest via the member pipeline must not un-guest it. Only
|
||||
# an explicit value (provision_guest_member passes 'guest') writes the column.
|
||||
@@ -2830,6 +2973,12 @@ def store_member(email: str, key_token: str, cloudron_user_id: str, slug: str =
|
||||
"ELSE COALESCE(members.account_type, 'member') END",
|
||||
(email, encrypt_key(key_token), cloudron_user_id, slug, account_type),
|
||||
)
|
||||
if prior and not prior[0] and (prior[1] or "member") != "guest":
|
||||
record_membership_event(
|
||||
conn, email, "reactivated",
|
||||
reason="Returned to active membership (provisioned again)",
|
||||
source="provision", account_type=prior[1] or "member",
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
@@ -2882,13 +3031,25 @@ def get_member_by_slug(slug: str) -> dict | None:
|
||||
return {"email": row[0], "key_token": decrypt_key(row[1]), "cloudron_user_id": row[2]}
|
||||
|
||||
|
||||
def deactivate_member(email: str) -> str | None:
|
||||
"""Mark member inactive and return their DECRYPTED key token (for deletion)."""
|
||||
def deactivate_member(email: str, reason: str = "", source: str = "",
|
||||
detail: str = "") -> str | None:
|
||||
"""Mark member inactive, log the transition, and return the DECRYPTED key.
|
||||
|
||||
The log row is written ONLY on the active → inactive transition, so an OC
|
||||
re-delivery (or a second sweep pass) cannot append duplicate "deactivated"
|
||||
events for one lapse.
|
||||
"""
|
||||
conn = get_db()
|
||||
row = conn.execute(
|
||||
"SELECT key_token FROM members WHERE email = ?", (email,)
|
||||
"SELECT key_token, active, COALESCE(account_type, 'member') "
|
||||
"FROM members WHERE email = ?", (email,)
|
||||
).fetchone()
|
||||
conn.execute("UPDATE members SET active = 0 WHERE email = ?", (email,))
|
||||
if row and row[1]:
|
||||
record_membership_event(
|
||||
conn, email, "deactivated", reason=reason, source=source,
|
||||
account_type=row[2], detail=detail,
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return decrypt_key(row[0]) if row else None
|
||||
@@ -3762,7 +3923,12 @@ async def reconcile_guest_lifecycles() -> dict:
|
||||
continue
|
||||
if INACTIVE_GROUP_ID and user_id:
|
||||
await cloudron_switch_group(user_id, INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,))
|
||||
deactivate_member(email)
|
||||
deactivate_member(
|
||||
email,
|
||||
reason=f"Guest access ended ({reason})",
|
||||
source="sweep-guest",
|
||||
detail=f"guest lifecycle rule: {reason}",
|
||||
)
|
||||
await revoke_member_litellm_access(email)
|
||||
await listmonk_sync(email, subscribe=False)
|
||||
conn = get_db()
|
||||
@@ -3911,7 +4077,12 @@ async def cancel_guest_account(email: str) -> dict:
|
||||
|
||||
# Deactivation, guest-lapse semantics: row inactive, group out of guests,
|
||||
# gateway budget zeroed, newsletter off.
|
||||
deactivate_member(email)
|
||||
deactivate_member(
|
||||
email,
|
||||
reason="Guest cancelled by recipient",
|
||||
source="guest-self-cancel",
|
||||
detail="unspent guest credit returned to the co-op",
|
||||
)
|
||||
ended_group = GUESTS_ENDED_GROUP_ID or INACTIVE_GROUP_ID
|
||||
if ended_group and user_id:
|
||||
await cloudron_switch_group(user_id, ended_group, (GUESTS_GROUP_ID,))
|
||||
@@ -4914,7 +5085,12 @@ async def _process_opencollective_webhook(request: Request, token: str):
|
||||
if INACTIVE_GROUP_ID and member.get("cloudron_user_id"):
|
||||
await cloudron_switch_group(member["cloudron_user_id"], INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,))
|
||||
# Mark inactive in our DB (key injector will refuse requests)
|
||||
deactivate_member(member["email"])
|
||||
deactivate_member(
|
||||
member["email"],
|
||||
reason=f"Open Collective membership deleted (slug {slug})",
|
||||
source="webhook-opencollective",
|
||||
detail="collective.member.deleted after OC live-roster re-check",
|
||||
)
|
||||
await revoke_member_litellm_access(member["email"])
|
||||
await listmonk_sync(member["email"], subscribe=False)
|
||||
await sync_loomio_memberships()
|
||||
@@ -5747,6 +5923,36 @@ OPERATOR_EMAILS = {
|
||||
}
|
||||
|
||||
|
||||
def _membership_events_for_overview(conn: sqlite3.Connection) -> tuple[list[dict], dict[str, dict]]:
|
||||
"""Return (newest-first event log, latest deactivation per member email)."""
|
||||
events = [
|
||||
{
|
||||
"id": r[0], "email": r[1], "account_type": r[2], "event": r[3],
|
||||
"reason": r[4] or "", "source": r[5] or "",
|
||||
"occurred_at": r[6], "recorded_at": r[7], "detail": r[8] or "",
|
||||
}
|
||||
for r in conn.execute(
|
||||
"SELECT id, email, account_type, event, reason, source, "
|
||||
"occurred_at, recorded_at, detail FROM membership_events "
|
||||
"ORDER BY (occurred_at IS NULL), "
|
||||
" COALESCE(occurred_at, recorded_at) DESC, id DESC LIMIT 500"
|
||||
).fetchall()
|
||||
]
|
||||
latest: dict[str, dict] = {}
|
||||
for r in conn.execute(
|
||||
"SELECT e.email, e.reason, e.source, e.occurred_at, e.recorded_at "
|
||||
"FROM membership_events e "
|
||||
"WHERE e.event = 'deactivated' AND e.account_type != 'guest' "
|
||||
"AND e.id = (SELECT MAX(x.id) FROM membership_events x "
|
||||
" WHERE x.email = e.email AND x.event = 'deactivated')"
|
||||
).fetchall():
|
||||
latest[(r[0] or "").strip().lower()] = {
|
||||
"at": r[3], "recorded_at": r[4],
|
||||
"reason": r[1] or "", "source": r[2] or "",
|
||||
}
|
||||
return events, latest
|
||||
|
||||
|
||||
@app.get("/admin/overview")
|
||||
@limiter.limit("30/minute")
|
||||
async def admin_overview(request: Request):
|
||||
@@ -5780,6 +5986,15 @@ async def admin_overview(request: Request):
|
||||
"sent": r[4]}
|
||||
except Exception as e:
|
||||
logger.warning("admin overview: guests ledger read failed: %s", e)
|
||||
# The durable membership log: newest first for the panel's Membership log.
|
||||
# occurred_at is NULL for rows backfilled from a pre-existing inactive row;
|
||||
# recorded_at is when the row was written, never a claim about when the
|
||||
# lapse happened.
|
||||
try:
|
||||
membership_events, latest_deactivation = _membership_events_for_overview(conn)
|
||||
except Exception as e:
|
||||
logger.warning("admin overview: membership events read failed: %s", e)
|
||||
membership_events, latest_deactivation = [], {}
|
||||
conn.close()
|
||||
|
||||
# Fetch Cloudron users once to map user_id → username + inviteAccepted.
|
||||
@@ -5882,6 +6097,7 @@ async def admin_overview(request: Request):
|
||||
mstate_reason = (f"awaiting setup — invite sent {str(sent)[:10]}, "
|
||||
"not yet accepted" if sent else
|
||||
"awaiting setup — invitation not yet accepted")
|
||||
dep = latest_deactivation.get((email or "").strip().lower())
|
||||
entry = {
|
||||
"email": email,
|
||||
"all_time_spend": round(member_all_time, 2),
|
||||
@@ -5914,6 +6130,12 @@ async def admin_overview(request: Request):
|
||||
"dues_frequency": dues_freq or None,
|
||||
"dues_updated_at": dues_updated or None,
|
||||
"guest_expires_at": guest_exp or None,
|
||||
# Latest deactivation on record. at is NULL for a backfilled row —
|
||||
# the panel must show "unknown", never the backfill's write time.
|
||||
"deactivated_at": dep.get("at") if dep else None,
|
||||
"deactivated_recorded_at": dep.get("recorded_at") if dep else None,
|
||||
"deactivated_reason": dep.get("reason", "") if dep else "",
|
||||
"deactivated_source": dep.get("source", "") if dep else "",
|
||||
}
|
||||
if (acct_type or "member") == "guest":
|
||||
gi = guest_info.get(email) or {}
|
||||
@@ -5984,6 +6206,7 @@ async def admin_overview(request: Request):
|
||||
"guests": guests,
|
||||
"admins": admins,
|
||||
"agents": agents,
|
||||
"membership_events": membership_events,
|
||||
"totals": {
|
||||
"members": len(members),
|
||||
"active": sum(1 for m in members if m["active"]),
|
||||
@@ -7838,7 +8061,12 @@ async def reconcile_memberships() -> dict:
|
||||
try:
|
||||
if INACTIVE_GROUP_ID and user_id:
|
||||
await cloudron_switch_group(user_id, INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,))
|
||||
deactivate_member(email)
|
||||
deactivate_member(
|
||||
email,
|
||||
reason="Membership lapsed: no longer on the live Open Collective member list",
|
||||
source="sweep",
|
||||
detail="reconcile_memberships: OC live roster checked; member absent",
|
||||
)
|
||||
await revoke_member_litellm_access(email)
|
||||
await listmonk_sync(email, subscribe=False)
|
||||
deactivated_count += 1
|
||||
@@ -8724,7 +8952,12 @@ async def reconcile_allowances(send: bool = False) -> dict:
|
||||
).fetchone()
|
||||
if INACTIVE_GROUP_ID and urow and urow[0]:
|
||||
await cloudron_switch_group(urow[0], INACTIVE_GROUP_ID, (MEMBERS_GROUP_ID,))
|
||||
deactivate_member(email)
|
||||
deactivate_member(
|
||||
email,
|
||||
reason="Membership lapsed after the payment grace window",
|
||||
source="allowance-reconcile",
|
||||
detail=f"last reminder {str(reminded[0])[:10] if reminded[0] else '?'}; grace {int(PAYMENT_GRACE_DAYS)}d elapsed",
|
||||
)
|
||||
await revoke_member_litellm_access(email)
|
||||
await listmonk_sync(email, subscribe=False)
|
||||
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Membership events — the durable record of who lapsed and who returned.
|
||||
|
||||
WHY THIS EXISTS
|
||||
Before this table, a lapse was only members.active = 0: no date, no reason,
|
||||
no source. A former member was indistinguishable from someone who had never
|
||||
paid, and a returning payer silently erased the fact that they had lapsed.
|
||||
Every deactivation/reactivation transition now writes one row, and the admin
|
||||
overview carries the log plus the latest deactivation per member.
|
||||
|
||||
The tests pin:
|
||||
1. deactivate_member logs ONE row on the active -> inactive transition;
|
||||
a repeated call (OC re-delivery / second sweep pass) does not duplicate.
|
||||
2. store_member logs `reactivated` when it flips an inactive member back on.
|
||||
3. backfill gives a pre-existing inactive member one row with occurred_at
|
||||
NULL and a reason derived from allowance_log; it runs once.
|
||||
4. the overview helper returns the newest-first log and maps the latest
|
||||
deactivation to the member's email (None date for a backfilled row).
|
||||
|
||||
Runnable: python3 tests/test_membership_events.py (from the repo root)
|
||||
"""
|
||||
import base64
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "events-fixture.db")
|
||||
os.environ["PORTAL_KEK"] = base64.b64encode(bytes(32)).decode()
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
import app.main as m # noqa: E402
|
||||
|
||||
m.DB_PATH = os.environ["DB_PATH"]
|
||||
|
||||
FAILS = []
|
||||
|
||||
|
||||
def check(cond, msg):
|
||||
print((" ok " if cond else " FAIL ") + msg)
|
||||
if not cond:
|
||||
FAILS.append(msg)
|
||||
|
||||
|
||||
def rows(q, args=()):
|
||||
conn = m.get_db()
|
||||
try:
|
||||
return conn.execute(q, args).fetchall()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
print("1. deactivation logs exactly one transition")
|
||||
conn = m.get_db()
|
||||
m._ensure_allowance_tables(conn)
|
||||
conn.execute("DELETE FROM members")
|
||||
conn.execute("DELETE FROM membership_events")
|
||||
conn.execute("DELETE FROM portal_state")
|
||||
conn.execute(
|
||||
"INSERT INTO members (email, active, account_type) VALUES (?, 1, 'member')",
|
||||
("lapse@example.org",),
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
m.deactivate_member(
|
||||
"lapse@example.org",
|
||||
reason="Membership lapsed: no longer on the live Open Collective member list",
|
||||
source="sweep",
|
||||
)
|
||||
ev = rows(
|
||||
"SELECT email, event, reason, source, occurred_at, account_type "
|
||||
"FROM membership_events WHERE email = ?",
|
||||
("lapse@example.org",),
|
||||
)
|
||||
check(len(ev) == 1, "one deactivation row written")
|
||||
check(ev[0][1] == "deactivated", "event is 'deactivated'")
|
||||
check(ev[0][3] == "sweep", "source records the calling path")
|
||||
check("Open Collective" in ev[0][2], "reason records why")
|
||||
check(bool(ev[0][4]), "live transition carries occurred_at")
|
||||
check(ev[0][5] == "member", "account_type is carried onto the event")
|
||||
|
||||
# A re-delivered webhook / second sweep pass must not append another lapse.
|
||||
m.deactivate_member(
|
||||
"lapse@example.org",
|
||||
reason="duplicate delivery",
|
||||
source="webhook-opencollective",
|
||||
)
|
||||
ev = rows(
|
||||
"SELECT event FROM membership_events WHERE email = ?",
|
||||
("lapse@example.org",),
|
||||
)
|
||||
check(len(ev) == 1, "a repeated deactivation writes no duplicate row")
|
||||
|
||||
print("2. a returning payer is logged as reactivated")
|
||||
m.store_member("lapse@example.org", "sk-fixture", "uid-fixture")
|
||||
ev = rows(
|
||||
"SELECT event, source FROM membership_events WHERE email = ? ORDER BY id",
|
||||
("lapse@example.org",),
|
||||
)
|
||||
check([r[0] for r in ev] == ["deactivated", "reactivated"],
|
||||
"deactivated then reactivated, in order")
|
||||
check(ev[-1][1] == "provision", "reactivation source is provisioning")
|
||||
active = rows("SELECT active FROM members WHERE email = ?", ("lapse@example.org",))
|
||||
check(active[0][0] == 1, "member is active again")
|
||||
|
||||
print("3. backfill gives a pre-existing inactive member a dated-unknown row")
|
||||
conn = m.get_db()
|
||||
conn.execute("DELETE FROM membership_events")
|
||||
conn.execute("DELETE FROM portal_state")
|
||||
conn.execute("DELETE FROM members")
|
||||
conn.execute(
|
||||
"INSERT INTO members (email, active, account_type, welcome_sent_at) "
|
||||
"VALUES (?, 0, 'member', ?)",
|
||||
("old@example.org", "2026-11-11 19:00:47"),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO allowance_log (email, cycle, decision, evidence, decided_at) "
|
||||
"VALUES (?, ?, ?, ?, ?)",
|
||||
("old@example.org", "2026-11-16", "in_grace",
|
||||
"no recurring (monthly) contribution on Open Collective; reminder sent 2026-11-16 (grace 7d)",
|
||||
"2026-11-18 11:02:37"),
|
||||
)
|
||||
conn.commit()
|
||||
m._backfill_membership_events(conn)
|
||||
conn.commit()
|
||||
ev = conn.execute(
|
||||
"SELECT event, reason, source, occurred_at, detail FROM membership_events "
|
||||
"WHERE email = ?", ("old@example.org",),
|
||||
).fetchall()
|
||||
conn.close()
|
||||
check(len(ev) == 1, "one backfilled row")
|
||||
check(ev[0][0] == "deactivated" and ev[0][2] == "backfill",
|
||||
"backfill event/source are explicit")
|
||||
check(ev[0][3] is None, "backfilled occurred_at stays NULL (unknown date)")
|
||||
check("in_grace" in ev[0][1] and "2026-11-18" in ev[0][1],
|
||||
"backfill reason quotes the allowance decision and date")
|
||||
check("exact" in ev[0][4].lower(), "detail says the exact date is unknown")
|
||||
|
||||
# Re-running the backfill must not duplicate the row (the marker gates it).
|
||||
conn = m.get_db()
|
||||
m._backfill_membership_events(conn)
|
||||
conn.commit()
|
||||
n = conn.execute(
|
||||
"SELECT COUNT(*) FROM membership_events WHERE email = ?", ("old@example.org",),
|
||||
).fetchone()[0]
|
||||
conn.close()
|
||||
check(n == 1, "backfill is idempotent")
|
||||
|
||||
print("4. the overview helper returns the log and the latest deactivation")
|
||||
conn = m.get_db()
|
||||
conn.execute(
|
||||
"INSERT INTO membership_events (email, account_type, event, reason, source, occurred_at) "
|
||||
"VALUES (?, 'member', 'reactivated', ?, 'provision', ?)",
|
||||
("old@example.org", "Returned to active membership", "2026-11-24 12:00:00"),
|
||||
)
|
||||
conn.commit()
|
||||
events, latest = m._membership_events_for_overview(conn)
|
||||
conn.close()
|
||||
check(len(events) == 2, "both events are in the log")
|
||||
check(events[0]["event"] == "reactivated", "newest event sorts first")
|
||||
check("old@example.org" in latest, "latest deactivation is keyed by email")
|
||||
check(latest["old@example.org"]["at"] is None,
|
||||
"backfilled latest deactivation reports an unknown date")
|
||||
check(latest["old@example.org"]["source"] == "backfill",
|
||||
"latest deactivation keeps its source")
|
||||
|
||||
print()
|
||||
if FAILS:
|
||||
print(f"FAILED: {len(FAILS)} check(s) red")
|
||||
sys.exit(1)
|
||||
print("all membership-event checks green")
|
||||
Reference in new issue
Block a user