Document the 2026-11-05 UI/UX upgrade and keep roster/live gates aligned with face-check and presence. Co-authored-by: Cursor <cursoragent@cursor.com>
441 lines
14 KiB
Python
441 lines
14 KiB
Python
"""Coffeechat booking store on PocketBase (no SQLite)."""
|
||
from __future__ import annotations
|
||
|
||
import time
|
||
import uuid
|
||
import os
|
||
from threading import RLock
|
||
from datetime import datetime, timedelta, timezone
|
||
from typing import Any
|
||
from zoneinfo import ZoneInfo
|
||
|
||
from nomadro_pb import get_pb, pb_quote
|
||
from nomadro_pb.ensure import ensure_selected
|
||
from coffee_svc.scheduling import available_times
|
||
|
||
C_HOSTS = "coffee_hosts"
|
||
C_SCHEDULES = "coffee_schedules"
|
||
C_EVENTS = "coffee_event_types"
|
||
C_BOOKINGS = "coffee_bookings"
|
||
_booking_lock = RLock()
|
||
|
||
|
||
def _now() -> str:
|
||
return time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())
|
||
|
||
|
||
def _id(prefix: str) -> str:
|
||
return f"{prefix}_{uuid.uuid4().hex[:12]}"
|
||
|
||
|
||
def init_db() -> None:
|
||
if not ensure_selected({C_HOSTS, C_SCHEDULES, C_EVENTS, C_BOOKINGS}):
|
||
raise RuntimeError('coffee_storage_unavailable')
|
||
if os.getenv('COFFEE_SEED_DEMO', '0') == '1': _seed()
|
||
|
||
|
||
def upsert_host(guest_id: str, data: dict[str, Any]) -> dict[str, Any]:
|
||
init_db()
|
||
pb = get_pb()
|
||
host = pb.first(C_HOSTS, filter=f'username={pb_quote(guest_id)}')
|
||
body = {'username': guest_id, 'name': data['name'].strip(), 'bio': data.get('bio', '').strip(), 'city': data.get('city', '').strip(), 'timezone': data['timezone'], 'created_at': (host or {}).get('created_at') or _now()}
|
||
host = pb.upsert(C_HOSTS, filter=f'username={pb_quote(guest_id)}', payload=body)
|
||
if data.get('owner_key_hash'): pb.update(C_HOSTS, host['id'], {'owner_key_hash': data['owner_key_hash']})
|
||
schedule = pb.first(C_SCHEDULES, filter=f'host_id={pb_quote(host["id"])}')
|
||
if schedule:
|
||
pb.update(C_SCHEDULES, schedule['id'], {'timezone': data['timezone']})
|
||
else:
|
||
pb.create(C_SCHEDULES, {'host_id': host['id'], 'name': 'Default', 'timezone': data['timezone'], 'availability': [], 'created_at': _now()})
|
||
if not pb.first(C_EVENTS, filter=f'host_id={pb_quote(host["id"])} && slug="30min"'):
|
||
upsert_event_type(guest_id, {'slug': '30min', 'title': 'Coffeechat · 30 min', 'length_minutes': 30, 'slot_interval': 30, 'active': True})
|
||
return get_host(guest_id) # type: ignore[return-value]
|
||
|
||
|
||
def _seed() -> None:
|
||
pb = get_pb()
|
||
if pb.first(C_HOSTS, filter='username="alice"'):
|
||
return
|
||
hid = _id("host")
|
||
now = _now()
|
||
pb.create(
|
||
C_HOSTS,
|
||
{
|
||
"username": "alice",
|
||
"name": "Alice Chen",
|
||
"bio": "演示主持人 · 可约 30 分钟咖啡聊",
|
||
"avatar": "",
|
||
"city": "Chengdu",
|
||
"timezone": "Asia/Shanghai",
|
||
"created_at": now,
|
||
},
|
||
)
|
||
# re-fetch for id
|
||
host = pb.first(C_HOSTS, filter='username="alice"')
|
||
if not host:
|
||
return
|
||
hid = host["id"]
|
||
sid = _id("sch")
|
||
pb.create(
|
||
C_SCHEDULES,
|
||
{
|
||
"host_id": hid,
|
||
"name": "Default",
|
||
"timezone": "Asia/Shanghai",
|
||
"availability": [
|
||
{"days": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"], "startTime": 600, "endTime": 1080}
|
||
],
|
||
"created_at": now,
|
||
},
|
||
)
|
||
sch = pb.first(C_SCHEDULES, filter=f"host_id={pb_quote(hid)}")
|
||
pb.create(
|
||
C_EVENTS,
|
||
{
|
||
"host_id": hid,
|
||
"schedule_id": (sch or {}).get("id") or sid,
|
||
"slug": "30min",
|
||
"title": "咖啡聊 30′",
|
||
"description": "线下咖啡馆或线上都行",
|
||
"length_minutes": 30,
|
||
"slot_interval": 30,
|
||
"buffer_before": 0,
|
||
"buffer_after": 0,
|
||
"locations": [{"type": "inPerson", "label": "咖啡馆(见面后定)"}],
|
||
"active": True,
|
||
"created_at": now,
|
||
},
|
||
)
|
||
|
||
|
||
def list_hosts() -> list[dict[str, Any]]:
|
||
init_db()
|
||
rows = get_pb().list_all(C_HOSTS, sort="username")
|
||
out = []
|
||
for r in rows:
|
||
n = len(
|
||
get_pb().list_all(
|
||
C_EVENTS,
|
||
filter=f'host_id={pb_quote(r["id"])} && active=true',
|
||
hard_limit=50,
|
||
)
|
||
)
|
||
out.append(_host_out(r, event_count=n))
|
||
return out
|
||
|
||
|
||
def get_host(username: str) -> dict[str, Any] | None:
|
||
init_db()
|
||
r = get_pb().first(C_HOSTS, filter=f"username={pb_quote(username)}")
|
||
if not r:
|
||
return None
|
||
events = get_pb().list_all(
|
||
C_EVENTS, filter=f'host_id={pb_quote(r["id"])} && active=true'
|
||
)
|
||
h = _host_out(r, event_count=len(events))
|
||
h["event_types"] = [_event_out(e) for e in events]
|
||
return h
|
||
|
||
|
||
def _host_out(r: dict[str, Any], *, event_count: int = 0) -> dict[str, Any]:
|
||
return {
|
||
"id": r.get("id"),
|
||
"username": r.get("username"),
|
||
"name": r.get("name"),
|
||
"bio": r.get("bio") or "",
|
||
"avatar": r.get("avatar"),
|
||
"timezone": r.get("timezone") or "Asia/Shanghai",
|
||
"city": r.get("city") or "",
|
||
"event_count": event_count,
|
||
"created_at": r.get("created_at"),
|
||
}
|
||
|
||
|
||
def get_event_type(username: str, slug: str) -> dict[str, Any] | None:
|
||
init_db()
|
||
host = get_pb().first(C_HOSTS, filter=f"username={pb_quote(username)}")
|
||
if not host:
|
||
return None
|
||
e = get_pb().first(
|
||
C_EVENTS,
|
||
filter=f'host_id={pb_quote(host["id"])} && slug={pb_quote(slug)}',
|
||
)
|
||
if not e:
|
||
return None
|
||
out = _event_out(e)
|
||
out["host"] = _host_out(host)
|
||
return out
|
||
|
||
|
||
def _event_out(r: dict[str, Any]) -> dict[str, Any]:
|
||
return {
|
||
"id": r.get("id"),
|
||
"host_id": r.get("host_id"),
|
||
"schedule_id": r.get("schedule_id"),
|
||
"slug": r.get("slug"),
|
||
"title": r.get("title"),
|
||
"description": r.get("description") or "",
|
||
"length_minutes": int(r.get("length_minutes") or 30),
|
||
"slot_interval": int(r.get("slot_interval") or 15),
|
||
"buffer_before": int(r.get("buffer_before") or 0),
|
||
"buffer_after": int(r.get("buffer_after") or 0),
|
||
"locations": r.get("locations") or [],
|
||
"active": bool(r.get("active", True)),
|
||
"created_at": r.get("created_at"),
|
||
}
|
||
|
||
|
||
def get_schedule(host_username: str) -> dict[str, Any] | None:
|
||
init_db()
|
||
host = get_pb().first(C_HOSTS, filter=f"username={pb_quote(host_username)}")
|
||
if not host:
|
||
return None
|
||
s = get_pb().first(C_SCHEDULES, filter=f'host_id={pb_quote(host["id"])}')
|
||
if not s:
|
||
return None
|
||
return {
|
||
"id": s.get("id"),
|
||
"host_id": host["id"],
|
||
"name": s.get("name") or "Default",
|
||
"timezone": s.get("timezone") or host.get("timezone") or "Asia/Shanghai",
|
||
"availability": s.get("availability") or [],
|
||
"created_at": s.get("created_at"),
|
||
}
|
||
|
||
|
||
def update_schedule(
|
||
username: str,
|
||
*,
|
||
availability: list[dict[str, Any]] | None = None,
|
||
timezone_name: str | None = None,
|
||
name: str | None = None,
|
||
) -> dict[str, Any]:
|
||
s = get_schedule(username)
|
||
if not s:
|
||
raise ValueError("schedule_not_found")
|
||
patch: dict[str, Any] = {}
|
||
if availability is not None:
|
||
patch["availability"] = availability
|
||
if timezone_name:
|
||
patch["timezone"] = timezone_name
|
||
host = get_pb().first(C_HOSTS, filter=f'username={pb_quote(username)}')
|
||
if host: get_pb().update(C_HOSTS, host['id'], {'timezone': timezone_name})
|
||
if name:
|
||
patch["name"] = name
|
||
if patch:
|
||
get_pb().update(C_SCHEDULES, s["id"], patch)
|
||
return get_schedule(username) # type: ignore[return-value]
|
||
|
||
|
||
def upsert_event_type(username: str, data: dict[str, Any]) -> dict[str, Any]:
|
||
init_db()
|
||
host = get_pb().first(C_HOSTS, filter=f"username={pb_quote(username)}")
|
||
if not host:
|
||
raise ValueError("host_not_found")
|
||
sch = get_pb().first(C_SCHEDULES, filter=f'host_id={pb_quote(host["id"])}')
|
||
slug = str(data.get("slug") or "").strip()
|
||
if not slug:
|
||
raise ValueError("slug_required")
|
||
existing = get_pb().first(
|
||
C_EVENTS,
|
||
filter=f'host_id={pb_quote(host["id"])} && slug={pb_quote(slug)}',
|
||
)
|
||
body = {
|
||
"host_id": host["id"],
|
||
"schedule_id": (sch or {}).get("id") or "",
|
||
"slug": slug,
|
||
"title": str(data.get("title") or slug)[:200],
|
||
"description": str(data.get("description") or "")[:2000],
|
||
"length_minutes": int(data.get("length_minutes") or 30),
|
||
"slot_interval": int(data.get("slot_interval") or 15),
|
||
"buffer_before": int(data.get("buffer_before") or 0),
|
||
"buffer_after": int(data.get("buffer_after") or 0),
|
||
"locations": data.get("locations") or [],
|
||
"active": bool(data.get("active", True)),
|
||
"created_at": _now(),
|
||
}
|
||
if existing:
|
||
get_pb().update(C_EVENTS, existing["id"], body)
|
||
else:
|
||
get_pb().create(C_EVENTS, body)
|
||
return get_event_type(username, slug) # type: ignore[return-value]
|
||
|
||
|
||
def available_slots(username: str, slug: str, day: str) -> dict[str, Any]:
|
||
et = get_event_type(username, slug)
|
||
if not et:
|
||
raise ValueError("event_type_not_found")
|
||
sch = get_schedule(username)
|
||
if not sch:
|
||
raise ValueError("schedule_not_found")
|
||
existing = get_pb().list_all(C_BOOKINGS, filter=f'host_id={pb_quote(et["host_id"])} && status="accepted"', hard_limit=10000)
|
||
slots = available_times(day, sch, et, existing)
|
||
length = int(et['length_minutes'])
|
||
return {
|
||
"ok": True,
|
||
"day": day,
|
||
"timezone": sch.get("timezone"),
|
||
"slots": slots,
|
||
"event_type": {
|
||
"slug": et["slug"],
|
||
"title": et["title"],
|
||
"length_minutes": length,
|
||
},
|
||
}
|
||
|
||
|
||
def create_booking(data: dict[str, Any]) -> dict[str, Any]:
|
||
# The service runs one worker. Serialize check-and-create to prevent two
|
||
# concurrent requests from accepting the same host slot.
|
||
with _booking_lock:
|
||
return _create_booking(data)
|
||
|
||
|
||
def _create_booking(data: dict[str, Any]) -> dict[str, Any]:
|
||
init_db()
|
||
username = str(data.get("username") or "").strip()
|
||
slug = str(data.get("event_slug") or "").strip()
|
||
start = str(data.get("start") or "").strip()
|
||
attendee_name = str(data.get("attendee_name") or "").strip()
|
||
if not username or not slug or not start or not attendee_name:
|
||
raise ValueError("username_slug_start_attendee_required")
|
||
et = get_event_type(username, slug)
|
||
if not et:
|
||
raise ValueError("event_type_not_found")
|
||
host = get_pb().first(C_HOSTS, filter=f"username={pb_quote(username)}")
|
||
length = int(et["length_minutes"])
|
||
start_dt = datetime.fromisoformat(start.replace("Z", "+00:00"))
|
||
if start_dt.tzinfo is None: raise ValueError('timezone_required')
|
||
schedule = get_schedule(username)
|
||
if not schedule: raise ValueError('schedule_not_found')
|
||
local_day = start_dt.astimezone(ZoneInfo(schedule['timezone'])).date().isoformat()
|
||
canonical_start = start_dt.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
|
||
if not any(slot['start'] == canonical_start for slot in available_slots(username, slug, local_day)['slots']):
|
||
raise ValueError('slot_unavailable')
|
||
end_dt = start_dt + timedelta(minutes=length)
|
||
now = _now()
|
||
uid = _id("uid")
|
||
body = {
|
||
"uid": uid,
|
||
"event_type_id": et["id"],
|
||
"host_id": host["id"],
|
||
"title": et["title"],
|
||
"status": "accepted",
|
||
"start_utc": start_dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||
"end_utc": end_dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||
"location": str(data.get("location") or ""),
|
||
"notes": str(data.get("notes") or ""),
|
||
"attendee_name": attendee_name[:120],
|
||
"attendee_email": data.get("attendee_email"),
|
||
"attendee_device": data.get("attendee_device"),
|
||
"attendee_key_hash": data.get("attendee_key_hash"),
|
||
"created_at": now,
|
||
"cancelled_at": "",
|
||
}
|
||
rec = get_pb().create(C_BOOKINGS, body)
|
||
return get_booking(rec["id"]) # type: ignore[return-value]
|
||
|
||
|
||
def get_booking(booking_id: str) -> dict[str, Any] | None:
|
||
init_db()
|
||
try:
|
||
r = get_pb().request(
|
||
"GET", f"/api/collections/{C_BOOKINGS}/records/{booking_id}", admin=True
|
||
)
|
||
except Exception:
|
||
r = get_pb().first(C_BOOKINGS, filter=f"uid={pb_quote(booking_id)}")
|
||
if not r:
|
||
return None
|
||
host = None
|
||
if r.get("host_id"):
|
||
try:
|
||
host = get_pb().request(
|
||
"GET",
|
||
f"/api/collections/{C_HOSTS}/records/{r['host_id']}",
|
||
admin=True,
|
||
)
|
||
except Exception:
|
||
host = None
|
||
return _booking_out(r, host=host)
|
||
|
||
|
||
def list_bookings(
|
||
*,
|
||
host_username: str | None = None,
|
||
status: str | None = None,
|
||
attendee_device: str | None = None,
|
||
attendee_key_hash: str | None = None,
|
||
) -> list[dict[str, Any]]:
|
||
init_db()
|
||
filters = []
|
||
if status: filters.append(f'status={pb_quote(status)}')
|
||
if attendee_device: filters.append(f'attendee_device={pb_quote(attendee_device)}')
|
||
if attendee_key_hash: filters.append(f'attendee_key_hash={pb_quote(attendee_key_hash)}')
|
||
if host_username:
|
||
host = get_pb().first(C_HOSTS, filter=f'username={pb_quote(host_username)}')
|
||
if not host: return []
|
||
filters.append(f'host_id={pb_quote(host["id"])}')
|
||
rows = get_pb().list_all(C_BOOKINGS, filter=' && '.join(filters) or None, sort="-start_utc", hard_limit=100)
|
||
out = []
|
||
for r in rows:
|
||
if status and r.get("status") != status:
|
||
continue
|
||
host = None
|
||
if r.get("host_id"):
|
||
try:
|
||
host = get_pb().request(
|
||
"GET",
|
||
f"/api/collections/{C_HOSTS}/records/{r['host_id']}",
|
||
admin=True,
|
||
)
|
||
except Exception:
|
||
host = None
|
||
if host_username and host and host.get("username") != host_username:
|
||
continue
|
||
out.append(_booking_out(r, host=host))
|
||
return out
|
||
|
||
|
||
def cancel_booking(booking_id: str) -> dict[str, Any] | None:
|
||
b = get_booking(booking_id)
|
||
if not b:
|
||
return None
|
||
get_pb().update(
|
||
C_BOOKINGS,
|
||
b["id"],
|
||
{"status": "cancelled", "cancelled_at": _now()},
|
||
)
|
||
return get_booking(b["id"])
|
||
|
||
|
||
def _booking_out(
|
||
r: dict[str, Any], host: dict[str, Any] | None = None
|
||
) -> dict[str, Any]:
|
||
return {
|
||
"id": r.get("id"),
|
||
"uid": r.get("uid"),
|
||
"event_type_id": r.get("event_type_id"),
|
||
"host_id": r.get("host_id"),
|
||
"host": (
|
||
{
|
||
"username": host.get("username"),
|
||
"name": host.get("name"),
|
||
"city": host.get("city"),
|
||
}
|
||
if host
|
||
else None
|
||
),
|
||
"title": r.get("title"),
|
||
"status": r.get("status"),
|
||
"start": r.get("start_utc"),
|
||
"end": r.get("end_utc"),
|
||
"location": r.get("location") or "",
|
||
"notes": r.get("notes") or "",
|
||
"attendee": {
|
||
"name": r.get("attendee_name"),
|
||
"email": r.get("attendee_email"),
|
||
"device": r.get("attendee_device"),
|
||
},
|
||
"created_at": r.get("created_at"),
|
||
"cancelled_at": r.get("cancelled_at") or None,
|
||
}
|