diff --git a/apps/api/services/notify_svc/store.py b/apps/api/services/notify_svc/store.py index f34a0a7..b58bf2d 100644 --- a/apps/api/services/notify_svc/store.py +++ b/apps/api/services/notify_svc/store.py @@ -218,9 +218,78 @@ def init_db() -> None: _ensure_column(c, "messages", "category", "TEXT NOT NULL DEFAULT 'system'") _ensure_column(c, "messages", "deleted", "INTEGER NOT NULL DEFAULT 0") _seed(c) + _ensure_onboarding_workflows(c) _ensure_demo_feed(c) +def _ensure_onboarding_workflows(c: sqlite3.Connection) -> None: + """Idempotent: city-recs workflow + welcome CTA → chat (existing DBs).""" + env_row = c.execute("SELECT id FROM environments LIMIT 1").fetchone() + if not env_row: + return + env = env_row["id"] + now = _now() + exists = c.execute( + "SELECT id FROM workflows WHERE workflow_id=?", + ("city-recs-onboarding",), + ).fetchone() + if not exists: + wf_city = _id("wf") + c.execute( + """INSERT INTO workflows(id,env_id,workflow_id,name,description,active,tags_json,created_at,updated_at) + VALUES(?,?,?,?,?,?,?,?,?)""", + ( + wf_city, + env, + "city-recs-onboarding", + "Same-city recommendations", + "Push 3 same-city people after join profile", + 1, + _json(["onboarding", "social", "city"]), + now, + now, + ), + ) + c.execute( + """INSERT INTO workflow_steps(id,workflow_pk,type,name,position,active,template_json,filters_json) + VALUES(?,?,?,?,?,?,?,?)""", + ( + _id("step"), + wf_city, + "in_app", + "City recs", + 0, + 1, + _json( + { + "subject": "{{city}} · 同城推荐", + "body": "为你挑了几位同城游民:\n{{recsText}}", + "ctaLabel": "去认识他们", + "ctaUrl": "/social/people", + "category": "social", + } + ), + "[]", + ), + ) + # Soft-update welcome in-app CTA toward chat if still pointing at /social/work + for row in c.execute( + """SELECT ws.id, ws.template_json FROM workflow_steps ws + JOIN workflows w ON w.id=ws.workflow_pk + WHERE w.workflow_id='welcome-onboarding' AND ws.type='in_app'""" + ).fetchall(): + tpl = _parse(row["template_json"], {}) + if tpl.get("ctaUrl") == "/social/work": + tpl["ctaUrl"] = "/social/chat" + tpl["ctaLabel"] = "进入群聊" + tpl["body"] = "嗨 {{firstName}}——先去群聊打个招呼,再看看同城推荐。" + tpl["category"] = "social" + c.execute( + "UPDATE workflow_steps SET template_json=? WHERE id=?", + (_json(tpl), row["id"]), + ) + + def _seed(c: sqlite3.Connection) -> None: if c.execute("SELECT 1 FROM environments LIMIT 1").fetchone(): return @@ -283,9 +352,10 @@ def _seed(c: sqlite3.Connection) -> None: 0, { "subject": "欢迎加入 Nomadro", - "body": "嗨 {{firstName}}——打开收件箱,开始远程一起做事。", - "ctaLabel": "打开工作台", - "ctaUrl": "/social/work", + "body": "嗨 {{firstName}}——先去群聊打个招呼,再看看同城推荐。", + "ctaLabel": "进入群聊", + "ctaUrl": "/social/chat", + "category": "social", }, ), ( @@ -306,6 +376,45 @@ def _seed(c: sqlite3.Connection) -> None: (sid, wf_welcome, typ, name, pos, 1, _json(tpl), "[]"), ) + wf_city = "wf_city_recs" + c.execute( + """INSERT INTO workflows(id,env_id,workflow_id,name,description,active,tags_json,created_at,updated_at) + VALUES(?,?,?,?,?,?,?,?,?)""", + ( + wf_city, + env, + "city-recs-onboarding", + "Same-city recommendations", + "Push 3 same-city people after join profile", + 1, + _json(["onboarding", "social", "city"]), + now, + now, + ), + ) + c.execute( + """INSERT INTO workflow_steps(id,workflow_pk,type,name,position,active,template_json,filters_json) + VALUES(?,?,?,?,?,?,?,?)""", + ( + _id("step"), + wf_city, + "in_app", + "City recs", + 0, + 1, + _json( + { + "subject": "{{city}} · 同城推荐", + "body": "为你挑了几位同城游民:\n{{recsText}}", + "ctaLabel": "去认识他们", + "ctaUrl": "/social/people", + "category": "social", + } + ), + "[]", + ), + ) + wf_meetup = "wf_meetup" c.execute( """INSERT INTO workflows(id,env_id,workflow_id,name,description,active,tags_json,created_at,updated_at) diff --git a/apps/api/services/social_svc/onboarding.py b/apps/api/services/social_svc/onboarding.py new file mode 100644 index 0000000..bedd796 --- /dev/null +++ b/apps/api/services/social_svc/onboarding.py @@ -0,0 +1,132 @@ +"""Cold-start: welcome + same-city recommendations via notify_svc (Novu-domain).""" +from __future__ import annotations + +import logging +import os +from typing import Any + +import urllib.error +import urllib.request +import json + +log = logging.getLogger("social_svc.onboarding") + +NOTIFY_INTERNAL_URL = os.getenv( + "NOTIFY_INTERNAL_URL", + os.getenv("NOTIFY_API_URL", "http://127.0.0.1:8023"), +).rstrip("/") +NOTIFY_ONBOARDING_ENABLED = os.getenv("SOCIAL_ONBOARDING_NOTIFY", "true").lower() in { + "1", + "true", + "yes", + "on", +} + + +def _post(path: str, body: dict[str, Any], timeout: float = 4.0) -> dict[str, Any] | None: + url = f"{NOTIFY_INTERNAL_URL}{path}" + data = json.dumps(body).encode("utf-8") + req = urllib.request.Request( + url, + data=data, + headers={"Content-Type": "application/json", "Accept": "application/json"}, + method="POST", + ) + try: + with urllib.request.urlopen(req, timeout=timeout) as res: + raw = res.read().decode("utf-8", errors="replace") + return json.loads(raw) if raw else {} + except (urllib.error.URLError, TimeoutError, json.JSONDecodeError, OSError) as exc: + log.warning("notify call failed %s: %s", path, exc) + return None + + +def ensure_subscriber(guest_id: str, name: str) -> None: + first = (name or "游民").strip()[:40] or "游民" + _post( + "/api/notify/v1/subscribers", + { + "subscriber_id": guest_id, + "first_name": first, + "data": {"source": "social-join"}, + }, + ) + + +def fire_join_onboarding( + *, + guest_id: str, + name: str, + city: str, + recs: list[dict[str, Any]], +) -> dict[str, Any]: + """First-profile hooks: welcome + up to 3 same-city cards into in-app inbox.""" + if not NOTIFY_ONBOARDING_ENABLED: + return {"ok": False, "skipped": "disabled"} + + ensure_subscriber(guest_id, name) + first = (name or "游民").strip()[:40] or "游民" + city_label = (city or "").strip() or "同城" + + welcome = _post( + "/api/notify/v1/events/trigger", + { + "workflow_id": "welcome-onboarding", + "subscriber_id": guest_id, + "payload": { + "firstName": first, + "city": city_label, + "category": "social", + }, + }, + ) + + lines: list[str] = [] + for i, r in enumerate(recs[:3], start=1): + n = str(r.get("name") or "游民").strip() + c = str(r.get("city") or city_label).strip() + t = str(r.get("title") or r.get("lookingFor") or "").strip() + bit = f"{i}. {n} · {c}" + if t: + bit += f" · {t[:40]}" + lines.append(bit) + recs_text = "\n".join(lines) if lines else "暂时还没有同城推荐,先去「想见的人」逛逛。" + + # Reuse welcome workflow shape by posting a direct social tip via a second trigger + # with city-recs-onboarding if present; otherwise welcome payload is enough + inbox CTA. + recs_result = _post( + "/api/notify/v1/events/trigger", + { + "workflow_id": "city-recs-onboarding", + "subscriber_id": guest_id, + "payload": { + "firstName": first, + "city": city_label, + "recsText": recs_text, + "category": "social", + "count": len(recs[:3]), + }, + }, + ) + # Fallback: if city-recs workflow missing, inject via welcome-style trigger body in activity only + if recs_result is None and lines: + _post( + "/api/notify/v1/events/trigger", + { + "workflow_id": "welcome-onboarding", + "subscriber_id": guest_id, + "payload": { + "firstName": first, + "city": city_label, + "category": "social", + "recsText": recs_text, + }, + }, + ) + + return { + "ok": True, + "welcome": bool(welcome), + "recs": len(recs[:3]), + "recsText": recs_text, + } diff --git a/apps/api/services/social_svc/routers/api.py b/apps/api/services/social_svc/routers/api.py index e9e31bc..1269853 100644 --- a/apps/api/services/social_svc/routers/api.py +++ b/apps/api/services/social_svc/routers/api.py @@ -98,13 +98,16 @@ class RosterIn(BaseModel): skills: str = Field(default="", max_length=200) bio: str = Field(default="", max_length=2000) avatar: str = Field(default="", max_length=500) - # extra join fields accepted but not all persisted as columns gender: str = Field(default="", max_length=16) relationship: str = Field(default="", max_length=32) education: str = Field(default="", max_length=32) graduation: str = Field(default="", max_length=32) wechat: str = Field(default="", max_length=64) intents: str = Field(default="", max_length=240) + availability: str = Field(default="", max_length=120) + status: str = Field(default="online", max_length=32) + lookingFor: str = Field(default="", max_length=200) + discoverable: bool | int | str = True updatedAt: str = Field(default="", max_length=40) @@ -620,6 +623,31 @@ def get_my_roster(x_social_guest_id: str | None = Header(default=None)): return {"item": store.get_roster(guest)} +@router.get("/roster/discovery") +def roster_discovery( + city: str = Query(default=""), + limit: int = Query(default=48, ge=1, le=100), + x_social_guest_id: str | None = Header(default=None), + guest: str | None = Query(default=None), +): + """Public discovery feed: same-city → online → tag match (no phone/wechat).""" + peer = _guest(x_social_guest_id, guest) + store.init_db() + items = store.list_discovery_roster( + viewer_guest_id=peer, + city=(city or "").strip(), + limit=limit, + exclude_self=True, + ) + viewer = store.get_roster(peer) + return { + "ok": True, + "viewerCity": (viewer or {}).get("city") or "", + "items": items, + "count": len(items), + } + + @router.put("/roster/me") def put_my_roster( body: RosterIn, @@ -627,7 +655,25 @@ def put_my_roster( ): guest = _guest(x_social_guest_id) store.init_db() - return store.upsert_roster(guest, body.model_dump()) + row = store.upsert_roster(guest, body.model_dump()) + onboarding = None + if row.get("isFirstProfile"): + try: + from social_svc.onboarding import fire_join_onboarding + + recs = store.city_recommendations(guest, limit=3) + onboarding = fire_join_onboarding( + guest_id=guest, + name=str(row.get("name") or ""), + city=str(row.get("city") or ""), + recs=recs, + ) + except Exception as exc: # noqa: BLE001 — never block profile save + onboarding = {"ok": False, "error": str(exc)[:160]} + out = {k: v for k, v in row.items() if k != "isFirstProfile"} + if onboarding is not None: + out["onboarding"] = onboarding + return out @router.post("/feedback") diff --git a/apps/api/services/social_svc/store.py b/apps/api/services/social_svc/store.py index 88816cd..3e8d552 100644 --- a/apps/api/services/social_svc/store.py +++ b/apps/api/services/social_svc/store.py @@ -163,6 +163,25 @@ def init_db() -> None: roster_cols = {r[1] for r in conn.execute("PRAGMA table_info(roster)").fetchall()} if "avatar" not in roster_cols: conn.execute("ALTER TABLE roster ADD COLUMN avatar TEXT") + # P0 cold-start profile fields (join → discovery ranking) + for col, decl in ( + ("gender", "TEXT"), + ("intents", "TEXT"), + ("availability", "TEXT"), + ("status", "TEXT"), + ("looking_for", "TEXT"), + ("relationship", "TEXT"), + ("education", "TEXT"), + ("graduation", "TEXT"), + ("wechat", "TEXT"), + ("discoverable", "INTEGER DEFAULT 1"), + ("onboarded_at", "TEXT"), + ): + if col not in roster_cols: + conn.execute(f"ALTER TABLE roster ADD COLUMN {col} {decl}") + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_roster_city ON roster(city)" + ) conn.executescript( """ CREATE TABLE IF NOT EXISTS files ( @@ -884,27 +903,68 @@ def add_review( return item +def _norm_city(city: str) -> str: + return "".join(str(city or "").strip().lower().split()) + + +def _split_tags(raw: str) -> list[str]: + return [ + t.strip() + for t in str(raw or "").replace(",", ",").replace("、", ",").split(",") + if t.strip() + ] + + +def _roster_row_to_dict(r: Any, *, public: bool = False) -> dict[str, Any]: + keys = set(r.keys()) + intents = (r["intents"] if "intents" in keys else "") or "" + skills = r["skills"] or "" + status = ((r["status"] if "status" in keys else "") or "online").strip() or "online" + item: dict[str, Any] = { + "guestId": r["guest_id"], + "name": r["name"], + "title": r["title"] or "", + "city": r["city"] or "", + "skills": skills, + "bio": r["bio"] or "", + "avatar": (r["avatar"] if "avatar" in keys else "") or "", + "gender": (r["gender"] if "gender" in keys else "") or "", + "intents": intents, + "availability": (r["availability"] if "availability" in keys else "") or "", + "status": status, + "lookingFor": (r["looking_for"] if "looking_for" in keys else "") or "", + "updatedAt": r["updated_at"], + "online": status in {"online", "here", "available"}, + "tags": _split_tags(skills)[:8], + } + if not public: + item.update( + { + "phone": r["phone"] or "", + "linktree": r["linktree"] or "", + "relationship": (r["relationship"] if "relationship" in keys else "") or "", + "education": (r["education"] if "education" in keys else "") or "", + "graduation": (r["graduation"] if "graduation" in keys else "") or "", + "wechat": (r["wechat"] if "wechat" in keys else "") or "", + "discoverable": int(r["discoverable"] if "discoverable" in keys and r["discoverable"] is not None else 1), + "onboardedAt": (r["onboarded_at"] if "onboarded_at" in keys else "") or "", + } + ) + else: + item["linktree"] = r["linktree"] or "" + return item + + def get_roster(guest_id: str) -> dict[str, Any] | None: with db() as conn: r = conn.execute("SELECT * FROM roster WHERE guest_id = ?", (guest_id,)).fetchone() if not r: return None - keys = set(r.keys()) - return { - "guestId": r["guest_id"], - "name": r["name"], - "title": r["title"] or "", - "city": r["city"] or "", - "phone": r["phone"] or "", - "linktree": r["linktree"] or "", - "skills": r["skills"] or "", - "bio": r["bio"] or "", - "avatar": (r["avatar"] if "avatar" in keys else "") or "", - "updatedAt": r["updated_at"], - } + return _roster_row_to_dict(r, public=False) def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]: + """Insert/update roster. Returns (row, is_first_profile).""" updated = _now() avatar = str(payload.get("avatar") or "").strip()[:500] if avatar and not ( @@ -913,6 +973,29 @@ def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]: 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 = 1 + else: + discoverable = 1 if str(discoverable).lower() not in {"0", "false", "no", "off"} else 0 + + existing = get_roster(guest_id) + is_first = existing is None + onboarded_at = (existing or {}).get("onboardedAt") or (updated if is_first else "") + row = { "guestId": guest_id, "name": str(payload.get("name") or "").strip()[:64] or "游民", @@ -923,13 +1006,29 @@ def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]: "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, + "lookingFor": 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, + "onboardedAt": onboarded_at, "updatedAt": updated, + "isFirstProfile": is_first, } with db() as conn: conn.execute( """ - INSERT INTO roster(guest_id, name, title, city, phone, linktree, skills, bio, avatar, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + INSERT INTO roster( + guest_id, name, title, city, phone, linktree, skills, bio, avatar, + gender, intents, availability, status, looking_for, + relationship, education, graduation, wechat, discoverable, onboarded_at, updated_at + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(guest_id) DO UPDATE SET name=excluded.name, title=excluded.title, @@ -939,6 +1038,17 @@ def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]: skills=excluded.skills, bio=excluded.bio, avatar=excluded.avatar, + gender=excluded.gender, + intents=excluded.intents, + availability=excluded.availability, + status=excluded.status, + looking_for=excluded.looking_for, + relationship=excluded.relationship, + education=excluded.education, + graduation=excluded.graduation, + wechat=excluded.wechat, + discoverable=excluded.discoverable, + onboarded_at=COALESCE(roster.onboarded_at, excluded.onboarded_at), updated_at=excluded.updated_at """, ( @@ -951,12 +1061,111 @@ def upsert_roster(guest_id: str, payload: dict[str, Any]) -> dict[str, Any]: row["skills"], row["bio"], row["avatar"], + row["gender"], + row["intents"], + row["availability"], + row["status"], + row["lookingFor"], + row["relationship"], + row["education"], + row["graduation"], + row["wechat"], + row["discoverable"], + row["onboardedAt"], updated, ), ) return row +def score_discovery( + viewer: dict[str, Any] | None, + item: dict[str, Any], +) -> int: + """Higher = better: same city >> online >> tag/intent overlap.""" + score = 0 + v_city = _norm_city((viewer or {}).get("city") or "") + i_city = _norm_city(item.get("city") or "") + if v_city and i_city and v_city == i_city: + score += 1000 + elif v_city and i_city and (v_city in i_city or i_city in v_city): + score += 600 + if item.get("online"): + score += 200 + v_tags = set( + t.lower() + for t in ( + _split_tags((viewer or {}).get("skills") or "") + + _split_tags((viewer or {}).get("intents") or "") + ) + ) + i_tags = set( + t.lower() + for t in ( + list(item.get("tags") or []) + + _split_tags(item.get("intents") or "") + + _split_tags(item.get("lookingFor") or "") + ) + ) + score += min(120, 40 * len(v_tags & i_tags)) + # fresher profiles float a bit + updated = str(item.get("updatedAt") or "") + if updated: + score += min(50, max(0, len(updated))) + return score + + +def list_discovery_roster( + *, + viewer_guest_id: str | None = None, + city: str = "", + limit: int = 48, + exclude_self: bool = True, +) -> list[dict[str, Any]]: + """Public discovery cards ranked for viewer (same-city + online + tags).""" + limit = max(1, min(int(limit or 48), 100)) + viewer = get_roster(viewer_guest_id) if viewer_guest_id else None + with db() as conn: + rows = conn.execute( + """ + SELECT * FROM roster + WHERE COALESCE(discoverable, 1) = 1 + AND TRIM(COALESCE(name, '')) != '' + ORDER BY updated_at DESC + LIMIT 400 + """ + ).fetchall() + items: list[dict[str, Any]] = [] + city_f = _norm_city(city) + for r in rows: + if exclude_self and viewer_guest_id and r["guest_id"] == viewer_guest_id: + continue + item = _roster_row_to_dict(r, public=True) + if city_f: + ic = _norm_city(item.get("city") or "") + if not ic or (city_f not in ic and ic not in city_f): + continue + item["score"] = score_discovery(viewer, item) + items.append(item) + items.sort( + key=lambda x: (-int(x.get("score") or 0), str(x.get("updatedAt") or "")), + ) + return items[:limit] + + +def city_recommendations( + guest_id: str, + *, + limit: int = 3, +) -> list[dict[str, Any]]: + """Top same-city (then tag-matched) people for onboarding push.""" + return list_discovery_roster( + viewer_guest_id=guest_id, + limit=limit, + exclude_self=True, + ) + + def add_feedback(kind: str, text: str, contact: str, guest_id: str) -> dict[str, Any]: item = { "id": _uid("fb"), diff --git a/src/modules/social/app/experience.css b/src/modules/social/app/experience.css index ec33f1d..0bd4303 100644 --- a/src/modules/social/app/experience.css +++ b/src/modules/social/app/experience.css @@ -811,6 +811,13 @@ padding-top: 0; border-top: 0; } +.social-join-req { + margin-left: 4px; + color: #f59e0b; + font-weight: 800; + text-transform: none; + letter-spacing: 0; +} .social-join-span-2 { grid-column: 1 / -1; } diff --git a/src/modules/social/components/CommunityWelcome.tsx b/src/modules/social/components/CommunityWelcome.tsx index f40f9d5..ad0c5e3 100644 --- a/src/modules/social/components/CommunityWelcome.tsx +++ b/src/modules/social/components/CommunityWelcome.tsx @@ -25,11 +25,13 @@ import { useSocialConfig } from "./SocialExperience"; import { socialApi } from "@social/lib/api"; import { useCaptureCapability } from "@social/lib/useCaptureCapability"; import { + JOIN_AVAILABILITY_OPTIONS, JOIN_EDUCATION_OPTIONS, JOIN_GENDER_OPTIONS, JOIN_INTENT_OPTIONS, JOIN_PROFILE_RETURN, JOIN_RELATIONSHIP_OPTIONS, + JOIN_STATUS_OPTIONS, isJoinPaid, isJoinProfileDone, markJoinPaid, @@ -37,6 +39,7 @@ import { type JoinOption, type JoinProfileDraft, } from "@social/lib/joinFlow"; +import { setRosterPublished } from "@social/lib/discoveryRoster"; import { loadJson, saveJson } from "@social/lib/storage"; import { useLocalState } from "@social/lib/useLocalState"; import { socialPath } from "@social/lib/socialPath"; @@ -190,6 +193,8 @@ const EMPTY_JOIN_PROFILE: JoinProfileDraft = { graduation: "", relationship: "", intents: [], + availability: "", + status: "online", linktree: "", bio: "", }; @@ -361,6 +366,12 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) { ...EMPTY_JOIN_PROFILE, ...saved, intents: Array.isArray(saved.intents) ? saved.intents : [], + availability: + typeof saved.availability === "string" ? saved.availability : "", + status: + typeof saved.status === "string" && saved.status + ? saved.status + : "online", name: typeof nick === "string" ? nick : "", avatar: typeof saved.avatar === "string" && !saved.avatar.startsWith("blob:") @@ -501,6 +512,18 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) { nameRef.current?.focus(); return; } + if (!draft.city.trim()) { + setErr(socialTx("请填写当前城市,方便同城推荐")); + return; + } + if (!draft.intents.length) { + setErr(socialTx("请至少选一个「想认识 / 想做什么」")); + return; + } + if (!draft.skills.trim()) { + setErr(socialTx("请填写技能或兴趣标签(逗号分隔)")); + return; + } if (draft.linktree.trim() && !/^https?:\/\//i.test(draft.linktree.trim())) { setErr(socialTx("作品链接请以 https:// 或 http:// 开头。")); return; @@ -517,15 +540,11 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) { ] || id, ) .filter(Boolean); - const metaBits = [ - draft.skills.trim(), - draft.relationship ? `关系:${draft.relationship}` : "", - draft.gender ? `性别:${draft.gender}` : "", - draft.education ? `学历:${draft.education}` : "", - draft.graduation.trim() ? `毕业:${draft.graduation.trim()}` : "", - intentLabels.length ? `想要:${intentLabels.join("、")}` : "", - draft.wechat.trim() ? `微信:${draft.wechat.trim()}` : "", - ].filter(Boolean); + const availLabel = + JOIN_AVAILABILITY_OPTIONS.find((o) => o.value === draft.availability)?.[ + locale === "en" ? "labelEn" : "labelZh" + ] || draft.availability; + const lookingFor = intentLabels.join(" · "); const avatar = draft.avatar.startsWith("blob:") ? "" : draft.avatar.trim(); @@ -535,9 +554,14 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) { city: draft.city.trim(), phone: draft.phone.trim(), linktree: draft.linktree.trim(), - skills: metaBits.join(" · "), + skills: draft.skills.trim(), bio: draft.bio.trim(), avatar, + intents: draft.intents.join(","), + availability: availLabel || draft.availability, + status: draft.status || "online", + lookingFor, + gender: draft.gender, updatedAt: new Date().toISOString(), }; @@ -545,6 +569,7 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) { saveJson("roster", roster); saveJson("nick", name); saveJson("join-profile", draft); + setRosterPublished(true); await socialApi.saveRoster({ name: roster.name, title: roster.title, @@ -560,6 +585,10 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) { graduation: draft.graduation.trim(), wechat: draft.wechat.trim(), intents: draft.intents.join(","), + availability: roster.availability || "", + status: roster.status || "online", + lookingFor, + discoverable: "1", updatedAt: roster.updatedAt || "", }); } catch { @@ -828,7 +857,9 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) { /> + update("status", value || "online")} + /> + update("availability", value)} + />

{socialTx("工作与背景")}

-

{socialTx("你想在社区做什么")}

+

+ {socialTx("你想在社区做什么")} + * +

= { export default function HomeClient() { const config = useSocialConfig(); const { locale, t } = useSocialI18n(); - const roster = useAudienceRoster(); + const roster = useDiscoveryRoster(); const [joinOpen, setJoinOpen] = useState(false); const [activeSection, setActiveSection] = useState("people"); const promoUrl = @@ -62,12 +62,12 @@ export default function HomeClient() { ); const meetups = catalog.meetups; const gigs = catalog.gigs; - // 封面必须是美女:女生优先,不够再用在线的人补 - const datePreview = (() => { + // Ranked discovery (same-city → online → tags); soft bias women for cover strip + const datePreview = useMemo(() => { const women = roster.filter((m) => m.gender === "f"); - const rest = roster.filter((m) => m.gender !== "f" && m.online); + const rest = roster.filter((m) => m.gender !== "f"); return [...women, ...rest].slice(0, 3); - })(); + }, [roster]); useEffect(() => { const root = document.querySelector(".social-home"); diff --git a/src/modules/social/components/ProfileStudio.tsx b/src/modules/social/components/ProfileStudio.tsx index 6798967..b637507 100644 --- a/src/modules/social/components/ProfileStudio.tsx +++ b/src/modules/social/components/ProfileStudio.tsx @@ -27,6 +27,11 @@ const EMPTY: SocialRosterProfile = { skills: "", bio: "", avatar: "", + intents: "", + availability: "", + status: "", + lookingFor: "", + gender: "", }; const FIELDS = [ { diff --git a/src/modules/social/lib/api.ts b/src/modules/social/lib/api.ts index b1f9b27..1775669 100644 --- a/src/modules/social/lib/api.ts +++ b/src/modules/social/lib/api.ts @@ -225,6 +225,38 @@ export const socialApi = { saveRoster: (payload: Record) => req("/roster/me", { method: "PUT", json: payload }), + /** Ranked public profiles: same-city → online → tag match. */ + discoveryRoster: (opts?: { city?: string; limit?: number }) => { + const q = new URLSearchParams(); + if (opts?.city) q.set("city", opts.city); + if (opts?.limit) q.set("limit", String(opts.limit)); + const qs = q.toString(); + return req<{ + ok: boolean; + viewerCity: string; + count: number; + items: Array<{ + guestId: string; + name: string; + title: string; + city: string; + skills: string; + bio: string; + avatar: string; + gender: string; + intents: string; + availability: string; + status: string; + lookingFor: string; + online: boolean; + tags: string[]; + score: number; + updatedAt: string; + linktree?: string; + }>; + }>(`/roster/discovery${qs ? `?${qs}` : ""}`, { ttlMs: 20_000 }); + }, + /** Two-frame live selfie challenge → verified front frame stored as avatar. */ uploadAvatarChallenge: async (front: Blob, turn: Blob) => { const form = new FormData(); diff --git a/src/modules/social/lib/discoveryRoster.ts b/src/modules/social/lib/discoveryRoster.ts index 6db0705..818cc2b 100644 --- a/src/modules/social/lib/discoveryRoster.ts +++ b/src/modules/social/lib/discoveryRoster.ts @@ -1,9 +1,14 @@ "use client"; -import { useMemo, useSyncExternalStore } from "react"; +import { useEffect, useMemo, useState, useSyncExternalStore } from "react"; import { useAudienceModule } from "~/modules/audience"; +import { socialApi } from "./api"; import { MOCK_ROSTER, type SocialRosterMember } from "./rosterMock"; import { cnAvatarForSeed, mapRosterAvatarPack } from "./rosterAvatars"; +import { + discoveryItemToMember, + sortDiscoveryMembers, +} from "./rankDiscovery"; import { loadJson, saveJson } from "./storage"; import type { SocialRosterProfile } from "./types"; @@ -20,6 +25,11 @@ const EMPTY: SocialRosterProfile = { skills: "", bio: "", avatar: "", + intents: "", + availability: "", + status: "", + lookingFor: "", + gender: "", }; const STORAGE_CHANGE = "nomadro-social-storage"; @@ -60,8 +70,10 @@ export function profileToMember( const avatar = ownOk ? own : avatarPack === "cn" - ? cnAvatarForSeed(name, "f") + ? cnAvatarForSeed(name, (profile.gender as "f" | "m") || "f") : `https://api.dicebear.com/7.x/initials/svg?seed=${encodeURIComponent(name)}`; + const status = (profile.status || "online").trim(); + const online = status === "online" || status === "here" || status === "available"; return { id: SELF_MEMBER_ID, name, @@ -70,14 +82,31 @@ export function profileToMember( tags: tags.length ? tags : ["新朋友"], avatar, bio: profile.bio.trim() || "刚写好介绍,想认识同频的人。", - vibe: "刚出现", - online: true, - lookingFor: "想认识同频游民", - gender: "f", + vibe: status === "here" ? "同城想出来" : online ? "在线" : "刚出现", + online, + lookingFor: + (profile.lookingFor || "").trim() || + (profile.intents || "").replace(/,/g, " · ") || + "想认识同频游民", + gender: profile.gender === "m" ? "m" : "f", + availability: (profile.availability || "").trim() || undefined, }; } -/** Seed roster + optional self card when user opted into discovery. */ +function readLocalProfile(): SocialRosterProfile { + const raw = loadJson>("roster", EMPTY); + const next = { ...EMPTY }; + (Object.keys(EMPTY) as (keyof SocialRosterProfile)[]).forEach((key) => { + const val = raw?.[key]; + if (typeof val === "string") next[key] = val; + }); + return next; +} + +/** + * Discovery list: live API (same-city / online / tags) → merge mock fallback → + * optional self card. Ranked for local viewer profile. + */ export function useDiscoveryRoster(): SocialRosterMember[] { const { bundle } = useAudienceModule(); const pack = bundle.module.social.rosterAvatarPack; @@ -86,8 +115,6 @@ export function useDiscoveryRoster(): SocialRosterMember[] { () => loadJson(ROSTER_PUBLISH_KEY, false), () => false, ); - // getSnapshot must be referentially stable: JSON.parse creates a new object - // on every read once a local profile exists, causing a React render loop. const profileSnapshot = useSyncExternalStore( subscribeSocialStorage, () => JSON.stringify(loadJson("roster", EMPTY)), @@ -102,13 +129,46 @@ export function useDiscoveryRoster(): SocialRosterMember[] { }); return next; }, [profileSnapshot]); + + const [remote, setRemote] = useState(null); + + useEffect(() => { + let cancelled = false; + void socialApi + .discoveryRoster({ limit: 48 }) + .then((res) => { + if (cancelled || !res?.items?.length) return; + setRemote(res.items.map(discoveryItemToMember)); + }) + .catch(() => { + /* offline → keep mock */ + }); + return () => { + cancelled = true; + }; + }, [profile.city, profile.skills, profile.intents]); + const seed = useMemo( () => mapRosterAvatarPack(MOCK_ROSTER, pack), [pack], ); + return useMemo(() => { + const live = remote || []; + const liveIds = new Set(live.map((m) => m.id)); + // Prefer real people; pad with mock so empty cities still feel alive + const merged = [ + ...live, + ...seed.filter((m) => !liveIds.has(m.id)), + ]; + const ranked = sortDiscoveryMembers(merged, profile); const self = published ? profileToMember(profile, pack) : null; - if (!self) return seed; - return [self, ...seed.filter((m) => m.id !== SELF_MEMBER_ID)]; - }, [published, profile, seed, pack]); + if (!self) return ranked; + return [self, ...ranked.filter((m) => m.id !== SELF_MEMBER_ID)]; + }, [published, profile, seed, pack, remote]); +} + +/** One-shot helper for non-hook call sites. */ +export function getLocalViewerProfile(): SocialRosterProfile { + return readLocalProfile(); } diff --git a/src/modules/social/lib/joinFlow.ts b/src/modules/social/lib/joinFlow.ts index aa9b961..008798b 100644 --- a/src/modules/social/lib/joinFlow.ts +++ b/src/modules/social/lib/joinFlow.ts @@ -18,7 +18,12 @@ export type JoinProfileDraft = { education: string; graduation: string; relationship: string; + /** who-to-meet / why join — required for cold-start matching */ intents: string[]; + /** e.g. 本周可 coffeechat / 欧洲晚间可视频 */ + availability: string; + /** online | away | offline — discovery “在线优先” */ + status: string; linktree: string; bio: string; }; @@ -58,12 +63,30 @@ export const JOIN_INTENT_OPTIONS: JoinOption[] = [ { value: "online", labelZh: "线上分享", labelEn: "Online hangouts" }, { value: "cowork", labelZh: "远程 cowork", labelEn: "Remote cowork" }, { value: "collab", labelZh: "找搭子做事", labelEn: "Find collaborators" }, + { value: "cofounder", labelZh: "找联创", labelEn: "Find a cofounder" }, { value: "friends", labelZh: "交朋友", labelEn: "Make friends" }, { value: "date", labelZh: "认识有缘人", labelEn: "Meet someone" }, { value: "learn", labelZh: "学习成长", labelEn: "Learn & grow" }, { value: "resource", labelZh: "资源互助", labelEn: "Share resources" }, ]; +/** Preferred hangout windows for coffeechat / meetup matching. */ +export const JOIN_AVAILABILITY_OPTIONS: JoinOption[] = [ + { value: "", labelZh: "先不填", labelEn: "Skip for now" }, + { value: "weekday-eve", labelZh: "工作日晚上", labelEn: "Weekday evenings" }, + { value: "weekend", labelZh: "周末可约", labelEn: "Weekends" }, + { value: "flexible", labelZh: "时间灵活", labelEn: "Flexible" }, + { value: "tz-async", labelZh: "跨时区异步", labelEn: "Async / timezone-friendly" }, +]; + +/** Discovery presence signal (not GPS). */ +export const JOIN_STATUS_OPTIONS: JoinOption[] = [ + { value: "online", labelZh: "在线 · 想认识人", labelEn: "Online · open to meet" }, + { value: "here", labelZh: "同城 · 想出来", labelEn: "In city · want to hang" }, + { value: "away", labelZh: "先潜水看看", labelEn: "Lurking for now" }, + { value: "offline", labelZh: "暂时隐身", labelEn: "Appear offline" }, +]; + export function markJoinPayIntent(): void { try { localStorage.setItem(JOIN_PENDING_PROFILE_KEY, "1"); diff --git a/src/modules/social/lib/phrases.ts b/src/modules/social/lib/phrases.ts index 8f226b7..05729c1 100644 --- a/src/modules/social/lib/phrases.ts +++ b/src/modules/social/lib/phrases.ts @@ -343,6 +343,14 @@ export const SOCIAL_PHRASES_EN: Record = { "Prefer a front-camera selfie — we check face presence & liveness", "建议现场自拍核验:正脸 + 微转头": "Live selfie check: front face + slight head turn", + "请填写当前城市,方便同城推荐": + "Add your city so we can recommend people nearby", + "请至少选一个「想认识 / 想做什么」": + "Pick at least one “who / what you’re looking for”", + "请填写技能或兴趣标签(逗号分隔)": + "Add skill or interest tags (comma-separated)", + "当前状态": "Status", + "可约时段": "Availability", "检测设备中…": "Detecting device…", "电脑已检测到摄像头:建议现场预览自拍(正脸 + 微转头)": "Webcam found — live preview selfie recommended (front + slight turn)", diff --git a/src/modules/social/lib/rankDiscovery.ts b/src/modules/social/lib/rankDiscovery.ts new file mode 100644 index 0000000..8807d01 --- /dev/null +++ b/src/modules/social/lib/rankDiscovery.ts @@ -0,0 +1,96 @@ +import type { SocialRosterMember } from "./rosterMock"; +import type { SocialRosterProfile } from "./types"; + +function normCity(city: string): string { + return city.trim().toLowerCase().replace(/\s+/g, ""); +} + +function tagSet(raw: string | string[] | undefined): Set { + const parts = Array.isArray(raw) + ? raw + : String(raw || "") + .split(/[,,、·|/\s]+/) + .map((t) => t.trim()) + .filter(Boolean); + return new Set(parts.map((t) => t.toLowerCase())); +} + +/** Client-side mirror of social_svc.score_discovery for mock merge. */ +export function scoreDiscoveryMember( + viewer: Partial | null | undefined, + member: SocialRosterMember, +): number { + let score = 0; + const vCity = normCity(viewer?.city || ""); + const mCity = normCity(member.city || ""); + if (vCity && mCity && vCity === mCity) score += 1000; + else if (vCity && mCity && (vCity.includes(mCity) || mCity.includes(vCity))) + score += 600; + if (member.online) score += 200; + const vTags = new Set([ + ...tagSet(viewer?.skills), + ...tagSet(viewer?.intents), + ...tagSet(viewer?.lookingFor), + ]); + const mTags = new Set([ + ...tagSet(member.tags), + ...tagSet(member.lookingFor), + ]); + let overlap = 0; + vTags.forEach((t) => { + if (mTags.has(t)) overlap += 1; + }); + score += Math.min(120, overlap * 40); + return score; +} + +export function sortDiscoveryMembers( + members: SocialRosterMember[], + viewer: Partial | null | undefined, +): SocialRosterMember[] { + return [...members].sort((a, b) => { + const sb = scoreDiscoveryMember(viewer, b); + const sa = scoreDiscoveryMember(viewer, a); + if (sb !== sa) return sb - sa; + return (a.name || "").localeCompare(b.name || "", "zh"); + }); +} + +export function discoveryItemToMember(item: { + guestId: string; + name: string; + title?: string; + city?: string; + skills?: string; + bio?: string; + avatar?: string; + gender?: string; + lookingFor?: string; + availability?: string; + online?: boolean; + tags?: string[]; + status?: string; +}): SocialRosterMember { + const tags = + item.tags?.length + ? item.tags + : String(item.skills || "") + .split(/[,,、]/) + .map((t) => t.trim()) + .filter(Boolean) + .slice(0, 8); + return { + id: item.guestId, + name: item.name, + title: item.title || "游民", + city: item.city || "探索中", + tags: tags.length ? tags : ["新朋友"], + avatar: item.avatar || "", + bio: item.bio || "", + vibe: item.status === "here" ? "同城想出来" : item.online ? "在线" : "刚出现", + online: Boolean(item.online), + lookingFor: item.lookingFor || "想认识同频游民", + gender: (item.gender as SocialRosterMember["gender"]) || "f", + availability: item.availability || "", + }; +} diff --git a/src/modules/social/lib/types.ts b/src/modules/social/lib/types.ts index 10713b0..7fa48fd 100644 --- a/src/modules/social/lib/types.ts +++ b/src/modules/social/lib/types.ts @@ -125,5 +125,10 @@ export type SocialRosterProfile = { skills: string; bio: string; avatar?: string; + gender?: string; + intents?: string; + availability?: string; + status?: string; + lookingFor?: string; updatedAt?: string; };