""" SQLite store — domain shaped after Cal.com (User/Host · EventType · Schedule · Availability · Booking · Attendee · Slot). Secondary-dev reimplementation for Nomadro coffeechat (not upstream Cal runtime). """ from __future__ import annotations import json import sqlite3 import time import uuid from datetime import date, datetime, timedelta, timezone from pathlib import Path from typing import Any from zoneinfo import ZoneInfo from .config import DATA_DIR, DB_PATH try: from ebook_svc.core.sqlite_util import connect as _connect except Exception: # pragma: no cover def _connect(path: str | Path, *, timeout: float = 30.0) -> sqlite3.Connection: p = Path(path) p.parent.mkdir(parents=True, exist_ok=True) c = sqlite3.connect(str(p), timeout=timeout) c.row_factory = sqlite3.Row c.execute("PRAGMA journal_mode=WAL") return c WEEKDAYS = ("sun", "mon", "tue", "wed", "thu", "fri", "sat") # Cal.com uses 0=Sunday … Python weekday() is 0=Monday — map carefully PY_TO_CAL = {0: "mon", 1: "tue", 2: "wed", 3: "thu", 4: "fri", 5: "sat", 6: "sun"} def _now() -> str: return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) def _id(prefix: str) -> str: return f"{prefix}_{uuid.uuid4().hex[:10]}" def _conn() -> sqlite3.Connection: DATA_DIR.mkdir(parents=True, exist_ok=True) return _connect(DB_PATH) def _json(v: Any) -> str: return json.dumps(v, ensure_ascii=False) def _parse(s: str | None, default: Any = None) -> Any: if not s: return default if default is not None else {} try: return json.loads(s) except Exception: return default if default is not None else {} def init_db() -> None: with _conn() as c: c.executescript( """ CREATE TABLE IF NOT EXISTS hosts ( id TEXT PRIMARY KEY, username TEXT NOT NULL UNIQUE, name TEXT NOT NULL, bio TEXT NOT NULL DEFAULT '', avatar TEXT, timezone TEXT NOT NULL DEFAULT 'Asia/Shanghai', city TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS schedules ( id TEXT PRIMARY KEY, host_id TEXT NOT NULL, name TEXT NOT NULL DEFAULT 'Working hours', timezone TEXT NOT NULL DEFAULT 'Asia/Shanghai', availability_json TEXT NOT NULL DEFAULT '[]', created_at TEXT NOT NULL, FOREIGN KEY(host_id) REFERENCES hosts(id) ); CREATE TABLE IF NOT EXISTS event_types ( id TEXT PRIMARY KEY, host_id TEXT NOT NULL, schedule_id TEXT NOT NULL, slug TEXT NOT NULL, title TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', length_minutes INTEGER NOT NULL DEFAULT 30, slot_interval INTEGER NOT NULL DEFAULT 15, buffer_before INTEGER NOT NULL DEFAULT 0, buffer_after INTEGER NOT NULL DEFAULT 0, locations_json TEXT NOT NULL DEFAULT '[]', active INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL, UNIQUE(host_id, slug), FOREIGN KEY(host_id) REFERENCES hosts(id), FOREIGN KEY(schedule_id) REFERENCES schedules(id) ); CREATE TABLE IF NOT EXISTS bookings ( id TEXT PRIMARY KEY, uid TEXT NOT NULL UNIQUE, event_type_id TEXT NOT NULL, host_id TEXT NOT NULL, title TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'accepted', start_utc TEXT NOT NULL, end_utc TEXT NOT NULL, location TEXT NOT NULL DEFAULT '', notes TEXT NOT NULL DEFAULT '', attendee_name TEXT NOT NULL, attendee_email TEXT, attendee_device TEXT, created_at TEXT NOT NULL, cancelled_at TEXT, FOREIGN KEY(event_type_id) REFERENCES event_types(id), FOREIGN KEY(host_id) REFERENCES hosts(id) ); CREATE INDEX IF NOT EXISTS idx_bookings_host_start ON bookings(host_id, start_utc); """ ) _seed(c) def _default_availability() -> list[dict[str, Any]]: """Cal.com-style weekly windows (local schedule timezone).""" windows = [{"days": ["mon", "tue", "wed", "thu", "fri"], "startTime": 600, "endTime": 720}] # 10:00–12:00 and 14:00–18:00 as minutes from midnight windows.append( {"days": ["mon", "tue", "wed", "thu", "fri"], "startTime": 840, "endTime": 1080} ) windows.append({"days": ["sat"], "startTime": 660, "endTime": 900}) return windows def _seed(c: sqlite3.Connection) -> None: if c.execute("SELECT 1 FROM hosts LIMIT 1").fetchone(): return now = _now() hosts = [ ("host_alice", "alice", "Alice Chen", "成都远程 · 爱咖啡闲聊产品与出海", "Chengdu", "Asia/Shanghai"), ("host_bob", "bob", "Bob Rivera", "EN/ZH · coffee or video walkthrough", "Chiang Mai", "Asia/Bangkok"), ("host_guest", "guest", "Guest Nomad", "演示主持人 · 可约 30 分钟咖啡聊", "Shenzhen", "Asia/Shanghai"), ] for hid, user, name, bio, city, tz in hosts: c.execute( """INSERT INTO hosts(id,username,name,bio,avatar,timezone,city,created_at) VALUES(?,?,?,?,?,?,?,?)""", (hid, user, name, bio, None, tz, city, now), ) sid = f"sch_{user}" c.execute( """INSERT INTO schedules(id,host_id,name,timezone,availability_json,created_at) VALUES(?,?,?,?,?,?)""", (sid, hid, "Working hours", tz, _json(_default_availability()), now), ) events = [ ( f"et_{user}_coffee", "coffee-30", "☕ 咖啡聊 30′", "同城咖啡馆或语音闲聊,认识一下就好。", 30, [ {"type": "inPerson", "label": "咖啡馆(见面后定)"}, {"type": "link", "label": "语音/视频", "link": "/social/meetup"}, ], ), ( f"et_{user}_video", "video-45", "📹 视频深聊 45′", "产品 / 副业 / 旅居经验,线上视频。", 45, [{"type": "link", "label": "Nomadro 视频厅", "link": "/social/meetup"}], ), ] for eid, slug, title, desc, length, locs in events: c.execute( """INSERT INTO event_types( id,host_id,schedule_id,slug,title,description,length_minutes, slot_interval,buffer_before,buffer_after,locations_json,active,created_at ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""", ( eid, hid, sid, slug, title, desc, length, 15, 0, 0, _json(locs), 1, now, ), ) # sample booking tomorrow 10:00 Asia/Shanghai for alice coffee tz = ZoneInfo("Asia/Shanghai") tomorrow = datetime.now(tz).date() + timedelta(days=1) start_local = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 10, 0, tzinfo=tz) end_local = start_local + timedelta(minutes=30) c.execute( """INSERT INTO bookings( id,uid,event_type_id,host_id,title,status,start_utc,end_utc,location,notes, attendee_name,attendee_email,attendee_device,created_at,cancelled_at ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", ( _id("bk"), _id("uid"), "et_alice_coffee", "host_alice", "☕ 咖啡聊 30′", "accepted", start_local.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), end_local.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "咖啡馆(见面后定)", "种子预约", "Demo Attendee", "demo@nomadro.com", None, now, None, ), ) # —— hosts / event types —— def list_hosts() -> list[dict[str, Any]]: with _conn() as c: rows = c.execute("SELECT * FROM hosts ORDER BY username").fetchall() out = [] for r in rows: n = c.execute( "SELECT COUNT(*) AS n FROM event_types WHERE host_id=? AND active=1", (r["id"],), ).fetchone()["n"] out.append(_host_out(dict(r), event_count=n)) return out def get_host(username: str) -> dict[str, Any] | None: with _conn() as c: r = c.execute( "SELECT * FROM hosts WHERE username=? OR id=?", (username, username), ).fetchone() if not r: return None events = [ _event_out(dict(e)) for e in c.execute( "SELECT * FROM event_types WHERE host_id=? AND active=1 ORDER BY length_minutes", (r["id"],), ).fetchall() ] h = _host_out(dict(r), event_count=len(events)) h["event_types"] = events return h def _host_out(r: dict[str, Any], *, event_count: int = 0) -> dict[str, Any]: return { "id": r["id"], "username": r["username"], "name": r["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: with _conn() as c: h = c.execute( "SELECT * FROM hosts WHERE username=? OR id=?", (username, username), ).fetchone() if not h: return None e = c.execute( "SELECT * FROM event_types WHERE host_id=? AND slug=?", (h["id"], slug), ).fetchone() if not e: return None out = _event_out(dict(e)) out["host"] = _host_out(dict(h)) sch = c.execute( "SELECT * FROM schedules WHERE id=?", (e["schedule_id"],) ).fetchone() if sch: out["schedule"] = _schedule_out(dict(sch)) return out def _event_out(r: dict[str, Any]) -> dict[str, Any]: return { "id": r["id"], "host_id": r["host_id"], "schedule_id": r["schedule_id"], "slug": r["slug"], "title": r["title"], "description": r.get("description") or "", "length_minutes": int(r["length_minutes"]), "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": _parse(r.get("locations_json"), []), "active": bool(r.get("active")), "created_at": r.get("created_at"), } def _schedule_out(r: dict[str, Any]) -> dict[str, Any]: return { "id": r["id"], "host_id": r["host_id"], "name": r["name"], "timezone": r["timezone"], "availability": _parse(r.get("availability_json"), []), "created_at": r["created_at"], } def get_schedule(host_username: str) -> dict[str, Any] | None: with _conn() as c: h = c.execute( "SELECT * FROM hosts WHERE username=? OR id=?", (host_username, host_username), ).fetchone() if not h: return None s = c.execute( "SELECT * FROM schedules WHERE host_id=? ORDER BY created_at LIMIT 1", (h["id"],), ).fetchone() return _schedule_out(dict(s)) if s else None def update_schedule( host_username: str, *, availability: list[dict[str, Any]] | None = None, timezone_name: str | None = None, name: str | None = None, ) -> dict[str, Any]: with _conn() as c: h = c.execute( "SELECT * FROM hosts WHERE username=? OR id=?", (host_username, host_username), ).fetchone() if not h: raise ValueError("host_not_found") s = c.execute( "SELECT * FROM schedules WHERE host_id=? ORDER BY created_at LIMIT 1", (h["id"],), ).fetchone() if not s: raise ValueError("schedule_not_found") avail = ( _json(availability) if availability is not None else s["availability_json"] ) tz = timezone_name or s["timezone"] nm = name or s["name"] c.execute( "UPDATE schedules SET availability_json=?, timezone=?, name=? WHERE id=?", (avail, tz, nm, s["id"]), ) if timezone_name: c.execute( "UPDATE hosts SET timezone=? WHERE id=?", (timezone_name, h["id"]), ) row = c.execute("SELECT * FROM schedules WHERE id=?", (s["id"],)).fetchone() return _schedule_out(dict(row)) def upsert_event_type( host_username: str, data: dict[str, Any], ) -> dict[str, Any]: slug = (data.get("slug") or "").strip() title = (data.get("title") or "").strip() if not slug or not title: raise ValueError("slug_and_title_required") with _conn() as c: h = c.execute( "SELECT * FROM hosts WHERE username=? OR id=?", (host_username, host_username), ).fetchone() if not h: raise ValueError("host_not_found") sch = c.execute( "SELECT id FROM schedules WHERE host_id=? LIMIT 1", (h["id"],), ).fetchone() if not sch: raise ValueError("schedule_not_found") existing = c.execute( "SELECT * FROM event_types WHERE host_id=? AND slug=?", (h["id"], slug), ).fetchone() length = int(data.get("length_minutes") or 30) interval = int(data.get("slot_interval") or 15) locs = data.get("locations") or [ {"type": "inPerson", "label": "咖啡馆(见面后定)"} ] now = _now() if existing: c.execute( """UPDATE event_types SET title=?,description=?,length_minutes=?, slot_interval=?,locations_json=?,active=? WHERE id=?""", ( title, data.get("description") or "", length, interval, _json(locs), 1 if data.get("active", True) else 0, existing["id"], ), ) eid = existing["id"] else: eid = _id("et") c.execute( """INSERT INTO event_types( id,host_id,schedule_id,slug,title,description,length_minutes, slot_interval,buffer_before,buffer_after,locations_json,active,created_at ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""", ( eid, h["id"], sch["id"], slug, title, data.get("description") or "", length, interval, int(data.get("buffer_before") or 0), int(data.get("buffer_after") or 0), _json(locs), 1, now, ), ) row = c.execute("SELECT * FROM event_types WHERE id=?", (eid,)).fetchone() return _event_out(dict(row)) # —— slots (Cal.com getSchedule / availableSlots parity) —— def _parse_utc(s: str) -> datetime: if s.endswith("Z"): s = s[:-1] + "+00:00" return datetime.fromisoformat(s).astimezone(timezone.utc) def available_slots( username: str, event_slug: str, day: str, ) -> dict[str, Any]: """Return bookable UTC slots for a local calendar day (YYYY-MM-DD).""" et = get_event_type(username, event_slug) if not et or not et.get("active"): raise ValueError("event_type_not_found") host = et["host"] sch = et.get("schedule") or {} tz_name = sch.get("timezone") or host.get("timezone") or "Asia/Shanghai" try: tz = ZoneInfo(tz_name) except Exception: tz = ZoneInfo("Asia/Shanghai") tz_name = "Asia/Shanghai" try: day_d = date.fromisoformat(day) except ValueError as e: raise ValueError("invalid_day") from e length = int(et["length_minutes"]) interval = int(et.get("slot_interval") or 15) buf_before = int(et.get("buffer_before") or 0) buf_after = int(et.get("buffer_after") or 0) cal_day = PY_TO_CAL[day_d.weekday()] windows = [ w for w in (sch.get("availability") or []) if cal_day in (w.get("days") or []) ] if not windows: return { "ok": True, "day": day, "timezone": tz_name, "slots": [], "event_type": {"slug": et["slug"], "length_minutes": length}, } # busy from accepted bookings that day (host local) day_start = datetime(day_d.year, day_d.month, day_d.day, 0, 0, tzinfo=tz) day_end = day_start + timedelta(days=1) with _conn() as c: busy_rows = c.execute( """SELECT start_utc,end_utc FROM bookings WHERE host_id=? AND status='accepted' AND start_utc < ? AND end_utc > ?""", ( host["id"], day_end.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), day_start.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), ), ).fetchall() busy = [(_parse_utc(b["start_utc"]), _parse_utc(b["end_utc"])) for b in busy_rows] now_utc = datetime.now(timezone.utc) slots: list[dict[str, str]] = [] for w in windows: start_m = int(w.get("startTime") or 0) end_m = int(w.get("endTime") or 0) cursor = day_start + timedelta(minutes=start_m) window_end = day_start + timedelta(minutes=end_m) while cursor + timedelta(minutes=length) <= window_end: slot_start = cursor slot_end = cursor + timedelta(minutes=length) slot_start_utc = slot_start.astimezone(timezone.utc) slot_end_utc = slot_end.astimezone(timezone.utc) # past if slot_start_utc <= now_utc + timedelta(minutes=5): cursor += timedelta(minutes=interval) continue # overlap busy with buffers blocked = False for b0, b1 in busy: a0 = slot_start_utc - timedelta(minutes=buf_before) a1 = slot_end_utc + timedelta(minutes=buf_after) if a0 < b1 and a1 > b0: blocked = True break if not blocked: slots.append( { "start": slot_start_utc.strftime("%Y-%m-%dT%H:%M:%SZ"), "end": slot_end_utc.strftime("%Y-%m-%dT%H:%M:%SZ"), "local": slot_start.strftime("%H:%M"), } ) cursor += timedelta(minutes=interval) return { "ok": True, "day": day, "timezone": tz_name, "slots": slots, "event_type": { "slug": et["slug"], "title": et["title"], "length_minutes": length, }, "host": {"username": host["username"], "name": host["name"]}, } # —— bookings —— def create_booking(data: dict[str, Any]) -> dict[str, Any]: username = (data.get("username") or "").strip() slug = (data.get("event_slug") or data.get("slug") or "").strip() start = (data.get("start") or "").strip() attendee_name = (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 or not et.get("active"): raise ValueError("event_type_not_found") start_utc = _parse_utc(start if "T" in start else start + "Z") end_utc = start_utc + timedelta(minutes=int(et["length_minutes"])) day = start_utc.astimezone( ZoneInfo(et["host"].get("timezone") or "Asia/Shanghai") ).date().isoformat() # re-validate slot still free avail = available_slots(username, slug, day) ok_starts = {s["start"] for s in avail["slots"]} start_key = start_utc.strftime("%Y-%m-%dT%H:%M:%SZ") if start_key not in ok_starts: raise ValueError("slot_unavailable") locs = et.get("locations") or [] loc_label = data.get("location") or ( locs[0].get("label") if locs else "Coffeechat" ) now = _now() bid = _id("bk") uid = _id("uid") with _conn() as c: c.execute( """INSERT INTO bookings( id,uid,event_type_id,host_id,title,status,start_utc,end_utc,location,notes, attendee_name,attendee_email,attendee_device,created_at,cancelled_at ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", ( bid, uid, et["id"], et["host"]["id"], et["title"], "accepted", start_key, end_utc.strftime("%Y-%m-%dT%H:%M:%SZ"), loc_label, data.get("notes") or "", attendee_name, data.get("attendee_email"), data.get("attendee_device"), now, None, ), ) return get_booking(bid) # type: ignore[return-value] def get_booking(booking_id: str) -> dict[str, Any] | None: with _conn() as c: r = c.execute( "SELECT * FROM bookings WHERE id=? OR uid=?", (booking_id, booking_id), ).fetchone() if not r: return None h = c.execute("SELECT username,name,city FROM hosts WHERE id=?", (r["host_id"],)).fetchone() return _booking_out(dict(r), host=dict(h) if h else None) def list_bookings( *, host_username: str | None = None, status: str | None = None, ) -> list[dict[str, Any]]: with _conn() as c: q = "SELECT b.* FROM bookings b" args: list[Any] = [] if host_username: q += " JOIN hosts h ON h.id=b.host_id WHERE (h.username=? OR h.id=?)" args.extend([host_username, host_username]) else: q += " WHERE 1=1" if status: q += " AND b.status=?" args.append(status) q += " ORDER BY b.start_utc DESC LIMIT 100" rows = c.execute(q, args).fetchall() out = [] for r in rows: h = c.execute( "SELECT username,name,city FROM hosts WHERE id=?", (r["host_id"],), ).fetchone() out.append(_booking_out(dict(r), host=dict(h) if h else None)) return out def cancel_booking(booking_id: str) -> dict[str, Any] | None: with _conn() as c: r = c.execute( "SELECT id FROM bookings WHERE id=? OR uid=?", (booking_id, booking_id), ).fetchone() if not r: return None c.execute( "UPDATE bookings SET status='cancelled', cancelled_at=? WHERE id=?", (_now(), r["id"]), ) return get_booking(r["id"]) def _booking_out(r: dict[str, Any], host: dict[str, Any] | None = None) -> dict[str, Any]: return { "id": r["id"], "uid": r["uid"], "event_type_id": r["event_type_id"], "host_id": r["host_id"], "host": host, "title": r["title"], "status": r["status"], "start": r["start_utc"], "end": r["end_utc"], "location": r.get("location") or "", "notes": r.get("notes") or "", "attendee": { "name": r["attendee_name"], "email": r.get("attendee_email"), "device": r.get("attendee_device"), }, "created_at": r["created_at"], "cancelled_at": r.get("cancelled_at"), }