"""Skill swap · meetup reviews · report/block · wrapped — PocketBase only.""" from __future__ import annotations from typing import Any from nomadro_pb import ensure_once, get_pb, pb_quote from social_svc import pb_data from social_svc.pb_data import _now, _uid C_SKILLS = "social_skill_posts" C_REVIEWS = "social_meetup_reviews" C_BLOCKS = "social_blocks" C_REPORTS = "social_reports" def ensure_community_tables() -> None: ensure_once() def create_skill_post( guest_id: str, *, author: str, city: str, offer: str, want: str, note: str = "", ) -> dict[str, Any]: ensure_community_tables() item = { "id": _uid("sk"), "guestId": guest_id, "author": (author or "游民").strip()[:64] or "游民", "city": (city or "").strip()[:64], "offer": (offer or "").strip()[:200], "want": (want or "").strip()[:200], "note": (note or "").strip()[:800], "status": "open", "createdAt": _now(), } if not item["offer"] or not item["want"]: raise ValueError("请填写能提供什么、想换什么") rec = get_pb().create( C_SKILLS, { "guest_id": guest_id, "author": item["author"], "city": item["city"], "offer": item["offer"], "want": item["want"], "note": item["note"], "status": "open", "created_at": item["createdAt"], }, ) item["id"] = rec.get("id") or item["id"] return item def list_skill_posts(*, city: str = "", limit: int = 60) -> list[dict[str, Any]]: ensure_community_tables() limit = max(1, min(int(limit or 60), 120)) filt = 'status="open"' rows = get_pb().list_all(C_SKILLS, filter=filt, sort="-created_at", hard_limit=200) city_f = city.strip().lower() out = [] for r in rows: if city_f and city_f not in (r.get("city") or "").lower(): continue out.append( { "id": r.get("id"), "guestId": r.get("guest_id"), "author": r.get("author"), "city": r.get("city") or "", "offer": r.get("offer"), "want": r.get("want"), "note": r.get("note") or "", "status": r.get("status"), "createdAt": r.get("created_at"), } ) if len(out) >= limit: break return out def close_skill_post(guest_id: str, post_id: str) -> dict[str, Any]: ensure_community_tables() r = get_pb().first(C_SKILLS, filter=f"id={pb_quote(post_id)}") if not r: # PB id filter uses record id field try: r = get_pb().request( "GET", f"/api/collections/{C_SKILLS}/records/{post_id}", admin=True ) except Exception: r = None if not r: raise ValueError("帖子不存在") if r.get("guest_id") != guest_id: raise ValueError("只能关闭自己的帖子") get_pb().update(C_SKILLS, r["id"], {"status": "closed"}) return {"ok": True, "id": post_id, "status": "closed"} def create_meetup_review( from_guest: str, *, to_guest: str, to_name: str = "", booking_id: str = "", punctuality: int, chemistry: int, professionalism: int, text: str = "", ) -> dict[str, Any]: ensure_community_tables() if from_guest == to_guest: raise ValueError("不能评价自己") for n in (punctuality, chemistry, professionalism): if not 1 <= int(n) <= 5: raise ValueError("评分须为 1–5") if booking_id: hit = get_pb().first( C_REVIEWS, filter=( f"booking_id={pb_quote(booking_id)} && " f"from_guest={pb_quote(from_guest)} && " f"to_guest={pb_quote(to_guest)}" ), ) if hit: raise ValueError("你已经评价过这次见面") item = { "id": _uid("rv"), "bookingId": (booking_id or "").strip()[:80], "fromGuest": from_guest, "toGuest": to_guest, "toName": (to_name or "").strip()[:64], "punctuality": int(punctuality), "chemistry": int(chemistry), "professionalism": int(professionalism), "text": (text or "").strip()[:800], "createdAt": _now(), } rec = get_pb().create( C_REVIEWS, { "booking_id": item["bookingId"], "from_guest": from_guest, "to_guest": to_guest, "to_name": item["toName"], "punctuality": item["punctuality"], "chemistry": item["chemistry"], "professionalism": item["professionalism"], "text": item["text"], "created_at": item["createdAt"], }, ) item["id"] = rec.get("id") or item["id"] return item def reviews_for_guest(guest_id: str, limit: int = 40) -> dict[str, Any]: ensure_community_tables() limit = max(1, min(int(limit or 40), 100)) rows = get_pb().list_all( C_REVIEWS, filter=f"to_guest={pb_quote(guest_id)}", sort="-created_at", hard_limit=limit, ) items = [ { "id": r.get("id"), "bookingId": r.get("booking_id") or "", "fromGuest": r.get("from_guest"), "toGuest": r.get("to_guest"), "toName": r.get("to_name") or "", "punctuality": r.get("punctuality"), "chemistry": r.get("chemistry"), "professionalism": r.get("professionalism"), "text": r.get("text") or "", "createdAt": r.get("created_at"), "avg": round( ( float(r.get("punctuality") or 0) + float(r.get("chemistry") or 0) + float(r.get("professionalism") or 0) ) / 3, 2, ), } for r in rows ] if not items: return {"guestId": guest_id, "count": 0, "averages": None, "items": []} n = len(items) averages = { "punctuality": round(sum(i["punctuality"] for i in items) / n, 2), "chemistry": round(sum(i["chemistry"] for i in items) / n, 2), "professionalism": round(sum(i["professionalism"] for i in items) / n, 2), "overall": round(sum(i["avg"] for i in items) / n, 2), } return {"guestId": guest_id, "count": n, "averages": averages, "items": items} def block_user(guest_id: str, blocked_guest: str, reason: str = "") -> dict[str, Any]: ensure_community_tables() if guest_id == blocked_guest: raise ValueError("不能屏蔽自己") get_pb().upsert( C_BLOCKS, filter=( f"guest_id={pb_quote(guest_id)} && blocked_guest={pb_quote(blocked_guest)}" ), payload={ "guest_id": guest_id, "blocked_guest": blocked_guest, "reason": (reason or "").strip()[:200], "created_at": _now(), }, ) return {"ok": True, "blockedGuest": blocked_guest} def unblock_user(guest_id: str, blocked_guest: str) -> dict[str, Any]: ensure_community_tables() r = get_pb().first( C_BLOCKS, filter=( f"guest_id={pb_quote(guest_id)} && blocked_guest={pb_quote(blocked_guest)}" ), ) if r: get_pb().delete(C_BLOCKS, r["id"]) return {"ok": True} def list_blocks(guest_id: str) -> list[dict[str, Any]]: ensure_community_tables() rows = get_pb().list_all( C_BLOCKS, filter=f"guest_id={pb_quote(guest_id)}", sort="-created_at" ) return [ { "blockedGuest": r.get("blocked_guest"), "reason": r.get("reason") or "", "createdAt": r.get("created_at"), } for r in rows ] def is_blocked(viewer: str, other: str) -> bool: ensure_community_tables() a = get_pb().first( C_BLOCKS, filter=f"guest_id={pb_quote(viewer)} && blocked_guest={pb_quote(other)}", ) if a: return True b = get_pb().first( C_BLOCKS, filter=f"guest_id={pb_quote(other)} && blocked_guest={pb_quote(viewer)}", ) return bool(b) def create_report( guest_id: str, *, target_guest: str, target_name: str = "", reason: str, detail: str = "", ) -> dict[str, Any]: ensure_community_tables() if guest_id == target_guest: raise ValueError("不能举报自己") reason = (reason or "").strip()[:80] if not reason: raise ValueError("请选择举报原因") item = { "id": _uid("rp"), "guestId": guest_id, "targetGuest": target_guest, "targetName": (target_name or "").strip()[:64], "reason": reason, "detail": (detail or "").strip()[:1000], "status": "open", "createdAt": _now(), } rec = get_pb().create( C_REPORTS, { "guest_id": guest_id, "target_guest": target_guest, "target_name": item["targetName"], "reason": reason, "detail": item["detail"], "status": "open", "result_note": "", "created_at": item["createdAt"], "resolved_at": "", }, ) item["id"] = rec.get("id") or item["id"] return item def resolve_report( report_id: str, *, status: str = "resolved", result_note: str = "" ) -> dict[str, Any]: ensure_community_tables() try: r = get_pb().request( "GET", f"/api/collections/{C_REPORTS}/records/{report_id}", admin=True ) except Exception as exc: raise ValueError("举报不存在") from exc now = _now() get_pb().update( C_REPORTS, report_id, { "status": status, "result_note": (result_note or "").strip()[:500], "resolved_at": now if status != "open" else "", }, ) return { "id": report_id, "guestId": r.get("guest_id"), "targetGuest": r.get("target_guest"), "status": status, "resultNote": result_note, "resolvedAt": now, } def list_reports(*, status: str = "open", limit: int = 40) -> list[dict[str, Any]]: ensure_community_tables() limit = max(1, min(int(limit or 40), 100)) filt = f"status={pb_quote(status)}" if status else None rows = get_pb().list_all(C_REPORTS, filter=filt, sort="-created_at", hard_limit=limit) return [ { "id": r.get("id"), "guestId": r.get("guest_id"), "targetGuest": r.get("target_guest"), "targetName": r.get("target_name") or "", "reason": r.get("reason"), "detail": r.get("detail") or "", "status": r.get("status"), "resultNote": r.get("result_note") or "", "createdAt": r.get("created_at"), "resolvedAt": r.get("resolved_at") or "", } for r in rows ] def wrapped_stats(guest_id: str, year: int | None = None) -> dict[str, Any]: ensure_community_tables() from datetime import datetime, timezone y = year or datetime.now(timezone.utc).year prefix = f"{y}-" roster = pb_data.get_roster(guest_id) or {} cities: list[str] = [] if roster.get("city"): cities = [roster["city"]] try: from social_svc import geo_pb trips = geo_pb.list_trips_for_guest(guest_id) if hasattr(geo_pb, "list_trips_for_guest") else [] for t in trips or []: c = t.get("city") or "" if c and c not in cities: cities.append(c) except Exception: pass reviews = get_pb().list_all( C_REVIEWS, filter=f"(from_guest={pb_quote(guest_id)} || to_guest={pb_quote(guest_id)})", hard_limit=500, ) reviews = [r for r in reviews if str(r.get("created_at") or "").startswith(prefix)] skills = get_pb().list_all( C_SKILLS, filter=f"guest_id={pb_quote(guest_id)}", hard_limit=200 ) skills = [s for s in skills if str(s.get("created_at") or "").startswith(prefix)] peers = set() for r in reviews: a, b = r.get("from_guest"), r.get("to_guest") if a == guest_id and b: peers.add(b) elif b == guest_id and a: peers.add(a) return { "year": y, "name": roster.get("name") or "游民", "homeCity": roster.get("city") or "", "cities": cities[:24], "cityCount": len(cities), "peopleMet": len(peers), "meetups": len(reviews), "skillPosts": len(skills), "livenessVerified": (roster.get("livenessStatus") or "") == "verified", } def city_digest_payload(city: str, limit: int = 8) -> dict[str, Any]: ensure_community_tables() city = (city or "").strip() people = ( pb_data.list_discovery_roster(city=city, limit=limit) if city else [] ) skills = list_skill_posts(city=city, limit=5) if city else list_skill_posts(limit=5) lines = [] for p in people[:5]: lines.append( f"· {p.get('name')} · {p.get('city') or city} · {p.get('lookingFor') or p.get('title') or ''}" ) for s in skills[:3]: lines.append( f"· 互换:{s['offer']} ↔ {s['want']}({s.get('city') or '全球'})" ) return { "city": city or "全球", "peopleCount": len(people), "skillCount": len(skills), "digestText": "\n".join(lines) if lines else "这周同城还比较安静,去发一条技能互换吧。", }