"""Social data access via online PocketBase (no SQLite).""" from __future__ import annotations import time import uuid from typing import Any from nomadro_pb import ensure_once, get_pb, pb_quote C_ROSTER = "social_roster" C_LIVENESS = "social_liveness_audits" C_SKILLS = "social_skill_posts" C_REVIEWS = "social_meetup_reviews" C_BLOCKS = "social_blocks" C_REPORTS = "social_reports" C_MESSAGES = "social_messages" C_CHMETA = "social_channel_meta" C_CAFE = "social_cafe_reviews" C_FEEDBACK = "social_feedback" C_JOIN_LEADS = "social_join_leads" C_GIGS = "social_gig_apps" C_READS = "social_channel_reads" C_FILES = "social_files" C_ARCHIVES = "social_archives" # Live collection names keyed by admin entity ENTITY_COLLECTIONS = { "roster": C_ROSTER, "messages": C_MESSAGES, "reviews": C_CAFE, "gigApps": C_GIGS, "feedback": C_FEEDBACK, "joinLeads": C_JOIN_LEADS, "skills": C_SKILLS, "liveness": C_LIVENESS, "meetupReviews": C_REVIEWS, "reports": C_REPORTS, "blocks": C_BLOCKS, "files": C_FILES, "trips": "social_trips", "coffeeBookings": "coffee_bookings", } def _uid(prefix: str) -> str: return f"{prefix}_{uuid.uuid4().hex[:12]}" def _now() -> str: return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()) def init_pb() -> None: ensure_once() def archive_snapshot( *, entity: str, entity_id: str, action: str, payload: dict[str, Any] | None, guest_id: str = "", note: str = "", ) -> dict[str, Any]: """Append-only archive. Never overwrite; never hard-delete archives.""" init_pb() body = { "entity": (entity or "unknown")[:64], "entity_id": str(entity_id or "")[:120], "guest_id": str(guest_id or "")[:120], "action": (action or "update")[:48], "payload": payload if isinstance(payload, dict) else {"raw": payload}, "note": (note or "")[:500], "created_at": _now(), } return get_pb().create(C_ARCHIVES, body) def _soft_deleted_ids(entity: str) -> set[str]: """Entity ids with a soft_delete archive (latest wins conceptually).""" init_pb() rows = get_pb().list_all( C_ARCHIVES, filter=f"entity={pb_quote(entity)} && action={pb_quote('soft_delete')}", hard_limit=5000, ) return {str(r.get("entity_id") or "") for r in rows if r.get("entity_id")} def soft_delete_record( *, entity: str, entity_id: str, live_collection: str, record: dict[str, Any] | None = None, guest_id: str = "", note: str = "", ) -> bool: """Soft-delete: full snapshot → archive, then hide live row (never PB delete).""" init_pb() pb = get_pb() rec = record if rec is None: try: rec = pb.request( "GET", f"/api/collections/{live_collection}/records/{entity_id}", admin=True ) except Exception: # roster keyed by guest_id if entity == "roster": rec = pb.first(live_collection, filter=f"guest_id={pb_quote(entity_id)}") else: rec = None if not rec: return False rid = str(rec.get("id") or entity_id) gid = guest_id or str(rec.get("guest_id") or "") archive_snapshot( entity=entity, entity_id=str(entity_id or rid), action="soft_delete", payload=dict(rec), guest_id=gid, note=note or "admin soft delete", ) # Hide without destroying bytes patch: dict[str, Any] = {"updated_at": _now()} if entity == "roster": patch.update({"discoverable": False, "status": "deleted"}) elif entity == "messages": patch.update({"recalled": True, "text": "", "reactions": {}}) elif entity in {"reviews", "gigApps", "feedback", "skills"}: # status field exists on skills; others get note marker in archive only if "status" in rec or entity == "skills": patch["status"] = "deleted" try: pb.update(live_collection, rid, patch) except Exception: # Field may be missing on older PB schema — archive already persisted. pass return True def health() -> dict[str, Any]: pb = get_pb() ok = pb.health_ok() return { "ok": ok, "backend": "pocketbase", "pb": pb.base_url, "db": pb.base_url, "dbBytes": 0, } # —— roster —— def _roster_from_rec(r: dict[str, Any], *, public: bool = False) -> dict[str, Any]: status = (r.get("status") or "online").strip() or "online" skills = r.get("skills") or "" intents = r.get("intents") or "" tags = [t.strip() for t in skills.replace(",", ",").replace("、", ",").split(",") if t.strip()][:8] item: dict[str, Any] = { "guestId": r.get("guest_id") or "", "name": r.get("name") or "游民", "title": r.get("title") or "", "city": r.get("city") or "", "skills": skills, "bio": r.get("bio") or "", "avatar": r.get("avatar") or "", "gender": r.get("gender") or "", "intents": intents, "availability": r.get("availability") or "", "status": status, "lookingFor": r.get("looking_for") or "", "updatedAt": r.get("updated_at") or "", "online": status in {"online", "here", "available"}, "tags": tags, "faceOk": bool(r.get("face_ok")), "livenessStatus": r.get("liveness_status") or "none", "livenessAt": r.get("liveness_at") or "", "livenessVideoUrl": r.get("liveness_video_url") or "", "onboardedAt": r.get("onboarded_at") or "", "_id": r.get("id") or "", } if not public: item.update( { "phone": r.get("phone") or "", "linktree": r.get("linktree") or "", "relationship": r.get("relationship") or "", "education": r.get("education") or "", "graduation": r.get("graduation") or "", "wechat": r.get("wechat") or "", "discoverable": bool(r.get("discoverable", True)), "livenessFrontUrl": r.get("liveness_front_url") or "", "livenessTurnUrl": r.get("liveness_turn_url") or "", } ) return item def get_roster(guest_id: str) -> dict[str, Any] | None: init_pb() rec = get_pb().first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") return _roster_from_rec(rec, public=False) if rec else None def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]: init_pb() existing = get_roster(guest_id) is_first = existing is None updated = _now() avatar = str(payload.get("avatar") or "").strip()[:500] if avatar and not ( avatar.startswith("https://") or avatar.startswith("http://") or avatar.startswith("/api/social/") ): avatar = "" intents_raw = payload.get("intents") if isinstance(intents_raw, list): intents = ",".join(str(x).strip() for x in intents_raw if str(x).strip())[:240] else: intents = str(intents_raw or "").strip()[:240] status = str(payload.get("status") or "online").strip()[:32] or "online" if status not in {"online", "away", "offline", "here", "available"}: status = "online" looking = str(payload.get("lookingFor") or payload.get("looking_for") or "").strip()[:200] if not looking and intents: looking = intents.replace(",", " · ")[:200] discoverable = payload.get("discoverable") if discoverable is None: discoverable = True else: discoverable = str(discoverable).lower() not in {"0", "false", "no", "off"} onboarded_at = (existing or {}).get("onboardedAt") or (updated if is_first else "") body = { "guest_id": guest_id, "name": str(payload.get("name") or "").strip()[:64] or "游民", "title": str(payload.get("title") or "").strip()[:80], "city": str(payload.get("city") or "").strip()[:64], "phone": str(payload.get("phone") or "").strip()[:32], "linktree": str(payload.get("linktree") or "").strip()[:240], "skills": str(payload.get("skills") or "").strip()[:200], "bio": str(payload.get("bio") or "").strip()[:2000], "avatar": avatar, "gender": str(payload.get("gender") or "").strip()[:16], "intents": intents, "availability": str(payload.get("availability") or "").strip()[:120], "status": status, "looking_for": looking, "relationship": str(payload.get("relationship") or "").strip()[:32], "education": str(payload.get("education") or "").strip()[:32], "graduation": str(payload.get("graduation") or "").strip()[:32], "wechat": str(payload.get("wechat") or "").strip()[:64], "discoverable": discoverable, "onboarded_at": onboarded_at, "updated_at": updated, } # Preserve face/liveness unless caller overwrites avatar via mark_face if existing: body.setdefault("face_ok", existing.get("faceOk", False)) body.setdefault("liveness_status", existing.get("livenessStatus") or "none") body.setdefault("liveness_at", existing.get("livenessAt") or "") body.setdefault("liveness_video_url", existing.get("livenessVideoUrl") or "") body.setdefault("liveness_front_url", existing.get("livenessFrontUrl") or "") body.setdefault("liveness_turn_url", existing.get("livenessTurnUrl") or "") if not avatar and existing.get("avatar"): body["avatar"] = existing["avatar"] if existing: archive_snapshot( entity="roster", entity_id=guest_id, action="update", payload=dict(existing), guest_id=guest_id, note="roster upsert before-write", ) get_pb().upsert(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}", payload=body) row = get_roster(guest_id) or {} row["isFirstProfile"] = is_first archive_snapshot( entity="roster", entity_id=guest_id, action="create" if is_first else "update_after", payload=dict(body), guest_id=guest_id, note="roster upsert after-write", ) return row def mark_face_photo( guest_id: str, avatar_url: str, *, face_ok: bool = True, ) -> None: """Album/selfie → avatar. face_ok only when detector saw a real face.""" init_pb() existing = get_pb().first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") url = avatar_url[:500] now = _now() if not existing: get_pb().create( C_ROSTER, { "guest_id": guest_id, "name": "游民", "avatar": url, "face_ok": bool(face_ok), "liveness_status": "none", "discoverable": True, "status": "online", "updated_at": now, }, ) return live = (existing.get("liveness_status") or "").strip() get_pb().update( C_ROSTER, existing["id"], { "avatar": url, "face_ok": bool(face_ok), "liveness_status": live if live in {"verified", "pending"} else "none", "updated_at": now, }, ) def save_liveness_audit( guest_id: str, *, front_url: str, turn_url: str, video_url: str, video_size: int, similarity: float | None, yaw_delta: float | None, meta: dict[str, Any] | None = None, ) -> dict[str, Any]: """Live capture audit only — never overwrites roster.avatar.""" init_pb() now = _now() item = { "id": _uid("live"), "guestId": guest_id, "frontUrl": front_url, "turnUrl": turn_url, "videoUrl": video_url, "videoSize": int(video_size or 0), "similarity": similarity, "yawDelta": yaw_delta, "status": "verified", "createdAt": now, } rec = get_pb().create( C_LIVENESS, { "guest_id": guest_id, "avatar_url": "", # not an avatar "front_url": front_url[:500], "turn_url": turn_url[:500], "video_url": (video_url or "")[:500], "video_size": item["videoSize"], "similarity": similarity, "yaw_delta": yaw_delta, "status": "verified", "meta": meta or {}, "created_at": now, }, ) item["id"] = rec.get("id") or item["id"] existing = get_pb().first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") patch = { # face_ok stays album-avatar only — live frames are not an avatar "liveness_status": "verified", "liveness_at": now, "liveness_video_url": (video_url or "")[:500], "liveness_front_url": front_url[:500], "liveness_turn_url": turn_url[:500], "updated_at": now, } if existing: get_pb().update(C_ROSTER, existing["id"], patch) else: # Placeholder only — not discoverable until profile + avatar submitted get_pb().create( C_ROSTER, { "guest_id": guest_id, "name": "游民", "avatar": "", "discoverable": False, "face_ok": False, "status": "offline", **patch, }, ) return item def list_liveness_audits(*, status: str = "", limit: int = 50) -> list[dict[str, Any]]: init_pb() filt = f"status={pb_quote(status)}" if status else None rows = get_pb().list_all(C_LIVENESS, filter=filt, sort="-created_at", hard_limit=limit) return [ { "id": r.get("id"), "guestId": r.get("guest_id"), "frontUrl": r.get("front_url") or "", "turnUrl": r.get("turn_url") or "", "videoUrl": r.get("video_url") or "", "videoSize": r.get("video_size") or 0, "status": r.get("status"), "createdAt": r.get("created_at"), } for r in rows ] def list_discovery_roster( *, viewer_guest_id: str | None = None, city: str = "", limit: int = 48, exclude_self: bool = True, require_face: bool = False, ) -> list[dict[str, Any]]: init_pb() rows = get_pb().list_all(C_ROSTER, sort="-updated_at", hard_limit=400) city_f = "".join((city or "").strip().lower().split()) viewer = get_roster(viewer_guest_id) if viewer_guest_id else None items: list[dict[str, Any]] = [] for r in rows: if exclude_self and viewer_guest_id and r.get("guest_id") == viewer_guest_id: continue if r.get("discoverable") is False: continue if not (r.get("name") or "").strip(): continue # Dating / 约会: no face in avatar → never show if require_face: face_raw = r.get("face_ok") face_ok = face_raw is True or face_raw == 1 or str(face_raw).lower() in { "1", "true", "yes", } avatar = str(r.get("avatar") or "").strip() if not face_ok: continue if not avatar: continue # reject placeholder / broken relative junk if "nomadro.webp" in avatar or avatar.startswith("data:"): continue if not ( avatar.startswith("https://") or avatar.startswith("http://") or avatar.startswith("/api/social/") ): continue item = _roster_from_rec(r, public=True) if city_f and city_f not in "".join((item.get("city") or "").lower().split()): # still allow if no city filter strict — filter when city provided if city_f: continue items.append(item) def score(it: dict[str, Any]) -> float: s = 0.0 if viewer and viewer.get("city") and viewer["city"] and viewer["city"] in (it.get("city") or ""): s += 100 if it.get("online"): s += 20 return s items.sort(key=score, reverse=True) return items[: max(1, min(int(limit or 48), 100))] def city_recommendations(guest_id: str, *, limit: int = 3) -> list[dict[str, Any]]: return list_discovery_roster( viewer_guest_id=guest_id, limit=limit, exclude_self=True ) def clear_liveness_for_guest(guest_id: str) -> dict[str, Any]: """Soft-clear live audits (archive each) and reset liveness fields; keep album avatar.""" init_pb() pb = get_pb() audits = pb.list_all(C_LIVENESS, filter=f"guest_id={pb_quote(guest_id)}") for a in audits: soft_delete_record( entity="liveness", entity_id=str(a.get("id")), live_collection=C_LIVENESS, record=a, guest_id=guest_id, note="clear_liveness_for_guest", ) rec = pb.first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") if rec: archive_snapshot( entity="roster", entity_id=guest_id, action="liveness_reset", payload=dict(rec), guest_id=guest_id, ) pb.update( C_ROSTER, rec["id"], { "liveness_status": "none", "liveness_at": "", "liveness_video_url": "", "liveness_front_url": "", "liveness_turn_url": "", "updated_at": _now(), }, ) return {"ok": True, "deletedAudits": len(audits), "soft": True} # —— channel messages —— def _ch_meta(channel_id: str) -> dict[str, Any] | None: return get_pb().first(C_CHMETA, filter=f"channel_id={pb_quote(channel_id)}") def channel_seq(channel_id: str) -> int: init_pb() meta = _ch_meta(channel_id) if meta: return max(0, int(meta.get("seq") or 0)) rows = get_pb().list_all( C_MESSAGES, filter=f"channel_id={pb_quote(channel_id)}", sort="-seq", hard_limit=1, ) return int(rows[0].get("seq") or 0) if rows else 0 def _avatars_for_guests(guest_ids: list[str]) -> dict[str, str]: """Batch roster.avatar for chat bubbles (guest_id → url).""" ids = sorted({str(g or "").strip() for g in guest_ids if str(g or "").strip()}) if not ids: return {} init_pb() out: dict[str, str] = {} pb = get_pb() for i in range(0, len(ids), 40): chunk = ids[i : i + 40] filt = " || ".join(f"guest_id={pb_quote(g)}" for g in chunk) try: rows = pb.list_all(C_ROSTER, filter=filt, hard_limit=len(chunk) + 8) except Exception: rows = [] for r in rows: gid = str(r.get("guest_id") or "").strip() av = str(r.get("avatar") or "").strip()[:500] if gid and av: out[gid] = av return out def _public_message(item: dict[str, Any], *, avatar: str = "") -> dict[str, Any]: """Flatten PB message for clients: at + avatar for chat UI.""" created = str(item.get("createdAt") or item.get("at") or "").strip() out = dict(item) out["at"] = created out["createdAt"] = created av = (avatar or str(item.get("avatar") or "")).strip()[:500] if av: out["avatar"] = av else: out.setdefault("avatar", "") return out def list_messages( channel_id: str, limit: int = 100, *, since: int | None = None, before: int | None = None, q: str | None = None, ) -> list[dict[str, Any]]: init_pb() lim = max(1, min(int(limit or 100), 500)) rows = get_pb().list_all( C_MESSAGES, filter=f"channel_id={pb_quote(channel_id)}", sort="seq", hard_limit=2000, ) needle = (q or "").strip().lower() out: list[dict[str, Any]] = [] for r in rows: seq = int(r.get("seq") or 0) if since is not None and since > 0 and seq <= since: continue if before is not None and before > 0 and seq >= before: continue text = r.get("text") or "" nick = r.get("nick") or "" if needle and needle not in text.lower() and needle not in nick.lower(): continue if r.get("recalled"): continue out.append( { "id": r.get("id"), "channelId": channel_id, "seq": seq, "guestId": r.get("guest_id"), "author": nick or "游民", "text": text, "kind": r.get("kind") or "text", "meta": r.get("meta") or {}, "attachments": r.get("attachments") or [], "replyTo": r.get("reply_to"), "reactions": r.get("reactions") or {}, "pinned": bool(r.get("pinned")), "createdAt": r.get("created_at"), "editedAt": r.get("edited_at") or "", } ) if before is not None and before > 0: out = out[-lim:] else: out = out[-lim:] avatars = _avatars_for_guests([str(m.get("guestId") or "") for m in out]) return [ _public_message(m, avatar=avatars.get(str(m.get("guestId") or ""), "")) for m in out ] def add_message( channel_id: str, author: str, text: str, guest_id: str, *, kind: str = "text", meta: dict[str, Any] | None = None, attachments: list[Any] | None = None, reply_to: dict[str, Any] | None = None, ) -> dict[str, Any]: init_pb() pb = get_pb() seq = channel_seq(channel_id) + 1 now = _now() body = { "channel_id": channel_id, "seq": seq, "guest_id": guest_id, "nick": (author or "游民")[:48], "text": (text or "")[:4000], "kind": kind or "text", "meta": meta or {}, "attachments": attachments or [], "reply_to": reply_to, "reactions": {}, "pinned": False, "recalled": False, "created_at": now, "edited_at": "", } rec = pb.create(C_MESSAGES, body) meta_rec = _ch_meta(channel_id) if meta_rec: pb.update(C_CHMETA, meta_rec["id"], {"seq": seq, "updated_at": now}) else: pb.create( C_CHMETA, { "channel_id": channel_id, "seq": seq, "pins": [], "presence": {}, "updated_at": now, }, ) avatars = _avatars_for_guests([guest_id]) return _public_message( { "id": rec.get("id"), "channelId": channel_id, "seq": seq, "guestId": guest_id, "author": body["nick"], "text": body["text"], "kind": body["kind"], "meta": body["meta"], "attachments": body["attachments"], "replyTo": reply_to, "reactions": {}, "pinned": False, "createdAt": now, }, avatar=avatars.get(guest_id, ""), ) def get_message(msg_id: str) -> dict[str, Any] | None: init_pb() try: r = get_pb().request( "GET", f"/api/collections/{C_MESSAGES}/records/{msg_id}", admin=True ) except Exception: return None gid = str(r.get("guest_id") or "") avatars = _avatars_for_guests([gid]) if gid else {} return _public_message( { "id": r.get("id"), "channelId": r.get("channel_id"), "seq": int(r.get("seq") or 0), "guestId": r.get("guest_id"), "author": r.get("nick") or "游民", "text": r.get("text") or "", "kind": r.get("kind") or "text", "meta": r.get("meta") or {}, "attachments": r.get("attachments") or [], "replyTo": r.get("reply_to"), "reactions": r.get("reactions") or {}, "pinned": bool(r.get("pinned")), "recalled": bool(r.get("recalled")), "createdAt": r.get("created_at"), "editedAt": r.get("edited_at") or "", }, avatar=avatars.get(gid, ""), ) def edit_message(channel_id: str, msg_id: str, guest_id: str, text: str) -> dict[str, Any]: m = get_message(msg_id) if not m or m.get("channelId") != channel_id: raise ValueError("message not found") if m.get("guestId") != guest_id: raise ValueError("not your message") if m.get("recalled"): raise ValueError("recalled") now = _now() get_pb().update( C_MESSAGES, msg_id, {"text": (text or "").strip()[:2000], "edited_at": now}, ) out = get_message(msg_id) if not out: raise ValueError("message not found") return out def recall_message(channel_id: str, msg_id: str, guest_id: str) -> dict[str, Any]: m = get_message(msg_id) if not m or m.get("channelId") != channel_id: raise ValueError("message not found") if m.get("guestId") != guest_id: raise ValueError("not your message") get_pb().update( C_MESSAGES, msg_id, {"text": "", "recalled": True, "attachments": [], "reactions": {}}, ) out = get_message(msg_id) if not out: raise ValueError("message not found") return out def react_message( channel_id: str, msg_id: str, guest_id: str, emoji: str ) -> dict[str, Any]: key = (emoji or "").strip()[:16] if not key: raise ValueError("empty emoji") m = get_message(msg_id) if not m or m.get("channelId") != channel_id: raise ValueError("message not found") if m.get("recalled"): raise ValueError("recalled") reactions: dict[str, list[str]] = dict(m.get("reactions") or {}) holders = list(reactions.get(key) or []) if guest_id in holders: holders = [g for g in holders if g != guest_id] else: holders.append(guest_id) if holders: reactions[key] = holders[:64] else: reactions.pop(key, None) get_pb().update(C_MESSAGES, msg_id, {"reactions": reactions}) out = get_message(msg_id) if not out: raise ValueError("message not found") return out def pin_message( channel_id: str, msg_id: str, guest_id: str, pinned: bool = True ) -> dict[str, Any]: m = get_message(msg_id) if not m or m.get("channelId") != channel_id: raise ValueError("message not found") if m.get("recalled"): raise ValueError("recalled") meta = dict(m.get("meta") or {}) now = _now() if pinned: meta["pinned"] = True meta["pinnedAt"] = now meta["pinnedBy"] = guest_id else: meta.pop("pinned", None) meta.pop("pinnedAt", None) meta.pop("pinnedBy", None) get_pb().update(C_MESSAGES, msg_id, {"pinned": bool(pinned), "meta": meta}) out = get_message(msg_id) if not out: raise ValueError("message not found") return out def report_message( channel_id: str, msg_id: str, guest_id: str, reason: str = "" ) -> dict[str, Any]: m = get_message(msg_id) if not m or m.get("channelId") != channel_id: raise ValueError("message not found") meta = dict(m.get("meta") or {}) reporters = list(meta.get("reporters") or []) if guest_id not in reporters: reporters.append(guest_id) meta["reported"] = True meta["reporters"] = reporters[:64] meta["reportReason"] = (reason or "").strip()[:240] meta["reportedAt"] = _now() get_pb().update(C_MESSAGES, msg_id, {"meta": meta}) out = get_message(msg_id) if not out: raise ValueError("message not found") return out def set_note(channel_id: str, guest_id: str, what: str, seq: int) -> dict[str, Any]: what = (what or "").strip().lower() if what not in {"recv", "read"}: raise ValueError("what must be recv or read") seq = max(0, int(seq)) init_pb() pb = get_pb() filt = f"guest_id={pb_quote(guest_id)} && channel_id={pb_quote(channel_id)}" existing = pb.first(C_READS, filter=filt) recv = int((existing or {}).get("recv_seq") or 0) read = int((existing or {}).get("read_seq") or 0) if what == "recv": recv = max(recv, seq) else: read = max(read, seq) recv = max(recv, read) now = _now() pb.upsert( C_READS, filter=filt, payload={ "guest_id": guest_id, "channel_id": channel_id, "recv_seq": recv, "read_seq": read, "updated_at": now, }, ) return {"channelId": channel_id, "what": what, "seq": seq, "recv": recv, "read": read} def channel_desc(channel_id: str, guest_id: str | None = None) -> dict[str, Any]: init_pb() seq = channel_seq(channel_id) recv = read = 0 if guest_id: mark = get_pb().first( C_READS, filter=f"guest_id={pb_quote(guest_id)} && channel_id={pb_quote(channel_id)}", ) if mark: recv = int(mark.get("recv_seq") or 0) read = int(mark.get("read_seq") or 0) return { "channelId": channel_id, "seq": seq, "recv": recv, "read": read, "unread": max(0, seq - read), } def save_file_meta( file_id: str, channel_id: str, guest_id: str, *, kind: str, name: str, mime: str, size: int, path: str, ) -> dict[str, Any]: init_pb() now = _now() get_pb().upsert( C_FILES, filter=f"file_id={pb_quote(file_id)}", payload={ "file_id": file_id, "channel_id": channel_id, "guest_id": guest_id, "kind": kind, "name": name, "mime": mime, "size": size, "path": path, "created_at": now, }, ) return { "id": file_id, "kind": kind, "name": name, "mime": mime, "size": size, "url": f"/api/social/v1/files/{file_id}", } def get_file(file_id: str) -> dict[str, Any] | None: init_pb() row = get_pb().first(C_FILES, filter=f"file_id={pb_quote(file_id)}") if not row: return None return { "id": row.get("file_id") or file_id, "channelId": row.get("channel_id"), "kind": row.get("kind"), "name": row.get("name"), "mime": row.get("mime"), "size": int(row.get("size") or 0), "path": row.get("path"), } def list_cafe_reviews(cafe_id: str, limit: int = 50) -> list[dict[str, Any]]: init_pb() lim = max(1, min(int(limit or 50), 200)) rows = get_pb().list_all( C_CAFE, filter=f"cafe_id={pb_quote(cafe_id)}" if cafe_id else None, sort="-created_at", hard_limit=lim, ) return [ { "id": r.get("id"), "cafeId": r.get("cafe_id"), "author": r.get("author"), "score": r.get("score"), "text": r.get("text"), "photoNote": r.get("photo_note") or "", "guestId": r.get("guest_id"), "at": r.get("created_at"), } for r in rows[:lim] ] def add_cafe_review( cafe_id: str, author: str, score: int, text: str, photo_note: str, guest_id: str, ) -> dict[str, Any]: init_pb() now = _now() body = { "cafe_id": cafe_id, "guest_id": guest_id, "author": (author or "游民").strip()[:48] or "游民", "score": max(1, min(int(score or 5), 5)), "text": (text or "").strip()[:2000], "photo_note": (photo_note or "").strip()[:200], "created_at": now, } rec = get_pb().create(C_CAFE, body) return { "id": rec.get("id"), "cafeId": cafe_id, "author": body["author"], "score": body["score"], "text": body["text"], "photoNote": body["photo_note"], "guestId": guest_id, "at": now, } def add_feedback(kind: str, text: str, contact: str, guest_id: str) -> dict[str, Any]: init_pb() now = _now() body = { "guest_id": guest_id, "kind": kind if kind in {"反馈", "建议"} else "建议", "text": (text or "").strip()[:4000], "contact": (contact or "").strip()[:120], "created_at": now, } rec = get_pb().create(C_FEEDBACK, body) return { "id": rec.get("id"), "kind": body["kind"], "text": body["text"], "contact": body["contact"], "guestId": guest_id, "at": now, } def upsert_join_lead( *, email: str, guest_id: str, stage: str = "email_submit", name: str = "", payload: dict[str, Any] | None = None, ua: str = "", paid: str = "", face_ok: str = "", liveness_status: str = "", ) -> dict[str, Any]: """Archive every join funnel event; upsert live lead row for admin list.""" init_pb() now = _now() email_n = (email or "").strip().lower()[:160] if not email_n or "@" not in email_n: raise ValueError("invalid email") gid = (guest_id or "")[:120] stage_n = (stage or "email_submit")[:48] body_payload = payload if isinstance(payload, dict) else {} snap = { "email": email_n, "guestId": gid, "stage": stage_n, "name": (name or "")[:64], "paid": (paid or "")[:8], "faceOk": (face_ok or "")[:8], "livenessStatus": (liveness_status or "")[:24], "ua": (ua or "")[:240], "payload": body_payload, "at": now, } archive_snapshot( entity="join_leads", entity_id=email_n, action=stage_n, payload=snap, guest_id=gid, note=f"join:{stage_n}", ) lead_id = email_n try: pb = get_pb() existing = pb.first(C_JOIN_LEADS, filter=f"email={pb_quote(email_n)}") row = { "email": email_n, "guest_id": gid, "stage": stage_n, "name": (name or "")[:64], "payload": body_payload, "ua": (ua or "")[:240], "paid": (paid or "")[:8], "face_ok": (face_ok or "")[:8], "liveness_status": (liveness_status or "")[:24], "updated_at": now, } if existing and existing.get("id"): for k in ("paid", "face_ok", "liveness_status", "name", "guest_id"): if not row.get(k) and existing.get(k): row[k] = existing.get(k) old_p = existing.get("payload") if isinstance(existing.get("payload"), dict) else {} row["payload"] = { **old_p, **body_payload, "stages": list({*list(old_p.get("stages") or []), stage_n}), } rec = pb.update(C_JOIN_LEADS, str(existing["id"]), row) else: row["created_at"] = now row["payload"] = {**body_payload, "stages": [stage_n]} rec = pb.create(C_JOIN_LEADS, row) lead_id = str(rec.get("id") or email_n) except Exception: # Collection may not exist yet — archive is enough for admin list fallback lead_id = email_n return { "ok": True, "id": lead_id, "email": email_n, "guestId": gid, "stage": stage_n, "at": now, } def admin_list_join_leads( *, q: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: """Prefer live social_join_leads; fall back to social_archives entity=join_leads.""" init_pb() lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) needle = (q or "").strip().lower() items: list[dict[str, Any]] = [] try: rows = get_pb().list_all(C_JOIN_LEADS, sort="-updated_at", hard_limit=5000) for r in rows: items.append( { "id": r.get("id"), "email": r.get("email") or "", "guestId": r.get("guest_id") or "", "stage": r.get("stage") or "", "name": r.get("name") or "", "paid": r.get("paid") or "", "faceOk": r.get("face_ok") or "", "livenessStatus": r.get("liveness_status") or "", "ua": r.get("ua") or "", "payload": r.get("payload") or {}, "createdAt": r.get("created_at") or "", "updatedAt": r.get("updated_at") or "", } ) except Exception: items = [] if not items: # Aggregate latest archive snapshot per email try: arch = get_pb().list_all( C_ARCHIVES, filter=f"entity={pb_quote('join_leads')}", sort="-created_at", hard_limit=5000, ) by_email: dict[str, dict[str, Any]] = {} for a in arch: payload = a.get("payload") if isinstance(a.get("payload"), dict) else {} email = str( payload.get("email") or a.get("entity_id") or "" ).strip().lower() if not email or email in by_email: continue by_email[email] = { "id": a.get("id") or email, "email": email, "guestId": payload.get("guestId") or a.get("guest_id") or "", "stage": payload.get("stage") or a.get("action") or "", "name": payload.get("name") or "", "paid": payload.get("paid") or "", "faceOk": payload.get("faceOk") or "", "livenessStatus": payload.get("livenessStatus") or "", "ua": payload.get("ua") or "", "payload": payload, "createdAt": a.get("created_at") or "", "updatedAt": a.get("created_at") or "", } items = list(by_email.values()) except Exception: items = [] if needle: items = [ r for r in items if needle in str(r.get("email") or "").lower() or needle in str(r.get("guestId") or "").lower() or needle in str(r.get("name") or "").lower() or needle in str(r.get("stage") or "").lower() ] total = len(items) page = items[off : off + lim] return {"ok": True, "total": total, "items": page} def add_gig_app( gig_id: str, name: str, contact: str, note: str, guest_id: str, request_id: str | None = None, ) -> dict[str, Any]: import hashlib import json as _json init_pb() now = _now() stable_id = None if request_id: stable_id = ( "app_" + hashlib.sha256( _json.dumps([guest_id, gig_id, request_id]).encode() ).hexdigest()[:32] ) body = { "gig_id": gig_id, "guest_id": guest_id, "name": (name or "").strip()[:64], "contact": (contact or "").strip()[:120], "note": (note or "").strip()[:2000], "request_id": request_id or "", "created_at": now, } pb = get_pb() if stable_id: existing = pb.first( C_GIGS, filter=f"request_id={pb_quote(request_id or '')} && guest_id={pb_quote(guest_id)} && gig_id={pb_quote(gig_id)}", ) if existing: if ( (existing.get("name"), existing.get("contact"), existing.get("note")) != (body["name"], body["contact"], body["note"]) ): raise ValueError("同一请求标识不能用于不同申请") return { "id": existing.get("id"), "gigId": gig_id, "name": existing.get("name"), "contact": existing.get("contact"), "note": existing.get("note") or "", "guestId": guest_id, "at": existing.get("created_at") or now, } rec = pb.create(C_GIGS, body) return { "id": rec.get("id") or stable_id, "gigId": gig_id, "name": body["name"], "contact": body["contact"], "note": body["note"], "guestId": guest_id, "at": now, } # —— admin / ugc helpers —— def _safe_count(pb: Any, collection: str) -> int: try: return len(pb.list_all(collection, hard_limit=5000)) except Exception: return 0 def admin_overview() -> dict[str, Any]: init_pb() pb = get_pb() counts = { "messages": _safe_count(pb, C_MESSAGES), "roster": _safe_count(pb, C_ROSTER), "reviews": _safe_count(pb, C_CAFE), "gigApps": _safe_count(pb, C_GIGS), "feedback": _safe_count(pb, C_FEEDBACK), "joinLeads": _safe_count(pb, C_JOIN_LEADS), "skills": _safe_count(pb, C_SKILLS), "liveness": _safe_count(pb, C_LIVENESS), "meetupReviews": _safe_count(pb, C_REVIEWS), "reports": _safe_count(pb, C_REPORTS), "blocks": _safe_count(pb, C_BLOCKS), "files": _safe_count(pb, C_FILES), "trips": _safe_count(pb, "social_trips"), "coffeeBookings": _safe_count(pb, "coffee_bookings"), "archives": _safe_count(pb, C_ARCHIVES), } return { "ok": pb.health_ok(), "backend": "pocketbase", "path": pb.base_url, "exists": True, "bytes": 0, "writable": True, "counts": counts, } def admin_list_messages( *, channel_id: str = "", q: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: init_pb() lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) filt = f"channel_id={pb_quote(channel_id)}" if channel_id.strip() else None rows = get_pb().list_all(C_MESSAGES, filter=filt, sort="-created_at", hard_limit=5000) needle = q.strip().lower() if needle: rows = [ r for r in rows if needle in (r.get("nick") or "").lower() or needle in (r.get("text") or "").lower() or needle in (r.get("guest_id") or "").lower() ] total = len(rows) page = rows[off : off + lim] return { "ok": True, "total": total, "items": [ { "id": r.get("id"), "channelId": r.get("channel_id"), "author": r.get("nick") or "游民", "text": r.get("text") or "", "guestId": r.get("guest_id"), "at": r.get("created_at"), } for r in page ], } def admin_delete_message(message_id: str) -> bool: return soft_delete_record( entity="messages", entity_id=message_id, live_collection=C_MESSAGES, ) def admin_list_roster( *, q: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: init_pb() lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) rows = get_pb().list_all(C_ROSTER, sort="-updated_at", hard_limit=5000) needle = q.strip().lower() if needle: rows = [ r for r in rows if needle in (r.get("name") or "").lower() or needle in (r.get("city") or "").lower() or needle in (r.get("title") or "").lower() or needle in (r.get("guest_id") or "").lower() or needle in (r.get("bio") or "").lower() ] total = len(rows) page = rows[off : off + lim] return { "ok": True, "total": total, "items": [ { "guestId": r.get("guest_id"), "name": r.get("name"), "title": r.get("title") or "", "city": r.get("city") or "", "phone": r.get("phone") or "", "linktree": r.get("linktree") or "", "skills": r.get("skills") or "", "bio": r.get("bio") or "", "updatedAt": r.get("updated_at"), } for r in page ], } def admin_update_roster(guest_id: str, patch: dict[str, Any]) -> dict[str, Any] | None: init_pb() existing = get_pb().first(C_ROSTER, filter=f"guest_id={pb_quote(guest_id)}") if not existing: return None archive_snapshot( entity="roster", entity_id=guest_id, action="admin_update", payload=dict(existing), guest_id=guest_id, ) fields = { "name": str(patch.get("name", existing.get("name") or ""))[:64] or "游民", "title": str(patch.get("title", existing.get("title") or ""))[:80], "city": str(patch.get("city", existing.get("city") or ""))[:64], "phone": str(patch.get("phone", existing.get("phone") or ""))[:32], "linktree": str(patch.get("linktree", existing.get("linktree") or ""))[:240], "skills": str(patch.get("skills", existing.get("skills") or ""))[:200], "bio": str(patch.get("bio", existing.get("bio") or ""))[:2000], "updated_at": _now(), } # Admin restore from soft-delete if patch.get("restore"): fields["status"] = str(patch.get("status") or "online")[:32] fields["discoverable"] = True get_pb().update(C_ROSTER, existing["id"], fields) out = { **{k: fields[k] for k in ("name", "title", "city", "phone", "linktree", "skills", "bio")}, "guestId": guest_id, "updatedAt": fields["updated_at"], } archive_snapshot( entity="roster", entity_id=guest_id, action="admin_update_after", payload=dict(fields), guest_id=guest_id, ) return out def admin_delete_roster(guest_id: str) -> bool: return soft_delete_record( entity="roster", entity_id=guest_id, live_collection=C_ROSTER, guest_id=guest_id, ) def admin_list_cafe_reviews( *, cafe_id: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: init_pb() lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) filt = f"cafe_id={pb_quote(cafe_id)}" if cafe_id.strip() else None rows = get_pb().list_all(C_CAFE, filter=filt, sort="-created_at", hard_limit=5000) total = len(rows) page = rows[off : off + lim] return { "ok": True, "total": total, "items": [ { "id": r.get("id"), "cafeId": r.get("cafe_id"), "author": r.get("author"), "score": r.get("score"), "text": r.get("text"), "photoNote": r.get("photo_note") or "", "guestId": r.get("guest_id"), "at": r.get("created_at"), } for r in page ], } def admin_delete_cafe_review(review_id: str) -> bool: return soft_delete_record( entity="reviews", entity_id=review_id, live_collection=C_CAFE, ) def admin_list_gig_apps( *, gig_id: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: init_pb() lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) filt = f"gig_id={pb_quote(gig_id)}" if gig_id.strip() else None rows = get_pb().list_all(C_GIGS, filter=filt, sort="-created_at", hard_limit=5000) total = len(rows) page = rows[off : off + lim] return { "ok": True, "total": total, "items": [ { "id": r.get("id"), "gigId": r.get("gig_id"), "name": r.get("name"), "contact": r.get("contact"), "note": r.get("note") or "", "guestId": r.get("guest_id"), "at": r.get("created_at"), } for r in page ], } def admin_delete_gig_app(app_id: str) -> bool: return soft_delete_record( entity="gigApps", entity_id=app_id, live_collection=C_GIGS, ) def admin_list_feedback(*, limit: int = 100, offset: int = 0) -> dict[str, Any]: init_pb() lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) rows = get_pb().list_all(C_FEEDBACK, sort="-created_at", hard_limit=5000) total = len(rows) page = rows[off : off + lim] return { "ok": True, "total": total, "items": [ { "id": r.get("id"), "kind": r.get("kind"), "text": r.get("text"), "contact": r.get("contact") or "", "guestId": r.get("guest_id"), "at": r.get("created_at"), } for r in page ], } def admin_delete_feedback(fid: str) -> bool: return soft_delete_record( entity="feedback", entity_id=fid, live_collection=C_FEEDBACK, ) def _page_rows(rows: list[dict[str, Any]], *, limit: int, offset: int) -> dict[str, Any]: lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) total = len(rows) return {"ok": True, "total": total, "items": rows[off : off + lim]} def admin_list_skills(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: init_pb() rows = get_pb().list_all(C_SKILLS, sort="-created_at", hard_limit=5000) needle = (q or "").strip().lower() items = [ { "id": r.get("id"), "guestId": r.get("guest_id") or "", "author": r.get("author") or "", "city": r.get("city") or "", "offer": r.get("offer") or "", "want": r.get("want") or "", "note": r.get("note") or "", "status": r.get("status") or "", "at": r.get("created_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("author") or "").lower() or needle in str(x.get("city") or "").lower() or needle in str(x.get("offer") or "").lower() or needle in str(x.get("want") or "").lower() or needle in str(x.get("guestId") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_list_liveness(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: init_pb() rows = get_pb().list_all(C_LIVENESS, sort="-created_at", hard_limit=5000) needle = (q or "").strip().lower() def _abs(u: str) -> str: s = (u or "").strip() if not s: return "" if s.startswith(("http://", "https://", "data:")): return s if s.startswith("/api/social/"): return f"https://api.nomadro.com{s}" if s.startswith("/"): return f"https://nomadro.com{s}" return s items = [ { "id": r.get("id"), "guestId": r.get("guest_id") or "", "status": r.get("status") or "", "similarity": r.get("similarity"), "yawDelta": r.get("yaw_delta"), "frontUrl": _abs(str(r.get("front_url") or "")), "turnUrl": _abs(str(r.get("turn_url") or "")), "videoUrl": _abs(str(r.get("video_url") or "")), "avatarUrl": _abs(str(r.get("avatar_url") or "")), "videoSize": r.get("video_size") or 0, "at": r.get("created_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("guestId") or "").lower() or needle in str(x.get("status") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_list_meetup_reviews( *, q: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: init_pb() rows = get_pb().list_all(C_REVIEWS, sort="-created_at", hard_limit=5000) needle = (q or "").strip().lower() items = [ { "id": r.get("id"), "bookingId": r.get("booking_id") or "", "fromGuest": r.get("from_guest") or "", "toGuest": r.get("to_guest") or "", "toName": r.get("to_name") or "", "punctuality": r.get("punctuality"), "chemistry": r.get("chemistry"), "professionalism": r.get("professionalism"), "text": r.get("text") or "", "at": r.get("created_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("toName") or "").lower() or needle in str(x.get("text") or "").lower() or needle in str(x.get("fromGuest") or "").lower() or needle in str(x.get("toGuest") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_list_reports(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: init_pb() rows = get_pb().list_all(C_REPORTS, sort="-created_at", hard_limit=5000) needle = (q or "").strip().lower() items = [ { "id": r.get("id"), "guestId": r.get("guest_id") or "", "targetGuest": r.get("target_guest") or "", "targetName": r.get("target_name") or "", "reason": r.get("reason") or "", "detail": r.get("detail") or "", "status": r.get("status") or "", "resultNote": r.get("result_note") or "", "at": r.get("created_at") or "", "resolvedAt": r.get("resolved_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("reason") or "").lower() or needle in str(x.get("targetName") or "").lower() or needle in str(x.get("status") or "").lower() or needle in str(x.get("guestId") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_list_blocks(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: init_pb() rows = get_pb().list_all(C_BLOCKS, sort="-created_at", hard_limit=5000) needle = (q or "").strip().lower() items = [ { "id": r.get("id"), "guestId": r.get("guest_id") or "", "blockedGuest": r.get("blocked_guest") or "", "reason": r.get("reason") or "", "at": r.get("created_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("guestId") or "").lower() or needle in str(x.get("blockedGuest") or "").lower() or needle in str(x.get("reason") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_list_trips(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: init_pb() try: rows = get_pb().list_all("social_trips", sort="-updated_at", hard_limit=5000) except Exception: rows = [] needle = (q or "").strip().lower() items = [ { "id": r.get("id"), "guestId": r.get("guest_id") or "", "cityId": r.get("city_id") or "", "city": r.get("city") or "", "country": r.get("country") or "", "lat": r.get("lat"), "lng": r.get("lng"), "arrivalDate": r.get("arrival_date") or "", "departureDate": r.get("departure_date") or "", "visibility": r.get("visibility") or "", "status": r.get("status") or "", "updatedAt": r.get("updated_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("city") or "").lower() or needle in str(x.get("country") or "").lower() or needle in str(x.get("guestId") or "").lower() or needle in str(x.get("status") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_list_files(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]: init_pb() rows = get_pb().list_all(C_FILES, sort="-created_at", hard_limit=5000) needle = (q or "").strip().lower() items = [ { "id": r.get("id"), "fileId": r.get("file_id") or r.get("id") or "", "channelId": r.get("channel_id") or "", "guestId": r.get("guest_id") or "", "kind": r.get("kind") or "", "name": r.get("name") or "", "mime": r.get("mime") or "", "size": r.get("size") or 0, "url": f"/api/social/v1/files/{r.get('file_id') or r.get('id') or ''}", "at": r.get("created_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("name") or "").lower() or needle in str(x.get("kind") or "").lower() or needle in str(x.get("guestId") or "").lower() or needle in str(x.get("channelId") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_list_coffee_bookings( *, q: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: """Coffeechat bookings — PB coffee_bookings.""" init_pb() try: rows = get_pb().list_all("coffee_bookings", sort="-created_at", hard_limit=5000) except Exception: rows = [] needle = (q or "").strip().lower() items = [ { "id": r.get("id"), "uid": r.get("uid") or "", "hostId": r.get("host_id") or "", "eventTypeId": r.get("event_type_id") or "", "title": r.get("title") or "", "status": r.get("status") or "", "startUtc": r.get("start_utc") or "", "endUtc": r.get("end_utc") or "", "location": r.get("location") or "", "notes": r.get("notes") or "", "attendeeName": r.get("attendee_name") or "", "attendeeEmail": r.get("attendee_email") or "", "attendeeTimezone": r.get("attendee_timezone") or "", "at": r.get("created_at") or "", "cancelledAt": r.get("cancelled_at") or "", } for r in rows ] if needle: items = [ x for x in items if needle in str(x.get("title") or "").lower() or needle in str(x.get("attendeeName") or "").lower() or needle in str(x.get("attendeeEmail") or "").lower() or needle in str(x.get("status") or "").lower() ] return _page_rows(items, limit=limit, offset=offset) def admin_stats() -> dict[str, Any]: """Dashboard aggregates for admin visualization.""" init_pb() pb = get_pb() counts = admin_overview().get("counts") or {} soft = { "roster": len(_soft_deleted_ids("roster")), "messages": len(_soft_deleted_ids("messages")), "reviews": len(_soft_deleted_ids("reviews")), "gigApps": len(_soft_deleted_ids("gigApps")), "feedback": len(_soft_deleted_ids("feedback")), "skills": len(_soft_deleted_ids("skills")), } # city breakdown from live roster (exclude soft-deleted) gone = _soft_deleted_ids("roster") roster = [ r for r in pb.list_all(C_ROSTER, hard_limit=5000) if str(r.get("guest_id") or "") not in gone and (r.get("status") or "") != "deleted" ] by_city: dict[str, int] = {} by_day: dict[str, int] = {} for r in roster: city = (r.get("city") or "未填").strip() or "未填" by_city[city] = by_city.get(city, 0) + 1 day = str(r.get("updated_at") or r.get("onboarded_at") or "")[:10] if day: by_day[day] = by_day.get(day, 0) + 1 city_top = sorted(by_city.items(), key=lambda x: -x[1])[:12] day_series = sorted(by_day.items())[-30:] return { "ok": True, "counts": counts, "softDeleted": soft, "activeRoster": len(roster), "byCity": [{"name": k, "value": v} for k, v in city_top], "rosterByDay": [{"date": d, "value": n} for d, n in day_series], } def _join_lead_public(r: dict[str, Any]) -> dict[str, Any]: return { "id": r.get("id"), "email": r.get("email") or "", "guestId": r.get("guest_id") or "", "stage": r.get("stage") or "", "name": r.get("name") or "", "paid": r.get("paid") or "", "faceOk": r.get("face_ok") or "", "livenessStatus": r.get("liveness_status") or "", "ua": r.get("ua") or "", "payload": r.get("payload") or {}, "createdAt": r.get("created_at") or "", "updatedAt": r.get("updated_at") or "", } def admin_get_join_lead(lead_id: str) -> dict[str, Any] | None: """Human join funnel detail: lead + stage timeline + roster media + liveness clips.""" init_pb() pb = get_pb() key = (lead_id or "").strip() if not key: return None rec = None try: rec = pb.request( "GET", f"/api/collections/{C_JOIN_LEADS}/records/{key}", admin=True ) except Exception: rec = None if not rec: email_n = key.lower() rec = pb.first(C_JOIN_LEADS, filter=f"email={pb_quote(email_n)}") if not rec: # Archive-only fallback: latest snapshot for this email / id arch = pb.list_all( C_ARCHIVES, filter=f"entity={pb_quote('join_leads')} && entity_id={pb_quote(key.lower())}", sort="-created_at", hard_limit=1, ) if not arch: return None a0 = arch[0] payload = a0.get("payload") if isinstance(a0.get("payload"), dict) else {} item = { "id": a0.get("id") or key, "email": payload.get("email") or a0.get("entity_id") or key, "guestId": payload.get("guestId") or a0.get("guest_id") or "", "stage": payload.get("stage") or a0.get("action") or "", "name": payload.get("name") or "", "paid": payload.get("paid") or "", "faceOk": payload.get("faceOk") or "", "livenessStatus": payload.get("livenessStatus") or "", "ua": payload.get("ua") or "", "payload": payload.get("payload") if isinstance(payload.get("payload"), dict) else payload, "createdAt": a0.get("created_at") or "", "updatedAt": a0.get("created_at") or "", } else: item = _join_lead_public(rec) email = str(item.get("email") or "").strip().lower() gid = str(item.get("guestId") or "").strip() hist_rows = pb.list_all( C_ARCHIVES, filter=f"entity={pb_quote('join_leads')} && entity_id={pb_quote(email)}", sort="-created_at", hard_limit=100, ) history = [ { "id": h.get("id"), "action": h.get("action"), "at": h.get("created_at"), "note": h.get("note") or "", "payload": h.get("payload") or {}, } for h in hist_rows ] roster = get_roster(gid) if gid else None audits: list[dict[str, Any]] = [] if gid: try: audits = [ a for a in list_liveness_audits(limit=40) if str(a.get("guestId") or "") == gid ][:8] except Exception: audits = [] def _abs_media(url: str) -> str: u = (url or "").strip() if not u: return "" if u.startswith("https://") or u.startswith("http://") or u.startswith("data:"): return u if u.startswith("/api/social/"): return f"https://api.nomadro.com{u}" if u.startswith("/"): return f"https://nomadro.com{u}" return u def _pick_url(*vals: Any) -> str: for v in vals: if isinstance(v, str) and v.strip(): return _abs_media(v.strip()) return "" # Harvest media from lead payload + stage history (localhost dual-write often # has relative /api/social/... URLs even when roster row is missing on US). lead_payload = item.get("payload") if isinstance(item.get("payload"), dict) else {} harvested: dict[str, str] = { "avatar": "", "livenessFrontUrl": "", "livenessTurnUrl": "", "livenessVideoUrl": "", } for blob in (lead_payload, *[h.get("payload") or {} for h in history]): if not isinstance(blob, dict): continue nested = blob.get("payload") if isinstance(blob.get("payload"), dict) else {} sources = (blob, nested) if not harvested["avatar"]: harvested["avatar"] = _pick_url( *(s.get("avatarUrl") or s.get("avatar") for s in sources) ) if not harvested["livenessFrontUrl"]: harvested["livenessFrontUrl"] = _pick_url( *(s.get("frontUrl") or s.get("livenessFrontUrl") for s in sources) ) if not harvested["livenessTurnUrl"]: harvested["livenessTurnUrl"] = _pick_url( *(s.get("turnUrl") or s.get("livenessTurnUrl") for s in sources) ) if not harvested["livenessVideoUrl"]: harvested["livenessVideoUrl"] = _pick_url( *(s.get("videoUrl") or s.get("livenessVideoUrl") for s in sources) ) if audits: a0 = audits[0] if not harvested["livenessFrontUrl"]: harvested["livenessFrontUrl"] = _abs_media(str(a0.get("frontUrl") or "")) if not harvested["livenessTurnUrl"]: harvested["livenessTurnUrl"] = _abs_media(str(a0.get("turnUrl") or "")) if not harvested["livenessVideoUrl"]: harvested["livenessVideoUrl"] = _abs_media(str(a0.get("videoUrl") or "")) media = { "avatar": _abs_media((roster or {}).get("avatar") or "") or harvested["avatar"], "livenessFrontUrl": _abs_media((roster or {}).get("livenessFrontUrl") or "") or harvested["livenessFrontUrl"], "livenessTurnUrl": _abs_media((roster or {}).get("livenessTurnUrl") or "") or harvested["livenessTurnUrl"], "livenessVideoUrl": _abs_media((roster or {}).get("livenessVideoUrl") or "") or harvested["livenessVideoUrl"], "audits": [ { **a, "frontUrl": _abs_media(str(a.get("frontUrl") or "")), "turnUrl": _abs_media(str(a.get("turnUrl") or "")), "videoUrl": _abs_media(str(a.get("videoUrl") or "")), } for a in audits ], } return { "ok": True, "entity": "joinLeads", "id": str(item.get("id") or email or key), "item": {**item, "media": media, "roster": roster or {}}, "softDeleted": False, "history": history, "media": media, "roster": roster or {}, } def admin_get_detail(entity: str, entity_id: str) -> dict[str, Any] | None: if entity == "joinLeads": return admin_get_join_lead(entity_id) init_pb() pb = get_pb() coll = ENTITY_COLLECTIONS.get(entity) if not coll: return None rec = None if entity == "roster": raw = pb.first(coll, filter=f"guest_id={pb_quote(entity_id)}") rec = _roster_from_rec(raw, public=False) if raw else None else: try: rec = pb.request( "GET", f"/api/collections/{coll}/records/{entity_id}", admin=True ) except Exception: rec = None if not rec: return None hist = pb.list_all( C_ARCHIVES, filter=f"entity={pb_quote(entity)} && entity_id={pb_quote(entity_id)}", sort="-created_at", hard_limit=50, ) return { "ok": True, "entity": entity, "id": entity_id, "item": rec, "softDeleted": entity_id in _soft_deleted_ids(entity) or (rec.get("status") == "deleted"), "history": [ { "id": h.get("id"), "action": h.get("action"), "at": h.get("created_at"), "note": h.get("note") or "", "payload": h.get("payload") or {}, } for h in hist ], } def admin_list_archives( *, entity: str = "", limit: int = 100, offset: int = 0 ) -> dict[str, Any]: """Default list excludes join_leads (those live under 加入线索 detail timeline).""" init_pb() lim = max(1, min(int(limit or 100), 500)) off = max(0, int(offset or 0)) entity_n = (entity or "").strip() filt = f"entity={pb_quote(entity_n)}" if entity_n else None rows = get_pb().list_all( C_ARCHIVES, filter=filt, sort="-created_at", hard_limit=5000 ) if not entity_n: rows = [r for r in rows if str(r.get("entity") or "") != "join_leads"] total = len(rows) page = rows[off : off + lim] return { "ok": True, "total": total, "items": [ { "id": r.get("id"), "entity": r.get("entity"), "entityId": r.get("entity_id"), "guestId": r.get("guest_id") or "", "action": r.get("action"), "note": r.get("note") or "", "at": r.get("created_at"), "payload": r.get("payload") or {}, } for r in page ], }