portal: member_aliases — credit a purchase made from a member's second OC profile
ci/woodpecker/push/woodpecker Pipeline was canceled

A person can hold two Open Collective profiles, one hiding its email. Purchases from
the hidden one have no email to match and no primary slug, so they land in held
credits. member_aliases maps extra slugs to a member email; the sweep's held-credit
pass resolves email -> slug -> alias before holding anything. Admin GET/POST
/admin/aliases manages rows; test covers grant and idempotency.
This commit is contained in:
inference-admin committed 2026-11-17 05:11:16 +00:00
1 parent d51fa55a1d
commit ea0f728af2
2 files changed
+87 -1

No files matched your search

+57 -1
View File
@@ -4977,6 +4977,60 @@ async def admin_held_refund(hold_id: int, request: Request):
return {"status": "refunded", "id": hold_id} return {"status": "refunded", "id": hold_id}
def _ensure_alias_table(conn) -> None:
conn.execute(
"CREATE TABLE IF NOT EXISTS member_aliases ("
" slug TEXT PRIMARY KEY,"
" email TEXT NOT NULL,"
" created_at TEXT DEFAULT CURRENT_TIMESTAMP)")
conn.commit()
def _alias_map(conn) -> dict:
"""extra OC slugs -> member email. A person can hold two OC profiles: one that
hides its email, one that does not. Without this table the hidden profile's
purchases look like a stranger's and land in held credits."""
_ensure_alias_table(conn)
return {(r[0] or "").strip().lower(): (r[1] or "").strip().lower()
for r in conn.execute("SELECT slug, email FROM member_aliases").fetchall()}
@app.get("/admin/aliases")
async def admin_aliases_list(request: Request):
if not ADMIN_TOKEN or request.headers.get("x-admin-token") != ADMIN_TOKEN:
raise HTTPException(401, "Invalid admin token")
conn = get_db()
try:
rows = conn.execute(
"SELECT slug, email, created_at FROM member_aliases ORDER BY created_at DESC"
).fetchall()
finally:
conn.close()
return {"aliases": [{"slug": r[0], "email": r[1], "created_at": r[2]} for r in rows]}
@app.post("/admin/aliases")
async def admin_aliases_add(request: Request):
"""Body: {"slug": "incognito-…", "email": "member@…"}. Idempotent on slug."""
if not ADMIN_TOKEN or request.headers.get("x-admin-token") != ADMIN_TOKEN:
raise HTTPException(401, "Invalid admin token")
body = await request.json() if request.headers.get("content-type", "").startswith("application/json") else {}
slug = (body.get("slug") or "").strip().lower()
email = (body.get("email") or "").strip().lower()
if not slug or not email:
raise HTTPException(400, "slug and email are required")
conn = get_db()
try:
if not conn.execute("SELECT 1 FROM members WHERE lower(email) = ?", (email,)).fetchone():
raise HTTPException(404, "No membership for that email")
_ensure_alias_table(conn)
conn.execute("INSERT OR REPLACE INTO member_aliases (slug, email) VALUES (?, ?)", (slug, email))
conn.commit()
finally:
conn.close()
return {"ok": True, "slug": slug, "email": email}
@app.post("/admin/held-credits/{hold_id}/grant") @app.post("/admin/held-credits/{hold_id}/grant")
@limiter.limit("20/minute") @limiter.limit("20/minute")
async def admin_held_grant(hold_id: int, request: Request): async def admin_held_grant(hold_id: int, request: Request):
@@ -9135,10 +9189,12 @@ async def settle_held_credits(send: bool = True) -> dict:
active = {r[0].strip().lower(): (r[1] or "") for r in active = {r[0].strip().lower(): (r[1] or "") for r in
conn.execute("SELECT email, slug FROM members WHERE active = 1")} conn.execute("SELECT email, slug FROM members WHERE active = 1")}
by_slug = {(sl or "").strip().lower(): em for em, sl in active.items() if sl} by_slug = {(sl or "").strip().lower(): em for em, sl in active.items() if sl}
by_alias = _alias_map(conn)
now = datetime.now(timezone.utc) now = datetime.now(timezone.utc)
for hold_id, slug, email, amount, created_at in held: for hold_id, slug, email, amount, created_at in held:
em = (email or "").strip().lower() em = (email or "").strip().lower()
target = em if em in active else by_slug.get((slug or "").strip().lower(), "") sl = (slug or "").strip().lower()
target = em if em in active else (by_slug.get(sl) or by_alias.get(sl) or "")
if target: if target:
moved = grant_held_credits(conn, target, slug or "") moved = grant_held_credits(conn, target, slug or "")
if moved: if moved:
+30
View File
@@ -0,0 +1,30 @@
import asyncio, os, sys, tempfile
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "aliases.db")
os.environ.setdefault("ADMIN_TOKEN", "admin-test")
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import app.main as m
m.DB_PATH = os.environ["DB_PATH"]; m.ADMIN_TOKEN = "admin-test"
conn = m.get_db(); m._ensure_allowance_tables(conn)
conn.execute("INSERT OR REPLACE INTO members (email, slug, active, credit_balance, source) VALUES (?,?,?,?,?)",
("a@example.org", "main-slug", 1, 0.0, "oc"))
conn.execute("INSERT INTO held_credits (slug, email, name, amount, oc_reference) VALUES (?,?,?,?,?)",
("hidden-abc", "", "A", 10.0, "oc:hidden-abc:ref1"))
conn.commit(); conn.close()
import httpx
async def add():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=m.app), base_url="http://p", timeout=60) as c:
r = await c.post("/admin/aliases", headers={"x-admin-token": "admin-test"},
json={"slug": "hidden-abc", "email": "a@example.org"})
return r.status_code, r.json()
st, d = asyncio.run(add())
assert st == 200, (st, d)
r1 = asyncio.run(m.settle_held_credits(send=False))
conn = m.get_db(); bal = conn.execute("SELECT credit_balance FROM members WHERE email='a@example.org'").fetchone()[0]; conn.close()
print(" alias add:", st, "| granted:", r1["granted"], "| balance:", bal)
assert bal == 10.0, "a purchase from the aliased hidden profile must credit the member"
assert len(r1["granted"]) == 1
r2 = asyncio.run(m.settle_held_credits(send=False))
assert len(r2["granted"]) == 0 and bal == 10.0
print("ALIAS TABLE OK: hidden-profile hold credits the member; no double-apply")