nomadro/apps/api/services/social_svc/onboarding.py
Eric ac754c700b Add social Profile cold-start: ranked discovery and join onboarding.
Persist city/intents/availability/status on roster, expose /roster/discovery, and fire welcome + same-city recs via notify on first profile save.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-04 14:46:19 +08:00

133 lines
3.6 KiB
Python

"""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,
}