Ship coffeechat scheduling, notify PB access, and social/admin UI polish for .com.
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>
This commit is contained in:
parent
8f32c3fbba
commit
499f2d3e26
@ -1,5 +1,7 @@
|
||||
# Nomadro
|
||||
|
||||
2026-11-05:UI/UX 与预约、通知功能升级已上线 .com,详见 [本轮发布与验收记录](docs/uiux-upgrade-2026-11-05.md),包括当前构建、备份位置及功能边界。
|
||||
|
||||
数字游民操作系统(主开发与默认发版:[nomadro.com](https://nomadro.com);中国独立站:[nomadro.cn](https://nomadro.cn))。
|
||||
|
||||
2026-11 平台升级已部署至 `.com` 门户、API 与 [Web 管理后台](https://admin.nomadro.com)。升级内容、验收范围、构建编号与回滚位置见 [升级记录](docs/platform-upgrade-2026-11.md)。`.cn` 未同步本次发版。
|
||||
|
||||
@ -11,6 +11,15 @@ SERVICES = ROOT / "services"
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(SERVICES))
|
||||
|
||||
# Must load before any nomadro_pb / social_svc import (PB admin empty → chat 500 offline)
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(ROOT / ".env")
|
||||
load_dotenv(ROOT / ".env.local", override=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
_LOCAL_ENV = """# 本地开发自动生成 — 勿提交
|
||||
DEBUG=true
|
||||
WX_ALLOW_DEVTOOLS_LOGIN=true
|
||||
|
||||
@ -3,16 +3,21 @@ 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 ensure_once, get_pb, pb_quote
|
||||
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:
|
||||
@ -24,8 +29,26 @@ def _id(prefix: str) -> str:
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
ensure_once()
|
||||
_seed()
|
||||
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:
|
||||
@ -194,6 +217,8 @@ def update_schedule(
|
||||
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:
|
||||
@ -242,24 +267,9 @@ def available_slots(username: str, slug: str, day: str) -> dict[str, Any]:
|
||||
sch = get_schedule(username)
|
||||
if not sch:
|
||||
raise ValueError("schedule_not_found")
|
||||
tz = ZoneInfo(sch.get("timezone") or "Asia/Shanghai")
|
||||
length = int(et["length_minutes"])
|
||||
interval = int(et["slot_interval"] or 15)
|
||||
# naive window: 10:00-18:00 local every interval
|
||||
slots = []
|
||||
base = datetime.fromisoformat(f"{day}T00:00:00").replace(tzinfo=tz)
|
||||
for mins in range(10 * 60, 18 * 60, interval):
|
||||
start = base + timedelta(minutes=mins)
|
||||
end = start + timedelta(minutes=length)
|
||||
if end.hour > 18 or (end.hour == 18 and end.minute > 0):
|
||||
continue
|
||||
slots.append(
|
||||
{
|
||||
"start": start.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"end": end.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"local": start.strftime("%H:%M"),
|
||||
}
|
||||
)
|
||||
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,
|
||||
@ -274,6 +284,13 @@ def available_slots(username: str, slug: str, day: str) -> dict[str, Any]:
|
||||
|
||||
|
||||
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()
|
||||
@ -287,6 +304,13 @@ def create_booking(data: dict[str, Any]) -> dict[str, Any]:
|
||||
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")
|
||||
@ -303,6 +327,7 @@ def create_booking(data: dict[str, Any]) -> dict[str, Any]:
|
||||
"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": "",
|
||||
}
|
||||
@ -337,9 +362,19 @@ 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()
|
||||
rows = get_pb().list_all(C_BOOKINGS, sort="-start_utc", hard_limit=100)
|
||||
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:
|
||||
|
||||
@ -1,20 +1,83 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from typing import Literal
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
import re
|
||||
import hashlib
|
||||
import hmac
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
from pydantic import BaseModel, Field, field_validator, model_validator
|
||||
|
||||
from coffee_svc import store
|
||||
from nomadro_pb import get_pb, pb_quote
|
||||
|
||||
router = APIRouter(tags=["coffee"])
|
||||
|
||||
|
||||
def valid_timezone(value: str) -> str:
|
||||
value = value.strip()
|
||||
try: ZoneInfo(value)
|
||||
except (ZoneInfoNotFoundError, ValueError): raise ValueError('invalid_timezone')
|
||||
return value
|
||||
|
||||
|
||||
def guest_identity(value: str | None) -> str:
|
||||
if not value or not re.fullmatch(r'[A-Za-z0-9_-]{1,80}', value):
|
||||
raise HTTPException(401, 'guest_identity_required')
|
||||
return value
|
||||
|
||||
|
||||
def key_hash(value: str | None) -> str:
|
||||
if not value or not re.fullmatch(r'[a-f0-9]{64}', value): raise HTTPException(401, 'booking_device_required')
|
||||
return hashlib.sha256(value.encode()).hexdigest()
|
||||
|
||||
|
||||
def check_host_key(guest: str, key: str | None):
|
||||
digest = key_hash(key)
|
||||
host = get_pb().first('coffee_hosts', filter=f'username={pb_quote(guest)}')
|
||||
if host and not hmac.compare_digest(str(host.get('owner_key_hash') or ''), digest):
|
||||
raise HTTPException(403, 'booking_device_mismatch')
|
||||
return digest
|
||||
|
||||
|
||||
class AvailabilityWindow(BaseModel):
|
||||
days: list[Literal['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']] = Field(max_length=7)
|
||||
startTime: int = Field(ge=0, lt=1440)
|
||||
endTime: int = Field(gt=0, le=1440)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_range(self):
|
||||
if self.endTime <= self.startTime: raise ValueError('end_must_follow_start')
|
||||
return self
|
||||
|
||||
|
||||
class HostIn(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
bio: str = Field(default='', max_length=2000)
|
||||
city: str = Field(default='', max_length=120)
|
||||
timezone: str = Field(max_length=80)
|
||||
|
||||
_timezone = field_validator('timezone')(valid_timezone)
|
||||
|
||||
@field_validator('name')
|
||||
@classmethod
|
||||
def nonempty_name(cls, value):
|
||||
if not value.strip(): raise ValueError('name_required')
|
||||
return value.strip()
|
||||
|
||||
|
||||
class SchedulePatch(BaseModel):
|
||||
availability: list[dict[str, Any]] | None = None
|
||||
availability: list[AvailabilityWindow] | None = Field(default=None, max_length=50)
|
||||
timezone: str | None = None
|
||||
name: str | None = None
|
||||
|
||||
@field_validator('timezone')
|
||||
@classmethod
|
||||
def check_timezone(cls, value):
|
||||
return valid_timezone(value) if value is not None else None
|
||||
|
||||
|
||||
class EventTypeIn(BaseModel):
|
||||
slug: str = Field(min_length=1, max_length=80)
|
||||
@ -24,8 +87,8 @@ class EventTypeIn(BaseModel):
|
||||
slot_interval: int = Field(default=15, ge=5, le=60)
|
||||
locations: list[dict[str, Any]] = Field(default_factory=list)
|
||||
active: bool = True
|
||||
buffer_before: int = 0
|
||||
buffer_after: int = 0
|
||||
buffer_before: int = Field(default=0, ge=0, le=1440)
|
||||
buffer_after: int = Field(default=0, ge=0, le=1440)
|
||||
|
||||
|
||||
class BookingIn(BaseModel):
|
||||
@ -33,10 +96,17 @@ class BookingIn(BaseModel):
|
||||
event_slug: str = Field(min_length=1, max_length=80)
|
||||
start: str = Field(min_length=1, max_length=40)
|
||||
attendee_name: str = Field(min_length=1, max_length=120)
|
||||
attendee_email: str | None = None
|
||||
attendee_device: str | None = None
|
||||
location: str | None = None
|
||||
notes: str = ""
|
||||
attendee_email: str | None = Field(default=None, max_length=254)
|
||||
attendee_device: str | None = Field(default=None, max_length=80)
|
||||
location: str | None = Field(default=None, max_length=500)
|
||||
notes: str = Field(default='', max_length=2000)
|
||||
|
||||
@field_validator('attendee_email')
|
||||
@classmethod
|
||||
def email_format(cls, value):
|
||||
if value is not None and not re.fullmatch(r'[^\s@]+@[^\s@]+\.[^\s@]+', value):
|
||||
raise ValueError('invalid_email')
|
||||
return value
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
@ -49,6 +119,21 @@ def hosts():
|
||||
return {"ok": True, "hosts": store.list_hosts()}
|
||||
|
||||
|
||||
@router.get('/me')
|
||||
def my_host(x_social_guest_id: str | None = Header(default=None), x_coffee_key: str | None = Header(default=None)):
|
||||
guest = guest_identity(x_social_guest_id)
|
||||
check_host_key(guest, x_coffee_key)
|
||||
return {'ok': True, 'host': store.get_host(guest), 'schedule': store.get_schedule(guest)}
|
||||
|
||||
|
||||
@router.put('/me')
|
||||
def save_my_host(body: HostIn, x_social_guest_id: str | None = Header(default=None), x_coffee_key: str | None = Header(default=None)):
|
||||
guest = guest_identity(x_social_guest_id)
|
||||
digest = check_host_key(guest, x_coffee_key)
|
||||
host = store.upsert_host(guest, {**body.model_dump(), 'owner_key_hash': digest})
|
||||
return {'ok': True, 'host': host, 'schedule': store.get_schedule(guest)}
|
||||
|
||||
|
||||
@router.get("/hosts/{username}")
|
||||
def host(username: str):
|
||||
h = store.get_host(username)
|
||||
@ -66,11 +151,13 @@ def schedule(username: str):
|
||||
|
||||
|
||||
@router.patch("/hosts/{username}/schedule")
|
||||
def patch_schedule(username: str, body: SchedulePatch):
|
||||
def patch_schedule(username: str, body: SchedulePatch, x_social_guest_id: str | None = Header(default=None), x_coffee_key: str | None = Header(default=None)):
|
||||
if guest_identity(x_social_guest_id) != username: raise HTTPException(403, 'host_identity_mismatch')
|
||||
check_host_key(username, x_coffee_key)
|
||||
try:
|
||||
s = store.update_schedule(
|
||||
username,
|
||||
availability=body.availability,
|
||||
availability=[window.model_dump() for window in body.availability] if body.availability is not None else None,
|
||||
timezone_name=body.timezone,
|
||||
name=body.name,
|
||||
)
|
||||
@ -88,7 +175,9 @@ def event_type(username: str, slug: str):
|
||||
|
||||
|
||||
@router.post("/hosts/{username}/event-types")
|
||||
def create_event_type(username: str, body: EventTypeIn):
|
||||
def create_event_type(username: str, body: EventTypeIn, x_social_guest_id: str | None = Header(default=None), x_coffee_key: str | None = Header(default=None)):
|
||||
if guest_identity(x_social_guest_id) != username: raise HTTPException(403, 'host_identity_mismatch')
|
||||
check_host_key(username, x_coffee_key)
|
||||
try:
|
||||
e = store.upsert_event_type(username, body.model_dump())
|
||||
except ValueError as e:
|
||||
@ -112,22 +201,43 @@ def slots(
|
||||
def bookings(
|
||||
host: str | None = Query(default=None),
|
||||
status: str | None = Query(default=None),
|
||||
x_social_guest_id: str | None = Header(default=None),
|
||||
x_coffee_key: str | None = Header(default=None),
|
||||
):
|
||||
return {"ok": True, "bookings": store.list_bookings(host_username=host, status=status)}
|
||||
guest = guest_identity(x_social_guest_id)
|
||||
digest = key_hash(x_coffee_key)
|
||||
if host and host != guest: raise HTTPException(403, 'host_identity_mismatch')
|
||||
if host: check_host_key(guest, x_coffee_key)
|
||||
return {"ok": True, "bookings": store.list_bookings(host_username=host, status=status, attendee_device=None if host else guest, attendee_key_hash=None if host else digest)}
|
||||
|
||||
|
||||
def check_booking_owner(booking: dict, guest: str, key: str | None):
|
||||
digest = key_hash(key)
|
||||
if (booking.get('host') or {}).get('username') == guest:
|
||||
check_host_key(guest, key)
|
||||
return
|
||||
raw = get_pb().first('coffee_bookings', filter=f'id={pb_quote(booking["id"])}') or {}
|
||||
if raw.get('attendee_device') != guest or not hmac.compare_digest(str(raw.get('attendee_key_hash') or ''), digest):
|
||||
raise HTTPException(403, 'booking_device_mismatch')
|
||||
|
||||
|
||||
@router.get("/bookings/{booking_id}")
|
||||
def booking(booking_id: str):
|
||||
def booking(booking_id: str, x_social_guest_id: str | None = Header(default=None), x_coffee_key: str | None = Header(default=None)):
|
||||
guest = guest_identity(x_social_guest_id)
|
||||
b = store.get_booking(booking_id)
|
||||
if not b:
|
||||
raise HTTPException(404, "booking_not_found")
|
||||
check_booking_owner(b, guest, x_coffee_key)
|
||||
return {"ok": True, "booking": b}
|
||||
|
||||
|
||||
@router.post("/bookings")
|
||||
def book(body: BookingIn):
|
||||
def book(body: BookingIn, x_social_guest_id: str | None = Header(default=None), x_coffee_key: str | None = Header(default=None)):
|
||||
guest = guest_identity(x_social_guest_id)
|
||||
digest = key_hash(x_coffee_key)
|
||||
if body.attendee_device and body.attendee_device != guest: raise HTTPException(403, 'booking_identity_mismatch')
|
||||
try:
|
||||
b = store.create_booking(body.model_dump())
|
||||
b = store.create_booking({**body.model_dump(), 'attendee_device': guest, 'attendee_key_hash': digest})
|
||||
except ValueError as e:
|
||||
code = 409 if str(e) == "slot_unavailable" else 400
|
||||
raise HTTPException(code, str(e)) from e
|
||||
@ -136,7 +246,7 @@ def book(body: BookingIn):
|
||||
from social_svc.notify_bridge import notify_coffee_invite
|
||||
|
||||
host = b.get("host") or {}
|
||||
to_id = str(b.get("host_id") or host.get("username") or "")
|
||||
to_id = str(host.get("username") or b.get("host_id") or "")
|
||||
if to_id:
|
||||
notify_coffee_invite(
|
||||
to_id,
|
||||
@ -149,7 +259,11 @@ def book(body: BookingIn):
|
||||
|
||||
|
||||
@router.post("/bookings/{booking_id}/cancel")
|
||||
def cancel(booking_id: str):
|
||||
def cancel(booking_id: str, x_social_guest_id: str | None = Header(default=None), x_coffee_key: str | None = Header(default=None)):
|
||||
guest = guest_identity(x_social_guest_id)
|
||||
existing = store.get_booking(booking_id)
|
||||
if not existing: raise HTTPException(404, 'booking_not_found')
|
||||
check_booking_owner(existing, guest, x_coffee_key)
|
||||
b = store.cancel_booking(booking_id)
|
||||
if not b:
|
||||
raise HTTPException(404, "booking_not_found")
|
||||
|
||||
37
apps/api/services/coffee_svc/scheduling.py
Normal file
37
apps/api/services/coffee_svc/scheduling.py
Normal file
@ -0,0 +1,37 @@
|
||||
"""Time-zone-aware availability calculation, independent of persistence."""
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
|
||||
def available_times(day: str, schedule: dict, event: dict, bookings: list[dict], now: datetime | None = None) -> list[dict]:
|
||||
local_date = date.fromisoformat(day)
|
||||
tz = ZoneInfo(schedule.get('timezone') or 'UTC')
|
||||
now = now or datetime.now(timezone.utc)
|
||||
if not event.get('active', True): return []
|
||||
length = int(event.get('length_minutes') or 30)
|
||||
interval = int(event.get('slot_interval') or 15)
|
||||
if length <= 0 or interval <= 0: raise ValueError('invalid_event_duration')
|
||||
before = timedelta(minutes=max(0, int(event.get('buffer_before') or 0)))
|
||||
after = timedelta(minutes=max(0, int(event.get('buffer_after') or 0)))
|
||||
occupied = []
|
||||
for booking in bookings:
|
||||
if booking.get('status') != 'accepted': continue
|
||||
start = datetime.fromisoformat(str(booking['start_utc']).replace('Z', '+00:00'))
|
||||
end = datetime.fromisoformat(str(booking['end_utc']).replace('Z', '+00:00'))
|
||||
occupied.append((start, end))
|
||||
slots = {}
|
||||
midnight = datetime.combine(local_date, datetime.min.time(), tzinfo=tz)
|
||||
for window in schedule.get('availability') or []:
|
||||
if local_date.strftime('%A') not in window.get('days', []): continue
|
||||
first, last = int(window['startTime']), int(window['endTime'])
|
||||
for minute in range(first, last - length + 1, interval):
|
||||
start_local = midnight + timedelta(minutes=minute)
|
||||
start = start_local.astimezone(timezone.utc)
|
||||
# Skip nonexistent wall-clock times during a daylight-saving jump.
|
||||
if start.astimezone(tz).replace(tzinfo=None) != start_local.replace(tzinfo=None): continue
|
||||
end = start + timedelta(minutes=length)
|
||||
if start <= now: continue
|
||||
if any(start - before < busy_end and end + after > busy_start for busy_start, busy_end in occupied): continue
|
||||
key = start.strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
slots[key] = {'start': key, 'end': end.strftime('%Y-%m-%dT%H:%M:%SZ'), 'local': start_local.strftime('%H:%M')}
|
||||
return [slots[key] for key in sorted(slots)]
|
||||
@ -14,4 +14,5 @@ from coffee_svc.pb_store import ( # noqa: F401
|
||||
list_hosts,
|
||||
update_schedule,
|
||||
upsert_event_type,
|
||||
upsert_host,
|
||||
)
|
||||
|
||||
@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from ebook_svc.core.security import require_admin
|
||||
from ebook_svc.services.audience_config import read_audience_config, write_audience_config
|
||||
@ -22,6 +22,7 @@ class LaneIn(BaseModel):
|
||||
|
||||
|
||||
class AudienceBody(BaseModel):
|
||||
expectedVersion: int | None = Field(default=None, ge=0)
|
||||
defaultLane: Literal["cn", "intl"] | None = None
|
||||
cn: LaneIn | None = None
|
||||
intl: LaneIn | None = None
|
||||
|
||||
@ -13,18 +13,19 @@ router = APIRouter(prefix="/api/admin/social/blog", tags=["social-blog-admin"])
|
||||
|
||||
|
||||
class BlogOpsPatch(BaseModel):
|
||||
featuredSlug: str | None = None
|
||||
hiddenSlugs: list[str] | None = None
|
||||
hideSlug: str | None = None
|
||||
showSlug: str | None = None
|
||||
note: str | None = None
|
||||
heroLead: str | None = None
|
||||
expectedVersion: int | None = Field(default=None, ge=0)
|
||||
featuredSlug: str | None = Field(default=None, max_length=200)
|
||||
hiddenSlugs: list[str] | None = Field(default=None, max_length=2000)
|
||||
hideSlug: str | None = Field(default=None, max_length=200)
|
||||
showSlug: str | None = Field(default=None, max_length=200)
|
||||
note: str | None = Field(default=None, max_length=500)
|
||||
heroLead: str | None = Field(default=None, max_length=400)
|
||||
moduleEnabled: bool | None = None
|
||||
adsenseEnabled: bool | None = None
|
||||
adsenseClientId: str | None = None
|
||||
adsensePublisherId: str | None = None
|
||||
adsenseSlotBlogMid: str | None = None
|
||||
adsenseSlotBlogEnd: str | None = None
|
||||
adsenseClientId: str | None = Field(default=None, max_length=64, pattern=r"^(ca-pub-[0-9]+)?$")
|
||||
adsensePublisherId: str | None = Field(default=None, max_length=64, pattern=r"^(pub-[0-9]+)?$")
|
||||
adsenseSlotBlogMid: str | None = Field(default=None, max_length=32, pattern=r"^[0-9]*$")
|
||||
adsenseSlotBlogEnd: str | None = Field(default=None, max_length=32, pattern=r"^[0-9]*$")
|
||||
|
||||
|
||||
@router.get("/overview")
|
||||
|
||||
@ -29,6 +29,75 @@ async def get_overview(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
return ugc.overview()
|
||||
|
||||
|
||||
@router.get("/presence")
|
||||
async def get_presence(
|
||||
city: str = "",
|
||||
limit: int = Query(48, ge=1, le=64),
|
||||
_: str = Depends(require_admin),
|
||||
) -> dict[str, Any]:
|
||||
"""Live who's-online for admin pulse.
|
||||
|
||||
Production: portal heartbeats land in ``nomadro-social`` (:8020). This process
|
||||
(``nomadmini-api``) must NOT read in-process ``_PRESENCE`` — that map is empty.
|
||||
Prefer HTTP to social; fall back to in-process store for unified local API.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
qs = urllib.parse.urlencode(
|
||||
{"limit": str(limit), **({"city": city.strip()} if (city or "").strip() else {})}
|
||||
)
|
||||
bases = []
|
||||
for raw in (
|
||||
os.environ.get("SOCIAL_INTERNAL_URL"),
|
||||
os.environ.get("SOCIAL_API_URL"),
|
||||
"http://127.0.0.1:8020",
|
||||
"http://127.0.0.1:8080",
|
||||
):
|
||||
b = (raw or "").strip().rstrip("/")
|
||||
if b and b not in bases:
|
||||
bases.append(b)
|
||||
|
||||
last_err: Exception | None = None
|
||||
for base in bases:
|
||||
url = f"{base}/api/social/v1/roster/online?{qs}"
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={"X-Social-Guest-Id": "admin-presence", "Accept": "application/json"},
|
||||
method="GET",
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=4) as res:
|
||||
data = json.loads(res.read().decode("utf-8", "replace") or "{}")
|
||||
if isinstance(data, dict) and (data.get("ok") is not False):
|
||||
return {
|
||||
"ok": True,
|
||||
"online": int(data.get("online") or 0),
|
||||
"peers": data.get("peers") if isinstance(data.get("peers"), list) else [],
|
||||
"cityOnline": int(data.get("cityOnline") or 0),
|
||||
"cityPeers": data.get("cityPeers")
|
||||
if isinstance(data.get("cityPeers"), list)
|
||||
else [],
|
||||
"source": base,
|
||||
}
|
||||
except Exception as e: # noqa: BLE001 — try next upstream
|
||||
last_err = e
|
||||
continue
|
||||
|
||||
try:
|
||||
from social_svc import store as social_store
|
||||
|
||||
data = social_store.list_social_online(city=(city or "").strip(), limit=limit)
|
||||
return {**data, "ok": True, "source": "inprocess"}
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
503, f"presence unavailable: {last_err or e}"
|
||||
) from e
|
||||
|
||||
|
||||
@router.get("/stats")
|
||||
async def get_stats(_: str = Depends(require_admin)) -> dict[str, Any]:
|
||||
"""Dashboard visualization payload (counts, city bars, day series, soft-delete)."""
|
||||
@ -168,6 +237,18 @@ async def get_join_leads(
|
||||
raise HTTPException(503, f"join leads unavailable: {e}") from e
|
||||
|
||||
|
||||
@router.post("/join-leads/dedupe")
|
||||
async def post_join_leads_dedupe(
|
||||
dryRun: bool = False,
|
||||
_: str = Depends(require_admin),
|
||||
) -> dict[str, Any]:
|
||||
"""Hard-delete duplicate social_join_leads (keep newest per email)."""
|
||||
try:
|
||||
return ugc.dedupe_join_leads(dry_run=dryRun)
|
||||
except Exception as e:
|
||||
raise HTTPException(503, f"join leads dedupe unavailable: {e}") from e
|
||||
|
||||
|
||||
@router.get("/skills")
|
||||
async def get_skills(
|
||||
q: str = "",
|
||||
|
||||
@ -3,9 +3,10 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from ebook_svc.services.tt_platform_config import resolve_config_file
|
||||
|
||||
DEFAULT_CN: dict[str, Any] = {
|
||||
@ -45,26 +46,9 @@ def _read_raw() -> dict[str, Any]:
|
||||
|
||||
|
||||
def _write_raw(out: dict[str, Any]) -> None:
|
||||
path = resolve_config_file()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out["updatedAt"] = datetime.now(timezone.utc).isoformat()
|
||||
try:
|
||||
out["version"] = int(out.get("version") or 1) + 1
|
||||
except Exception:
|
||||
out["version"] = 2
|
||||
if path.is_file():
|
||||
bak = path.with_suffix(path.suffix + f".bak-{out['updatedAt'].replace(':', '-')}")
|
||||
try:
|
||||
bak.write_text(path.read_text(encoding="utf-8"), encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
path.write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
try:
|
||||
from ebook_svc.services.config_live import notify_config_written
|
||||
from ebook_svc.services.weapp_switches import _write_raw as write_config
|
||||
|
||||
notify_config_written(out)
|
||||
except Exception:
|
||||
pass
|
||||
write_config(out)
|
||||
|
||||
|
||||
def _norm_lane(raw: Any, fallback: dict[str, Any]) -> dict[str, Any]:
|
||||
@ -110,6 +94,8 @@ def read_audience_config() -> dict[str, Any]:
|
||||
|
||||
def write_audience_config(patch: dict[str, Any]) -> dict[str, Any]:
|
||||
raw = _read_raw()
|
||||
if patch.get("expectedVersion") is not None and patch["expectedVersion"] != raw.get("version"):
|
||||
raise HTTPException(409, "配置已更新,请加载最新配置后重试;当前草稿尚未保存")
|
||||
out: dict[str, Any] = dict(raw) if raw else {"version": 2}
|
||||
cur = out.get("audience") if isinstance(out.get("audience"), dict) else {}
|
||||
audience = {
|
||||
|
||||
@ -7,6 +7,7 @@ import re
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from typing import Any
|
||||
from fastapi import HTTPException
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
from ebook_svc.services.tt_platform_config import resolve_config_file
|
||||
@ -169,13 +170,15 @@ def list_posts() -> dict[str, Any]:
|
||||
p["hidden"] = p["slug"] in hidden
|
||||
p["featured"] = bool(featured) and p["slug"] == featured
|
||||
# featured first, then date desc-ish (already from source)
|
||||
posts.sort(key=lambda x: (not x["featured"], x.get("hidden", False), x.get("date") or ""), reverse=False)
|
||||
posts.sort(key=lambda x: x.get("date") or "", reverse=True)
|
||||
posts.sort(key=lambda x: (0 if x["featured"] else 1, 1 if x["hidden"] else 0))
|
||||
return {"ok": True, "items": posts, "total": len(posts), "ops": ops}
|
||||
|
||||
|
||||
def patch_ops(body: dict[str, Any]) -> dict[str, Any]:
|
||||
raw = _read_raw()
|
||||
if body.get("expectedVersion") is not None and body["expectedVersion"] != raw.get("version"):
|
||||
raise HTTPException(409, "配置已更新,请加载最新配置后重试;当前草稿尚未保存")
|
||||
out = dict(raw) if raw else {"version": 1, "modules": {}, "flags": {}, "copy": {}}
|
||||
copy = dict(out.get("copy") or {})
|
||||
ops = _ops_from_raw(out)
|
||||
|
||||
@ -126,6 +126,10 @@ def list_join_leads(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[s
|
||||
return _pb().admin_list_join_leads(q=q, limit=limit, offset=offset)
|
||||
|
||||
|
||||
def dedupe_join_leads(*, dry_run: bool = False) -> dict[str, Any]:
|
||||
return _pb().dedupe_join_leads_collection(dry_run=dry_run)
|
||||
|
||||
|
||||
def list_skills(*, q: str = "", limit: int = 100, offset: int = 0) -> dict[str, Any]:
|
||||
return _pb().admin_list_skills(q=q, limit=limit, offset=offset)
|
||||
|
||||
|
||||
@ -13,10 +13,21 @@ China / hackrobot PB only via explicit env on that deploy — not in code defaul
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# Same-box default (US VPS or local). Do NOT point at hackrobot.cn.
|
||||
DEFAULT_PB_URL = "http://127.0.0.1:8090"
|
||||
|
||||
# Ensure apps/api/.env is loaded even if run.py wasn't the entry (tests / spawn).
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
|
||||
_api_root = Path(__file__).resolve().parents[2]
|
||||
load_dotenv(_api_root / ".env")
|
||||
load_dotenv(_api_root / ".env.local", override=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def resolve_pb_url() -> str:
|
||||
internal = (
|
||||
|
||||
@ -6,6 +6,7 @@ PB 0.25+ ignores legacy `schema` on create and may leave empty collections
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from threading import RLock
|
||||
from typing import Any
|
||||
|
||||
from nomadro_pb.client import PocketBaseClient, PocketBaseError, get_pb
|
||||
@ -13,6 +14,30 @@ from nomadro_pb.schemas import ALL_COLLECTIONS
|
||||
|
||||
log = logging.getLogger("nomadro_pb.ensure")
|
||||
_ensured = False
|
||||
_selected_ready: set[frozenset[str]] = set()
|
||||
_selected_lock = RLock()
|
||||
|
||||
|
||||
def ensure_selected(names: set[str]) -> bool:
|
||||
"""Initialize only this service's collections; leave other domains alone."""
|
||||
key = frozenset(names)
|
||||
with _selected_lock:
|
||||
if key in _selected_ready: return True
|
||||
specs = [spec for spec in ALL_COLLECTIONS if spec['name'] in names]
|
||||
if len(specs) != len(names): raise ValueError('unknown_collection')
|
||||
results = []
|
||||
pb = get_pb()
|
||||
for spec in specs:
|
||||
private = {**spec, **{rule: None for rule in ('listRule', 'viewRule', 'createRule', 'updateRule', 'deleteRule')}}
|
||||
ok = ensure_collection(pb, private)
|
||||
if ok:
|
||||
current = pb.get_collection(spec['name'])
|
||||
if current and any(current.get(rule) is not None for rule in ('listRule', 'viewRule', 'createRule', 'updateRule', 'deleteRule')):
|
||||
pb.request('PATCH', f"/api/collections/{current['id']}", admin=True,
|
||||
json={rule: None for rule in ('listRule', 'viewRule', 'createRule', 'updateRule', 'deleteRule')})
|
||||
results.append(ok)
|
||||
if all(results): _selected_ready.add(key)
|
||||
return all(results)
|
||||
|
||||
|
||||
def _legacy_schema(fields: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
@ -79,10 +104,16 @@ def _sync_fields(client: PocketBaseClient, existing: dict[str, Any], body: dict[
|
||||
missing = [f for f in want if f["name"] not in have]
|
||||
if not missing and have:
|
||||
return True
|
||||
# Empty or incomplete → replace with full field list (keeps system id)
|
||||
patch: dict[str, Any] = {"fields": want}
|
||||
# Preserve field IDs and extensions already present on production collections.
|
||||
existing_fields = existing.get("fields") or existing.get("schema") or []
|
||||
modern = "fields" in existing
|
||||
patch: dict[str, Any] = (
|
||||
{"fields": [*existing_fields, *missing]} if modern
|
||||
else {"schema": [*existing_fields, *_legacy_schema(missing)]}
|
||||
)
|
||||
if body.get("indexes"):
|
||||
patch["indexes"] = body["indexes"]
|
||||
patch["indexes"] = list(dict.fromkeys([*(existing.get("indexes") or []), *body["indexes"]]))
|
||||
expected = {field["name"] for field in want}
|
||||
try:
|
||||
client.request(
|
||||
"PATCH",
|
||||
@ -90,6 +121,8 @@ def _sync_fields(client: PocketBaseClient, existing: dict[str, Any], body: dict[
|
||||
admin=True,
|
||||
json=patch,
|
||||
)
|
||||
if not expected.issubset(_field_names(client.get_collection(body["name"]))):
|
||||
raise PocketBaseError("collection update did not persist requested fields")
|
||||
log.info(
|
||||
"patched PB collection %s (+%d fields)",
|
||||
body["name"],
|
||||
@ -103,8 +136,10 @@ def _sync_fields(client: PocketBaseClient, existing: dict[str, Any], body: dict[
|
||||
"PATCH",
|
||||
f"/api/collections/{existing['id']}",
|
||||
admin=True,
|
||||
json={"schema": _legacy_schema(want)},
|
||||
json={"schema": [*existing_fields, *_legacy_schema(missing)]},
|
||||
)
|
||||
if not expected.issubset(_field_names(client.get_collection(body["name"]))):
|
||||
raise PocketBaseError("legacy schema update did not persist requested fields")
|
||||
log.info("patched PB collection %s via legacy schema", body["name"])
|
||||
return True
|
||||
except PocketBaseError as exc2:
|
||||
|
||||
@ -288,7 +288,7 @@ SOCIAL_JOIN_LEADS = _base(
|
||||
_text("updated_at", True),
|
||||
],
|
||||
indexes=[
|
||||
"CREATE INDEX idx_social_join_email ON social_join_leads (email)",
|
||||
"CREATE UNIQUE INDEX idx_social_join_email ON social_join_leads (email)",
|
||||
"CREATE INDEX idx_social_join_guest ON social_join_leads (guest_id)",
|
||||
"CREATE INDEX idx_social_join_at ON social_join_leads (updated_at)",
|
||||
],
|
||||
@ -331,6 +331,7 @@ COFFEE_HOSTS = _base(
|
||||
"coffee_hosts",
|
||||
[
|
||||
_text("username", True),
|
||||
_text("owner_key_hash"),
|
||||
_text("name", True),
|
||||
_text("bio"),
|
||||
_text("avatar"),
|
||||
@ -385,6 +386,7 @@ COFFEE_BOOKINGS = _base(
|
||||
_text("attendee_name"),
|
||||
_text("attendee_email"),
|
||||
_text("attendee_device"),
|
||||
_text("attendee_key_hash"),
|
||||
_text("created_at", True),
|
||||
_text("cancelled_at"),
|
||||
],
|
||||
|
||||
33
apps/api/services/notify_svc/access.py
Normal file
33
apps/api/services/notify_svc/access.py
Normal file
@ -0,0 +1,33 @@
|
||||
"""Separate device-owned inbox requests from trusted service operations."""
|
||||
import hmac
|
||||
import os
|
||||
import re
|
||||
|
||||
from fastapi import HTTPException, Request
|
||||
|
||||
|
||||
async def require_access(request: Request):
|
||||
expected = os.getenv('NOTIFY_INTERNAL_TOKEN', '')
|
||||
supplied = request.headers.get('x-notify-internal-token', '')
|
||||
if expected and hmac.compare_digest(expected, supplied):
|
||||
return
|
||||
path = request.url.path.removeprefix('/api/notify/v1').strip('/')
|
||||
if path == 'health': return
|
||||
guest = request.headers.get('x-social-guest-id', '')
|
||||
if not re.fullmatch(r'[A-Za-z0-9_-]{1,80}', guest):
|
||||
raise HTTPException(401, 'guest_identity_required')
|
||||
if path in ('inbox', 'inbox/unread') and request.method == 'GET':
|
||||
target = request.query_params.get('subscriber_id', 'guest')
|
||||
elif path == 'inbox/read-all' and request.method == 'POST':
|
||||
try: target = (await request.json()).get('subscriber_id', 'guest')
|
||||
except (ValueError, AttributeError): raise HTTPException(400, 'invalid_body')
|
||||
elif re.fullmatch(r'subscribers/[^/]+/preferences', path) and request.method in ('GET', 'PUT'):
|
||||
target = request.path_params.get('subscriber_id')
|
||||
elif re.fullmatch(r'inbox/[^/]+', path) and request.method in ('PATCH', 'DELETE'):
|
||||
from notify_svc.pb_store import get_message
|
||||
message = get_message(request.path_params['message_id'])
|
||||
if not message: raise HTTPException(404, 'message_not_found')
|
||||
target = message.get('subscriber_id')
|
||||
else:
|
||||
raise HTTPException(403, 'notify_management_requires_admin')
|
||||
if target != guest: raise HTTPException(403, 'subscriber_identity_mismatch')
|
||||
@ -3,9 +3,11 @@ from __future__ import annotations
|
||||
|
||||
import time
|
||||
import uuid
|
||||
from threading import RLock
|
||||
from typing import Any
|
||||
|
||||
from nomadro_pb import ensure_once, get_pb, pb_quote
|
||||
from nomadro_pb import get_pb, pb_quote
|
||||
from nomadro_pb.ensure import ensure_selected
|
||||
|
||||
C_SUB = "notify_subscribers"
|
||||
C_TOPICS = "notify_topics"
|
||||
@ -14,6 +16,8 @@ C_PREFS = "notify_preferences"
|
||||
C_MSG = "notify_messages"
|
||||
C_ACT = "notify_activity"
|
||||
C_INT = "notify_integrations"
|
||||
_seed_lock = RLock()
|
||||
_seeded = False
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
@ -44,8 +48,13 @@ def _default_prefs() -> dict[str, Any]:
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
ensure_once()
|
||||
_seed_workflows()
|
||||
global _seeded
|
||||
if not ensure_selected({C_SUB, C_TOPICS, C_WF, C_PREFS, C_MSG, C_ACT, C_INT}):
|
||||
raise RuntimeError('notify_storage_unavailable')
|
||||
with _seed_lock:
|
||||
if not _seeded:
|
||||
_seed_workflows()
|
||||
_seeded = True
|
||||
|
||||
|
||||
def _seed_workflows() -> None:
|
||||
@ -115,6 +124,8 @@ def upsert_subscriber(data: dict[str, Any]) -> dict[str, Any]:
|
||||
}
|
||||
existing = get_pb().first(C_SUB, filter=f"subscriber_id={pb_quote(sid)}")
|
||||
if existing:
|
||||
for key in ['email', 'phone', 'first_name', 'last_name', 'avatar', 'locale', 'data']:
|
||||
if key not in data and not (key == 'first_name' and 'firstName' in data): body.pop(key, None)
|
||||
get_pb().update(C_SUB, existing["id"], body)
|
||||
else:
|
||||
body["created_at"] = now
|
||||
@ -157,7 +168,6 @@ def delete_subscriber(subscriber_id: str) -> bool:
|
||||
|
||||
def get_preferences(subscriber_id: str) -> dict[str, Any] | None:
|
||||
init_db()
|
||||
upsert_subscriber({"subscriber_id": subscriber_id})
|
||||
r = get_pb().first(C_PREFS, filter=f"subscriber_id={pb_quote(subscriber_id)}")
|
||||
channels = _default_prefs()
|
||||
if r and isinstance(r.get("channels"), dict):
|
||||
@ -334,12 +344,16 @@ def list_inbox(
|
||||
subscriber_id: str,
|
||||
*,
|
||||
category: str | None = None,
|
||||
include_archived: bool = False,
|
||||
limit: int = 50,
|
||||
) -> list[dict[str, Any]]:
|
||||
init_db()
|
||||
filters = [f'subscriber_id={pb_quote(subscriber_id)}', 'deleted=false']
|
||||
if not include_archived: filters.append('archived=false')
|
||||
if category: filters.append(f'category={pb_quote(category)}')
|
||||
rows = get_pb().list_all(
|
||||
C_MSG,
|
||||
filter=f"subscriber_id={pb_quote(subscriber_id)}",
|
||||
filter=' && '.join(filters),
|
||||
sort="-created_at",
|
||||
hard_limit=limit,
|
||||
)
|
||||
@ -372,6 +386,10 @@ def _message_out(r: dict[str, Any]) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def get_message(message_id: str) -> dict[str, Any] | None:
|
||||
return get_pb().first(C_MSG, filter=f'id={pb_quote(message_id)}')
|
||||
|
||||
|
||||
def patch_message(message_id: str, patch: dict[str, Any]) -> dict[str, Any] | None:
|
||||
try:
|
||||
get_pb().update(C_MSG, message_id, patch)
|
||||
|
||||
@ -2,12 +2,13 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from notify_svc import store
|
||||
from notify_svc.access import require_access
|
||||
|
||||
router = APIRouter(tags=["notify"])
|
||||
router = APIRouter(tags=["notify"], dependencies=[Depends(require_access)])
|
||||
|
||||
|
||||
class SubscriberIn(BaseModel):
|
||||
|
||||
@ -10,6 +10,7 @@ from notify_svc.pb_store import ( # noqa: F401
|
||||
delete_subscriber,
|
||||
delete_workflow,
|
||||
get_preferences,
|
||||
get_message,
|
||||
get_subscriber,
|
||||
get_workflow,
|
||||
init_db,
|
||||
|
||||
@ -350,15 +350,15 @@ def check_face(
|
||||
log.warning("face engine %s failed: %s", eng, exc)
|
||||
continue
|
||||
|
||||
if _env_bool("SOCIAL_AVATAR_FACE_STRICT", False):
|
||||
return FaceCheckResult(
|
||||
ok=False,
|
||||
faces=0,
|
||||
engine="none",
|
||||
detail=f"人脸检测不可用: {last_err or 'no engine'}",
|
||||
)
|
||||
log.warning("face check skipped (no engine); allowing upload")
|
||||
return FaceCheckResult(ok=True, faces=-1, engine="skipped", detail=last_err)
|
||||
# Fail closed: never stamp face_ok=true when no detector ran.
|
||||
# Upload path still persists the file with face_ok=false when gate is off.
|
||||
log.warning("face check unavailable (%s); marking no-face", last_err or "no engine")
|
||||
return FaceCheckResult(
|
||||
ok=False,
|
||||
faces=0,
|
||||
engine="none",
|
||||
detail=f"人脸检测不可用: {last_err or 'no engine'}",
|
||||
)
|
||||
|
||||
|
||||
def assert_avatar_has_face(
|
||||
|
||||
@ -28,6 +28,8 @@ def _request(
|
||||
url = f"{NOTIFY_INTERNAL_URL}{path}"
|
||||
data = json.dumps(body).encode("utf-8") if body is not None else None
|
||||
headers = {"Accept": "application/json"}
|
||||
token = os.getenv('NOTIFY_INTERNAL_TOKEN')
|
||||
if token: headers['X-Notify-Internal-Token'] = token
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
|
||||
@ -29,7 +29,7 @@ def _post(path: str, body: dict[str, Any], timeout: float = 4.0) -> dict[str, An
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={"Content-Type": "application/json", "Accept": "application/json"},
|
||||
headers={"Content-Type": "application/json", "Accept": "application/json", "X-Notify-Internal-Token": os.getenv('NOTIFY_INTERNAL_TOKEN', '')},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
|
||||
@ -319,7 +319,7 @@ def mark_face_photo(
|
||||
guest_id: str,
|
||||
avatar_url: str,
|
||||
*,
|
||||
face_ok: bool = True,
|
||||
face_ok: bool = False,
|
||||
) -> None:
|
||||
"""Album/selfie → avatar. face_ok only when detector saw a real face."""
|
||||
init_pb()
|
||||
@ -473,7 +473,7 @@ def list_discovery_roster(
|
||||
city: str = "",
|
||||
limit: int = 48,
|
||||
exclude_self: bool = True,
|
||||
require_face: bool = False,
|
||||
require_face: bool = True,
|
||||
) -> list[dict[str, Any]]:
|
||||
init_pb()
|
||||
rows = get_pb().list_all(C_ROSTER, sort="-updated_at", hard_limit=400)
|
||||
@ -1184,7 +1184,7 @@ _JOIN_FACE_STAGES = frozenset(
|
||||
"join_done",
|
||||
}
|
||||
)
|
||||
_JOIN_EARLY_STAGES = frozenset({"email_submit", "pay_launched"})
|
||||
_JOIN_EARLY_STAGES = frozenset({"email_submit", "pay_launched", "profile_started"})
|
||||
|
||||
|
||||
def _sanitize_join_lead_item(item: dict[str, Any]) -> dict[str, Any]:
|
||||
@ -1307,7 +1307,7 @@ def upsert_join_lead(
|
||||
# email_submit 等禁止写入浏览器残留核验,避免串号
|
||||
face_in = (face_ok or "")[:8] if allow_face else ""
|
||||
live_in = (liveness_status or "")[:24] if allow_face else ""
|
||||
early = stage_n in {"email_submit", "pay_launched"}
|
||||
early = stage_n in {"email_submit", "pay_launched", "profile_started"}
|
||||
paid_in = (paid or "")[:8]
|
||||
intent = str(body_payload.get("intent") or "")
|
||||
if early:
|
||||
@ -1343,7 +1343,23 @@ def upsert_join_lead(
|
||||
lead_id = email_n
|
||||
try:
|
||||
pb = get_pb()
|
||||
existing = pb.first(C_JOIN_LEADS, filter=f"email={pb_quote(email_n)}")
|
||||
# Collapse any historical duplicates for this email before upsert.
|
||||
twins = pb.list_all(
|
||||
C_JOIN_LEADS,
|
||||
filter=f"email={pb_quote(email_n)}",
|
||||
sort="-updated_at",
|
||||
hard_limit=50,
|
||||
)
|
||||
existing = twins[0] if twins else pb.first(
|
||||
C_JOIN_LEADS, filter=f"email={pb_quote(email_n)}"
|
||||
)
|
||||
for extra in twins[1:]:
|
||||
rid = str(extra.get("id") or "")
|
||||
if rid and rid != str((existing or {}).get("id") or ""):
|
||||
try:
|
||||
pb.delete(C_JOIN_LEADS, rid)
|
||||
except Exception:
|
||||
pass
|
||||
if existing and existing.get("id"):
|
||||
face_val = face_in or (existing.get("face_ok") or "") if allow_face else (existing.get("face_ok") or "")
|
||||
live_val = (
|
||||
@ -1405,6 +1421,164 @@ def upsert_join_lead(
|
||||
}
|
||||
|
||||
|
||||
def _join_lead_newer(a: dict[str, Any], b: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Keep the fresher lead; tie-break prefers guestId then smaller id."""
|
||||
ta = str(a.get("updatedAt") or a.get("updated_at") or "")
|
||||
tb = str(b.get("updatedAt") or b.get("updated_at") or "")
|
||||
if tb > ta:
|
||||
return b
|
||||
if ta > tb:
|
||||
return a
|
||||
ga = str(a.get("guestId") or a.get("guest_id") or "")
|
||||
gb = str(b.get("guestId") or b.get("guest_id") or "")
|
||||
if gb and not ga:
|
||||
return b
|
||||
if ga and not gb:
|
||||
return a
|
||||
return a if str(a.get("id") or "") <= str(b.get("id") or "") else b
|
||||
|
||||
|
||||
def _dedupe_join_leads_by_email(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""One row per email (case-insensitive). Empty email keeps distinct ids."""
|
||||
by_email: dict[str, dict[str, Any]] = {}
|
||||
no_email: list[dict[str, Any]] = []
|
||||
for r in rows:
|
||||
em = str(r.get("email") or "").strip().lower()
|
||||
if not em:
|
||||
no_email.append(r)
|
||||
continue
|
||||
prev = by_email.get(em)
|
||||
by_email[em] = _join_lead_newer(prev, r) if prev else r
|
||||
return list(by_email.values()) + no_email
|
||||
|
||||
|
||||
def dedupe_join_leads_collection(*, dry_run: bool = False) -> dict[str, Any]:
|
||||
"""Hard-delete duplicate social_join_leads rows (keep newest per email)."""
|
||||
init_pb()
|
||||
pb = get_pb()
|
||||
rows = pb.list_all(C_JOIN_LEADS, sort="-updated_at", hard_limit=5000)
|
||||
by_email: dict[str, list[dict[str, Any]]] = {}
|
||||
for r in rows:
|
||||
em = str(r.get("email") or "").strip().lower()
|
||||
if not em:
|
||||
continue
|
||||
by_email.setdefault(em, []).append(r)
|
||||
deleted: list[str] = []
|
||||
kept = 0
|
||||
for em, group in by_email.items():
|
||||
if len(group) < 2:
|
||||
kept += 1 if group else 0
|
||||
continue
|
||||
kept += 1
|
||||
for extra in group[1:]:
|
||||
rid = str(extra.get("id") or "")
|
||||
if not rid:
|
||||
continue
|
||||
if not dry_run:
|
||||
try:
|
||||
pb.delete(C_JOIN_LEADS, rid)
|
||||
except Exception:
|
||||
continue
|
||||
deleted.append(rid)
|
||||
return {
|
||||
"ok": True,
|
||||
"emails": len(by_email),
|
||||
"kept": kept,
|
||||
"deleted": len(deleted),
|
||||
"deletedIds": deleted[:50],
|
||||
"dryRun": dry_run,
|
||||
}
|
||||
|
||||
|
||||
def _admin_abs_media(url: str) -> str:
|
||||
u = (url or "").strip()
|
||||
if not u:
|
||||
return ""
|
||||
if u.startswith("https://") or u.startswith("http://") or u.startswith("data:"):
|
||||
return u
|
||||
if u.startswith("/api/social/"):
|
||||
return f"https://api.nomadro.com{u}"
|
||||
if u.startswith("/"):
|
||||
return f"https://nomadro.com{u}"
|
||||
return u
|
||||
|
||||
|
||||
def _enrich_join_leads_for_admin(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Attach roster avatar + faceOk for ops list (always show album photo in admin)."""
|
||||
if not items:
|
||||
return items
|
||||
by_gid: dict[str, dict[str, Any]] = {}
|
||||
by_email: dict[str, dict[str, Any]] = {}
|
||||
try:
|
||||
init_pb()
|
||||
rows = get_pb().list_all(C_ROSTER, sort="-updated_at", hard_limit=4000)
|
||||
for r in rows:
|
||||
gid = str(r.get("guest_id") or "").strip().lower()
|
||||
em = str(r.get("email") or "").strip().lower()
|
||||
if gid and gid not in by_gid:
|
||||
by_gid[gid] = r
|
||||
if em and em not in by_email:
|
||||
by_email[em] = r
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
out: list[dict[str, Any]] = []
|
||||
for item in items:
|
||||
row = dict(item)
|
||||
stage = str(row.get("stage") or "")
|
||||
payload = row.get("payload") if isinstance(row.get("payload"), dict) else {}
|
||||
gid = str(row.get("guestId") or row.get("guest_id") or "").strip().lower()
|
||||
email = str(row.get("email") or "").strip().lower()
|
||||
roster = by_gid.get(gid) if gid else None
|
||||
if roster is None and email:
|
||||
roster = by_email.get(email)
|
||||
|
||||
# Admin ops: always surface album photo when we can match roster/payload.
|
||||
# (Public surfaces still strip no-face; this list is behind admin auth.)
|
||||
avatar = ""
|
||||
for key in ("avatar", "avatarUrl"):
|
||||
cand = payload.get(key)
|
||||
if isinstance(cand, str) and cand.strip():
|
||||
avatar = cand.strip()
|
||||
break
|
||||
nested = payload.get("payload") if isinstance(payload.get("payload"), dict) else {}
|
||||
if not avatar and nested:
|
||||
for key in ("avatar", "avatarUrl"):
|
||||
cand = nested.get(key)
|
||||
if isinstance(cand, str) and cand.strip():
|
||||
avatar = cand.strip()
|
||||
break
|
||||
if not avatar and roster:
|
||||
avatar = str(roster.get("avatar") or "").strip()
|
||||
|
||||
# Ops faceOk = roster detector only. Never trust client join-lead face_ok
|
||||
# (payload often stamped "1" after liveness skip / browser residue).
|
||||
# No avatar → never OK. Liveness verified ≠ album faceOk.
|
||||
abs_avatar = _admin_abs_media(avatar)
|
||||
face_ok = False
|
||||
if abs_avatar and roster is not None:
|
||||
face_ok = _face_ok_raw(roster.get("face_ok"))
|
||||
if stage in {"email_submit", "pay_launched"}:
|
||||
face_ok = False
|
||||
# Placeholder / empty-looking URLs cannot be face-ok in the ops list.
|
||||
low = abs_avatar.lower()
|
||||
if (
|
||||
not abs_avatar
|
||||
or "nomadro.webp" in low
|
||||
or low.endswith("/avatar.png")
|
||||
or "/placeholder" in low
|
||||
or low.startswith("data:")
|
||||
):
|
||||
face_ok = False
|
||||
|
||||
row["avatar"] = abs_avatar
|
||||
row["faceOk"] = face_ok
|
||||
if roster and not row.get("name"):
|
||||
row["name"] = roster.get("name") or row.get("name") or ""
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
|
||||
def admin_list_join_leads(
|
||||
*, q: str = "", limit: int = 100, offset: int = 0
|
||||
) -> dict[str, Any]:
|
||||
@ -1472,24 +1646,13 @@ def admin_list_join_leads(
|
||||
except Exception:
|
||||
items = []
|
||||
|
||||
# Merge portal local file (dev / offline) — newer updatedAt wins per email
|
||||
# Merge portal local file (dev / offline), then always collapse by email.
|
||||
local_items = _join_leads_local_list()
|
||||
if local_items:
|
||||
by_email: dict[str, dict[str, Any]] = {}
|
||||
for r in items:
|
||||
em = str(r.get("email") or "").strip().lower()
|
||||
if em:
|
||||
by_email[em] = r
|
||||
for r in local_items:
|
||||
em = str(r.get("email") or "").strip().lower()
|
||||
if not em:
|
||||
continue
|
||||
prev = by_email.get(em)
|
||||
if not prev or str(r.get("updatedAt") or "") >= str(prev.get("updatedAt") or ""):
|
||||
by_email[em] = r
|
||||
items = list(by_email.values())
|
||||
|
||||
items = items + local_items
|
||||
items = _dedupe_join_leads_by_email(items)
|
||||
items = [_sanitize_join_lead_item(r) for r in items]
|
||||
items = _enrich_join_leads_for_admin(items)
|
||||
items.sort(key=lambda r: str(r.get("updatedAt") or ""), reverse=True)
|
||||
|
||||
if needle:
|
||||
|
||||
@ -942,7 +942,7 @@ def get_my_roster(x_social_guest_id: str | None = Header(default=None)):
|
||||
def roster_discovery(
|
||||
city: str = Query(default=""),
|
||||
limit: int = Query(default=48, ge=1, le=100),
|
||||
require_face: bool = Query(default=False, alias="requireFace"),
|
||||
require_face: bool = Query(default=True, alias="requireFace"),
|
||||
x_social_guest_id: str | None = Header(default=None),
|
||||
guest: str | None = Query(default=None),
|
||||
):
|
||||
|
||||
@ -901,7 +901,7 @@ def mark_face_photo(
|
||||
guest_id: str,
|
||||
avatar_url: str,
|
||||
*,
|
||||
face_ok: bool = True,
|
||||
face_ok: bool = False,
|
||||
) -> None:
|
||||
"""Album/selfie → avatar. face_ok only when a real face was detected."""
|
||||
from social_svc import pb_data
|
||||
|
||||
@ -75,6 +75,8 @@ def isolate_social(test):
|
||||
('nomadro_pb.ensure_once', lambda: None),
|
||||
('social_svc.im.check_rate', lambda guest_id: None),
|
||||
('social_svc.trial_gate.assert_chat_trial_ok', lambda guest_id: None),
|
||||
('social_svc.notify_bridge._request', lambda *args, **kwargs: None),
|
||||
('social_svc.onboarding._post', lambda *args, **kwargs: None),
|
||||
]:
|
||||
override = patch(target, value)
|
||||
override.start()
|
||||
|
||||
117
apps/api/tests/test_coffee_notify_api.py
Normal file
117
apps/api/tests/test_coffee_notify_api.py
Normal file
@ -0,0 +1,117 @@
|
||||
"""Real router/store behavior with isolated persistence and no external sends."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'services'))
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from pb_fixture import MemoryPocketBase
|
||||
from coffee_svc.routers.api import router as coffee_router
|
||||
from notify_svc.routers.api import router as notify_router
|
||||
from notify_svc import pb_store as notifications
|
||||
|
||||
|
||||
class CoffeeNotifyTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.pb = MemoryPocketBase()
|
||||
for target, value in [
|
||||
('coffee_svc.pb_store.get_pb', lambda: self.pb),
|
||||
('coffee_svc.routers.api.get_pb', lambda: self.pb),
|
||||
('coffee_svc.pb_store.ensure_selected', lambda names: True),
|
||||
('notify_svc.pb_store.get_pb', lambda: self.pb),
|
||||
('notify_svc.pb_store.ensure_selected', lambda names: True),
|
||||
('notify_svc.pb_store._seeded', False),
|
||||
('social_svc.notify_bridge.notify_coffee_invite', lambda *args: None),
|
||||
]:
|
||||
override = patch(target, value); override.start(); self.addCleanup(override.stop)
|
||||
env = patch.dict('os.environ', {'COFFEE_SEED_DEMO': '0', 'NOTIFY_INTERNAL_TOKEN': 'isolated-internal-secret'})
|
||||
env.start(); self.addCleanup(env.stop)
|
||||
app = FastAPI()
|
||||
app.include_router(coffee_router, prefix='/api/coffee/v1')
|
||||
app.include_router(notify_router, prefix='/api/notify/v1')
|
||||
self.client = TestClient(app); self.addCleanup(self.client.close)
|
||||
self.host = {'X-Social-Guest-Id': 'host-test', 'X-Coffee-Key': 'a' * 64}
|
||||
self.guest = {'X-Social-Guest-Id': 'visitor-test', 'X-Coffee-Key': 'b' * 64}
|
||||
|
||||
def prepare_host(self):
|
||||
res = self.client.put('/api/coffee/v1/me', headers=self.host, json={'name': 'Test host', 'timezone': 'America/New_York'})
|
||||
self.assertEqual(res.status_code, 200, res.text)
|
||||
res = self.client.patch('/api/coffee/v1/hosts/host-test/schedule', headers=self.host, json={'availability': [{'days': ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], 'startTime': 600, 'endTime': 660}]})
|
||||
self.assertEqual(res.status_code, 200, res.text)
|
||||
day = (datetime.now(timezone.utc) + timedelta(days=2)).date().isoformat()
|
||||
result = self.client.get('/api/coffee/v1/hosts/host-test/event-types/30min/slots', params={'day': day})
|
||||
return result.json()['slots'][0]['start']
|
||||
|
||||
def test_host_onboarding_empty_schedule_then_usable_slots(self):
|
||||
self.assertEqual(self.client.get('/api/coffee/v1/hosts').json()['hosts'], [])
|
||||
self.prepare_host()
|
||||
public = self.client.get('/api/coffee/v1/hosts/host-test').json()
|
||||
self.assertNotIn('owner_key_hash', str(public))
|
||||
self.assertEqual(public['host']['event_count'], 1)
|
||||
|
||||
def test_public_id_does_not_allow_host_takeover(self):
|
||||
self.prepare_host()
|
||||
attacker = {**self.host, 'X-Coffee-Key': 'c' * 64}
|
||||
for method, url, body in [('GET', '/me', None), ('PUT', '/me', {'name': 'Hijacked', 'timezone': 'UTC'}), ('PATCH', '/hosts/host-test/schedule', {'availability': []})]:
|
||||
result = self.client.request(method, '/api/coffee/v1' + url, headers=attacker, json=body)
|
||||
self.assertEqual(result.status_code, 403, result.text)
|
||||
|
||||
def test_duplicate_parallel_booking_conflicts_and_cancellation_reopens_slot(self):
|
||||
start = self.prepare_host()
|
||||
body = {'username': 'host-test', 'event_slug': '30min', 'start': start, 'attendee_name': 'Visitor'}
|
||||
def reserve(_): return self.client.post('/api/coffee/v1/bookings', headers=self.guest, json=body)
|
||||
with ThreadPoolExecutor(max_workers=6) as pool: results = list(pool.map(reserve, range(6)))
|
||||
self.assertEqual(sorted(r.status_code for r in results), [200, 409, 409, 409, 409, 409])
|
||||
booking = next(r.json()['booking'] for r in results if r.status_code == 200)
|
||||
self.assertNotIn('attendee_key_hash', booking)
|
||||
url = '/api/coffee/v1/bookings/' + booking['id']
|
||||
attacker = {**self.guest, 'X-Coffee-Key': 'c' * 64}
|
||||
self.assertEqual(self.client.get(url, headers=attacker).status_code, 403)
|
||||
self.assertEqual(self.client.post(url + '/cancel', headers=attacker).status_code, 403)
|
||||
self.assertEqual(self.client.get('/api/coffee/v1/bookings', headers=attacker).json()['bookings'], [])
|
||||
self.assertEqual(self.client.get(url, headers=self.host).status_code, 200)
|
||||
self.assertEqual(self.client.post(url + '/cancel', headers=self.guest).status_code, 200)
|
||||
self.assertEqual(reserve(0).status_code, 200)
|
||||
|
||||
def test_invalid_booking_and_schedule_rejected_without_writes(self):
|
||||
self.prepare_host()
|
||||
res = self.client.post('/api/coffee/v1/bookings', headers=self.guest, json={'username': 'host-test', 'event_slug': '30min', 'start': '2000-01-01T10:00:00Z', 'attendee_name': 'Visitor'})
|
||||
self.assertEqual(res.status_code, 409)
|
||||
res = self.client.patch('/api/coffee/v1/hosts/host-test/schedule', headers=self.host, json={'availability': [{'days': ['Monday'], 'startTime': 600, 'endTime': 500}]})
|
||||
self.assertEqual(res.status_code, 422)
|
||||
self.assertEqual(len(self.pb.rows.get('coffee_bookings', {})), 0)
|
||||
|
||||
def test_notify_management_cannot_be_triggered_by_a_visitor(self):
|
||||
for method, path, body in [('GET', '/subscribers', None), ('GET', '/workflows', None), ('POST', '/events/trigger', {'workflow_id': 'welcome', 'subscriber_id': 'visitor-test'})]:
|
||||
self.assertEqual(self.client.request(method, '/api/notify/v1' + path, headers=self.guest, json=body).status_code, 403)
|
||||
self.assertEqual(self.client.get('/api/notify/v1/workflows', headers={'X-Notify-Internal-Token': 'isolated-internal-secret'}).status_code, 200)
|
||||
|
||||
def test_notify_inbox_filters_before_limit_and_owns_mutations(self):
|
||||
notifications.init_db()
|
||||
for index in range(60):
|
||||
self.pb.create('notify_messages', {'subscriber_id': 'visitor-test', 'created_at': str(index).zfill(3), 'category': 'social', 'deleted': False, 'archived': False, 'read': False})
|
||||
specific = self.pb.create('notify_messages', {'subscriber_id': 'visitor-test', 'created_at': '000', 'category': 'system', 'deleted': False, 'archived': False, 'read': False})
|
||||
self.pb.create('notify_messages', {'subscriber_id': 'visitor-test', 'created_at': '999', 'category': 'system', 'deleted': False, 'archived': True, 'read': False})
|
||||
res = self.client.get('/api/notify/v1/inbox?subscriber_id=visitor-test&category=system', headers=self.guest)
|
||||
self.assertEqual(res.status_code, 200, res.text)
|
||||
self.assertEqual([m['id'] for m in res.json()['messages']], [specific['id']])
|
||||
self.assertEqual(self.client.get('/api/notify/v1/inbox?subscriber_id=host-test', headers=self.guest).status_code, 403)
|
||||
url = '/api/notify/v1/inbox/' + specific['id']
|
||||
self.assertEqual(self.client.patch(url, headers=self.host, json={'read': True}).status_code, 403)
|
||||
self.assertEqual(self.client.patch(url, headers=self.guest, json={'read': True}).status_code, 200)
|
||||
|
||||
def test_notify_preference_read_preserves_profile_and_partial_update(self):
|
||||
notifications.upsert_subscriber({'subscriber_id': 'visitor-test', 'email': 'owner@example.test', 'first_name': 'Owner'})
|
||||
url = '/api/notify/v1/subscribers/visitor-test/preferences'
|
||||
self.assertEqual(self.client.get(url, headers=self.guest).status_code, 200)
|
||||
self.client.put(url, headers=self.guest, json={'channels': {'timezone': 'UTC'}})
|
||||
res = self.client.put(url, headers=self.guest, json={'channels': {'dnd': True}})
|
||||
self.assertEqual(res.json()['preferences']['channels']['timezone'], 'UTC')
|
||||
self.assertEqual(notifications.get_subscriber('visitor-test')['email'], 'owner@example.test')
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
50
apps/api/tests/test_coffee_scheduling.py
Normal file
50
apps/api/tests/test_coffee_scheduling.py
Normal file
@ -0,0 +1,50 @@
|
||||
from datetime import datetime, timezone
|
||||
import unittest
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'services'))
|
||||
|
||||
from coffee_svc.scheduling import available_times
|
||||
|
||||
|
||||
class CoffeeSchedulingTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.schedule = {
|
||||
'timezone': 'America/New_York',
|
||||
'availability': [{'days': ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], 'startTime': 9 * 60, 'endTime': 12 * 60}],
|
||||
}
|
||||
self.event = {'active': True, 'length_minutes': 30, 'slot_interval': 30}
|
||||
|
||||
def test_uses_host_local_weekday_and_utc_output(self):
|
||||
result = available_times('2026-11-09', self.schedule, self.event, [], datetime(2026, 11, 1, tzinfo=timezone.utc))
|
||||
self.assertEqual(result[0]['local'], '09:00')
|
||||
self.assertEqual(result[0]['start'], '2026-11-09T14:00:00Z')
|
||||
|
||||
def test_excludes_past_and_overlapping_buffered_booking(self):
|
||||
bookings = [{'status': 'accepted', 'start_utc': '2026-11-09T15:00:00Z', 'end_utc': '2026-11-09T15:30:00Z'}]
|
||||
event = {**self.event, 'buffer_before': 15, 'buffer_after': 15}
|
||||
result = available_times('2026-11-09', self.schedule, event, bookings, datetime(2026, 11, 9, 13, 45, tzinfo=timezone.utc))
|
||||
self.assertNotIn('2026-11-09T15:00:00Z', {row['start'] for row in result})
|
||||
self.assertNotIn('2026-11-09T14:30:00Z', {row['start'] for row in result})
|
||||
self.assertNotIn('2026-11-09T15:30:00Z', {row['start'] for row in result})
|
||||
self.assertIn('2026-11-09T16:00:00Z', {row['start'] for row in result})
|
||||
|
||||
def test_inactive_and_wrong_weekday_have_no_slots(self):
|
||||
self.assertEqual(available_times('2026-11-08', self.schedule, self.event, []), [])
|
||||
self.assertEqual(available_times('2026-11-09', self.schedule, {**self.event, 'active': False}, []), [])
|
||||
|
||||
def test_dst_spring_forward_skips_nonexistent_wall_time(self):
|
||||
schedule = {'timezone': 'America/New_York', 'availability': [{'days': ['Sunday'], 'startTime': 1 * 60, 'endTime': 4 * 60}]}
|
||||
event = {'active': True, 'length_minutes': 30, 'slot_interval': 30}
|
||||
result = available_times('2026-03-08', schedule, event, [], datetime(2026, 1, 1, tzinfo=timezone.utc))
|
||||
self.assertNotIn('02:00', {row['local'] for row in result})
|
||||
|
||||
def test_duplicate_windows_are_deduplicated(self):
|
||||
schedule = {**self.schedule, 'availability': self.schedule['availability'] * 2}
|
||||
result = available_times('2026-11-09', schedule, self.event, [], datetime(2026, 1, 1, tzinfo=timezone.utc))
|
||||
self.assertEqual(len(result), len({row['start'] for row in result}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
40
apps/api/tests/test_scoped_schema.py
Normal file
40
apps/api/tests/test_scoped_schema.py
Normal file
@ -0,0 +1,40 @@
|
||||
"""Protect production schema extensions and verify old/new PB field persistence."""
|
||||
import copy
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'services'))
|
||||
from nomadro_pb.ensure import ensure_collection
|
||||
|
||||
|
||||
class SchemaAdapter:
|
||||
def __init__(self, modern, ignore=False):
|
||||
self.kind = 'fields' if modern else 'schema'
|
||||
self.ignore = ignore
|
||||
self.record = {'id': 'collection-id', 'name': 'test_collection', self.kind: [
|
||||
{'id': 'stable-field-id', 'name': 'custom_production_field', 'type': 'text'},
|
||||
], 'indexes': ['CREATE INDEX custom_index ON test_collection (custom_production_field)']}
|
||||
def get_collection(self, name): return copy.deepcopy(self.record)
|
||||
def request(self, method, path, admin=False, json=None):
|
||||
if not self.ignore:
|
||||
for key in [self.kind, 'indexes']:
|
||||
if key in json: self.record[key] = copy.deepcopy(json[key])
|
||||
return copy.deepcopy(self.record)
|
||||
|
||||
|
||||
class ScopedSchemaTests(unittest.TestCase):
|
||||
def test_old_and_new_pocketbase_preserve_extensions_and_add_credential_field(self):
|
||||
spec = {'name': 'test_collection', 'fields': [{'name': 'owner_key_hash', 'type': 'text'}]}
|
||||
for modern in [False, True]:
|
||||
with self.subTest(modern=modern):
|
||||
pb = SchemaAdapter(modern)
|
||||
self.assertTrue(ensure_collection(pb, spec))
|
||||
fields = pb.record[pb.kind]
|
||||
self.assertEqual(fields[0]['id'], 'stable-field-id')
|
||||
self.assertEqual({field['name'] for field in fields}, {'custom_production_field', 'owner_key_hash'})
|
||||
self.assertEqual(len(pb.record['indexes']), 1)
|
||||
|
||||
def test_silent_schema_noop_must_not_be_reported_as_success(self):
|
||||
pb = SchemaAdapter(True, ignore=True)
|
||||
self.assertFalse(ensure_collection(pb, {'name': 'test_collection', 'fields': [{'name': 'owner_key_hash', 'type': 'text'}]}))
|
||||
79
apps/api/tests/test_uiux_config.py
Normal file
79
apps/api/tests/test_uiux_config.py
Normal file
@ -0,0 +1,79 @@
|
||||
"""Config edit regression tests: no business DB or network calls."""
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'services'))
|
||||
|
||||
|
||||
def load(relative, name):
|
||||
spec = importlib.util.spec_from_file_location(name, ROOT / 'services/ebook_svc' / relative)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[name] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class ConfigEditingTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.path = Path(self.temporary.name) / 'config.json'
|
||||
self.original = {'version': 5, 'modules': {'social': {'enabled': True}}, 'audience': {'cn': {'homeLead': '中文原稿'}, 'intl': {'homeLead': 'English'}}, 'flags': {'payEnabled': True}}
|
||||
self.path.write_text(json.dumps(self.original), encoding='utf-8')
|
||||
self.audience = load('services/audience_config.py', 'uiux_audience')
|
||||
self.blog = load('services/social_blog_ops.py', 'uiux_blog')
|
||||
for module in [self.audience, self.blog]:
|
||||
handle = patch.object(module, 'resolve_config_file', return_value=self.path)
|
||||
handle.start(); self.addCleanup(handle.stop)
|
||||
|
||||
def test_stale_audience_write_preserves_file(self):
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
self.audience.write_audience_config({'expectedVersion': 4, 'cn': {'homeLead': 'overwrite'}})
|
||||
self.assertEqual(error.exception.status_code, 409)
|
||||
self.assertEqual(json.loads(self.path.read_text()), self.original)
|
||||
|
||||
def test_stale_blog_write_preserves_file(self):
|
||||
with self.assertRaises(HTTPException) as error:
|
||||
self.blog.patch_ops({'expectedVersion': 4, 'adsenseEnabled': False})
|
||||
self.assertEqual(error.exception.status_code, 409)
|
||||
self.assertEqual(json.loads(self.path.read_text()), self.original)
|
||||
|
||||
def test_audience_uses_atomic_writer_and_preserves_other_lane(self):
|
||||
written = []
|
||||
def atomic_writer(data):
|
||||
data['version'] += 1
|
||||
written.append(data)
|
||||
self.path.write_text(json.dumps(data), encoding='utf-8')
|
||||
with patch.dict(sys.modules, {'ebook_svc.services.weapp_switches': SimpleNamespace(_write_raw=atomic_writer)}):
|
||||
result = self.audience.write_audience_config({'expectedVersion': 5, 'cn': {'homeLead': '新文案'}})
|
||||
self.assertEqual(result['version'], 6)
|
||||
self.assertEqual(result['cn']['homeLead'], '新文案')
|
||||
self.assertEqual(result['intl']['homeLead'], 'English')
|
||||
self.assertEqual(written[0]['modules'], self.original['modules'])
|
||||
|
||||
def test_blog_order_is_featured_then_visible_then_newest(self):
|
||||
posts = [{'slug': 'old', 'date': '2026-01-01'}, {'slug': 'new', 'date': '2026-11-05'}, {'slug': 'pinned', 'date': '2025-01-01'}]
|
||||
with patch.object(self.blog, '_fetch_posts', return_value=posts), patch.object(self.blog, '_ops_from_raw', return_value={'featuredSlug': 'pinned', 'hiddenSlugs': [], 'note': '', 'heroLead': ''}):
|
||||
result = self.blog.list_posts()
|
||||
self.assertEqual([item['slug'] for item in result['items']], ['pinned', 'new', 'old'])
|
||||
|
||||
def test_blog_schema_validates_ads_and_keeps_optional_legacy_version(self):
|
||||
with patch.dict(sys.modules, {'ebook_svc.services.social_blog_ops': self.blog}):
|
||||
router = load('routers/social_blog_admin.py', 'uiux_blog_router')
|
||||
self.assertIsNone(router.BlogOpsPatch.model_validate({'moduleEnabled': True}).expectedVersion)
|
||||
self.assertEqual(router.BlogOpsPatch.model_validate({'expectedVersion': 5, 'adsenseClientId': 'ca-pub-123'}).expectedVersion, 5)
|
||||
for body in [{'adsenseClientId': 'invalid'}, {'adsenseSlotBlogMid': 'x'}, {'expectedVersion': -1}, {'note': 'x' * 501}]:
|
||||
with self.assertRaises(ValidationError): router.BlogOpsPatch.model_validate(body)
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
@ -30,26 +30,31 @@ export async function api<T = unknown>(path: string, init: RequestInit = {}): Pr
|
||||
if (init.signal?.aborted) timeout.abort()
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}${path}`, { ...init, headers, signal: timeout.signal, cache: 'no-store' })
|
||||
if (res.status === 401) {
|
||||
if (res.status === 401 && getToken() === token) {
|
||||
clearToken()
|
||||
if (!path.includes('/login')) {
|
||||
sessionStorage.setItem('nomadro_admin_return', window.location.pathname + window.location.search)
|
||||
window.location.replace('/login')
|
||||
}
|
||||
}
|
||||
const data = await res.json().catch(() => ({}))
|
||||
if (res.status === 204) return {} as T
|
||||
const isJson = /(?:application\/json|\+json)(?:;|$)/i.test(res.headers.get('content-type') || '')
|
||||
let data: unknown
|
||||
try { data = await res.json() }
|
||||
catch { throw new Error(`服务返回异常(${res.status}),请稍后重试;保存操作请先确认结果`) }
|
||||
if (!res.ok) {
|
||||
const err = data as { detail?: unknown; message?: string }
|
||||
const detail = typeof err.detail === 'string' ? err.detail : Array.isArray(err.detail)
|
||||
? err.detail.map((item: { msg?: string }) => item.msg || '参数错误').join(';') : ''
|
||||
throw new Error(detail || err.message || `请求失败(${res.status})`)
|
||||
}
|
||||
if (res.status !== 204 && !res.headers.get('content-type')?.includes('application/json')) {
|
||||
if (!isJson || data == null) {
|
||||
throw new Error('服务返回异常,请稍后重试')
|
||||
}
|
||||
return data as T
|
||||
} catch (error) {
|
||||
if (timeout.signal.aborted && !init.signal?.aborted) throw new Error('请求超时,请刷新重试;保存操作请先确认结果')
|
||||
if (error instanceof TypeError) throw new Error('网络连接失败,请检查网络后重试;保存操作请先确认结果')
|
||||
throw error
|
||||
} finally {
|
||||
window.clearTimeout(timer)
|
||||
|
||||
70
apps/com/admin/src/components/PresenceLivePulse.tsx
Normal file
70
apps/com/admin/src/components/PresenceLivePulse.tsx
Normal file
@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Admin live presence: pulsing badge + toast when a guest comes online.
|
||||
*/
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useSharedSocialPresence } from '../lib/SocialPresenceContext'
|
||||
|
||||
export default function PresenceLivePulse() {
|
||||
const snap = useSharedSocialPresence()
|
||||
const [toast, setToast] = useState('')
|
||||
const [flash, setFlash] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!snap.bumped) return
|
||||
const nick = (snap.bumped.nick || '游民').trim() || '游民'
|
||||
const city = (snap.bumped.city || '').trim()
|
||||
setToast(city ? `${nick} 上线了 · ${city}` : `${nick} 上线了`)
|
||||
setFlash(true)
|
||||
const t = window.setTimeout(() => setToast(''), 4200)
|
||||
const f = window.setTimeout(() => setFlash(false), 1600)
|
||||
return () => {
|
||||
window.clearTimeout(t)
|
||||
window.clearTimeout(f)
|
||||
}
|
||||
}, [snap.bumped])
|
||||
|
||||
const count = Math.max(snap.online, snap.peers.length)
|
||||
const live = count > 0 && !snap.fromOffline
|
||||
|
||||
return (
|
||||
<>
|
||||
<span
|
||||
className={`com-presence${live ? ' is-live' : ''}${flash ? ' is-flash' : ''}${snap.fromOffline ? ' is-soft' : ''}`}
|
||||
role="status"
|
||||
title={
|
||||
live
|
||||
? snap.peers
|
||||
.slice(0, 8)
|
||||
.map((p) => p.nick)
|
||||
.join(' · ')
|
||||
: snap.fromOffline
|
||||
? '在线心跳暂时连不上'
|
||||
: '暂无访客心跳'
|
||||
}
|
||||
>
|
||||
<i className="com-presence-dot" aria-hidden />
|
||||
<em className="com-presence-count">{count}</em>
|
||||
<span className="com-presence-label">
|
||||
{live ? '人在线' : snap.fromOffline ? '心跳离线' : '等待访客'}
|
||||
</span>
|
||||
{live && snap.peers.length ? (
|
||||
<span className="com-presence-avs" aria-hidden>
|
||||
{snap.peers.slice(0, 4).map((p) => (
|
||||
<b key={p.guestId} title={p.nick}>
|
||||
{(p.nick || '?').slice(0, 1)}
|
||||
</b>
|
||||
))}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
|
||||
{toast ? (
|
||||
<div className="com-presence-toast" role="status" aria-live="polite">
|
||||
<i className="com-presence-dot is-ok" aria-hidden />
|
||||
<strong>{toast}</strong>
|
||||
<span>实时</span>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
)
|
||||
}
|
||||
36
apps/com/admin/src/components/UnsavedChanges.tsx
Normal file
36
apps/com/admin/src/components/UnsavedChanges.tsx
Normal file
@ -0,0 +1,36 @@
|
||||
import { useCallback, useEffect, useId, useRef } from 'react'
|
||||
import { useBeforeUnload, useBlocker } from 'react-router-dom'
|
||||
|
||||
export default function UnsavedChanges({ dirty }: { dirty: boolean }) {
|
||||
const blocker = useBlocker(({ currentLocation, nextLocation }) => dirty &&
|
||||
(currentLocation.pathname !== nextLocation.pathname || currentLocation.search !== nextLocation.search))
|
||||
const dialog = useRef<HTMLDialogElement>(null)
|
||||
const titleId = useId()
|
||||
const descriptionId = useId()
|
||||
useBeforeUnload(useCallback((event: BeforeUnloadEvent) => {
|
||||
if (!dirty) return
|
||||
event.preventDefault()
|
||||
event.returnValue = ''
|
||||
}, [dirty]))
|
||||
|
||||
useEffect(() => {
|
||||
const element = dialog.current
|
||||
if (blocker.state !== 'blocked') { element?.close(); return }
|
||||
const opener = document.activeElement as HTMLElement | null
|
||||
element?.showModal()
|
||||
return () => { element?.close(); opener?.focus() }
|
||||
}, [blocker.state])
|
||||
|
||||
return <>
|
||||
{dirty && <div className="com-draft-status" role="status">有未保存修改</div>}
|
||||
<dialog ref={dialog} className="com-unsaved-dialog" aria-labelledby={titleId} aria-describedby={descriptionId}
|
||||
onCancel={event => { event.preventDefault(); if (blocker.state === 'blocked') blocker.reset() }}>
|
||||
<h2 id={titleId}>保留当前修改?</h2>
|
||||
<p id={descriptionId}>当前修改尚未保存。你可以继续编辑,或放弃修改后离开。</p>
|
||||
<div className="com-actions">
|
||||
<button type="button" className="com-btn" autoFocus onClick={() => { if (blocker.state === 'blocked') blocker.reset() }}>继续编辑</button>
|
||||
<button type="button" className="com-btn com-btn-ghost" onClick={() => { if (blocker.state === 'blocked') blocker.proceed() }}>放弃修改并离开</button>
|
||||
</div>
|
||||
</dialog>
|
||||
</>
|
||||
}
|
||||
@ -1,8 +1,9 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { NavLink, Outlet, useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||
import { clearToken } from '../api/client'
|
||||
import { writeLane } from '../lib/lane'
|
||||
import type { LaneKey } from '../pages/LaneHub'
|
||||
import PresenceLivePulse from './PresenceLivePulse'
|
||||
import { SocialPresenceProvider } from '../lib/SocialPresenceContext'
|
||||
|
||||
type NavLinkItem = {
|
||||
to: string
|
||||
@ -197,13 +198,11 @@ export default function WebLayout() {
|
||||
}, [open])
|
||||
|
||||
function logout() {
|
||||
clearToken()
|
||||
nav('/login')
|
||||
}
|
||||
|
||||
function switchLane(next: LaneKey) {
|
||||
if (next === lane) return
|
||||
writeLane(next)
|
||||
const rest =
|
||||
pathname.replace(/^\/(cn|intl)/, '').replace(/(\/social\/[^/]+)\/[^/]+$/, '$1') ||
|
||||
'/social/overview'
|
||||
@ -211,6 +210,7 @@ export default function WebLayout() {
|
||||
}
|
||||
|
||||
return (
|
||||
<SocialPresenceProvider>
|
||||
<div className={`com-shell com-shell--${lane}${open ? ' com-shell--nav-open' : ''}`}>
|
||||
<a className="com-skip" href="#main-content">
|
||||
跳至主要内容
|
||||
@ -353,10 +353,13 @@ export default function WebLayout() {
|
||||
{meta.title}受众 <span>/</span> {pageTitle}
|
||||
</p>
|
||||
</div>
|
||||
<span className={`com-connection${online ? '' : ' is-offline'}`} role="status">
|
||||
<i />
|
||||
{online ? '网络已连接' : '网络已断开'}
|
||||
</span>
|
||||
<div className="com-workspace-live">
|
||||
<PresenceLivePulse />
|
||||
<span className={`com-connection${online ? '' : ' is-offline'}`} role="status">
|
||||
<i />
|
||||
{online ? '网络已连接' : '网络已断开'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{!online ? (
|
||||
<div className="com-toast com-toast-err" role="alert">
|
||||
@ -366,5 +369,6 @@ export default function WebLayout() {
|
||||
<Outlet key={lane} />
|
||||
</main>
|
||||
</div>
|
||||
</SocialPresenceProvider>
|
||||
)
|
||||
}
|
||||
|
||||
31
apps/com/admin/src/lib/SocialPresenceContext.tsx
Normal file
31
apps/com/admin/src/lib/SocialPresenceContext.tsx
Normal file
@ -0,0 +1,31 @@
|
||||
/**
|
||||
* One presence poll for the whole admin shell — top pulse + join/roster rows share state.
|
||||
*/
|
||||
import { createContext, useContext, type ReactNode } from 'react'
|
||||
import {
|
||||
useSocialPresenceLive,
|
||||
type PresenceSnap,
|
||||
type PresencePeer,
|
||||
} from './useSocialPresenceLive'
|
||||
|
||||
export type { PresencePeer, PresenceSnap }
|
||||
|
||||
const EMPTY: PresenceSnap = {
|
||||
online: 0,
|
||||
peers: [],
|
||||
cityOnline: 0,
|
||||
ok: false,
|
||||
fromOffline: true,
|
||||
bumped: null,
|
||||
}
|
||||
|
||||
const Ctx = createContext<PresenceSnap>(EMPTY)
|
||||
|
||||
export function SocialPresenceProvider({ children }: { children: ReactNode }) {
|
||||
const snap = useSocialPresenceLive()
|
||||
return <Ctx.Provider value={snap}>{children}</Ctx.Provider>
|
||||
}
|
||||
|
||||
export function useSharedSocialPresence(): PresenceSnap {
|
||||
return useContext(Ctx)
|
||||
}
|
||||
26
apps/com/admin/src/lib/useDraft.ts
Normal file
26
apps/com/admin/src/lib/useDraft.ts
Normal file
@ -0,0 +1,26 @@
|
||||
import { useState } from 'react'
|
||||
|
||||
/** Rebase untouched fields after a partial save without losing other edits. */
|
||||
export function useDraft<T extends Record<string, string | number | boolean>>(initial: T) {
|
||||
const [draft, setDraft] = useState(initial)
|
||||
const [baseline, setBaseline] = useState(initial)
|
||||
const dirty = (Object.keys(draft) as Array<keyof T>).some(key => draft[key] !== baseline[key])
|
||||
|
||||
function accept(next: T, savedFields: Array<keyof T> = []) {
|
||||
setDraft(current => {
|
||||
const rebased = { ...current }
|
||||
for (const key of Object.keys(next) as Array<keyof T>) {
|
||||
if (savedFields.includes(key) || current[key] === baseline[key]) rebased[key] = next[key]
|
||||
}
|
||||
return rebased
|
||||
})
|
||||
setBaseline(next)
|
||||
}
|
||||
|
||||
function reset(next: T) {
|
||||
setDraft(next)
|
||||
setBaseline(next)
|
||||
}
|
||||
|
||||
return { draft, setDraft, dirty, accept, reset }
|
||||
}
|
||||
97
apps/com/admin/src/lib/useSocialPresenceLive.ts
Normal file
97
apps/com/admin/src/lib/useSocialPresenceLive.ts
Normal file
@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Poll social who's-online for admin chrome.
|
||||
* Emits toast when someone newly appears.
|
||||
*/
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { api } from '../api/client'
|
||||
|
||||
export type PresencePeer = {
|
||||
guestId: string
|
||||
nick: string
|
||||
city?: string
|
||||
avatar?: string
|
||||
}
|
||||
|
||||
export type PresenceSnap = {
|
||||
online: number
|
||||
peers: PresencePeer[]
|
||||
cityOnline: number
|
||||
ok: boolean
|
||||
fromOffline: boolean
|
||||
bumped?: PresencePeer | null
|
||||
}
|
||||
|
||||
const EMPTY: PresenceSnap = {
|
||||
online: 0,
|
||||
peers: [],
|
||||
cityOnline: 0,
|
||||
ok: false,
|
||||
fromOffline: true,
|
||||
bumped: null,
|
||||
}
|
||||
|
||||
const POLL_MS = 4000
|
||||
|
||||
export function useSocialPresenceLive(): PresenceSnap {
|
||||
const [snap, setSnap] = useState<PresenceSnap>(EMPTY)
|
||||
const seen = useRef<Set<string>>(new Set())
|
||||
const booted = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
let timer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
const pull = async () => {
|
||||
if (cancelled || document.hidden) return
|
||||
try {
|
||||
const data = await api<{
|
||||
ok?: boolean
|
||||
online?: number
|
||||
peers?: PresencePeer[]
|
||||
cityOnline?: number
|
||||
}>('/api/admin/social/ugc/presence?limit=48')
|
||||
if (cancelled) return
|
||||
const peers = Array.isArray(data.peers) ? data.peers : []
|
||||
const online = Number(data.online) || peers.length
|
||||
let bumped: PresencePeer | null = null
|
||||
if (booted.current) {
|
||||
for (const p of peers) {
|
||||
const id = String(p.guestId || '')
|
||||
if (id && !seen.current.has(id)) {
|
||||
bumped = p
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
const nextIds = new Set(peers.map((p) => String(p.guestId || '')).filter(Boolean))
|
||||
seen.current = nextIds
|
||||
booted.current = true
|
||||
setSnap({
|
||||
online,
|
||||
peers,
|
||||
cityOnline: Number(data.cityOnline) || 0,
|
||||
ok: data.ok !== false,
|
||||
fromOffline: false,
|
||||
bumped,
|
||||
})
|
||||
} catch {
|
||||
if (cancelled) return
|
||||
setSnap((prev) => ({ ...prev, fromOffline: true, bumped: null }))
|
||||
}
|
||||
}
|
||||
|
||||
void pull()
|
||||
timer = setInterval(() => void pull(), POLL_MS)
|
||||
const onVis = () => {
|
||||
if (!document.hidden) void pull()
|
||||
}
|
||||
document.addEventListener('visibilitychange', onVis)
|
||||
return () => {
|
||||
cancelled = true
|
||||
if (timer) clearInterval(timer)
|
||||
document.removeEventListener('visibilitychange', onVis)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return snap
|
||||
}
|
||||
@ -1,15 +1,15 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
|
||||
import App from './App'
|
||||
import ErrorBoundary from './components/ErrorBoundary'
|
||||
import './styles.css'
|
||||
import './upgrade.css'
|
||||
|
||||
const router = createBrowserRouter([{ path: '*', element: <ErrorBoundary><App /></ErrorBoundary> }])
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<BrowserRouter>
|
||||
<ErrorBoundary><App /></ErrorBoundary>
|
||||
</BrowserRouter>
|
||||
<RouterProvider router={router} />
|
||||
</React.StrictMode>,
|
||||
)
|
||||
|
||||
@ -4,6 +4,9 @@
|
||||
*/
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { api } from '../api/client'
|
||||
import { useConfigLive } from '../lib/useConfigLive'
|
||||
import { useDraft } from '../lib/useDraft'
|
||||
import UnsavedChanges from '../components/UnsavedChanges'
|
||||
|
||||
type Overview = {
|
||||
ok?: boolean
|
||||
@ -52,7 +55,16 @@ const TABS: Array<{ key: TabKey; label: string }> = [
|
||||
{ key: 'module', label: '模块 / 文案' },
|
||||
]
|
||||
|
||||
function draftFrom(overview: Overview) {
|
||||
return {
|
||||
adsenseClientId: overview.adsenseClientId || '', adsensePublisherId: overview.adsensePublisherId || '',
|
||||
adsenseSlotBlogMid: overview.adsenseSlotBlogMid || '', adsenseSlotBlogEnd: overview.adsenseSlotBlogEnd || '',
|
||||
heroLead: overview.ops?.heroLead || '', note: overview.ops?.note || '',
|
||||
}
|
||||
}
|
||||
|
||||
export default function Blog() {
|
||||
const live = useConfigLive()
|
||||
const [tab, setTab] = useState<TabKey>('posts')
|
||||
const [ov, setOv] = useState<Overview | null>(null)
|
||||
const [posts, setPosts] = useState<Post[]>([])
|
||||
@ -61,7 +73,7 @@ export default function Blog() {
|
||||
const [busy, setBusy] = useState('')
|
||||
const [msg, setMsg] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
const [draft, setDraft] = useState({
|
||||
const editor = useDraft({
|
||||
adsenseClientId: '',
|
||||
adsensePublisherId: '',
|
||||
adsenseSlotBlogMid: '',
|
||||
@ -69,6 +81,8 @@ export default function Blog() {
|
||||
heroLead: '',
|
||||
note: '',
|
||||
})
|
||||
const { draft, setDraft } = editor
|
||||
const stale = ov?.version != null && live.meta != null && live.meta.version > ov.version
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
@ -80,14 +94,7 @@ export default function Blog() {
|
||||
])
|
||||
setOv(overview)
|
||||
setPosts(Array.isArray(list.items) ? list.items : [])
|
||||
setDraft({
|
||||
adsenseClientId: overview.adsenseClientId || '',
|
||||
adsensePublisherId: overview.adsensePublisherId || '',
|
||||
adsenseSlotBlogMid: overview.adsenseSlotBlogMid || '',
|
||||
adsenseSlotBlogEnd: overview.adsenseSlotBlogEnd || '',
|
||||
heroLead: overview.ops?.heroLead || '',
|
||||
note: overview.ops?.note || '',
|
||||
})
|
||||
editor.reset(draftFrom(overview))
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : '加载失败')
|
||||
} finally {
|
||||
@ -99,19 +106,36 @@ export default function Blog() {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
useEffect(() => {
|
||||
if (stale && !editor.dirty && !busy) void load()
|
||||
}, [stale, editor.dirty, busy, load])
|
||||
|
||||
async function patch(body: Record<string, unknown>, okHint: string) {
|
||||
if (!ov || loading || busy) return
|
||||
if (stale) { setErr('配置已更新,请加载最新配置后重试;当前草稿已保留'); return }
|
||||
for (const [key, pattern, label] of [
|
||||
['adsenseClientId', /^(ca-pub-[0-9]+)?$/, 'clientId 应为 ca-pub- 加数字'],
|
||||
['adsensePublisherId', /^(pub-[0-9]+)?$/, 'publisher 应为 pub- 加数字'],
|
||||
['adsenseSlotBlogMid', /^[0-9]*$/, '文中 slot 只能填写数字'],
|
||||
['adsenseSlotBlogEnd', /^[0-9]*$/, '文末 slot 只能填写数字'],
|
||||
] as const) {
|
||||
if (key in body && !pattern.test(String(body[key]))) { setErr(label); return }
|
||||
}
|
||||
setBusy(okHint)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
const next = await api<Overview>('/api/admin/social/blog/ops', {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(body),
|
||||
body: JSON.stringify({ ...body, expectedVersion: ov.version }),
|
||||
})
|
||||
setOv(next)
|
||||
editor.accept(draftFrom(next), Object.keys(body) as Array<keyof typeof draft>)
|
||||
setMsg(okHint)
|
||||
const list = await api<{ items?: Post[] }>('/api/admin/social/blog/posts')
|
||||
setPosts(Array.isArray(list.items) ? list.items : [])
|
||||
try {
|
||||
const list = await api<{ items?: Post[] }>('/api/admin/social/blog/posts')
|
||||
setPosts(Array.isArray(list.items) ? list.items : [])
|
||||
} catch { setErr('修改已保存,文章列表刷新失败,请点刷新重试') }
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : '保存失败')
|
||||
} finally {
|
||||
@ -156,14 +180,16 @@ export default function Blog() {
|
||||
打开博客 ↗
|
||||
</a>
|
||||
) : null}
|
||||
<button type="button" className="com-btn com-btn-ghost" onClick={() => void load()} disabled={!!busy}>
|
||||
<button type="button" className="com-btn com-btn-ghost" onClick={() => { if (!editor.dirty || window.confirm('刷新将放弃未保存修改,继续?')) void load() }} disabled={!!busy || loading}>
|
||||
{loading ? '刷新中…' : '刷新'}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
<UnsavedChanges dirty={editor.dirty} />
|
||||
{msg ? <div className="com-toast com-toast-ok" role="status">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err" role="alert">{err}</div> : null}
|
||||
{stale && <div className="com-toast" role="status">线上配置已更新,当前草稿已保留。请使用刷新按钮加载最新配置后再保存。</div>}
|
||||
|
||||
<div className="com-stat-grid com-stat-grid-4">
|
||||
<article className="com-stat">
|
||||
@ -228,6 +254,8 @@ export default function Blog() {
|
||||
<div className="com-toolbar">
|
||||
<input
|
||||
className="com-input"
|
||||
type="search"
|
||||
aria-label="搜索博客文章"
|
||||
placeholder="搜标题 / slug / 标签"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
@ -308,6 +336,7 @@ export default function Blog() {
|
||||
<label className="com-switch" title="AdSense">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label="AdSense 展示开关"
|
||||
checked={Boolean(ov?.adsenseEnabled)}
|
||||
disabled={!!busy}
|
||||
onChange={(e) =>
|
||||
@ -380,6 +409,7 @@ export default function Blog() {
|
||||
<label className="com-switch" title="socialBlog">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label="博客模块开关"
|
||||
checked={ov?.moduleEnabled !== false}
|
||||
disabled={!!busy}
|
||||
onChange={(e) =>
|
||||
@ -399,6 +429,7 @@ export default function Blog() {
|
||||
<span>运营备注(仅后台)</span>
|
||||
<input
|
||||
value={draft.note}
|
||||
maxLength={500}
|
||||
disabled={!!busy}
|
||||
onChange={(e) => setDraft((d) => ({ ...d, note: e.target.value }))}
|
||||
/>
|
||||
@ -407,6 +438,7 @@ export default function Blog() {
|
||||
<span>Hero 导语覆盖(可选)</span>
|
||||
<input
|
||||
value={draft.heroLead}
|
||||
maxLength={400}
|
||||
disabled={!!busy}
|
||||
onChange={(e) => setDraft((d) => ({ ...d, heroLead: e.target.value }))}
|
||||
/>
|
||||
|
||||
@ -5,6 +5,9 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { api } from '../api/client'
|
||||
import { useDraft } from '../lib/useDraft'
|
||||
import { useConfigLive } from '../lib/useConfigLive'
|
||||
import UnsavedChanges from '../components/UnsavedChanges'
|
||||
|
||||
export type LaneKey = 'cn' | 'intl'
|
||||
|
||||
@ -90,38 +93,45 @@ export default function LaneHub({ lane }: { lane: LaneKey }) {
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [msg, setMsg] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
const [vipCta, setVipCta] = useState('')
|
||||
const [homeLead, setHomeLead] = useState('')
|
||||
const live = useConfigLive()
|
||||
const editor = useDraft({ vipCta: '', homeLead: '' })
|
||||
const { vipCta, homeLead } = editor.draft
|
||||
const setVipCta = (value: string) => editor.setDraft(d => ({ ...d, vipCta: value }))
|
||||
const setHomeLead = (value: string) => editor.setDraft(d => ({ ...d, homeLead: value }))
|
||||
const stale = cfg?.version != null && live.meta != null && live.meta.version > cfg.version
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setErr('')
|
||||
const data = await api<AudienceCfg>('/api/admin/audience')
|
||||
setCfg(data)
|
||||
const L = data[lane]
|
||||
setVipCta(L.vipCta)
|
||||
setHomeLead(L.homeLead)
|
||||
editor.reset({ vipCta: L.vipCta, homeLead: L.homeLead })
|
||||
}, [lane])
|
||||
|
||||
useEffect(() => {
|
||||
load().catch((e: Error) => setErr(e.message || '加载失败'))
|
||||
}, [load])
|
||||
|
||||
useEffect(() => {
|
||||
if (stale && !editor.dirty && !busy) void load().catch(e => setErr(String(e)))
|
||||
}, [stale, editor.dirty, busy, load])
|
||||
|
||||
async function patchLane(partial: Partial<Lane>, okHint: string) {
|
||||
if (!cfg || busy) return
|
||||
if (stale) { setErr('配置已更新,请加载最新配置后重试;当前草稿已保留'); return }
|
||||
setBusy(true)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
try {
|
||||
const data = await api<AudienceCfg>('/api/admin/audience', {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({ [lane]: partial }),
|
||||
body: JSON.stringify({ [lane]: partial, expectedVersion: cfg.version }),
|
||||
})
|
||||
setCfg(data)
|
||||
setVipCta(data[lane].vipCta)
|
||||
setHomeLead(data[lane].homeLead)
|
||||
editor.accept({ vipCta: data[lane].vipCta, homeLead: data[lane].homeLead }, Object.keys(partial) as Array<'vipCta' | 'homeLead'>)
|
||||
setMsg(okHint)
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : '保存失败')
|
||||
await load().catch(() => undefined)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
@ -178,8 +188,10 @@ export default function LaneHub({ lane }: { lane: LaneKey }) {
|
||||
</Link>
|
||||
</header>
|
||||
|
||||
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
<UnsavedChanges dirty={editor.dirty} />
|
||||
{msg ? <div className="com-toast com-toast-ok" role="status">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err" role="alert">{err}</div> : null}
|
||||
{(stale || (!cfg && err)) && <div className="com-toast" role="status">{stale ? '线上配置已更新,当前草稿已保留。' : '配置加载失败。'}<button type="button" className="com-btn" disabled={busy} onClick={() => { if (!editor.dirty || window.confirm('加载最新配置将放弃未保存修改,继续?')) void load().catch(e => setErr(String(e))) }}>加载最新配置</button></div>}
|
||||
|
||||
{(stats || socialCounts) && (
|
||||
<div className="com-stat-grid" style={{ marginBottom: 18 }}>
|
||||
@ -280,6 +292,7 @@ export default function LaneHub({ lane }: { lane: LaneKey }) {
|
||||
<label className="com-field" style={{ gridColumn: '1 / -1' }}>
|
||||
<span>首页导语</span>
|
||||
<textarea
|
||||
aria-label="首页导语"
|
||||
className="com-textarea"
|
||||
rows={3}
|
||||
value={homeLead}
|
||||
@ -292,11 +305,12 @@ export default function LaneHub({ lane }: { lane: LaneKey }) {
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn"
|
||||
disabled={busy}
|
||||
disabled={busy || stale || !editor.dirty}
|
||||
onClick={() => void patchLane({ vipCta, homeLead }, '文案已保存')}
|
||||
>
|
||||
保存文案
|
||||
</button>
|
||||
<button type="button" className="com-btn com-btn-ghost" disabled={busy || !editor.dirty} onClick={() => editor.reset({ vipCta: L.vipCta, homeLead: L.homeLead })}>重置文案草稿</button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { FormEvent, useState } from 'react'
|
||||
import { FormEvent, useEffect, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { api, setToken } from '../api/client'
|
||||
import { api, clearToken, setToken } from '../api/client'
|
||||
import { readLane } from '../lib/lane'
|
||||
|
||||
export default function Login() {
|
||||
@ -9,6 +9,7 @@ export default function Login() {
|
||||
const [password, setPassword] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
useEffect(() => { clearToken() }, [])
|
||||
|
||||
async function onSubmit(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
|
||||
@ -6,6 +6,8 @@ import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Link, useParams } from 'react-router-dom'
|
||||
import { api } from '../api/client'
|
||||
import { useConfigLive } from '../lib/useConfigLive'
|
||||
import { useDraft } from '../lib/useDraft'
|
||||
import UnsavedChanges from '../components/UnsavedChanges'
|
||||
|
||||
type PricingCfg = {
|
||||
flags: {
|
||||
@ -48,6 +50,21 @@ function formatYuan(fen: number) {
|
||||
return fen % 100 === 0 ? `¥${fen / 100}` : `¥${(fen / 100).toFixed(2)}`
|
||||
}
|
||||
|
||||
function priceFrom(data: PricingCfg) {
|
||||
return { priceYuan: fenToYuanInput(Math.max(0, Number(data.copy?.vipPriceFen) || 0)), vipCta: data.copy?.vipCta || '' }
|
||||
}
|
||||
|
||||
function trialFrom(data: PricingCfg) {
|
||||
const tr = data.copy?.socialTrial || {}
|
||||
return {
|
||||
enabled: data.flags?.socialTrialEnabled !== false && tr.enabled !== false,
|
||||
chatMessages: Math.max(0, Number(tr.chatMessages ?? 1) || 0),
|
||||
dateViews: Math.max(0, Number(tr.dateViews ?? 5) || 0),
|
||||
coffeeBookings: Math.max(0, Number(tr.coffeeBookings ?? 0) || 0),
|
||||
mapOpens: Math.max(0, Number(tr.mapOpens ?? 3) || 0),
|
||||
}
|
||||
}
|
||||
|
||||
function Switch({
|
||||
checked,
|
||||
onChange,
|
||||
@ -83,31 +100,20 @@ export default function Pricing() {
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [msg, setMsg] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
const [priceYuan, setPriceYuan] = useState('88')
|
||||
const [vipCta, setVipCta] = useState('')
|
||||
const [trialDraft, setTrialDraft] = useState({
|
||||
enabled: true,
|
||||
chatMessages: 1,
|
||||
dateViews: 5,
|
||||
coffeeBookings: 0,
|
||||
mapOpens: 3,
|
||||
})
|
||||
const price = useDraft({ priceYuan: '88', vipCta: '' })
|
||||
const trial = useDraft(trialFrom({ flags: {}, copy: {} }))
|
||||
const { priceYuan, vipCta } = price.draft
|
||||
const trialDraft = trial.draft
|
||||
const setPriceYuan = (value: string) => price.setDraft(d => ({ ...d, priceYuan: value }))
|
||||
const setVipCta = (value: string) => price.setDraft(d => ({ ...d, vipCta: value }))
|
||||
const setTrialDraft = trial.setDraft
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setErr('')
|
||||
const data = await api<PricingCfg>('/api/admin/weapp/switches')
|
||||
setCfg(data)
|
||||
const fen = Math.max(0, Number(data.copy?.vipPriceFen) || 0)
|
||||
setPriceYuan(fenToYuanInput(fen))
|
||||
setVipCta(data.copy?.vipCta || '')
|
||||
const tr = data.copy?.socialTrial || {}
|
||||
setTrialDraft({
|
||||
enabled: data.flags?.socialTrialEnabled !== false && tr.enabled !== false,
|
||||
chatMessages: Math.max(0, Number(tr.chatMessages ?? 1) || 0),
|
||||
dateViews: Math.max(0, Number(tr.dateViews ?? 5) || 0),
|
||||
coffeeBookings: Math.max(0, Number(tr.coffeeBookings ?? 0) || 0),
|
||||
mapOpens: Math.max(0, Number(tr.mapOpens ?? 3) || 0),
|
||||
})
|
||||
price.reset(priceFrom(data))
|
||||
trial.reset(trialFrom(data))
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
@ -124,17 +130,9 @@ export default function Pricing() {
|
||||
body: JSON.stringify({ ...body, expectedVersion: cfg?.version }),
|
||||
})
|
||||
setCfg(data)
|
||||
const fen = Math.max(0, Number(data.copy?.vipPriceFen) || 0)
|
||||
setPriceYuan(fenToYuanInput(fen))
|
||||
setVipCta(data.copy?.vipCta || '')
|
||||
const tr = data.copy?.socialTrial || {}
|
||||
setTrialDraft({
|
||||
enabled: data.flags?.socialTrialEnabled !== false && tr.enabled !== false,
|
||||
chatMessages: Math.max(0, Number(tr.chatMessages ?? 1) || 0),
|
||||
dateViews: Math.max(0, Number(tr.dateViews ?? 5) || 0),
|
||||
coffeeBookings: Math.max(0, Number(tr.coffeeBookings ?? 0) || 0),
|
||||
mapOpens: Math.max(0, Number(tr.mapOpens ?? 3) || 0),
|
||||
})
|
||||
const copy = body.copy as Record<string, unknown> | undefined
|
||||
price.accept(priceFrom(data), copy && 'vipPriceFen' in copy ? ['priceYuan', 'vipCta'] : [])
|
||||
trial.accept(trialFrom(data), copy && 'socialTrial' in copy ? ['enabled', 'chatMessages', 'dateViews', 'coffeeBookings', 'mapOpens'] : [])
|
||||
setMsg(okHint)
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : '保存失败')
|
||||
@ -147,17 +145,16 @@ export default function Pricing() {
|
||||
const isFree = liveFen <= 0
|
||||
const draftFen = useMemo(() => {
|
||||
const yuan = Number(priceYuan)
|
||||
if (!Number.isFinite(yuan) || yuan < 0) return null
|
||||
if (!/^\d+(\.\d{1,2})?$/.test(priceYuan.trim()) || !Number.isFinite(yuan) || yuan < 0 || yuan > 1000000) return null
|
||||
return Math.round(yuan * 100)
|
||||
}, [priceYuan])
|
||||
const dirty =
|
||||
draftFen != null &&
|
||||
(draftFen !== liveFen || (vipCta || '').trim() !== (cfg?.copy?.vipCta || '').trim())
|
||||
const dirty = price.dirty || trial.dirty
|
||||
const stale = cfg?.version != null && live.meta != null && live.meta.version > cfg.version
|
||||
|
||||
// 其他页面 / 进程改了配置 → 本页跟价,避免脏 expectedVersion 覆盖
|
||||
useEffect(() => {
|
||||
if (!live.meta?.version || cfg?.version == null) return
|
||||
if (live.meta.version === cfg.version) return
|
||||
if (live.meta.version <= cfg.version) return
|
||||
if (dirty || busy) return
|
||||
void load().catch((e: Error) => setErr(e.message || '加载失败'))
|
||||
}, [live.meta?.version, cfg?.version, dirty, busy, load])
|
||||
@ -186,7 +183,7 @@ export default function Pricing() {
|
||||
<h1>动态价格</h1>
|
||||
<p>加载远程配置…</p>
|
||||
</header>
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err" role="alert">{err}<button type="button" className="com-btn" onClick={() => void load().catch(e => setErr(String(e)))}>重试加载</button></div> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -212,8 +209,9 @@ export default function Pricing() {
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
<UnsavedChanges dirty={dirty} />
|
||||
{msg ? <div className="com-toast com-toast-ok" role="status">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err" role="alert">{err}</div> : null}
|
||||
|
||||
<div className="com-config-live" role="status">
|
||||
<span className={`com-status-dot${live.connected ? '' : ' is-polling'}`} />
|
||||
@ -222,7 +220,7 @@ export default function Pricing() {
|
||||
服务端 v{live.meta?.version ?? '—'} · 当前编辑 v{cfg.version ?? '—'}
|
||||
</span>
|
||||
</div>
|
||||
{live.meta && cfg.version != null && live.meta.version !== cfg.version ? (
|
||||
{stale ? (
|
||||
<div className="com-toast">
|
||||
配置已在其他页面更新。请刷新后再保存,避免覆盖。
|
||||
<button
|
||||
@ -262,7 +260,7 @@ export default function Pricing() {
|
||||
</div>
|
||||
<Switch
|
||||
checked={cfg.flags?.payEnabled !== false}
|
||||
disabled={busy}
|
||||
disabled={busy || stale}
|
||||
label="支付总开关"
|
||||
onChange={(v) => void patch({ flags: { payEnabled: v } }, v ? '支付已开启' : '支付已关闭')}
|
||||
/>
|
||||
@ -302,7 +300,10 @@ export default function Pricing() {
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
max={1000000}
|
||||
step="0.01"
|
||||
aria-invalid={draftFen == null}
|
||||
aria-describedby="price-validation"
|
||||
value={priceYuan}
|
||||
disabled={busy}
|
||||
onChange={(e) => setPriceYuan(e.target.value)}
|
||||
@ -323,18 +324,17 @@ export default function Pricing() {
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{draftFen == null && <p id="price-validation" className="com-toast com-toast-err" role="alert">请填写 0–1,000,000 元,最多两位小数;免费填 0。</p>}
|
||||
|
||||
<div className="com-actions">
|
||||
<button type="button" className="com-btn" disabled={busy || !dirty} onClick={savePrice}>
|
||||
{busy ? '保存中…' : dirty ? '保存动态价格' : '已是当前价'}
|
||||
<button type="button" className="com-btn" disabled={busy || stale || !price.dirty || draftFen == null} onClick={savePrice}>
|
||||
{busy ? '保存中…' : price.dirty ? '保存动态价格' : '已是当前价'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn-ghost"
|
||||
disabled={busy || priceYuan === fenToYuanInput(liveFen)}
|
||||
onClick={() => {
|
||||
setPriceYuan(fenToYuanInput(liveFen))
|
||||
setVipCta(cfg.copy?.vipCta || '')
|
||||
}}
|
||||
disabled={busy || !price.dirty}
|
||||
onClick={() => price.reset(priceFrom(cfg))}
|
||||
>
|
||||
重置草稿
|
||||
</button>
|
||||
@ -393,7 +393,7 @@ export default function Pricing() {
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn"
|
||||
disabled={busy}
|
||||
disabled={busy || stale || !trial.dirty}
|
||||
onClick={() =>
|
||||
void patch(
|
||||
{
|
||||
@ -414,8 +414,9 @@ export default function Pricing() {
|
||||
)
|
||||
}
|
||||
>
|
||||
保存体验次数
|
||||
{busy ? '保存中…' : trial.dirty ? '保存体验次数' : '体验次数已保存'}
|
||||
</button>
|
||||
<button type="button" className="com-btn com-btn-ghost" disabled={busy || !trial.dirty} onClick={() => trial.reset(trialFrom(cfg))}>重置体验草稿</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@ -5,6 +5,10 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Link, Navigate, useLocation, useNavigate, useParams } from 'react-router-dom'
|
||||
import { api } from '../api/client'
|
||||
import {
|
||||
useSharedSocialPresence,
|
||||
type PresencePeer,
|
||||
} from '../lib/SocialPresenceContext'
|
||||
import {
|
||||
OVERVIEW_STATS,
|
||||
SECTIONS,
|
||||
@ -13,6 +17,8 @@ import {
|
||||
SECTION_TITLE,
|
||||
type SectionKey,
|
||||
fmtTime,
|
||||
joinFaceOk,
|
||||
joinFaceOkLabel,
|
||||
joinLivenessLabel,
|
||||
joinPaidLabel,
|
||||
joinStageLabel,
|
||||
@ -20,6 +26,28 @@ import {
|
||||
pickId,
|
||||
short,
|
||||
} from './socialMeta'
|
||||
import { looksLikeUrl, MediaValue } from './MediaValue'
|
||||
|
||||
function rowLivePeer(
|
||||
row: Record<string, unknown>,
|
||||
peers: PresencePeer[],
|
||||
): PresencePeer | null {
|
||||
if (!peers.length) return null
|
||||
const gid = String(row.guestId || row.guest_id || '').trim().toLowerCase()
|
||||
const name = String(row.name || '').trim().toLowerCase()
|
||||
const email = String(row.email || '').trim().toLowerCase()
|
||||
const local = email.includes('@') ? email.split('@')[0] : email
|
||||
// Strict only — never prefix-match (nick "test" used to light up test8/test7/…)
|
||||
for (const p of peers) {
|
||||
const pid = String(p.guestId || '').trim().toLowerCase()
|
||||
const nick = String(p.nick || '').trim().toLowerCase()
|
||||
if (gid && pid && gid === pid) return p
|
||||
if (name && nick && name === nick) return p
|
||||
if (local && nick && local === nick) return p
|
||||
if (email && nick && email === nick) return p
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
type Stats = {
|
||||
ok?: boolean
|
||||
@ -172,6 +200,7 @@ export default function Social() {
|
||||
const [msg, setMsg] = useState('')
|
||||
const [catalogJson, setCatalogJson] = useState('')
|
||||
const [editRoster, setEditRoster] = useState<Record<string, unknown> | null>(null)
|
||||
const presence = useSharedSocialPresence()
|
||||
|
||||
const loadOverview = useCallback(async () => {
|
||||
const data = await api<Overview>('/api/admin/social/ugc/overview')
|
||||
@ -216,8 +245,23 @@ export default function Social() {
|
||||
}
|
||||
const path = `/api/admin/social/ugc/${apiSeg}?${qs}`
|
||||
const data = await api<{ items?: Record<string, unknown>[]; total?: number }>(path)
|
||||
setItems(Array.isArray(data.items) ? data.items : [])
|
||||
setTotal(Number(data.total || 0))
|
||||
let rows = Array.isArray(data.items) ? data.items : []
|
||||
if (section === 'joins') {
|
||||
const byEmail = new Map<string, Record<string, unknown>>()
|
||||
for (const row of rows) {
|
||||
const em = String(row.email || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
if (!em) continue
|
||||
const prev = byEmail.get(em)
|
||||
const ta = String(row.updatedAt || row.updated_at || '')
|
||||
const tb = String(prev?.updatedAt || prev?.updated_at || '')
|
||||
if (!prev || ta >= tb) byEmail.set(em, row)
|
||||
}
|
||||
rows = [...byEmail.values()]
|
||||
}
|
||||
setItems(rows)
|
||||
setTotal(section === 'joins' ? rows.length : Number(data.total || 0))
|
||||
} catch (e: unknown) {
|
||||
if (!silent) {
|
||||
setErr(e instanceof Error ? e.message : '加载失败')
|
||||
@ -667,9 +711,11 @@ export default function Social() {
|
||||
) : null}
|
||||
{section === 'joins' ? (
|
||||
<tr>
|
||||
<th>头像</th>
|
||||
<th>谁</th>
|
||||
<th>当前进度</th>
|
||||
<th>支付</th>
|
||||
<th>人脸</th>
|
||||
<th>真人核验</th>
|
||||
<th>最近更新</th>
|
||||
<th>操作</th>
|
||||
@ -771,10 +817,14 @@ export default function Social() {
|
||||
{items.map((row) => {
|
||||
const id = pickId(row, section)
|
||||
const href = detailPath(row)
|
||||
const live =
|
||||
section === 'joins' || section === 'roster'
|
||||
? Boolean(rowLivePeer(row, presence.peers))
|
||||
: false
|
||||
return (
|
||||
<tr
|
||||
key={id || JSON.stringify(row).slice(0, 40)}
|
||||
className="com-tr-link"
|
||||
className={`com-tr-link${live ? ' is-live-row' : ''}`}
|
||||
onClick={() => openDetail(row)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
@ -803,7 +853,12 @@ export default function Social() {
|
||||
{section === 'roster' ? (
|
||||
<>
|
||||
<td>
|
||||
<strong>{String(row.name || '—')}</strong>
|
||||
<strong className="com-who-live">
|
||||
{rowLivePeer(row, presence.peers) ? (
|
||||
<i className="com-row-live" title="在线" aria-label="在线" />
|
||||
) : null}
|
||||
{String(row.name || '—')}
|
||||
</strong>
|
||||
<div className="com-muted" style={{ fontSize: 11 }}>
|
||||
<code>{String(row.guestId || row.guest_id || '')}</code>
|
||||
</div>
|
||||
@ -856,7 +911,27 @@ export default function Social() {
|
||||
{section === 'joins' ? (
|
||||
<>
|
||||
<td>
|
||||
<strong>{String(row.name || row.email || '—')}</strong>
|
||||
{looksLikeUrl(row.avatar) ? (
|
||||
<div className="com-join-avatar">
|
||||
<MediaValue
|
||||
value={row.avatar}
|
||||
fieldKey="avatar"
|
||||
compact
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<span className="com-join-avatar-empty" title="无头像">
|
||||
—
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<strong className="com-who-live">
|
||||
{rowLivePeer(row, presence.peers) ? (
|
||||
<i className="com-row-live" title="在线" aria-label="在线" />
|
||||
) : null}
|
||||
{String(row.name || row.email || '—')}
|
||||
</strong>
|
||||
<div className="com-muted" style={{ fontSize: 12 }}>
|
||||
{String(row.email || '')}
|
||||
</div>
|
||||
@ -878,6 +953,17 @@ export default function Social() {
|
||||
return <span className="com-muted">未付</span>
|
||||
})()}
|
||||
</td>
|
||||
<td>
|
||||
{joinFaceOk(row) ? (
|
||||
<span className="com-badge tone-ok">
|
||||
{joinFaceOkLabel(row)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="com-badge tone-bad">
|
||||
{joinFaceOkLabel(row)}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{joinLivenessLabel(row) === '已过' ? (
|
||||
<span className="com-badge tone-ok">已过</span>
|
||||
|
||||
@ -136,6 +136,12 @@ function JoinPrimary({
|
||||
>
|
||||
const stage = String(val(item, 'stage') || '')
|
||||
const liveOk = joinLivenessLabel(item as Record<string, unknown>) === '已过'
|
||||
const faceOkRaw = item.faceOk ?? item.face_ok
|
||||
const faceOk =
|
||||
faceOkRaw === true ||
|
||||
faceOkRaw === 1 ||
|
||||
String(faceOkRaw).toLowerCase() === 'true' ||
|
||||
String(faceOkRaw) === '1'
|
||||
// 前端硬闸:未核验 / 只填邮箱 → 绝不渲染任何照片视频(防 API 旧副本串号)
|
||||
const early =
|
||||
stage === 'email_submit' ||
|
||||
@ -196,7 +202,10 @@ function JoinPrimary({
|
||||
支付 <strong>{joinPaidLabel(item as Record<string, unknown>)}</strong>
|
||||
</span>
|
||||
<span>
|
||||
人脸 <strong>{liveOk ? '通过' : '未过'}</strong>
|
||||
人脸{' '}
|
||||
<strong className={faceOk ? 'tone-ok' : 'tone-bad'}>
|
||||
{faceOk ? 'OK' : '否'}
|
||||
</strong>
|
||||
</span>
|
||||
<span>
|
||||
核验 <strong>{liveOk ? 'verified' : '未核验'}</strong>
|
||||
|
||||
@ -6,6 +6,8 @@ import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Link, useParams } from 'react-router-dom'
|
||||
import { api } from '../api/client'
|
||||
import { useConfigLive } from '../lib/useConfigLive'
|
||||
import { useDraft } from '../lib/useDraft'
|
||||
import UnsavedChanges from '../components/UnsavedChanges'
|
||||
|
||||
type Mod = { enabled: boolean; title: string; tabLabel?: string; note?: string }
|
||||
|
||||
@ -133,6 +135,14 @@ const VIP_ENTRIES = [
|
||||
{ key: 'reviewMode', label: '审核模式', desc: '隐藏促销诱导' },
|
||||
] as const
|
||||
|
||||
function copyFrom(data: SwitchesCfg) {
|
||||
return {
|
||||
homeBrand: data.copy?.homeBrand || '', homeTagline: data.copy?.homeTagline || '',
|
||||
homeLead: data.copy?.homeLead || '', vipCta: data.copy?.vipCta || '',
|
||||
xHandle: data.copy?.xHandle ?? 'noamdcna',
|
||||
}
|
||||
}
|
||||
|
||||
function Switch({
|
||||
checked,
|
||||
onChange,
|
||||
@ -169,32 +179,33 @@ export default function Switches() {
|
||||
const [msg, setMsg] = useState('')
|
||||
const [err, setErr] = useState('')
|
||||
const [tab, setTab] = useState<TabKey>('pages')
|
||||
const [draftCopy, setDraftCopy] = useState({
|
||||
const copyDraft = useDraft({
|
||||
homeBrand: '',
|
||||
homeTagline: '',
|
||||
homeLead: '',
|
||||
vipCta: '',
|
||||
xHandle: '',
|
||||
})
|
||||
const { draft: draftCopy, setDraft: setDraftCopy } = copyDraft
|
||||
const stale = cfg?.version != null && live.meta != null && live.meta.version > cfg.version
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setErr('')
|
||||
const data = await api<SwitchesCfg>('/api/admin/weapp/switches')
|
||||
setCfg(data)
|
||||
setDraftCopy({
|
||||
homeBrand: data.copy?.homeBrand || '',
|
||||
homeTagline: data.copy?.homeTagline || '',
|
||||
homeLead: data.copy?.homeLead || '',
|
||||
vipCta: data.copy?.vipCta || '',
|
||||
xHandle: data.copy?.xHandle || 'noamdcna',
|
||||
})
|
||||
copyDraft.reset(copyFrom(data))
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
load().catch((e: Error) => setErr(e.message || '加载失败'))
|
||||
}, [load])
|
||||
|
||||
useEffect(() => {
|
||||
if (stale && !copyDraft.dirty && !busy) void load().catch(e => setErr(String(e)))
|
||||
}, [stale, copyDraft.dirty, busy, load])
|
||||
|
||||
async function patch(body: Record<string, unknown>, okHint: string) {
|
||||
if (stale) { setErr('配置已更新,请加载最新配置后重试;当前草稿已保留'); return }
|
||||
setBusy(true)
|
||||
setMsg('')
|
||||
setErr('')
|
||||
@ -204,13 +215,7 @@ export default function Switches() {
|
||||
body: JSON.stringify({ ...body, expectedVersion: cfg?.version }),
|
||||
})
|
||||
setCfg(data)
|
||||
setDraftCopy({
|
||||
homeBrand: data.copy?.homeBrand || '',
|
||||
homeTagline: data.copy?.homeTagline || '',
|
||||
homeLead: data.copy?.homeLead || '',
|
||||
vipCta: data.copy?.vipCta || '',
|
||||
xHandle: data.copy?.xHandle || 'noamdcna',
|
||||
})
|
||||
copyDraft.accept(copyFrom(data), Object.keys(body.copy || {}) as Array<keyof typeof draftCopy>)
|
||||
setMsg(okHint)
|
||||
} catch (e: unknown) {
|
||||
setErr(e instanceof Error ? e.message : '保存失败')
|
||||
@ -231,7 +236,7 @@ export default function Switches() {
|
||||
<h1>动态开关</h1>
|
||||
<p>加载远程配置…</p>
|
||||
</header>
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err" role="alert">{err}<button type="button" className="com-btn" onClick={() => void load().catch(e => setErr(String(e)))}>重试加载</button></div> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@ -259,11 +264,12 @@ export default function Switches() {
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{msg ? <div className="com-toast com-toast-ok">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err">{err}</div> : null}
|
||||
<UnsavedChanges dirty={copyDraft.dirty} />
|
||||
{msg ? <div className="com-toast com-toast-ok" role="status">{msg}</div> : null}
|
||||
{err ? <div className="com-toast com-toast-err" role="alert">{err}</div> : null}
|
||||
|
||||
<div className="com-config-live" role="status"><span className={`com-status-dot${live.connected ? '' : ' is-polling'}`} />{live.connected ? '实时配置通道已连接' : '配置轮询兜底中'}<span>服务端 v{live.meta?.version ?? '—'} · 当前编辑 v{cfg.version ?? '—'}</span></div>
|
||||
{live.meta && cfg.version != null && live.meta.version !== cfg.version && <div className="com-toast">配置已在其他页面更新。请刷新后再保存,避免覆盖新配置。<button className="com-btn" disabled={busy} onClick={() => { if (window.confirm('刷新将放弃当前未保存的修改,是否继续?')) void load().catch(e => setErr(String(e))) }}>加载最新配置</button></div>}
|
||||
{stale && <div className="com-toast" role="status">配置已在其他页面更新。当前草稿已保留,请加载最新配置后再保存。<button className="com-btn" disabled={busy} onClick={() => { if (!copyDraft.dirty || window.confirm('刷新将放弃当前未保存的修改,是否继续?')) void load().catch(e => setErr(String(e))) }}>加载最新配置</button></div>}
|
||||
|
||||
<nav className="com-tabs" aria-label="开关分类">
|
||||
{TABS.map((t) => (
|
||||
@ -582,11 +588,12 @@ export default function Switches() {
|
||||
<button
|
||||
type="button"
|
||||
className="com-btn"
|
||||
disabled={busy}
|
||||
disabled={busy || stale || !copyDraft.dirty}
|
||||
onClick={() => void patch({ copy: draftCopy }, '文案已保存')}
|
||||
>
|
||||
保存文案
|
||||
</button>
|
||||
<button type="button" className="com-btn com-btn-ghost" disabled={busy || !copyDraft.dirty} onClick={() => copyDraft.reset(copyFrom(cfg))}>重置文案草稿</button>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
@ -108,6 +108,7 @@ export const JOIN_STAGE_LABEL: Record<string, string> = {
|
||||
email_submit: '提交邮箱',
|
||||
pay_launched: '发起支付',
|
||||
pay_confirmed: '支付确认',
|
||||
profile_started: '填写资料中',
|
||||
profile_done: '资料完成',
|
||||
liveness_verified: '自拍已通过',
|
||||
liveness_failed: '自拍未通过',
|
||||
@ -169,6 +170,18 @@ export function joinLivenessLabel(row: Record<string, unknown>): string {
|
||||
return '未核验'
|
||||
}
|
||||
|
||||
/** 人脸检测:与真人核验分开;true / 1 / "true" 才算 OK */
|
||||
export function joinFaceOk(row: Record<string, unknown>): boolean {
|
||||
const stage = String(row.stage || '')
|
||||
if (JOIN_EARLY.has(stage)) return false
|
||||
const v = row.faceOk ?? row.face_ok
|
||||
return v === true || v === 1 || String(v).toLowerCase() === 'true' || String(v) === '1'
|
||||
}
|
||||
|
||||
export function joinFaceOkLabel(row: Record<string, unknown>): 'OK' | '否' {
|
||||
return joinFaceOk(row) ? 'OK' : '否'
|
||||
}
|
||||
|
||||
export function joinStageTone(stage: unknown): 'ok' | 'warn' | 'bad' | 'info' | 'muted' {
|
||||
const s = String(stage || '').toLowerCase()
|
||||
if (s.includes('fail') || s.includes('skip')) return 'bad'
|
||||
|
||||
@ -8,6 +8,8 @@
|
||||
--muted: #9daec5;
|
||||
--accent: #f6b44b;
|
||||
--accent-2: #64c9ed;
|
||||
--danger: #ef4444;
|
||||
--ok: #34d399;
|
||||
--side-w: 268px;
|
||||
--radius: 14px;
|
||||
--shadow: 0 8px 28px #00000020;
|
||||
@ -26,6 +28,11 @@
|
||||
--shadow: 0 8px 28px #233c5910;
|
||||
}
|
||||
body { background: var(--bg); }
|
||||
.com-draft-status { color: var(--accent); font-size: 13px; margin: 12px 0; }
|
||||
.com-unsaved-dialog { width: min(440px, calc(100vw - 32px)); max-height: calc(100dvh - 32px); overflow: auto; margin: auto; padding: 24px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); color: var(--text); box-shadow: var(--shadow); }
|
||||
.com-unsaved-dialog::backdrop { background: #0009; }
|
||||
.com-unsaved-dialog h2 { margin: 0 0 12px; font-size: 20px; }
|
||||
.com-unsaved-dialog p { color: var(--muted); line-height: 1.65; }
|
||||
button, input, select, textarea { font: inherit; }
|
||||
button, a, input, select, textarea { -webkit-tap-highlight-color: transparent; }
|
||||
button { transition: background .15s, border-color .15s, box-shadow .15s; }
|
||||
@ -93,6 +100,159 @@ button:disabled { cursor: not-allowed; opacity: .55; }
|
||||
.com-connection { display: flex; align-items: center; gap: 7px; font-size: 11px; color: var(--muted); white-space: nowrap; }
|
||||
.com-connection i, .com-status-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ok); flex-shrink: 0; }
|
||||
.com-connection.is-offline i { background: var(--danger); }
|
||||
.com-workspace-live { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; justify-content: flex-end; }
|
||||
.com-presence {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
min-height: 34px;
|
||||
padding: 4px 10px 4px 8px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--panel);
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
transition: border-color .2s, background .2s, color .2s, box-shadow .2s;
|
||||
}
|
||||
.com-presence-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: #64748b;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.com-presence.is-live {
|
||||
color: var(--text);
|
||||
border-color: color-mix(in srgb, var(--ok) 45%, var(--line));
|
||||
background: color-mix(in srgb, var(--ok) 10%, var(--panel));
|
||||
}
|
||||
.com-presence.is-live .com-presence-dot {
|
||||
background: var(--ok);
|
||||
box-shadow: 0 0 0 4px color-mix(in srgb, var(--ok) 18%, transparent);
|
||||
animation: com-presence-pulse 1.8s ease-in-out infinite;
|
||||
}
|
||||
.com-presence.is-flash {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 4px color-mix(in srgb, var(--accent) 22%, transparent);
|
||||
animation: com-presence-flash .7s ease-out;
|
||||
}
|
||||
.com-presence.is-soft { opacity: .72; }
|
||||
.com-presence-count {
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
color: var(--ok);
|
||||
min-width: .9em;
|
||||
}
|
||||
.com-presence-label { color: inherit; }
|
||||
.com-presence-avs { display: inline-flex; margin-left: 2px; }
|
||||
.com-presence-avs b {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
margin-left: -5px;
|
||||
border-radius: 999px;
|
||||
border: 1.5px solid var(--panel);
|
||||
background: color-mix(in srgb, var(--accent) 28%, var(--panel-2));
|
||||
color: #fff;
|
||||
font-size: 9px;
|
||||
font-weight: 700;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.com-presence-avs b:first-child { margin-left: 0; }
|
||||
.com-presence-toast {
|
||||
position: fixed;
|
||||
right: 22px;
|
||||
bottom: 22px;
|
||||
z-index: 80;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
max-width: min(92vw, 360px);
|
||||
padding: 12px 16px;
|
||||
border-radius: 12px;
|
||||
border: 1px solid color-mix(in srgb, var(--ok) 40%, var(--line));
|
||||
background: var(--panel);
|
||||
box-shadow: 0 16px 48px #00000055;
|
||||
animation: com-presence-toast-in .28s ease-out;
|
||||
}
|
||||
.com-presence-toast .com-presence-dot.is-ok {
|
||||
background: var(--ok);
|
||||
box-shadow: 0 0 0 4px color-mix(in srgb, var(--ok) 20%, transparent);
|
||||
animation: com-presence-pulse 1.6s ease-in-out infinite;
|
||||
}
|
||||
.com-presence-toast strong { font-size: 13px; font-weight: 650; }
|
||||
.com-presence-toast > span:last-child {
|
||||
margin-left: 4px;
|
||||
font-size: 10px;
|
||||
letter-spacing: .08em;
|
||||
color: var(--ok);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
@keyframes com-presence-pulse {
|
||||
0%, 100% { transform: scale(1); opacity: 1; }
|
||||
50% { transform: scale(1.2); opacity: .72; }
|
||||
}
|
||||
@keyframes com-presence-flash {
|
||||
0% { transform: scale(1); }
|
||||
40% { transform: scale(1.04); }
|
||||
100% { transform: scale(1); }
|
||||
}
|
||||
@keyframes com-presence-toast-in {
|
||||
from { opacity: 0; transform: translateY(10px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.com-join-avatar {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
background: #09090b;
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
.com-join-avatar .com-media,
|
||||
.com-join-avatar .com-media-sm {
|
||||
margin: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
.com-join-avatar img {
|
||||
width: 48px !important;
|
||||
height: 48px !important;
|
||||
max-height: 48px !important;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
.com-join-avatar-empty {
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 10px;
|
||||
border: 1px dashed var(--line);
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.com-who-live {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
}
|
||||
.com-row-live {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--ok, #34d399);
|
||||
box-shadow: 0 0 0 4px color-mix(in srgb, var(--ok, #34d399) 22%, transparent);
|
||||
animation: com-presence-pulse 1.6s ease-in-out infinite;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
tr.is-live-row td:first-child {
|
||||
box-shadow: inset 3px 0 0 var(--ok, #34d399);
|
||||
}
|
||||
.com-page { max-width: 1500px; margin: 0 auto; }
|
||||
.com-page-head { margin-bottom: 24px; }
|
||||
.com-page-head h1 { font-size: clamp(24px, 3vw, 32px); letter-spacing: -.035em; line-height: 1.25; }
|
||||
@ -183,3 +343,13 @@ button:disabled { cursor: not-allowed; opacity: .55; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; }
|
||||
}
|
||||
.com-switch input {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
z-index: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.com-switch input:disabled { cursor: not-allowed; }
|
||||
|
||||
80
apps/com/deploy/install-uiux-services.py
Normal file
80
apps/com/deploy/install-uiux-services.py
Normal file
@ -0,0 +1,80 @@
|
||||
"""Run on the US VPS via the focused deploy script; never print credentials."""
|
||||
import json
|
||||
import pathlib
|
||||
import secrets
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
stage, backup = map(pathlib.Path, sys.argv[1:3])
|
||||
targets = json.loads((stage / 'manifest.json').read_text())
|
||||
extras = ['/etc/nomadro/uiux-services.env', '/etc/nomadro/uiux-notify.env',
|
||||
'/etc/systemd/system/nomadro-notify.service', '/etc/systemd/system/nomadro-coffee.service',
|
||||
'/etc/systemd/system/nomadro.service.d/uiux-notify.conf',
|
||||
'/etc/systemd/system/nomadro-social.service.d/uiux-notify.conf']
|
||||
state = {}
|
||||
for target in targets + extras:
|
||||
path = pathlib.Path(target)
|
||||
state[target] = path.exists()
|
||||
if path.exists():
|
||||
dest = backup / 'files' / target.lstrip('/')
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(path, dest)
|
||||
(backup / 'manifest.json').write_text(json.dumps(state))
|
||||
|
||||
# Consistent SQLite backup including committed WAL contents, before any schema changes.
|
||||
for source in pathlib.Path('/opt/pocketbase/pb_data').glob('*.db'):
|
||||
target = backup / ('pb-' + source.name)
|
||||
with sqlite3.connect(f'file:{source}?mode=ro', uri=True) as db, sqlite3.connect(target) as copy:
|
||||
db.backup(copy)
|
||||
assert copy.execute('PRAGMA quick_check').fetchone()[0] == 'ok'
|
||||
print('Database backup verified:', target.name, flush=True)
|
||||
|
||||
pid = subprocess.check_output(['systemctl', 'show', 'nomadro-social', '-p', 'MainPID', '--value']).decode().strip()
|
||||
env = dict(item.split('=', 1) for item in pathlib.Path('/proc/' + pid + '/environ').read_bytes().decode().split('\0') if '=' in item)
|
||||
keys = ['PB_URL', 'PB_ADMIN_EMAIL', 'PB_ADMIN_PASSWORD', 'POCKETBASE_URL', 'POCKETBASE_EMAIL', 'POCKETBASE_PASSWORD']
|
||||
selected = {key: env[key] for key in keys if key in env}
|
||||
assert selected.get('PB_ADMIN_EMAIL') or selected.get('POCKETBASE_EMAIL')
|
||||
assert selected.get('PB_ADMIN_PASSWORD') or selected.get('POCKETBASE_PASSWORD')
|
||||
selected['PB_INTERNAL_URL'] = 'http://127.0.0.1:8090'
|
||||
secretfile = pathlib.Path('/etc/nomadro/uiux-notify.env')
|
||||
if secretfile.exists():
|
||||
token = secretfile.read_text().strip().split('=', 1)[1]
|
||||
else:
|
||||
token = secrets.token_hex(32)
|
||||
secretfile.write_text('NOTIFY_INTERNAL_TOKEN=' + token + '\n')
|
||||
secretfile.chmod(0o600)
|
||||
selected['NOTIFY_INTERNAL_TOKEN'] = token
|
||||
envfile = pathlib.Path('/etc/nomadro/uiux-services.env')
|
||||
envfile.write_text(''.join(key + '=' + json.dumps(value) + '\n' for key, value in selected.items()))
|
||||
envfile.chmod(0o600)
|
||||
|
||||
for target in targets:
|
||||
path = pathlib.Path(target)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(stage / target.lstrip('/'), path)
|
||||
for service, port in [('notify', 8023), ('coffee', 8024)]:
|
||||
unit = f"""[Unit]
|
||||
Description=Nomadro {service} service (.com)
|
||||
After=network.target pocketbase.service
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=/var/www/nomadro.cn/apps/api
|
||||
EnvironmentFile=/etc/nomadro/uiux-services.env
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
Environment=COFFEE_SEED_DEMO=0
|
||||
ExecStart=/var/www/nomadro.cn/apps/api/.venv-social/bin/uvicorn {service}_main:app --host 127.0.0.1 --port {port} --workers 1
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
"""
|
||||
pathlib.Path('/etc/systemd/system/nomadro-' + service + '.service').write_text(unit)
|
||||
for service in ['nomadro', 'nomadro-social']:
|
||||
path = pathlib.Path('/etc/systemd/system/' + service + '.service.d/uiux-notify.conf')
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text('[Service]\nEnvironmentFile=/etc/nomadro/uiux-notify.env\n')
|
||||
print('Backups and source installation complete:', str(backup), flush=True)
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"version": 6,
|
||||
"updatedAt": "2026-11-04T12:35:00.000Z",
|
||||
"version": 14,
|
||||
"updatedAt": "2026-11-05T02:33:23.200227+00:00",
|
||||
"modules": {
|
||||
"home": {
|
||||
"enabled": true,
|
||||
@ -44,6 +44,12 @@
|
||||
"enabled": false,
|
||||
"title": "数字游民",
|
||||
"note": "冻结隐藏 · 勿开入口"
|
||||
},
|
||||
"socialBlog": {
|
||||
"enabled": true,
|
||||
"title": "Nomad Blog",
|
||||
"tabLabel": "Blog",
|
||||
"note": "/social/blog · EN long-form · AdSense"
|
||||
}
|
||||
},
|
||||
"flags": {
|
||||
@ -59,9 +65,9 @@
|
||||
"homeBrand": "nomadro",
|
||||
"homeTagline": "",
|
||||
"homeLead": "",
|
||||
"vipPriceFen": 10,
|
||||
"vipPriceFen": 0,
|
||||
"vipProductId": "tiktok",
|
||||
"vipCta": "立即加入 · ¥0.1",
|
||||
"vipCta": "免费加入",
|
||||
"vipOfferKey": "tiktok",
|
||||
"wechatOaName": "异度世界",
|
||||
"joinGroupDouyinHint": "打开抖音搜群「数字游民」或扫码进群",
|
||||
@ -157,5 +163,14 @@
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"audience": {
|
||||
"cn": {
|
||||
"vipCta": "免费加入"
|
||||
},
|
||||
"intl": {
|
||||
"vipCta": "Join free"
|
||||
},
|
||||
"defaultLane": "intl"
|
||||
}
|
||||
}
|
||||
|
||||
@ -103,7 +103,9 @@ img.spinner-logo[src*="logo.svg"] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Kill MiroTalk promo / share / about chrome */
|
||||
/* Kill MiroTalk promo / share / about chrome
|
||||
* DO NOT hide #initVideoAudioBtn / .init-wrap / init video UI —
|
||||
* that left the hall black with only a text avatar after “美化”. */
|
||||
#shareRoomBtn,
|
||||
#shareRoomBtn *,
|
||||
#qrRoomBtn,
|
||||
@ -118,8 +120,6 @@ button#shareButton,
|
||||
button[data-umami-event*="Share"],
|
||||
button[data-umami-event*="About"],
|
||||
button[data-umami-event*="Support"],
|
||||
#initVideoAudioBtn,
|
||||
.init-wrap,
|
||||
.emoji-picker-react,
|
||||
#showChatOnMsgDiv,
|
||||
.swal2-image {
|
||||
@ -128,12 +128,136 @@ button[data-umami-event*="Support"],
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
/* Hide Share-the-room / about / survey SweetAlerts (permissions still work via browser UI) */
|
||||
/*
|
||||
* Codex “美化”曾把 .swal2-container 整块 display:none,进房弹窗没了。
|
||||
* 后续又给 .swal2-popup 强加 display:flex 却不设 column →「进入房间」竖条贴右边。
|
||||
* 这里只恢复正常 SweetAlert 纵向布局(相机预览 + 昵称 + 横条进房)。
|
||||
*/
|
||||
html.nomadro-embed .swal2-container,
|
||||
body.nomadro-embed .swal2-container {
|
||||
display: none !important;
|
||||
pointer-events: none !important;
|
||||
opacity: 0 !important;
|
||||
display: flex !important;
|
||||
pointer-events: auto !important;
|
||||
opacity: 1 !important;
|
||||
visibility: visible !important;
|
||||
z-index: 10000 !important;
|
||||
background: rgba(5, 7, 12, 0.72) !important;
|
||||
padding: 12px !important;
|
||||
align-items: center !important;
|
||||
justify-content: center !important;
|
||||
overflow-y: auto !important;
|
||||
}
|
||||
|
||||
html.nomadro-embed .swal2-popup,
|
||||
html.nomadro-embed .swal2-popup.init-modal-size,
|
||||
body.nomadro-embed .swal2-popup,
|
||||
body.nomadro-embed .swal2-popup.init-modal-size {
|
||||
display: flex !important;
|
||||
flex-direction: column !important;
|
||||
align-items: stretch !important;
|
||||
visibility: visible !important;
|
||||
opacity: 1 !important;
|
||||
background: #111827 !important;
|
||||
color: #f1f5f9 !important;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1) !important;
|
||||
border-radius: 16px !important;
|
||||
box-shadow: 0 16px 48px rgba(0, 0, 0, 0.55) !important;
|
||||
width: min(92vw, 420px) !important;
|
||||
max-width: calc(100% - 16px) !important;
|
||||
max-height: calc(100vh - 24px) !important;
|
||||
height: auto !important;
|
||||
margin: 0 auto !important;
|
||||
padding: 16px !important;
|
||||
overflow: auto !important;
|
||||
box-sizing: border-box !important;
|
||||
}
|
||||
|
||||
/* MiroTalk .init-user 默认横排;窄 iframe 里改成竖排,避免预览被挤没 */
|
||||
html.nomadro-embed .init-user,
|
||||
html.nomadro-embed #initUser {
|
||||
display: flex !important;
|
||||
flex-direction: column !important;
|
||||
gap: 10px !important;
|
||||
width: 100% !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
|
||||
html.nomadro-embed #initVideoContainer,
|
||||
html.nomadro-embed .init-video-container {
|
||||
width: 100% !important;
|
||||
margin: 0 !important;
|
||||
max-height: 200px !important;
|
||||
}
|
||||
|
||||
html.nomadro-embed #initVideo {
|
||||
width: 100% !important;
|
||||
height: 180px !important;
|
||||
max-height: 180px !important;
|
||||
object-fit: cover !important;
|
||||
border-radius: 12px !important;
|
||||
background: #05070c !important;
|
||||
}
|
||||
|
||||
html.nomadro-embed .initComands,
|
||||
html.nomadro-embed #initUser select,
|
||||
html.nomadro-embed .init-wrap select {
|
||||
width: 100% !important;
|
||||
max-width: 100% !important;
|
||||
box-sizing: border-box !important;
|
||||
}
|
||||
|
||||
html.nomadro-embed .swal2-html-container {
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
overflow: visible !important;
|
||||
}
|
||||
|
||||
html.nomadro-embed .swal2-title,
|
||||
html.nomadro-embed .swal2-html-container,
|
||||
html.nomadro-embed .swal2-input,
|
||||
body.nomadro-embed .swal2-title,
|
||||
body.nomadro-embed .swal2-html-container,
|
||||
body.nomadro-embed .swal2-input {
|
||||
color: #f1f5f9 !important;
|
||||
}
|
||||
|
||||
html.nomadro-embed .swal2-input {
|
||||
width: 100% !important;
|
||||
box-sizing: border-box !important;
|
||||
background: #0a0e17 !important;
|
||||
border: 1px solid rgba(255, 255, 255, 0.12) !important;
|
||||
border-radius: 10px !important;
|
||||
margin: 10px 0 0 !important;
|
||||
}
|
||||
|
||||
/* 进房按钮:必须横排全宽,禁止竖排贴边 */
|
||||
html.nomadro-embed .swal2-actions,
|
||||
body.nomadro-embed .swal2-actions {
|
||||
display: flex !important;
|
||||
flex-direction: row !important;
|
||||
flex-wrap: nowrap !important;
|
||||
width: 100% !important;
|
||||
margin: 12px 0 0 !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
|
||||
html.nomadro-embed .swal2-confirm,
|
||||
body.nomadro-embed .swal2-confirm {
|
||||
display: inline-flex !important;
|
||||
align-items: center !important;
|
||||
justify-content: center !important;
|
||||
width: 100% !important;
|
||||
min-height: 44px !important;
|
||||
margin: 0 !important;
|
||||
padding: 12px 16px !important;
|
||||
writing-mode: horizontal-tb !important;
|
||||
text-orientation: mixed !important;
|
||||
white-space: nowrap !important;
|
||||
background: linear-gradient(135deg, #ff6b6b 0%, #ffe66d 50%, #4ecdc4 100%) !important;
|
||||
color: #0a0e17 !important;
|
||||
font-weight: 700 !important;
|
||||
font-size: 15px !important;
|
||||
border: 0 !important;
|
||||
border-radius: 12px !important;
|
||||
}
|
||||
|
||||
/* Toolbar: glass dark like portal */
|
||||
|
||||
62
docs/uiux-upgrade-2026-11-05.md
Normal file
62
docs/uiux-upgrade-2026-11-05.md
Normal file
@ -0,0 +1,62 @@
|
||||
# .com UI、交互与功能升级 — 2026-11-05
|
||||
|
||||
已发布到美国服务器 108.174.50.68 的 [门户](https://nomadro.com) 和 [管理后台](https://admin.nomadro.com)。本轮保留现有视觉风格,集中修复真实业务流程、操作反馈、移动表单和服务联通。
|
||||
|
||||
## 用户可见变化
|
||||
|
||||
- **管理后台**:价格、体验次数、受众文案、页面开关、博客设置分别保存草稿;保存一个区域不再覆盖其他未保存内容。离开页面、切换受众或退出时可继续编辑或确认放弃。价格空值、小数位、AdSense 字段会校验;加载失败可重试;版本变化会提示冲突并保留草稿。开关支持键盘焦点。
|
||||
- **Coffeechat**:可创建自己的公开预约页,编辑资料、时区及每周可约时间,查看收到和发出的预约并取消。服务按主持人当地日期、时区和真实日程生成时段,排除过去时间、已约时段和缓冲区;并发争抢同一时段返回 409。取消会释放时段。
|
||||
- **预约交互**:日期与时段时区一致;切换日期清理旧选择,过期请求不会替换新结果;邮箱和姓名校验、防重复点击、失败保留输入、冲突后重新选择。详情显示当地时间,可导出标准 ICS 日历;见面结束后才开放参与者评价入口。
|
||||
- **通知**:收件箱、角标与偏好使用当前社区访客 ID,修复统一使用 guest 导致收不到个人通知的问题。支持分类已读、错误反馈和重试。静默时段先编辑再保存,修改每个字符不再立即发请求;其他开关保存不丢失静默时段草稿。
|
||||
- **服务与数据**:原先未部署的通知、预约服务已运行,相关接口由 503 恢复正常。修复收件箱参数不匹配、分类过滤顺序、读取偏好覆盖联系人字段、PocketBase 旧版字段更新静默失效等问题。只初始化通知与预约集合,保留已有扩展字段和索引,并关闭这两个领域集合的直接匿名访问。
|
||||
- **构建与适配**:修复通知设置窄屏溢出和静默时段控件挤压;Outfit 使用同字体的 OFL 本地文件,规避 Google Fonts CSS 查询参数触发的 Turbopack 构建错误。
|
||||
|
||||
## 验证
|
||||
|
||||
| 检查 | 结果 |
|
||||
|---|---|
|
||||
| 根 TypeScript 检查、Next 与 .com 后台生产构建 | 通过 |
|
||||
| Python 隔离回归 | 43 项通过 |
|
||||
| 服务器同版本 PocketBase、独立临时数据库集成 | 预约创建/归属/时段/并发冲突/列表/取消;通知偏好/站内触发/已读/删除;集合访问规则通过 |
|
||||
| 正式域名加载前端、模拟接口的后台交互 | 5 组多步骤流程通过,无浏览器异常 |
|
||||
| 正式域名加载前端、模拟接口的门户交互 | 4 组多步骤流程通过,无浏览器异常 |
|
||||
| 正式域名真实服务及权限请求 | 9 项预期状态通过 |
|
||||
| 正式域名真实服务页面,390px 移动布局 | 通知、通知设置、咖啡聊、我的咖啡聊全部通过,无 API/JS 错误和横向溢出 |
|
||||
| 门户 HTTP 扫描 | 164 页面无 404/5xx,10 项未登录/支付负向检查符合预期 |
|
||||
| .com 管理后台真实登录与只读浏览 | 中文/国际共 56 页面无 API/JS 错误;主题、搜索、移动菜单通过 |
|
||||
| 管理接口只读检查 | 50 个接口匿名拒绝、登录可用 |
|
||||
|
||||
浏览器中的预约创建、取消、配置修改场景使用模拟接口;PocketBase 写入集成使用独立空数据库并在结束后销毁。没有创建正式用户预约、真实扣款或主动向外发送测试通知。
|
||||
|
||||
验收报告在 artifacts/uiux-upgrade/;全站 HTTP 与后台只读报告在 artifacts/platform-upgrade/。测试脚本:
|
||||
|
||||
- scripts/check-admin-editing.py
|
||||
- scripts/check-portal-uiux.py
|
||||
- scripts/check-live-uiux-com.py
|
||||
- scripts/check-services-pocketbase.py
|
||||
- python -m unittest discover -s apps/api/tests
|
||||
|
||||
## 部署与回滚
|
||||
|
||||
门户当前构建 **kitaRRvmX-xEW16HB2SNY**,发布 20261105T082315Z(北京时间 16:23)。
|
||||
|
||||
| 部分 | 回滚备份 |
|
||||
|---|---|
|
||||
| 门户旧构建及源码 | /var/backups/nomadro-upgrade/20261105T082315Z |
|
||||
| .com 后台旧 HTML | /var/backups/nomadro-upgrade/admin-20261105T082216Z |
|
||||
| API、通知、预约、环境和 systemd 配置,PB 一致性备份 | /var/backups/nomadro-upgrade/uiux-20261105T081823Z |
|
||||
| PocketBase 旧版字段兼容修复前代码及数据库 | /var/backups/nomadro-upgrade/schema-20261105T083051Z |
|
||||
|
||||
新增 nomadro-notify(loopback 8023)、nomadro-coffee(loopback 8024),均已设为开机启动。Coffee 服务必须保持 **一个 worker**,目前用进程内锁保证预约检查和创建串行;多进程扩容前需要数据库事务或分布式锁。
|
||||
|
||||
服务器门户路径仍叫 /var/www/nomadro.cn,实际是美国机器;没有部署中国站或小程序。所有运行时数据库、远程业务配置、密钥均沿用服务器内容,没有用本地数据覆盖。
|
||||
|
||||
发布工具为 scripts/deploy_uiux_services_com.py、scripts/deploy_portal_upgrade_com.py、scripts/deploy_admin_dist_com.py。门户回滚应停止 nomadro,保留故障构建,再将备份 next 恢复到运行目录 .next 并还原 sources.tgz。后台恢复对应 index.html 即可,旧哈希资源保留。服务源码与环境按服务发布目录的 manifest.json 还原并重启相应服务。数据库备份用于人工恢复,不自动覆盖发布后新增的用户数据;字段和访问规则升级应优先保留。
|
||||
|
||||
## 当前边界
|
||||
|
||||
预约管理使用与当前浏览器、社区访客 ID 绑定的独立随机凭证,服务端只保存摘要;公开主页 ID 不能直接用于修改日程或读取、取消预约。清理浏览器数据或换账号后不能自动恢复这份凭证,跨设备账号恢复仍需完整身份认证整合。
|
||||
|
||||
通知沿用现有社区访客身份模型;增加了 ID 一致性校验、管理操作内部令牌及门户管理员会话检查,但访客 ID 不是经过验证的账号身份,不能把本轮改动当作完整认证升级。工作流、订阅者和批量触发需要门户管理员会话。邮件投递和离线 Web Push 尚未接入真实投递提供商;界面已明确邮件状态,本轮上线的是站内收件箱及偏好。
|
||||
|
||||
全站 HTTP 扫描验证可达性;模拟浏览器测试、隔离数据库测试和正式环境只读检查分别验证对应范围,不能代替所有第三方支付、真实多人协作或全部异常场景的验收。
|
||||
@ -78,11 +78,27 @@ const nextConfig: NextConfig = {
|
||||
"@nomadro/sdk": "./packages/sdk/src/index.ts",
|
||||
},
|
||||
},
|
||||
webpack: (config) => {
|
||||
webpack: (config, { dev }) => {
|
||||
config.resolve.alias = {
|
||||
...config.resolve.alias,
|
||||
...aliases,
|
||||
};
|
||||
// PB 库文件一直在写(*.db-wal/shm);不忽略会触发 Fast Refresh 全页闪烁花屏
|
||||
if (dev) {
|
||||
config.watchOptions = {
|
||||
...config.watchOptions,
|
||||
ignored: [
|
||||
"**/node_modules/**",
|
||||
"**/.git/**",
|
||||
"**/pb/pb_data/**",
|
||||
"**/pb_data/**",
|
||||
"**/*.db",
|
||||
"**/*.db-*",
|
||||
"**/__pycache__/**",
|
||||
"**/.next/**",
|
||||
],
|
||||
};
|
||||
}
|
||||
return config;
|
||||
},
|
||||
async rewrites() {
|
||||
|
||||
18
scripts/audit_uiux_runtime_com.py
Normal file
18
scripts/audit_uiux_runtime_com.py
Normal file
@ -0,0 +1,18 @@
|
||||
"""Read-only US runtime audit; never print environment values or credentials."""
|
||||
import runpy
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
client = runpy.run_path(str(ROOT / 'apps/admin/deploy/_upload_next_us.py'))['connect']()
|
||||
try:
|
||||
command = r'''systemctl list-unit-files 'nomadro*' --no-pager
|
||||
systemctl show nomadro-notify nomadro-coffee -p LoadState -p FragmentPath -p WorkingDirectory -p ExecStart --no-pager
|
||||
ss -lntp | head -25
|
||||
ls /var/www/nomadro.cn/apps/api/notify_main.py /var/www/nomadro.cn/apps/api/coffee_main.py /var/www/nomadro.cn/apps/api/.venv-social/bin/uvicorn
|
||||
find /etc/systemd/system -maxdepth 1 \( -iname '*coffee*' -o -iname '*notify*' \)
|
||||
'''
|
||||
_, output, error = client.exec_command(command, timeout=30)
|
||||
print(output.read().decode('utf-8', 'replace'))
|
||||
print(error.read().decode('utf-8', 'replace'))
|
||||
finally:
|
||||
client.close()
|
||||
196
scripts/check-admin-editing.py
Normal file
196
scripts/check-admin-editing.py
Normal file
@ -0,0 +1,196 @@
|
||||
"""Browser regression checks with mocked APIs; never writes production data."""
|
||||
import copy
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from playwright.sync_api import sync_playwright, expect
|
||||
|
||||
sys.stdout.reconfigure(encoding='utf-8')
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / 'artifacts/uiux-upgrade'
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
BASE = sys.argv[1] if len(sys.argv) > 1 else 'http://localhost:5174'
|
||||
report = {'base': BASE, 'checks': [], 'pageErrors': []}
|
||||
|
||||
|
||||
class Backend:
|
||||
def __init__(self):
|
||||
self.config = {'version': 10, 'modules': {}, 'flags': {'payEnabled': True, 'socialTrialEnabled': True},
|
||||
'copy': {'vipPriceFen': 8800, 'vipCta': '立即加入 · ¥88', 'homeBrand': 'Nomadro', 'homeTagline': 'Original tagline', 'homeLead': 'Original lead', 'xHandle': 'nomadro', 'socialTrial': {'enabled': True, 'chatMessages': 1, 'dateViews': 5, 'coffeeBookings': 0, 'mapOpens': 3}}, 'vipEntries': {}}
|
||||
self.audience = {'defaultLane': 'intl', 'cn': {'payEnabled': True, 'socialFollow': True, 'followChannel': 'wechat', 'vipCta': '原始 CTA', 'homeLead': '原始导语'}, 'intl': {'payEnabled': True, 'socialFollow': True, 'followChannel': 'x', 'vipCta': 'Join VIP', 'homeLead': 'Original lead'}}
|
||||
self.blog = {'moduleEnabled': True, 'adsenseEnabled': False, 'adsenseClientId': '', 'adsensePublisherId': '', 'adsenseSlotBlogMid': '', 'adsenseSlotBlogEnd': '', 'ops': {'note': '', 'heroLead': ''}, 'counts': {'posts': 0}}
|
||||
self.mutations = []
|
||||
self.failure = None
|
||||
|
||||
def route(self, route):
|
||||
request = route.request
|
||||
path = urlparse(request.url).path
|
||||
if not path.startswith('/api/'): return route.continue_()
|
||||
if path == '/api/config/stream':
|
||||
return route.fulfill(status=200, content_type='text/event-stream', body=': mock\n\n')
|
||||
body = request.post_data_json if request.method in ['POST', 'PUT', 'PATCH'] and request.post_data else {}
|
||||
if request.method in ['PUT', 'PATCH', 'DELETE']:
|
||||
self.mutations.append({'path': path, 'body': body})
|
||||
if self.failure:
|
||||
failure, self.failure = self.failure, None
|
||||
if failure == 'malformed': return route.fulfill(status=200, content_type='application/json', body='{broken')
|
||||
return route.fulfill(status=409, json={'detail': '配置已更新,请加载最新配置后重试;当前草稿尚未保存'})
|
||||
if body.get('expectedVersion') != self.config['version']:
|
||||
return route.fulfill(status=409, json={'detail': 'stale config'})
|
||||
self.config['version'] += 1
|
||||
if path.endswith('/weapp/switches'):
|
||||
for key in ['copy', 'flags', 'modules', 'vipEntries']:
|
||||
self.config.setdefault(key, {}).update(body.get(key, {}))
|
||||
elif path.endswith('/audience'):
|
||||
for lane in ['cn', 'intl']: self.audience[lane].update(body.get(lane, {}))
|
||||
elif path.endswith('/blog/ops'):
|
||||
for key, value in body.items():
|
||||
if key in ['note', 'heroLead']: self.blog['ops'][key] = value
|
||||
elif key != 'expectedVersion': self.blog[key] = value
|
||||
if path.endswith('/weapp/switches'): data = self.config
|
||||
elif path.endswith('/audience'): data = {**self.audience, 'version': self.config['version']}
|
||||
elif path.endswith('/config/meta'): data = {'version': self.config['version']}
|
||||
elif path.endswith('/blog/overview') or path.endswith('/blog/ops'): data = {**self.blog, 'version': self.config['version']}
|
||||
elif path.endswith('/orders') or path.endswith('/users'): data = []
|
||||
else: data = {'ok': True, 'items': [], 'messages': [], 'counts': {}, 'total': 0}
|
||||
route.fulfill(json=copy.deepcopy(data))
|
||||
|
||||
|
||||
def run_check(name, function):
|
||||
try:
|
||||
function()
|
||||
report['checks'].append({'name': name, 'passed': True})
|
||||
except Exception as error:
|
||||
report['checks'].append({'name': name, 'passed': False, 'error': str(error)[:1800]})
|
||||
print(json.dumps(report['checks'][-1], ensure_ascii=False), flush=True)
|
||||
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch()
|
||||
|
||||
def scenario(path, callback):
|
||||
backend = Backend()
|
||||
context = browser.new_context(viewport={'width': 1440, 'height': 1000})
|
||||
context.add_init_script("localStorage.setItem('nomadro_admin_com_token', 'mock-admin-token')")
|
||||
context.route('**/api/**', backend.route)
|
||||
page = context.new_page()
|
||||
page.set_default_timeout(10000)
|
||||
page.set_default_navigation_timeout(45000)
|
||||
page.on('pageerror', lambda error: report['pageErrors'].append(str(error)))
|
||||
page.on('dialog', lambda dialog: dialog.accept())
|
||||
try:
|
||||
page.goto(BASE + path, wait_until='domcontentloaded')
|
||||
page.locator('.com-page').wait_for()
|
||||
callback(page, backend)
|
||||
finally: context.close()
|
||||
|
||||
def price(page, backend):
|
||||
amount = page.locator('.com-pricing-form input[type=number]')
|
||||
chat = page.get_by_label('群聊可发句数')
|
||||
expect(amount).to_have_value('88')
|
||||
chat.fill('7')
|
||||
amount.fill('99')
|
||||
page.get_by_role('button', name='保存动态价格', exact=True).click()
|
||||
expect(page.get_by_role('status').filter(has_text='动态价格已更新')).to_be_visible()
|
||||
expect(chat).to_have_value('7')
|
||||
amount.fill('108')
|
||||
page.get_by_role('button', name='保存体验次数', exact=True).click()
|
||||
expect(page.get_by_role('status').filter(has_text='体验已保存')).to_be_visible()
|
||||
expect(amount).to_have_value('108')
|
||||
expect(chat).to_have_value('7')
|
||||
page.get_by_role('button', name='重置草稿', exact=True).click()
|
||||
expect(amount).to_have_value('99')
|
||||
amount.fill('')
|
||||
expect(page.get_by_role('button', name='保存动态价格', exact=True)).to_be_disabled()
|
||||
expect(amount).to_have_attribute('aria-invalid', 'true')
|
||||
page.get_by_role('button', name='重置草稿', exact=True).click()
|
||||
chat.fill('9')
|
||||
backend.config['version'] += 1
|
||||
expect(page.get_by_text('配置已在其他页面更新。请刷新后再保存,避免覆盖。')).to_be_visible(timeout=7000)
|
||||
expect(chat).to_have_value('9')
|
||||
expect(page.get_by_role('button', name='保存体验次数', exact=True)).to_be_disabled()
|
||||
page.screenshot(path=str(OUT / 'admin-draft-conflict-desktop.png'), full_page=True)
|
||||
|
||||
run_check('Pricing: independent drafts, numeric validation and live conflict retention', lambda: scenario('/intl/pricing', price))
|
||||
|
||||
def navigation(page, backend):
|
||||
field = page.locator('.com-pricing-form input[type=number]')
|
||||
expect(field).to_have_value('88')
|
||||
field.fill('99')
|
||||
page.locator('.com-nav a[href="/intl/orders"]').click()
|
||||
expect(page.get_by_role('dialog')).to_be_visible()
|
||||
page.get_by_role('button', name='继续编辑', exact=True).click()
|
||||
expect(field).to_have_value('99')
|
||||
page.get_by_role('button', name='退出', exact=True).click()
|
||||
expect(page.get_by_role('dialog')).to_be_visible()
|
||||
page.keyboard.press('Escape')
|
||||
assert page.evaluate("localStorage.getItem('nomadro_admin_com_token')") == 'mock-admin-token'
|
||||
page.locator('.com-nav a[href="/intl/orders"]').click()
|
||||
page.get_by_role('button', name='放弃修改并离开', exact=True).click()
|
||||
expect(page).to_have_url(BASE + '/intl/orders')
|
||||
|
||||
run_check('Navigation: cancel, Escape, discard and logout keep the correct session', lambda: scenario('/intl/pricing', navigation))
|
||||
|
||||
def switches(page, backend):
|
||||
page.get_by_role('button', name='文案', exact=True).click()
|
||||
lead = page.get_by_label('导语', exact=True)
|
||||
expect(lead).to_have_value('Original lead')
|
||||
lead.fill('Unpublished draft')
|
||||
page.get_by_role('button', name='功能', exact=True).click()
|
||||
page.get_by_label('支付总开关', exact=True).click()
|
||||
expect(page.get_by_role('status').filter(has_text='支付总开关已关闭')).to_be_visible()
|
||||
page.get_by_role('button', name='文案', exact=True).click()
|
||||
expect(lead).to_have_value('Unpublished draft')
|
||||
backend.failure = 'malformed'
|
||||
page.get_by_role('button', name='保存文案', exact=True).click()
|
||||
expect(page.get_by_role('alert')).to_contain_text('服务返回异常')
|
||||
expect(lead).to_have_value('Unpublished draft')
|
||||
page.get_by_role('button', name='保存文案', exact=True).click()
|
||||
expect(page.get_by_role('status').filter(has_text='文案已保存')).to_be_visible()
|
||||
|
||||
run_check('Switches: partial save preserves copy, malformed response fails visibly, retry works', lambda: scenario('/intl/switches', switches))
|
||||
|
||||
def audience(page, backend):
|
||||
field = page.get_by_label('首页导语', exact=True)
|
||||
expect(field).to_have_value('Original lead')
|
||||
field.fill('Keep this audience draft')
|
||||
page.get_by_label('pay', exact=True).click()
|
||||
expect(page.get_by_role('status').filter(has_text='支付已关')).to_be_visible()
|
||||
expect(field).to_have_value('Keep this audience draft')
|
||||
backend.failure = 'conflict'
|
||||
page.get_by_role('button', name='保存文案', exact=True).click()
|
||||
expect(page.get_by_role('alert')).to_contain_text('配置已更新')
|
||||
expect(field).to_have_value('Keep this audience draft')
|
||||
|
||||
run_check('Audience: toggle and failed save preserve copy, sends expected version', lambda: scenario('/intl/audience', audience))
|
||||
|
||||
def blog(page, backend):
|
||||
page.get_by_role('button', name='模块 / 文案', exact=True).click()
|
||||
note = page.get_by_label('运营备注(仅后台)', exact=True)
|
||||
expect(note).to_have_value('')
|
||||
note.fill('Unpublished blog note')
|
||||
page.get_by_label('博客模块开关', exact=True).click()
|
||||
expect(page.get_by_role('status').filter(has_text='Blog 模块已关')).to_be_visible()
|
||||
expect(note).to_have_value('Unpublished blog note')
|
||||
page.get_by_role('button', name='AdSense', exact=True).click()
|
||||
page.get_by_label('clientId (ca-pub-…)', exact=True).fill('invalid')
|
||||
before = len(backend.mutations)
|
||||
page.get_by_role('button', name='保存 AdSense', exact=True).click()
|
||||
expect(page.get_by_role('alert')).to_contain_text('clientId 应为')
|
||||
assert len(backend.mutations) == before
|
||||
page.set_viewport_size({'width': 390, 'height': 844})
|
||||
page.locator('.com-topbar-menu').click()
|
||||
page.locator('.com-nav a[href="/intl/orders"]').click()
|
||||
expect(page.get_by_role('dialog')).to_be_visible()
|
||||
assert page.evaluate('document.documentElement.scrollWidth <= innerWidth + 1')
|
||||
page.screenshot(path=str(OUT / 'admin-unsaved-mobile.png'), full_page=True)
|
||||
|
||||
run_check('Blog: partial draft retention, client validation, mobile exit dialog', lambda: scenario('/intl/blog', blog))
|
||||
browser.close()
|
||||
|
||||
(OUT / 'admin-editing.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print(json.dumps(report, ensure_ascii=False))
|
||||
raise SystemExit(0 if all(row['passed'] for row in report['checks']) and not report['pageErrors'] else 1)
|
||||
38
scripts/check-live-uiux-com.py
Normal file
38
scripts/check-live-uiux-com.py
Normal file
@ -0,0 +1,38 @@
|
||||
"""Read-only browser check of real service responses on the deployed US portal."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
sys.stdout.reconfigure(encoding='utf-8', line_buffering=True)
|
||||
OUT = Path(__file__).resolve().parents[1] / 'artifacts/uiux-upgrade'
|
||||
report = {'checks': [], 'pageErrors': [], 'apiErrors': []}
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch()
|
||||
context = browser.new_context(viewport={'width': 390, 'height': 844}, locale='en-US')
|
||||
page = context.new_page()
|
||||
page.on('pageerror', lambda error: report['pageErrors'].append(str(error)))
|
||||
page.on('response', lambda response: report['apiErrors'].append({'path': response.url.split('?')[0], 'status': response.status})
|
||||
if response.status >= 500 and '/api/' in response.url else None)
|
||||
for path, selector in [
|
||||
('/notifications', '.ntf-empty'),
|
||||
('/notifications/settings', '.ntf-quiet-fields input'),
|
||||
('/social/coffeechat', '.cf-empty'),
|
||||
('/social/coffeechat/manage', '.cf-form input'),
|
||||
]:
|
||||
try:
|
||||
response = page.goto('https://nomadro.com' + path, wait_until='domcontentloaded', timeout=45000)
|
||||
page.locator(selector).first.wait_for(timeout=30000)
|
||||
errors = page.locator('.ntf-error,.cf-error').all_text_contents()
|
||||
report['checks'].append({'path': path, 'status': response.status, 'errors': errors,
|
||||
'overflow': page.evaluate('document.documentElement.scrollWidth > innerWidth + 1')})
|
||||
except Exception as error:
|
||||
report['checks'].append({'path': path, 'errors': [str(error)]})
|
||||
page.evaluate('window.scrollTo(0, 0)')
|
||||
page.screenshot(path=str(OUT / ('live' + path.replace('/', '-') + '.png')), full_page=True)
|
||||
browser.close()
|
||||
(OUT / 'live-services-browser.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print(json.dumps(report, ensure_ascii=False))
|
||||
assert not report['pageErrors'] and not report['apiErrors'] and all(
|
||||
item.get('status') == 200 and not item['errors'] and not item.get('overflow') for item in report['checks']
|
||||
)
|
||||
189
scripts/check-portal-uiux.py
Normal file
189
scripts/check-portal-uiux.py
Normal file
@ -0,0 +1,189 @@
|
||||
"""Production-build interaction checks. Every browser API call is mocked."""
|
||||
import copy
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
from playwright.sync_api import sync_playwright, expect
|
||||
|
||||
sys.stdout.reconfigure(encoding='utf-8', line_buffering=True)
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / 'artifacts/uiux-upgrade'
|
||||
BASE = sys.argv[1] if len(sys.argv) > 1 else 'http://localhost:3008'
|
||||
report = {'base': BASE, 'checks': [], 'pageErrors': []}
|
||||
guest = 'uiux-browser-test'
|
||||
host = {'id': 'host-test', 'username': 'test-host', 'name': 'Test Host', 'timezone': 'Pacific/Kiritimati', 'bio': 'Coffee together', 'city': 'Chengdu', 'event_count': 1}
|
||||
event = {'id': 'event-test', 'slug': '30min', 'title': 'Test coffee', 'length_minutes': 30, 'host': host, 'locations': []}
|
||||
booking = {'id': 'booking-test', 'uid': 'calendar-test', 'status': 'accepted', 'title': '咖啡, test; calendar', 'host': host, 'attendee': {'name': 'Visitor', 'device': guest, 'email': 'visitor@example.test'}, 'start': '2030-01-15T14:00:00Z', 'end': '2030-01-15T14:30:00Z', 'notes': 'First line\nSecond line', 'location': 'Cafe'}
|
||||
|
||||
|
||||
class Backend:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
self.conflict = False
|
||||
self.fail = False
|
||||
self.saved = None
|
||||
self.schedule = {'availability': [], 'timezone': 'UTC'}
|
||||
self.channels = {'in_app': True, 'email': True, 'timezone': 'UTC', 'quiet_start': '22:00', 'quiet_end': '08:00'}
|
||||
self.messages = [{'id': 'message-test', 'category': 'system', 'subject': 'Test notice', 'body': 'Test body', 'created_at': '2026-11-01T12:00:00Z', 'read': False}]
|
||||
|
||||
def route(self, route):
|
||||
req = route.request
|
||||
parsed = urlparse(req.url); path = parsed.path
|
||||
if not path.startswith('/api/'): return route.continue_()
|
||||
body = req.post_data_json if req.post_data and req.method in ['POST', 'PUT', 'PATCH'] else {}
|
||||
self.calls.append({'path': path, 'method': req.method, 'body': body, 'headers': req.headers, 'query': parse_qs(parsed.query)})
|
||||
mutation = req.method in ['POST', 'PUT', 'PATCH', 'DELETE']
|
||||
if mutation and (path.startswith('/api/coffee/') or path.startswith('/api/notify/')):
|
||||
if self.fail:
|
||||
self.fail = False
|
||||
return route.fulfill(status=503, json={'error': 'temporary_failure'})
|
||||
if path.startswith('/api/config'):
|
||||
if path.endswith('/stream'): return route.fulfill(content_type='text/event-stream', body=': mock\n\n')
|
||||
return route.fulfill(json={'version': 999999, 'flags': {'socialTrialEnabled': False}, 'copy': {'socialTrial': {'enabled': False}}, 'modules': {'social': True}})
|
||||
if path.startswith('/api/coffee/v1/'):
|
||||
suffix = path.removeprefix('/api/coffee/v1')
|
||||
if suffix == '/me':
|
||||
if req.method == 'PUT': self.saved = {**host, **body, 'username': guest}
|
||||
data = {'host': self.saved, 'schedule': self.schedule}
|
||||
elif suffix.endswith('/schedule') and mutation:
|
||||
self.schedule.update(body); data = {'schedule': self.schedule}
|
||||
elif suffix == '/hosts': data = {'hosts': [host]}
|
||||
elif suffix.endswith('/slots'):
|
||||
day = parse_qs(parsed.query)['day'][0]
|
||||
data = {'timezone': host['timezone'], 'day': day, 'slots': [{'start': day + 'T20:00:00Z', 'end': day + 'T20:30:00Z', 'local': '10:00'}]}
|
||||
elif suffix.endswith('/event-types/30min'): data = {'event_type': event}
|
||||
elif suffix == '/bookings' and mutation:
|
||||
if self.conflict:
|
||||
self.conflict = False
|
||||
return route.fulfill(status=409, json={'detail': 'slot_unavailable'})
|
||||
data = {'booking': booking}
|
||||
elif suffix == '/bookings': data = {'bookings': []}
|
||||
elif suffix.endswith('/cancel'): data = {'booking': {**booking, 'status': 'cancelled'}}
|
||||
elif suffix.startswith('/bookings/'): data = {'booking': booking}
|
||||
else: data = {'host': {**host, 'event_types': [event]}}
|
||||
return route.fulfill(json={'ok': True, **data})
|
||||
if path.startswith('/api/notify/v1/'):
|
||||
if path.endswith('/preferences'):
|
||||
if mutation: self.channels.update(body.get('channels', {}))
|
||||
data = {'preferences': {'subscriber_id': guest, 'channels': self.channels}}
|
||||
elif path.endswith('/read-all'):
|
||||
self.messages = [{**m, 'read': True} for m in self.messages]
|
||||
data = {'updated': 1, 'unread': 0}
|
||||
elif req.method == 'DELETE':
|
||||
self.messages = []; data = {}
|
||||
else: data = {'messages': self.messages, 'unread': sum(not m['read'] for m in self.messages), 'unread_by_category': {'system': sum(not m['read'] for m in self.messages)}}
|
||||
return route.fulfill(json={'ok': True, **data})
|
||||
route.fulfill(json={'ok': True, 'items': [], 'item': None, 'peers': [], 'enabled': False})
|
||||
|
||||
|
||||
with sync_playwright() as pw:
|
||||
browser = pw.chromium.launch()
|
||||
def run(name, path, callback, width=390):
|
||||
context = browser.new_context(viewport={'width': width, 'height': 900}, locale='en-US', timezone_id='America/Los_Angeles', reduced_motion='reduce')
|
||||
context.add_init_script("localStorage.setItem('nomadro-social:guest-id', JSON.stringify('uiux-browser-test')); localStorage.setItem('userEmail','visitor@example.test'); localStorage.setItem('userName','Visitor'); localStorage.setItem('nomadro_web_remote_config_v2', JSON.stringify({config:{version:999999,flags:{socialTrialEnabled:false},copy:{socialTrial:{enabled:false}}}}))")
|
||||
backend = Backend()
|
||||
context.route('**/api/**', backend.route)
|
||||
page = context.new_page(); page.set_default_timeout(10000)
|
||||
page.set_default_navigation_timeout(45000)
|
||||
page.on('pageerror', lambda e: report['pageErrors'].append(str(e)))
|
||||
page.on('dialog', lambda d: d.accept())
|
||||
try:
|
||||
page.goto(BASE + path, wait_until='domcontentloaded')
|
||||
callback(page, backend)
|
||||
assert page.evaluate('document.documentElement.scrollWidth <= innerWidth + 1'), 'horizontal overflow'
|
||||
page.evaluate('window.scrollTo(0, 0)')
|
||||
page.screenshot(path=str(OUT / (name + '.png')), full_page=True)
|
||||
report['checks'].append({'name': name, 'passed': True})
|
||||
except Exception as error:
|
||||
report['checks'].append({'name': name, 'passed': False, 'error': str(error)[:1500]})
|
||||
(OUT / (name + '-failure.txt')).write_text(page.locator('body').inner_text(), encoding='utf-8')
|
||||
finally: context.close()
|
||||
print(json.dumps(report['checks'][-1], ensure_ascii=False))
|
||||
|
||||
def book_flow(page, backend):
|
||||
expect(page.locator('.cf-day')).to_have_count(14)
|
||||
expected = (datetime.now(timezone.utc) + timedelta(hours=14)).date().isoformat()
|
||||
expect(page.locator('.cf-day').first).to_have_attribute('aria-label', expected)
|
||||
page.locator('.cf-slot').first.click()
|
||||
page.locator('.cf-form input[autocomplete=name]').fill('Visitor')
|
||||
page.locator('.cf-form input[type=email]').fill('invalid')
|
||||
submit = page.locator('.cf-form button[type=submit]')
|
||||
submit.click()
|
||||
assert not [c for c in backend.calls if c['path'].endswith('/bookings') and c['method'] == 'POST']
|
||||
page.locator('.cf-form input[type=email]').fill('visitor@example.test')
|
||||
backend.conflict = True
|
||||
submit.click()
|
||||
expect(page.locator('.cf-error')).to_contain_text(re.compile('no longer available|重新选择'))
|
||||
expect(submit).to_be_disabled()
|
||||
page.locator('.cf-slot').first.click()
|
||||
submit.click()
|
||||
expect(page).to_have_url(re.compile('/bookings/booking-test'))
|
||||
expect(page.locator('.cf-panel')).to_contain_text('Visitor')
|
||||
calls = [c for c in backend.calls if c['path'].endswith('/bookings') and c['method'] == 'POST']
|
||||
assert len(calls) == 2
|
||||
assert calls[0]['headers']['x-social-guest-id'] == guest
|
||||
assert len(calls[0]['headers']['x-coffee-key']) == 64
|
||||
with page.expect_download() as download:
|
||||
page.get_by_role('button', name=re.compile('Add to calendar|添加到日历')).click()
|
||||
text = Path(download.value.path()).read_text(encoding='utf-8')
|
||||
assert 'DTSTART:20300115T140000Z' in text and 'SUMMARY:咖啡\\, test\\; calendar' in text
|
||||
page.get_by_role('button', name=re.compile('Cancel booking|取消预约')).click()
|
||||
expect(page.locator('.cf-panel')).to_contain_text('cancelled')
|
||||
|
||||
run('coffee-booking-mobile', '/social/coffeechat/test-host/30min', book_flow)
|
||||
|
||||
def manage(page, backend):
|
||||
expect(page.locator('.cf-form input[autocomplete=name]')).to_be_visible()
|
||||
page.locator('.cf-form input[autocomplete=name]').fill('New host')
|
||||
page.locator('.cf-form input[placeholder="Asia/Shanghai"]').fill('UTC')
|
||||
page.locator('.cf-form button[type=submit]').click()
|
||||
expect(page.get_by_role('link', name=re.compile('Public booking page|公开预约页'))).to_be_visible()
|
||||
page.get_by_role('button', name=re.compile('Add window|添加时段')).click()
|
||||
page.get_by_role('button', name=re.compile('Save availability|保存可约时间')).click()
|
||||
expect(page.get_by_role('status').filter(has_text=re.compile('Availability updated|可约时间已更新'))).to_be_visible()
|
||||
assert backend.schedule['availability'][0]['startTime'] == 600
|
||||
run('coffee-management-desktop', '/social/coffeechat/manage', manage, 1440)
|
||||
|
||||
def preferences(page, backend):
|
||||
timezone_input = page.locator('.ntf-quiet-fields input[type=text]')
|
||||
expect(timezone_input).to_have_value('UTC')
|
||||
timezone_input.fill('Asia/Shanghai')
|
||||
assert not [c for c in backend.calls if c['method'] == 'PUT']
|
||||
page.locator('#dnd').click()
|
||||
expect(page.locator('#dnd')).to_be_checked()
|
||||
expect(timezone_input).to_have_value('Asia/Shanghai')
|
||||
save = page.get_by_role('button', name=re.compile('Save quiet hours|保存静默时段'))
|
||||
backend.fail = True
|
||||
save.click()
|
||||
expect(page.locator('.ntf-error')).to_be_visible()
|
||||
expect(timezone_input).to_have_value('Asia/Shanghai')
|
||||
save.click()
|
||||
expect(save).to_be_disabled()
|
||||
assert timezone_input.bounding_box()['width'] >= 200, 'quiet hours input must remain usable on mobile'
|
||||
assert save.bounding_box()['height'] < 80, 'save button must not wrap vertically'
|
||||
assert backend.channels['timezone'] == 'Asia/Shanghai' and backend.channels['dnd']
|
||||
assert all(c['headers'].get('x-social-guest-id') == guest for c in backend.calls if c['path'].startswith('/api/notify/'))
|
||||
run('notification-preferences-mobile', '/notifications/settings', preferences)
|
||||
|
||||
def inbox(page, backend):
|
||||
expect(page.locator('.ntf-card h2')).to_have_text('Test notice')
|
||||
page.get_by_role('tab', name=re.compile('System|系统')).click()
|
||||
backend.fail = True
|
||||
page.locator('.ntf-card-actions button').last.click()
|
||||
expect(page.locator('.ntf-error')).to_be_visible()
|
||||
expect(page.locator('.ntf-card')).to_have_count(1)
|
||||
page.get_by_role('button', name=re.compile('Mark category read|本类全部已读')).click()
|
||||
expect(page.locator('.ntf-card.is-unread')).to_have_count(0)
|
||||
call = next(c for c in backend.calls if c['path'].endswith('/read-all'))
|
||||
assert call['body']['subscriber_id'] == guest and call['body']['category'] == 'system'
|
||||
page.locator('.ntf-card-actions button').last.click()
|
||||
expect(page.locator('.ntf-card')).to_have_count(0)
|
||||
run('notification-inbox-desktop', '/notifications', inbox, 1440)
|
||||
browser.close()
|
||||
|
||||
(OUT / 'portal-interactions.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print(json.dumps(report, ensure_ascii=False))
|
||||
raise SystemExit(0 if all(item['passed'] for item in report['checks']) and not report['pageErrors'] else 1)
|
||||
98
scripts/check-services-pocketbase.py
Normal file
98
scripts/check-services-pocketbase.py
Normal file
@ -0,0 +1,98 @@
|
||||
"""Run with the VPS Python venv and PB binary against a disposable empty database."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from urllib.request import urlopen
|
||||
from unittest.mock import patch
|
||||
|
||||
binary, services = sys.argv[1:3]
|
||||
with socket.socket() as sock:
|
||||
sock.bind(('127.0.0.1', 0))
|
||||
port = sock.getsockname()[1]
|
||||
email, password = 'isolated@example.test', secrets.token_hex(32)
|
||||
report = []
|
||||
with tempfile.TemporaryDirectory(prefix='nomadro-pb-check-') as temporary:
|
||||
directory = Path(temporary)
|
||||
migration = subprocess.run([binary, 'migrate', 'up', '--dir=' + temporary], capture_output=True, input=b'')
|
||||
assert migration.returncode == 0 and b'Error:' not in migration.stdout, 'isolated PocketBase schema initialization failed'
|
||||
setup = subprocess.run([binary, 'admin', 'create', email, password, '--dir=' + temporary], capture_output=True)
|
||||
assert setup.returncode == 0 and b'Error:' not in setup.stdout, 'isolated PocketBase admin setup failed'
|
||||
with (directory / 'server.log').open('wb') as log:
|
||||
process = subprocess.Popen([binary, 'serve', '--http=127.0.0.1:' + str(port), '--dir=' + temporary], stdout=log, stderr=log)
|
||||
try:
|
||||
for attempt in range(40):
|
||||
try:
|
||||
with urlopen(f'http://127.0.0.1:{port}/api/health', timeout=1) as res:
|
||||
if res.status == 200: break
|
||||
except OSError: time.sleep(0.25)
|
||||
else: raise RuntimeError('isolated PocketBase did not start')
|
||||
os.environ.update(PB_INTERNAL_URL=f'http://127.0.0.1:{port}', PB_ADMIN_EMAIL=email, PB_ADMIN_PASSWORD=password,
|
||||
PB_URL=f'http://127.0.0.1:{port}', POCKETBASE_URL=f'http://127.0.0.1:{port}',
|
||||
POCKETBASE_INTERNAL_URL=f'http://127.0.0.1:{port}', POCKETBASE_EMAIL=email, POCKETBASE_PASSWORD=password,
|
||||
COFFEE_SEED_DEMO='0', NOTIFY_INTERNAL_TOKEN='isolated-test-token')
|
||||
sys.path.insert(0, services)
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from coffee_svc.routers.api import router as coffee_router
|
||||
from coffee_svc import store as coffee
|
||||
from notify_svc.routers.api import router as notify_router
|
||||
from notify_svc import store as notify
|
||||
from nomadro_pb import get_pb
|
||||
assert get_pb().base_url == f'http://127.0.0.1:{port}', 'integration checks must use the isolated server'
|
||||
# Explicit credentials also support older deployed config loaders.
|
||||
get_pb().email = email
|
||||
get_pb().password = password
|
||||
coffee.init_db(); notify.init_db()
|
||||
app = FastAPI()
|
||||
app.include_router(coffee_router, prefix='/api/coffee/v1')
|
||||
app.include_router(notify_router, prefix='/api/notify/v1')
|
||||
def valid(response, status=200):
|
||||
assert response.status_code == status, f'Expected {status}, got {response.status_code}: {response.text[:200]}'
|
||||
return response.json()
|
||||
with TestClient(app) as client, patch('social_svc.notify_bridge.notify_coffee_invite'):
|
||||
host = {'X-Social-Guest-Id': 'isolated-host', 'X-Coffee-Key': 'a' * 64}
|
||||
guest = {'X-Social-Guest-Id': 'isolated-attendee', 'X-Coffee-Key': 'b' * 64}
|
||||
valid(client.put('/api/coffee/v1/me', headers=host, json={'name': 'Isolated host', 'timezone': 'America/New_York'}))
|
||||
valid(client.get('/api/coffee/v1/me', headers=host))
|
||||
valid(client.put('/api/coffee/v1/me', headers={**host, 'X-Coffee-Key': 'c' * 64}, json={'name': 'Untrusted', 'timezone': 'UTC'}), 403)
|
||||
valid(client.patch('/api/coffee/v1/hosts/isolated-host/schedule', headers=host, json={'availability': [{'days': ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'], 'startTime': 600, 'endTime': 660}]}))
|
||||
day = (datetime.now(timezone.utc) + timedelta(days=2)).date().isoformat()
|
||||
slots_url = '/api/coffee/v1/hosts/isolated-host/event-types/30min/slots?day=' + day
|
||||
slots = valid(client.get(slots_url))['slots']
|
||||
assert len(slots) == 2
|
||||
body = {'username': 'isolated-host', 'event_slug': '30min', 'start': slots[0]['start'], 'attendee_name': 'Isolated attendee'}
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
responses = list(pool.map(lambda _: client.post('/api/coffee/v1/bookings', headers=guest, json=body), range(4)))
|
||||
assert sorted(response.status_code for response in responses) == [200,409,409,409]
|
||||
booking = next(response.json()['booking'] for response in responses if response.status_code == 200)
|
||||
assert len(valid(client.get('/api/coffee/v1/bookings', headers=guest))['bookings']) == 1
|
||||
assert len(valid(client.get('/api/coffee/v1/bookings?host=isolated-host', headers=host))['bookings']) == 1
|
||||
valid(client.post('/api/coffee/v1/bookings/' + booking['id'] + '/cancel', headers=guest))
|
||||
assert len(valid(client.get(slots_url))['slots']) == 2
|
||||
report.append('coffee: real persistence, private ownership, availability, concurrent conflict, list, cancellation')
|
||||
valid(client.put('/api/notify/v1/subscribers/isolated-attendee/preferences', headers=guest, json={'channels': {'timezone': 'UTC'}}))
|
||||
valid(client.get('/api/notify/v1/subscribers/isolated-attendee/preferences', headers=guest))
|
||||
valid(client.post('/api/notify/v1/events/trigger', headers={'X-Notify-Internal-Token': 'isolated-test-token'}, json={'workflow_id': 'welcome', 'subscriber_id': 'isolated-attendee'}))
|
||||
inbox = valid(client.get('/api/notify/v1/inbox?subscriber_id=isolated-attendee', headers=guest))
|
||||
assert len(inbox['messages']) == 1
|
||||
valid(client.post('/api/notify/v1/inbox/read-all', headers=guest, json={'subscriber_id': 'isolated-attendee'}))
|
||||
valid(client.delete('/api/notify/v1/inbox/' + inbox['messages'][0]['id'], headers=guest))
|
||||
assert valid(client.get('/api/notify/v1/inbox?subscriber_id=isolated-attendee', headers=guest))['messages'] == []
|
||||
report.append('notify: real preferences, internal in-app trigger, inbox, mark read, delete')
|
||||
for name in ['coffee_hosts','coffee_bookings','notify_subscribers','notify_messages']:
|
||||
schema = get_pb().get_collection(name)
|
||||
assert all(schema.get(rule) is None for rule in ['listRule','viewRule','createRule','updateRule','deleteRule'])
|
||||
report.append('PocketBase: private collection rules verified')
|
||||
finally:
|
||||
process.terminate()
|
||||
try: process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired: process.kill(); process.wait(timeout=5)
|
||||
print(json.dumps({'passed': True, 'checks': report, 'productionDataWritten': False}))
|
||||
@ -23,7 +23,7 @@ API_FILES = [
|
||||
'services/weapp_switches.py', 'services/config_live.py',
|
||||
'services/ntfy.py', 'services/track.py', 'services/social_ugc.py',
|
||||
]
|
||||
SOCIAL_FILES = ['pb_data.py', 'store.py', 'routers/api.py', 's3_upload.py']
|
||||
SOCIAL_FILES = ['pb_data.py', 'store.py', 'face_check.py', 'routers/api.py', 's3_upload.py']
|
||||
SOURCE_FILES = [
|
||||
'next.config.ts', 'src/middleware.ts', 'src/lib/service-proxy.ts', 'src/lib/admin-auth.ts',
|
||||
'src/lib/ntfy.ts', 'src/lib/ntfy-rich.ts',
|
||||
@ -90,7 +90,11 @@ def main():
|
||||
try:
|
||||
sftp.put(str(package), f'/tmp/nomadro-upgrade-{RELEASE}.tgz')
|
||||
finally: sftp.close()
|
||||
targets = [f'/opt/nomadmini/backend/app/{name}' for name in API_FILES] + [f'{PORTAL}/apps/api/services/social_svc/{name}' for name in SOCIAL_FILES]
|
||||
targets = (
|
||||
[f'/opt/nomadmini/backend/app/{name}' for name in API_FILES]
|
||||
+ [f'{PORTAL}/apps/api/services/social_svc/{name}' for name in SOCIAL_FILES]
|
||||
+ [f'/opt/nomadmini/backend/social_svc/{name}' for name in SOCIAL_FILES]
|
||||
)
|
||||
target_args = ' '.join(targets)
|
||||
try:
|
||||
run(client, f'''set -eu
|
||||
@ -109,6 +113,8 @@ test -f {STAGE}/portal/.next/BUILD_ID
|
||||
run(client, f'cp {STAGE}/api/{relative} /opt/nomadmini/backend/app/{relative}')
|
||||
for relative in SOCIAL_FILES:
|
||||
run(client, f'cp {STAGE}/social/{relative} {PORTAL}/apps/api/services/social_svc/{relative}')
|
||||
# admin.nomadro.com → :8010 imports /opt/nomadmini/backend/social_svc (not portal tree)
|
||||
run(client, f'mkdir -p /opt/nomadmini/backend/social_svc/$(dirname {relative}) && cp {STAGE}/social/{relative} /opt/nomadmini/backend/social_svc/{relative}')
|
||||
# Source parity for the legacy API tree and repository service tree.
|
||||
for relative in API_FILES:
|
||||
source = ROOT / 'apps/api/services/ebook_svc' / relative
|
||||
|
||||
@ -4,6 +4,7 @@ import json
|
||||
import runpy
|
||||
import tarfile
|
||||
import tempfile
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
deployment = runpy.run_path(str(Path(__file__).with_name('deploy_platform_upgrade_com.py')))
|
||||
@ -11,7 +12,15 @@ ROOT, PORTAL, RELEASE = (deployment[key] for key in ['ROOT', 'PORTAL', 'RELEASE'
|
||||
run = deployment['run']
|
||||
backup = deployment['BACKUP']
|
||||
stage = deployment['STAGE']
|
||||
sources = set(deployment['SOURCE_FILES'])
|
||||
for command in [
|
||||
['git', 'diff', '--name-only', '--', 'src'],
|
||||
['git', 'ls-files', '--others', '--exclude-standard', '--', 'src/lib', 'src/modules/coffee', 'src/modules/notify', 'src/modules/social'],
|
||||
]:
|
||||
sources.update(line for line in subprocess.check_output(command, cwd=ROOT, text=True, encoding='utf-8').splitlines() if (ROOT / line).is_file())
|
||||
deployment['SOURCE_FILES'] = sorted(sources)
|
||||
client = runpy.run_path(str(ROOT / 'apps/admin/deploy/_upload_next_us.py'))['connect']()
|
||||
assert client.get_transport().getpeername()[0] == '108.174.50.68', 'US host only'
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
package = Path(temporary) / 'portal.tgz'
|
||||
@ -51,6 +60,8 @@ done
|
||||
curl -fsS --max-time 15 https://nomadro.com/ >/dev/null
|
||||
curl -fsS --max-time 15 https://nomadro.com/social/chat >/dev/null
|
||||
curl -fsS --max-time 15 https://nomadro.com/notifications/settings >/dev/null
|
||||
curl -fsS --max-time 15 https://nomadro.com/api/coffee/v1/hosts >/dev/null
|
||||
curl -fsS --max-time 15 -H 'X-Social-Guest-Id: release-readonly-probe' 'https://nomadro.com/api/notify/v1/inbox?subscriber_id=release-readonly-probe' >/dev/null
|
||||
systemctl is-active nomadro
|
||||
cat .next/BUILD_ID
|
||||
''')
|
||||
|
||||
99
scripts/deploy_uiux_services_com.py
Normal file
99
scripts/deploy_uiux_services_com.py
Normal file
@ -0,0 +1,99 @@
|
||||
"""Focused US service release with backup and code/runtime rollback."""
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.stdout.reconfigure(encoding='utf-8', errors='replace', line_buffering=True)
|
||||
RELEASE = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
|
||||
PORTAL = '/var/www/nomadro.cn'
|
||||
BACKUP = f'/var/backups/nomadro-upgrade/uiux-{RELEASE}'
|
||||
STAGE = f'/var/tmp/nomadro-uiux-{RELEASE}'
|
||||
API_FILES = ['routers/audience_admin.py', 'routers/social_blog_admin.py', 'services/audience_config.py', 'services/social_blog_ops.py']
|
||||
|
||||
|
||||
def run(client, command, timeout=120):
|
||||
_, out, err = client.exec_command(command, timeout=timeout)
|
||||
output, error = out.read().decode('utf-8', 'replace'), err.read().decode('utf-8', 'replace')
|
||||
code = out.channel.recv_exit_status()
|
||||
if output.strip(): print(output.strip())
|
||||
if error.strip(): print(error.strip(), file=sys.stderr)
|
||||
if code: raise RuntimeError(f'remote step failed ({code})')
|
||||
|
||||
|
||||
def main():
|
||||
files = {}
|
||||
for domain in ['coffee_svc', 'notify_svc']:
|
||||
for source in (ROOT / 'apps/api/services' / domain).rglob('*.py'):
|
||||
files[PORTAL + '/' + source.relative_to(ROOT).as_posix()] = source.read_bytes()
|
||||
for name in ['coffee_main.py', 'notify_main.py', 'services/nomadro_pb/ensure.py', 'services/nomadro_pb/schemas.py', 'services/social_svc/notify_bridge.py', 'services/social_svc/onboarding.py']:
|
||||
files[PORTAL + '/apps/api/' + name] = (ROOT / 'apps/api' / name).read_bytes()
|
||||
for name in API_FILES:
|
||||
source = (ROOT / 'apps/api/services/ebook_svc' / name).read_text(encoding='utf-8')
|
||||
files['/opt/nomadmini/backend/app/' + name] = source.replace('ebook_svc.', 'app.').encode('utf-8')
|
||||
files[PORTAL + '/apps/api/services/ebook_svc/' + name] = source.encode('utf-8')
|
||||
manifest = list(files)
|
||||
client = runpy.run_path(str(ROOT / 'apps/admin/deploy/_upload_next_us.py'))['connect']()
|
||||
assert client.get_transport().getpeername()[0] == '108.174.50.68', 'US host only'
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
package = Path(temporary) / 'services.tgz'
|
||||
with tarfile.open(package, 'w:gz') as archive:
|
||||
for target, blob in files.items():
|
||||
info = tarfile.TarInfo(target.lstrip('/')); info.size = len(blob); info.mode = 0o644
|
||||
archive.addfile(info, io.BytesIO(blob))
|
||||
blob = json.dumps(manifest).encode()
|
||||
info = tarfile.TarInfo('manifest.json'); info.size = len(blob)
|
||||
archive.addfile(info, io.BytesIO(blob))
|
||||
archive.add(ROOT / 'apps/com/deploy/install-uiux-services.py', arcname='install.py')
|
||||
digest = hashlib.sha256(package.read_bytes()).hexdigest()
|
||||
with client.open_sftp() as sftp: sftp.put(str(package), f'/tmp/nomadro-uiux-{RELEASE}.tgz')
|
||||
run(client, f"mkdir -p {STAGE} {BACKUP} && chmod 700 {BACKUP} && echo '{digest} /tmp/nomadro-uiux-{RELEASE}.tgz' | sha256sum -c - && tar -xzf /tmp/nomadro-uiux-{RELEASE}.tgz -C {STAGE}")
|
||||
try:
|
||||
run(client, f'python3 {STAGE}/install.py {STAGE} {BACKUP}')
|
||||
run(client, f'''set -eu
|
||||
cd {PORTAL}/apps/api
|
||||
.venv-social/bin/python -c 'import coffee_main,notify_main; print("service imports OK")'
|
||||
cd /opt/nomadmini/backend
|
||||
.venv/bin/python -c 'from app.routers import audience_admin,social_blog_admin; print("config API imports OK")'
|
||||
systemctl daemon-reload
|
||||
systemctl enable nomadro-notify nomadro-coffee
|
||||
systemctl restart nomadro-notify nomadro-coffee
|
||||
for attempt in $(seq 1 30); do
|
||||
if curl -fsS --max-time 2 http://127.0.0.1:8023/api/notify/v1/health >/dev/null && curl -fsS --max-time 2 http://127.0.0.1:8024/api/coffee/v1/hosts >/dev/null; then break; fi
|
||||
sleep 1
|
||||
done
|
||||
curl -fsS --max-time 5 http://127.0.0.1:8023/api/notify/v1/health
|
||||
curl -fsS --max-time 5 http://127.0.0.1:8024/api/coffee/v1/hosts
|
||||
systemctl restart nomadmini-api nomadro-social
|
||||
systemctl is-active nomadro-notify nomadro-coffee nomadmini-api nomadro-social
|
||||
''')
|
||||
except Exception:
|
||||
run(client, f'''systemctl stop nomadro-notify nomadro-coffee
|
||||
python3 - <<'PY'
|
||||
import json,pathlib,shutil
|
||||
backup=pathlib.Path({BACKUP!r})
|
||||
manifest=backup/'manifest.json'
|
||||
for target,existed in json.loads(manifest.read_text()).items() if manifest.exists() else []:
|
||||
p=pathlib.Path(target)
|
||||
if existed: shutil.copy2(backup/'files'/target.lstrip('/'),p)
|
||||
elif p.is_file(): p.unlink()
|
||||
print('Code and runtime restored; database backup retained without overwriting user data.')
|
||||
PY
|
||||
systemctl daemon-reload
|
||||
systemctl restart nomadmini-api nomadro-social
|
||||
''')
|
||||
raise
|
||||
report = {'release': RELEASE, 'backup': BACKUP, 'sha256': digest, 'servicePorts': [8023, 8024], 'files': manifest, 'deployed': True}
|
||||
(ROOT / 'artifacts/uiux-upgrade/services-deployment.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
|
||||
print('SERVICES DEPLOYED', RELEASE)
|
||||
finally: client.close()
|
||||
|
||||
|
||||
if __name__ == '__main__': main()
|
||||
@ -134,7 +134,18 @@ export async function GET(req: NextRequest) {
|
||||
Number(req.nextUrl.searchParams.get("offset") || 0) || 0,
|
||||
);
|
||||
const store = await readStore();
|
||||
let rows = store.items.map(sanitizeLead).sort((a, b) =>
|
||||
// One row per email — collapse historical duplicates before paging.
|
||||
const byEmail = new Map<string, Lead>();
|
||||
for (const raw of store.items) {
|
||||
const lead = sanitizeLead(raw);
|
||||
const em = (lead.email || "").trim().toLowerCase();
|
||||
if (!em) continue;
|
||||
const prev = byEmail.get(em);
|
||||
if (!prev || (lead.updatedAt || "") >= (prev.updatedAt || "")) {
|
||||
byEmail.set(em, lead);
|
||||
}
|
||||
}
|
||||
let rows = [...byEmail.values()].sort((a, b) =>
|
||||
(b.updatedAt || "").localeCompare(a.updatedAt || ""),
|
||||
);
|
||||
if (q) {
|
||||
@ -232,9 +243,23 @@ export async function POST(req: NextRequest) {
|
||||
});
|
||||
store.items.unshift(lead);
|
||||
}
|
||||
// Collapse any leftover same-email rows in the local file.
|
||||
{
|
||||
const map = new Map<string, Lead>();
|
||||
for (const it of store.items) {
|
||||
const em = (it.email || "").trim().toLowerCase();
|
||||
if (!em) continue;
|
||||
const prev = map.get(em);
|
||||
if (!prev || (it.updatedAt || "") >= (prev.updatedAt || "")) map.set(em, it);
|
||||
}
|
||||
store.items = [...map.values()].sort((a, b) =>
|
||||
(b.updatedAt || "").localeCompare(a.updatedAt || ""),
|
||||
);
|
||||
}
|
||||
await writeStore(store);
|
||||
|
||||
// Forward to social_svc → PocketBase social_join_leads (local + .com)
|
||||
// Forward to social_svc → PocketBase. Only env-configured upstreams —
|
||||
// never hardcode nomadro.com (local QA was double-writing production leads).
|
||||
const bodies = JSON.stringify({
|
||||
email,
|
||||
stage,
|
||||
@ -251,15 +276,16 @@ export async function POST(req: NextRequest) {
|
||||
"X-Social-Guest-Id": guestId || "portal",
|
||||
};
|
||||
const upstreams = new Set<string>();
|
||||
for (const raw of [
|
||||
process.env.SOCIAL_API_URL,
|
||||
process.env.API_URL,
|
||||
"http://127.0.0.1:8080",
|
||||
"https://nomadro.com",
|
||||
]) {
|
||||
for (const raw of [process.env.SOCIAL_API_URL, process.env.API_URL]) {
|
||||
const base = (raw || "").replace(/\/$/, "");
|
||||
if (base) upstreams.add(base);
|
||||
}
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
upstreams.add("http://127.0.0.1:8080");
|
||||
}
|
||||
// Optional explicit mirror (ops only) — never implicit production hardcode.
|
||||
const mirror = (process.env.JOIN_LEAD_MIRROR_URL || "").replace(/\/$/, "");
|
||||
if (mirror) upstreams.add(mirror);
|
||||
for (const upstream of upstreams) {
|
||||
void fetch(`${upstream}/api/social/v1/join/leads`, {
|
||||
method: "POST",
|
||||
|
||||
@ -3,7 +3,8 @@ import "./hub.css";
|
||||
|
||||
import { type Metadata, type Viewport } from "next";
|
||||
import { Suspense } from "react";
|
||||
import { Noto_Sans_SC, Outfit } from "next/font/google";
|
||||
import { Noto_Sans_SC } from "next/font/google";
|
||||
import { outfit } from "~/lib/fonts";
|
||||
import { LocaleProvider } from "~/components/locale-provider";
|
||||
import {
|
||||
ThemeProvider,
|
||||
@ -69,13 +70,6 @@ export const metadata: Metadata = {
|
||||
},
|
||||
};
|
||||
|
||||
const outfit = Outfit({
|
||||
subsets: ["latin"],
|
||||
weight: ["400", "500", "600", "700", "800"],
|
||||
variable: "--font-outfit",
|
||||
display: "swap",
|
||||
});
|
||||
|
||||
const notoSansSC = Noto_Sans_SC({
|
||||
subsets: ["latin"],
|
||||
weight: ["300", "400", "500", "700"],
|
||||
|
||||
52
src/lib/client-request.ts
Normal file
52
src/lib/client-request.ts
Normal file
@ -0,0 +1,52 @@
|
||||
/** Shared browser transport for native work, notification and booking services. */
|
||||
export class RequestError extends Error {
|
||||
constructor(message: string, public readonly status: number) { super(message); this.name = 'RequestError' }
|
||||
}
|
||||
|
||||
export async function requestJson<T>(url: string, init: RequestInit = {}): Promise<T> {
|
||||
const zh = typeof document !== 'undefined' && document.documentElement.lang.startsWith('zh')
|
||||
const copy = (cn: string, en: string) => zh ? cn : en
|
||||
const controller = new AbortController()
|
||||
const abort = () => controller.abort(init.signal?.reason)
|
||||
init.signal?.addEventListener('abort', abort, { once: true })
|
||||
if (init.signal?.aborted) abort()
|
||||
const timer = setTimeout(() => controller.abort(), 20000)
|
||||
const headers = new Headers(init.headers)
|
||||
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json')
|
||||
try {
|
||||
const response = await fetch(url, { ...init, headers, signal: controller.signal, cache: 'no-store' })
|
||||
if (response.status === 204) return undefined as T
|
||||
let data: Record<string, unknown>
|
||||
try {
|
||||
data = await response.json()
|
||||
if (!data || typeof data !== 'object') throw new Error('invalid_response')
|
||||
} catch {
|
||||
if (controller.signal.aborted) throw new DOMException('Aborted', 'AbortError')
|
||||
throw new RequestError(copy('服务暂时不可用,请稍后重试。', 'The service is temporarily unavailable. Please try again.'), response.status)
|
||||
}
|
||||
if (!response.ok || data.ok === false) {
|
||||
const detail = typeof data.detail === 'string' ? data.detail : typeof data.error === 'string' ? data.error : ''
|
||||
const known: Record<string, string> = {
|
||||
booking_device_mismatch: copy('请使用创建预约时的浏览器和账号管理此预约。', 'Use the browser and account that created this booking to manage it.'),
|
||||
booking_device_required: copy('请启用浏览器本地存储后重试。', 'Please enable browser storage and try again.'),
|
||||
slot_unavailable: copy('这个时段刚被预约,请重新选择。', 'This slot is no longer available. Please choose another.'),
|
||||
host_not_found: copy('找不到这位主持人,请返回重新选择。', 'This host could not be found. Please choose another.'),
|
||||
event_type_not_found: copy('这个预约类型已不可用,请返回重新选择。', 'This event type is no longer available. Please choose another.'),
|
||||
booking_not_found: copy('找不到这条预约,请检查链接。', 'This booking could not be found. Please check the link.'),
|
||||
}
|
||||
const fallback = response.status === 422 || response.status === 400
|
||||
? copy('请检查填写内容后重试。', 'Please check your details and try again.')
|
||||
: copy('操作未完成,请稍后重试。', 'The action could not be completed. Please try again.')
|
||||
throw new RequestError(known[detail] || (detail && !/^[a-z_]+$/.test(detail) ? detail : fallback), response.status)
|
||||
}
|
||||
return data as T
|
||||
} catch (error) {
|
||||
if (init.signal?.aborted) throw error
|
||||
if (controller.signal.aborted) throw new RequestError(copy('请求超时。请重试;提交操作请先确认结果。', 'The request timed out. Please check the result before submitting again.'), 408)
|
||||
if (error instanceof TypeError) throw new RequestError(copy('网络连接失败,请检查网络后重试。', 'Connection failed. Please check your network and try again.'), 0)
|
||||
throw error
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
init.signal?.removeEventListener('abort', abort)
|
||||
}
|
||||
}
|
||||
9
src/lib/fonts.ts
Normal file
9
src/lib/fonts.ts
Normal file
@ -0,0 +1,9 @@
|
||||
import localFont from 'next/font/local';
|
||||
|
||||
// Same Outfit typeface; vendored OFL asset keeps builds independent of Google CSS URLs.
|
||||
export const outfit = localFont({
|
||||
src: './fonts/Outfit.ttf',
|
||||
weight: '100 900',
|
||||
variable: '--font-outfit',
|
||||
display: 'swap',
|
||||
});
|
||||
93
src/lib/fonts/OFL.txt
Normal file
93
src/lib/fonts/OFL.txt
Normal file
@ -0,0 +1,93 @@
|
||||
Copyright 2021 The Outfit Project Authors (https://github.com/Outfitio/Outfit-Fonts)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
BIN
src/lib/fonts/Outfit.ttf
Normal file
BIN
src/lib/fonts/Outfit.ttf
Normal file
Binary file not shown.
@ -145,11 +145,11 @@ export type SocialLiveFlags = {
|
||||
|
||||
export const DEFAULT_SOCIAL_LIVE: SocialLiveFlags = {
|
||||
presenceEnabled: true,
|
||||
presenceStrip: true,
|
||||
presenceStrip: false,
|
||||
presenceCityScope: true,
|
||||
discoveryAutoRefresh: true,
|
||||
discoveryRefreshSec: 45,
|
||||
configHotReloadToast: true,
|
||||
configHotReloadToast: false,
|
||||
offlineFallbackShell: true,
|
||||
hideNoFaceAvatar: true,
|
||||
livenessGate: true,
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { requireAdminSession } from './admin-auth';
|
||||
|
||||
/** Bounded bridge for native business services; never cache private responses. */
|
||||
export async function proxyService(req: NextRequest, options: {
|
||||
@ -9,12 +10,18 @@ export async function proxyService(req: NextRequest, options: {
|
||||
}) {
|
||||
const suffix = options.path.map(segment => encodeURIComponent(segment)).join('/');
|
||||
const target = `${options.upstream}${options.prefix}/${suffix}${new URL(req.url).search}`;
|
||||
const notifySelf = suffix === 'health' || suffix === 'inbox' || suffix.startsWith('inbox/') || /^subscribers\/[^/]+\/preferences$/.test(suffix);
|
||||
const notifyAdmin = options.service === 'notify' && !notifySelf;
|
||||
if (notifyAdmin && !await requireAdminSession()) {
|
||||
return NextResponse.json({ detail: 'admin_session_required' }, { status: 401, headers: { 'Cache-Control': 'no-store' } });
|
||||
}
|
||||
try {
|
||||
const headers = new Headers();
|
||||
for (const key of ['content-type', 'authorization', 'accept', 'x-request-id']) {
|
||||
for (const key of ['content-type', 'authorization', 'accept', 'x-request-id', 'x-social-guest-id', 'x-coffee-key']) {
|
||||
const value = req.headers.get(key);
|
||||
if (value) headers.set(key, value);
|
||||
}
|
||||
if (notifyAdmin && process.env.NOTIFY_INTERNAL_TOKEN) headers.set('X-Notify-Internal-Token', process.env.NOTIFY_INTERNAL_TOKEN);
|
||||
const response = await fetch(target, {
|
||||
method: req.method,
|
||||
headers,
|
||||
|
||||
@ -145,7 +145,18 @@ async function pull(force = false) {
|
||||
}
|
||||
inFlight = (async () => {
|
||||
const config = await fetchFullConfig();
|
||||
if (!config) return;
|
||||
if (!config) {
|
||||
// Keep last good config but surface offline so UI can fall back.
|
||||
if (!snapshot.fromOffline) {
|
||||
snapshot = {
|
||||
...snapshot,
|
||||
fromOffline: true,
|
||||
version: snapshot.version + 1,
|
||||
};
|
||||
emit();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!force &&
|
||||
Number(config.version) === knownVersion &&
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import SiteShell from "@social/components/SiteShell";
|
||||
@ -10,6 +10,8 @@ import { getGuestId } from "@social/lib/api";
|
||||
import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||
import { coffeeApi } from "../lib/api";
|
||||
import type { CoffeeEventType, CoffeeSlot } from "../lib/types";
|
||||
import { upcomingDays } from "../lib/calendar";
|
||||
import { RequestError } from "~/lib/client-request";
|
||||
import {
|
||||
canUseTrial,
|
||||
consumeTrial,
|
||||
@ -19,19 +21,6 @@ import {
|
||||
import { useSocialConfig } from "@social/components/SocialExperience";
|
||||
import "./coffee.css";
|
||||
|
||||
function upcomingDays(n = 14) {
|
||||
const out: { iso: string; label: string }[] = [];
|
||||
const now = new Date();
|
||||
for (let i = 0; i < n; i += 1) {
|
||||
const d = new Date(now);
|
||||
d.setDate(now.getDate() + i);
|
||||
const iso = d.toISOString().slice(0, 10);
|
||||
const label = `${d.getMonth() + 1}/${d.getDate()}`;
|
||||
out.push({ iso, label });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export default function CoffeeBookPage({
|
||||
username,
|
||||
slug,
|
||||
@ -44,9 +33,9 @@ export default function CoffeeBookPage({
|
||||
const router = useRouter();
|
||||
const config = useSocialConfig();
|
||||
const trialLimits = resolveTrialLimits(config);
|
||||
const days = useMemo(() => upcomingDays(14), []);
|
||||
const [day, setDay] = useState(days[0]?.iso || "");
|
||||
const [day, setDay] = useState("");
|
||||
const [et, setEt] = useState<CoffeeEventType | null>(null);
|
||||
const [metadataRetry, setMetadataRetry] = useState(0);
|
||||
const [slots, setSlots] = useState<CoffeeSlot[]>([]);
|
||||
const [tz, setTz] = useState("");
|
||||
const [slot, setSlot] = useState<CoffeeSlot | null>(null);
|
||||
@ -55,39 +44,70 @@ export default function CoffeeBookPage({
|
||||
const [notes, setNotes] = useState("");
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [loadingSlots, setLoadingSlots] = useState(false);
|
||||
const [slotsFor, setSlotsFor] = useState("");
|
||||
const slotRequest = useRef(0);
|
||||
const submitting = useRef(false);
|
||||
const hostZone = tz || et?.schedule?.timezone || et?.host?.timezone;
|
||||
const days = useMemo(() => {
|
||||
try { return hostZone ? upcomingDays(14, hostZone) : []; }
|
||||
catch { return []; }
|
||||
}, [hostZone]);
|
||||
const currentSlots = slotsFor === day ? slots : [];
|
||||
|
||||
useEffect(() => {
|
||||
if (days.length) setDay(current => days.some(d => d.iso === current) ? current : days[0].iso);
|
||||
}, [days]);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setEt(null);
|
||||
setTz("");
|
||||
setDay("");
|
||||
void coffeeApi
|
||||
.eventType(username, slug)
|
||||
.then((r) => setEt(r.event_type))
|
||||
.catch((e) => setErr(e instanceof Error ? e.message : String(e)));
|
||||
}, [username, slug]);
|
||||
.then((r) => { if (active) { setEt(r.event_type); setErr(null); } })
|
||||
.catch((e) => { if (active) setErr(e instanceof Error ? e.message : String(e)); });
|
||||
return () => { active = false; };
|
||||
}, [username, slug, metadataRetry]);
|
||||
|
||||
const loadSlots = useCallback(async () => {
|
||||
const loadSlots = useCallback(async (signal?: AbortSignal, preserveError = false) => {
|
||||
if (!day) return;
|
||||
setErr(null);
|
||||
const request = ++slotRequest.current;
|
||||
if (!preserveError) setErr(null);
|
||||
setSlot(null);
|
||||
setLoadingSlots(true);
|
||||
setSlots([]);
|
||||
try {
|
||||
const r = await coffeeApi.slots(username, slug, day);
|
||||
const r = await coffeeApi.slots(username, slug, day, signal);
|
||||
if (signal?.aborted || request !== slotRequest.current) return;
|
||||
setSlots(r.slots);
|
||||
setSlotsFor(day);
|
||||
setTz(r.timezone);
|
||||
} catch (e) {
|
||||
if (signal?.aborted || request !== slotRequest.current) return;
|
||||
setErr(e instanceof Error ? e.message : String(e));
|
||||
setSlots([]);
|
||||
} finally {
|
||||
if (!signal?.aborted && request === slotRequest.current) setLoadingSlots(false);
|
||||
}
|
||||
}, [username, slug, day]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadSlots();
|
||||
const controller = new AbortController();
|
||||
void loadSlots(controller.signal);
|
||||
return () => controller.abort();
|
||||
}, [loadSlots]);
|
||||
|
||||
async function submit() {
|
||||
if (!slot || !name.trim()) return;
|
||||
if (!slot || !name.trim() || submitting.current || loadingSlots || slotsFor !== day) return;
|
||||
if (!canUseTrial("coffeeBookings", trialLimits)) {
|
||||
setErr(socialTx(trialPaywallHint("coffeeBookings")));
|
||||
return;
|
||||
}
|
||||
submitting.current = true;
|
||||
setBusy(true);
|
||||
let booked = false;
|
||||
setErr(null);
|
||||
try {
|
||||
const loc = et?.locations?.[0]?.label;
|
||||
@ -102,12 +122,13 @@ export default function CoffeeBookPage({
|
||||
notes: notes.trim(),
|
||||
});
|
||||
consumeTrial("coffeeBookings", trialLimits);
|
||||
booked = true;
|
||||
router.push(socialPath(`/coffeechat/bookings/${res.booking.id}`));
|
||||
} catch (e) {
|
||||
setErr(e instanceof Error ? e.message : String(e));
|
||||
void loadSlots();
|
||||
if (e instanceof RequestError && e.status === 409) void loadSlots(undefined, true);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
if (!booked) { setBusy(false); submitting.current = false; }
|
||||
}
|
||||
}
|
||||
|
||||
@ -128,7 +149,9 @@ export default function CoffeeBookPage({
|
||||
{tz ? ` · ${tz}` : ""}
|
||||
</p>
|
||||
)}
|
||||
{err && <p className="cf-error">{err}</p>}
|
||||
{err && <p className="cf-error" role="alert">{err}</p>}
|
||||
{err && !et && <button type="button" className="cf-btn cf-btn-ghost" onClick={() => setMetadataRetry(value => value + 1)}>{zh ? '重新加载' : 'Retry'}</button>}
|
||||
{!et && !err && <p className="cf-hint" role="status">{zh ? '加载预约信息…' : 'Loading booking details…'}</p>}
|
||||
|
||||
<div className="cf-split">
|
||||
<section className="cf-panel">
|
||||
@ -140,8 +163,11 @@ export default function CoffeeBookPage({
|
||||
<button
|
||||
key={d.iso}
|
||||
type="button"
|
||||
aria-pressed={day === d.iso}
|
||||
aria-label={d.iso}
|
||||
disabled={busy}
|
||||
className={`cf-day${day === d.iso ? " is-active" : ""}`}
|
||||
onClick={() => setDay(d.iso)}
|
||||
onClick={() => { setSlot(null); setDay(d.iso); }}
|
||||
>
|
||||
{d.label}
|
||||
</button>
|
||||
@ -150,12 +176,17 @@ export default function CoffeeBookPage({
|
||||
<h2 style={{ margin: "0.5rem 0 0.75rem", fontFamily: "Syne, sans-serif", fontSize: "1.05rem" }}>
|
||||
{zh ? "可约时段" : "Available slots"}
|
||||
</h2>
|
||||
{!slots.length && <p className="cf-empty">{zh ? "这天没有空档" : "No slots this day"}</p>}
|
||||
<div className="cf-slots">
|
||||
{slots.map((s) => (
|
||||
{hostZone && <p className="cf-hint">{zh ? '以下日期和时段均为主持人当地时间' : 'Dates and times are shown in the host’s time zone'} · {hostZone}</p>}
|
||||
{loadingSlots && <p className="cf-empty" role="status">{zh ? '正在查找可约时段…' : 'Finding available slots…'}</p>}
|
||||
{!loadingSlots && day && !currentSlots.length && !err && <p className="cf-empty">{zh ? "这天没有空档,请换一个日期。" : "No slots this day. Please choose another date."}</p>}
|
||||
{err && day && <button type="button" className="cf-btn cf-btn-ghost" disabled={loadingSlots || busy} onClick={() => void loadSlots()}>{zh ? '重新加载时段' : 'Retry slots'}</button>}
|
||||
<div className="cf-slots" aria-busy={loadingSlots}>
|
||||
{currentSlots.map((s) => (
|
||||
<button
|
||||
key={s.start}
|
||||
type="button"
|
||||
aria-pressed={slot?.start === s.start}
|
||||
disabled={busy || loadingSlots}
|
||||
className={`cf-slot${slot?.start === s.start ? " is-active" : ""}`}
|
||||
onClick={() => setSlot(s)}
|
||||
>
|
||||
@ -176,33 +207,35 @@ export default function CoffeeBookPage({
|
||||
? "先选一个时段"
|
||||
: "Pick a slot first"}
|
||||
</p>
|
||||
<div className="cf-form">
|
||||
<form className="cf-form" onSubmit={event => { event.preventDefault(); void submit(); }}>
|
||||
<label>
|
||||
{zh ? "你的称呼" : "Your name"}
|
||||
<input value={name} onChange={(e) => setName(e.target.value)} required />
|
||||
<input value={name} onChange={(e) => setName(e.target.value)} required maxLength={120} autoComplete="name" disabled={busy} />
|
||||
</label>
|
||||
<label>
|
||||
Email
|
||||
<input
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
maxLength={254}
|
||||
disabled={busy}
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="optional"
|
||||
placeholder={zh ? '可选' : 'optional'}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{zh ? "备注" : "Notes"}
|
||||
<textarea value={notes} onChange={(e) => setNotes(e.target.value)} />
|
||||
<textarea value={notes} maxLength={2000} disabled={busy} onChange={(e) => setNotes(e.target.value)} />
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
type="submit"
|
||||
className="cf-btn cf-btn-primary"
|
||||
disabled={busy || !slot || !name.trim()}
|
||||
onClick={() => void submit()}
|
||||
disabled={busy || loadingSlots || slotsFor !== day || !slot || !name.trim()}
|
||||
>
|
||||
{zh ? "确认预约" : "Confirm booking"}
|
||||
{busy ? (zh ? '正在确认…' : 'Confirming…') : (zh ? "确认预约" : "Confirm booking")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import SiteShell from "@social/components/SiteShell";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
@ -10,6 +10,7 @@ import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||
import { coffeeApi } from "../lib/api";
|
||||
import type { CoffeeBooking } from "../lib/types";
|
||||
import CoffeeReviewForm from "./CoffeeReviewForm";
|
||||
import { bookingCalendar } from "../lib/calendar";
|
||||
import "./coffee.css";
|
||||
|
||||
export default function CoffeeBookingDetail({ id }: { id: string }) {
|
||||
@ -17,22 +18,59 @@ export default function CoffeeBookingDetail({ id }: { id: string }) {
|
||||
const zh = locale === "zh";
|
||||
const [booking, setBooking] = useState<CoffeeBooking | null>(null);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const cancelling = useRef(false);
|
||||
const me = typeof window !== "undefined" ? getGuestId() : "";
|
||||
|
||||
useEffect(() => {
|
||||
void coffeeApi
|
||||
.booking(id)
|
||||
.then((r) => setBooking(r.booking))
|
||||
.catch((e) => setErr(e instanceof Error ? e.message : String(e)));
|
||||
const load = useCallback(async (signal?: AbortSignal) => {
|
||||
setLoading(true);
|
||||
setErr(null);
|
||||
try {
|
||||
const result = await coffeeApi.booking(id, signal);
|
||||
if (!signal?.aborted) setBooking(result.booking);
|
||||
} catch (e) {
|
||||
if (!signal?.aborted) setErr(e instanceof Error ? e.message : String(e));
|
||||
} finally { if (!signal?.aborted) setLoading(false); }
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setBooking(null);
|
||||
void load(controller.signal);
|
||||
return () => controller.abort();
|
||||
}, [load]);
|
||||
|
||||
async function cancel() {
|
||||
const r = await coffeeApi.cancel(id);
|
||||
setBooking(r.booking);
|
||||
if (cancelling.current || !window.confirm(zh ? '确定取消这次预约?取消后时段将重新开放。' : 'Cancel this booking and release the slot?')) return;
|
||||
cancelling.current = true;
|
||||
setBusy(true);
|
||||
setErr(null);
|
||||
try {
|
||||
const r = await coffeeApi.cancel(id);
|
||||
setBooking(r.booking);
|
||||
} catch (e) { setErr(e instanceof Error ? e.message : String(e)); }
|
||||
finally { cancelling.current = false; setBusy(false); }
|
||||
}
|
||||
|
||||
function addToCalendar() {
|
||||
if (!booking) return;
|
||||
try {
|
||||
const url = URL.createObjectURL(new Blob([bookingCalendar(booking)], { type: 'text/calendar;charset=utf-8' }));
|
||||
const link = document.createElement('a');
|
||||
link.href = url; link.download = `nomadro-coffee-${booking.id.replace(/[^a-zA-Z0-9_-]/g, '')}.ics`;
|
||||
document.body.appendChild(link); link.click(); link.remove();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
} catch { setErr(zh ? '日程导出失败,请重新加载预约后重试。' : 'Calendar export failed. Please reload the booking and try again.'); }
|
||||
}
|
||||
|
||||
function formatTime(value: string) {
|
||||
const date = new Date(value);
|
||||
return Number.isFinite(date.getTime()) ? new Intl.DateTimeFormat(zh ? 'zh-CN' : 'en-US', { dateStyle: 'medium', timeStyle: 'short' }).format(date) : value;
|
||||
}
|
||||
|
||||
const hostGuest =
|
||||
booking?.host_id || booking?.host?.username || "";
|
||||
booking?.host?.username || booking?.host_id || "";
|
||||
const attendeeGuest = booking?.attendee.device || "";
|
||||
// Attendee reviews host; host reviews attendee when device guest matches me
|
||||
const reviewTarget =
|
||||
@ -43,9 +81,7 @@ export default function CoffeeBookingDetail({ id }: { id: string }) {
|
||||
guest: attendeeGuest,
|
||||
name: booking?.attendee.name || "",
|
||||
}
|
||||
: hostGuest
|
||||
? { guest: hostGuest, name: booking?.host?.name || "" }
|
||||
: null;
|
||||
: null;
|
||||
|
||||
return (
|
||||
<SiteShell title={socialTx("预约详情")}>
|
||||
@ -58,7 +94,9 @@ export default function CoffeeBookingDetail({ id }: { id: string }) {
|
||||
{zh ? "咖啡聊" : "Coffee"}
|
||||
</Link>
|
||||
</header>
|
||||
{err && <p className="cf-error">{err}</p>}
|
||||
{loading && <p className="cf-empty" role="status">{zh ? '正在加载预约…' : 'Loading booking…'}</p>}
|
||||
{err && <p className="cf-error" role="alert">{err}</p>}
|
||||
{err && !booking && <button type="button" className="cf-btn cf-btn-ghost" disabled={loading} onClick={() => void load()}>{zh ? '重试' : 'Retry'}</button>}
|
||||
{booking && (
|
||||
<section className="cf-panel">
|
||||
<div className="cf-meta">
|
||||
@ -71,8 +109,9 @@ export default function CoffeeBookingDetail({ id }: { id: string }) {
|
||||
{booking.title}
|
||||
</h2>
|
||||
<p className="cf-lead" style={{ margin: 0 }}>
|
||||
{booking.start} → {booking.end}
|
||||
<time dateTime={booking.start}>{formatTime(booking.start)}</time> → <time dateTime={booking.end}>{formatTime(booking.end)}</time>
|
||||
</p>
|
||||
<p className="cf-hint">{zh ? '显示为你的当地时间' : 'Shown in your local time'} · {Intl.DateTimeFormat().resolvedOptions().timeZone}</p>
|
||||
<p className="cf-hint">
|
||||
{zh ? "地点" : "Location"}: {booking.location || "—"}
|
||||
</p>
|
||||
@ -89,10 +128,11 @@ export default function CoffeeBookingDetail({ id }: { id: string }) {
|
||||
{booking.notes && <p className="cf-hint">{booking.notes}</p>}
|
||||
<div className="cf-cta" style={{ marginTop: "1rem" }}>
|
||||
{booking.status === "accepted" && (
|
||||
<button type="button" className="cf-btn cf-btn-ghost" onClick={() => void cancel()}>
|
||||
{zh ? "取消预约" : "Cancel booking"}
|
||||
<button type="button" className="cf-btn cf-btn-ghost" disabled={busy} onClick={() => void cancel()}>
|
||||
{busy ? (zh ? '取消中…' : 'Cancelling…') : (zh ? "取消预约" : "Cancel booking")}
|
||||
</button>
|
||||
)}
|
||||
{booking.status !== 'cancelled' && <button type="button" className="cf-btn cf-btn-ghost" onClick={addToCalendar}>{zh ? '添加到日历' : 'Add to calendar'}</button>}
|
||||
{booking.host?.username && (
|
||||
<Link
|
||||
className="cf-btn cf-btn-primary"
|
||||
@ -105,7 +145,7 @@ export default function CoffeeBookingDetail({ id }: { id: string }) {
|
||||
{zh ? "去视频厅" : "Video room"}
|
||||
</Link>
|
||||
</div>
|
||||
{reviewTarget && booking.status !== "cancelled" ? (
|
||||
{reviewTarget && booking.status !== "cancelled" && new Date(booking.end).getTime() <= Date.now() ? (
|
||||
<CoffeeReviewForm
|
||||
bookingId={booking.id}
|
||||
toGuest={reviewTarget.guest}
|
||||
|
||||
@ -15,13 +15,17 @@ export default function CoffeeHostPage({ username }: { username: string }) {
|
||||
const zh = locale === "zh";
|
||||
const [host, setHost] = useState<CoffeeHost | null>(null);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setHost(null); setErr(null);
|
||||
void coffeeApi
|
||||
.host(username)
|
||||
.then((r) => setHost(r.host))
|
||||
.catch((e) => setErr(e instanceof Error ? e.message : String(e)));
|
||||
}, [username]);
|
||||
.then((r) => { if (active) setHost(r.host); })
|
||||
.catch((e) => { if (active) setErr(e instanceof Error ? e.message : String(e)); });
|
||||
return () => { active = false; };
|
||||
}, [username, retry]);
|
||||
|
||||
return (
|
||||
<SiteShell title={socialTx("预约主持人")}>
|
||||
@ -34,7 +38,9 @@ export default function CoffeeHostPage({ username }: { username: string }) {
|
||||
{zh ? "全部主持人" : "All hosts"}
|
||||
</Link>
|
||||
</header>
|
||||
{err && <p className="cf-error">{err}</p>}
|
||||
{err && <p className="cf-error" role="alert">{err}</p>}
|
||||
{err && <button type="button" className="cf-btn cf-btn-ghost" onClick={() => setRetry(value => value + 1)}>{zh ? '重新加载' : 'Retry'}</button>}
|
||||
{!err && !host && <p className="cf-hint" role="status">{zh ? '加载中…' : 'Loading…'}</p>}
|
||||
{host && (
|
||||
<>
|
||||
<p className="cf-lead" style={{ marginTop: 0 }}>
|
||||
@ -45,6 +51,7 @@ export default function CoffeeHostPage({ username }: { username: string }) {
|
||||
<span>{host.timezone}</span>
|
||||
</div>
|
||||
<div className="cf-list">
|
||||
{!host.event_types?.length && <p className="cf-empty">{zh ? '目前尚未开放预约。' : 'Bookings are not open yet.'}</p>}
|
||||
{(host.event_types || []).map((e) => (
|
||||
<Link
|
||||
key={e.id}
|
||||
|
||||
@ -39,6 +39,8 @@ export default function CoffeeLanding() {
|
||||
const zh = locale === "zh";
|
||||
const [hosts, setHosts] = useState<CoffeeHost[]>([]);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [cityId, setCityId] = useState<string>("all");
|
||||
|
||||
const cities = useMemo(() => {
|
||||
@ -51,16 +53,19 @@ export default function CoffeeLanding() {
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
if (cityId === "all" || !activeCity) return hosts;
|
||||
const hit = hosts.filter((h) => cityMatch(h.city, activeCity));
|
||||
return hit.length ? hit : hosts;
|
||||
return hosts.filter((h) => cityMatch(h.city, activeCity));
|
||||
}, [hosts, cityId, activeCity]);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setLoading(true); setErr(null);
|
||||
void coffeeApi
|
||||
.hosts()
|
||||
.then((r) => setHosts(r.hosts))
|
||||
.catch((e) => setErr(e instanceof Error ? e.message : String(e)));
|
||||
}, []);
|
||||
.then((r) => { if (active) setHosts(r.hosts); })
|
||||
.catch((e) => { if (active) setErr(e instanceof Error ? e.message : String(e)); })
|
||||
.finally(() => { if (active) setLoading(false); });
|
||||
return () => { active = false; };
|
||||
}, [retry]);
|
||||
|
||||
return (
|
||||
<SiteShell title={socialTx("线下咖啡聊")}>
|
||||
@ -229,7 +234,9 @@ export default function CoffeeLanding() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{err && <p className="cf-error">{err}</p>}
|
||||
{err && <p className="cf-error" role="alert">{err}</p>}
|
||||
{err && <button className="cf-btn cf-btn-ghost" type="button" onClick={() => setRetry(value => value + 1)}>{zh ? '重新加载' : 'Retry'}</button>}
|
||||
{loading && <p className="cf-hint" role="status">{zh ? '正在寻找可约的人…' : 'Loading hosts…'}</p>}
|
||||
|
||||
<div className="cf-grid">
|
||||
{filtered.map((h) => (
|
||||
@ -252,7 +259,7 @@ export default function CoffeeLanding() {
|
||||
))}
|
||||
</div>
|
||||
|
||||
{!filtered.length && !err ? (
|
||||
{!filtered.length && !err && !loading ? (
|
||||
<p className="cf-empty">
|
||||
{zh
|
||||
? "这城暂时没人开放预约,先逛咖啡馆地图,或换一座城。"
|
||||
|
||||
@ -1,154 +1,138 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import SiteShell from "@social/components/SiteShell";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||
import { coffeeApi } from "../lib/api";
|
||||
import type { CoffeeBooking, CoffeeSchedule } from "../lib/types";
|
||||
import "./coffee.css";
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import SiteShell from '@social/components/SiteShell';
|
||||
import { socialPath } from '@social/lib/socialPath';
|
||||
import { socialTx } from '@social/lib/socialTx';
|
||||
import { getSocialSession } from '@social/lib/socialSession';
|
||||
import { useSocialI18n } from '@social/lib/useSocialI18n';
|
||||
import { coffeeApi } from '../lib/api';
|
||||
import type { CoffeeAvailabilityWindow, CoffeeBooking, CoffeeHost } from '../lib/types';
|
||||
import './coffee.css';
|
||||
|
||||
const HOST = "guest";
|
||||
const DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
|
||||
const DAYS_ZH = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
|
||||
const hm = (minutes: number) => `${String(Math.floor(minutes / 60) % 24).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
|
||||
const mins = (value: string) => { const [hours, minutes] = value.split(':').map(Number); return hours * 60 + minutes; };
|
||||
|
||||
export default function CoffeeManagePage() {
|
||||
const { locale } = useSocialI18n();
|
||||
const zh = locale === "zh";
|
||||
const [schedule, setSchedule] = useState<CoffeeSchedule | null>(null);
|
||||
const zh = locale === 'zh';
|
||||
const [host, setHost] = useState<CoffeeHost | null>(null);
|
||||
const [profile, setProfile] = useState({ name: '', bio: '', city: '', timezone: 'UTC' });
|
||||
const [savedProfile, setSavedProfile] = useState('');
|
||||
const [windows, setWindows] = useState<CoffeeAvailabilityWindow[]>([]);
|
||||
const [savedWindows, setSavedWindows] = useState('[]');
|
||||
const [bookings, setBookings] = useState<CoffeeBooking[]>([]);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const [toast, setToast] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [err, setErr] = useState('');
|
||||
const [toast, setToast] = useState('');
|
||||
const running = useRef(false);
|
||||
const profileDirty = !!savedProfile && JSON.stringify(profile) !== savedProfile;
|
||||
const windowsDirty = JSON.stringify(windows) !== savedWindows;
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setErr(null);
|
||||
setLoading(true); setErr('');
|
||||
try {
|
||||
const [s, b] = await Promise.all([
|
||||
coffeeApi.schedule(HOST),
|
||||
coffeeApi.bookings(HOST),
|
||||
]);
|
||||
setSchedule(s.schedule);
|
||||
setBookings(b.bookings);
|
||||
} catch (e) {
|
||||
setErr(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
const [mine, outgoing] = await Promise.all([coffeeApi.me(), coffeeApi.bookings()]);
|
||||
const next = mine.host ? { name: mine.host.name, bio: mine.host.bio || '', city: mine.host.city || '', timezone: mine.host.timezone } : { name: getSocialSession()?.name || '', bio: '', city: '', timezone: Intl.DateTimeFormat().resolvedOptions().timeZone };
|
||||
setHost(mine.host); setProfile(next); setSavedProfile(JSON.stringify(next));
|
||||
setWindows(mine.schedule?.availability || []); setSavedWindows(JSON.stringify(mine.schedule?.availability || []));
|
||||
const incoming = mine.host ? (await coffeeApi.bookings(mine.host.username)).bookings : [];
|
||||
setBookings([...new Map([...incoming, ...outgoing.bookings].map(item => [item.id, item])).values()].sort((a, b) => b.start.localeCompare(a.start)));
|
||||
} catch (error) { setErr(error instanceof Error ? error.message : String(error)); }
|
||||
finally { setLoading(false); }
|
||||
}, []);
|
||||
|
||||
useEffect(() => { void load(); }, [load]);
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
const protect = (event: BeforeUnloadEvent) => { if (profileDirty || windowsDirty) { event.preventDefault(); event.returnValue = ''; } };
|
||||
window.addEventListener('beforeunload', protect);
|
||||
return () => window.removeEventListener('beforeunload', protect);
|
||||
}, [profileDirty, windowsDirty]);
|
||||
|
||||
async function cancel(id: string) {
|
||||
await coffeeApi.cancel(id);
|
||||
setToast(zh ? "已取消" : "Cancelled");
|
||||
await load();
|
||||
async function action(fn: () => Promise<void>) {
|
||||
if (running.current) return;
|
||||
running.current = true; setBusy(true); setErr(''); setToast('');
|
||||
try { await fn(); }
|
||||
catch (error) { setErr(error instanceof Error ? error.message : String(error)); }
|
||||
finally { running.current = false; setBusy(false); }
|
||||
}
|
||||
|
||||
function minutesToHm(m: number) {
|
||||
const h = Math.floor(m / 60);
|
||||
const mm = m % 60;
|
||||
return `${String(h).padStart(2, "0")}:${String(mm).padStart(2, "0")}`;
|
||||
function saveProfile() {
|
||||
try { new Intl.DateTimeFormat('en-US', { timeZone: profile.timezone.trim() }).format(); }
|
||||
catch { setErr(zh ? '请输入有效时区,例如 Asia/Shanghai。' : 'Enter a valid time zone, such as Asia/Shanghai.'); return; }
|
||||
void action(async () => {
|
||||
const result = await coffeeApi.saveHost({ ...profile, name: profile.name.trim(), timezone: profile.timezone.trim() });
|
||||
const next = { name: result.host.name, bio: result.host.bio || '', city: result.host.city || '', timezone: result.host.timezone };
|
||||
setHost(result.host); setProfile(next); setSavedProfile(JSON.stringify(next));
|
||||
setToast(zh ? '个人资料已保存。添加可约时间后,别人就能预约你。' : 'Profile saved. Add availability so people can book you.');
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<SiteShell title={socialTx("咖啡聊日程")}>
|
||||
<div className="cf-root">
|
||||
<header className="cf-head">
|
||||
<h1>
|
||||
{zh ? "我的日程" : "My schedule"} <span>@{HOST}</span>
|
||||
</h1>
|
||||
<Link className="cf-btn cf-btn-ghost" href={socialPath(`/coffeechat/${HOST}`)}>
|
||||
{zh ? "公开页" : "Public page"}
|
||||
</Link>
|
||||
<Link className="cf-btn cf-btn-primary" href={socialPath("/coffeechat")}>
|
||||
{zh ? "咖啡聊首页" : "Coffee home"}
|
||||
</Link>
|
||||
</header>
|
||||
{err && <p className="cf-error">{err}</p>}
|
||||
{toast && <p className="cf-hint">{toast}</p>}
|
||||
function saveSchedule() {
|
||||
if (!host) return;
|
||||
if (windows.some(window => !window.days.length || !Number.isFinite(window.startTime) || !Number.isFinite(window.endTime) || window.startTime >= window.endTime)) {
|
||||
setErr(zh ? '每个时段至少选择一天,结束时间须晚于开始时间。' : 'Choose at least one day per window, with an end time after its start.'); return;
|
||||
}
|
||||
void action(async () => {
|
||||
const result = await coffeeApi.patchSchedule(host.username, { availability: windows });
|
||||
setWindows(result.schedule.availability); setSavedWindows(JSON.stringify(result.schedule.availability));
|
||||
setToast(zh ? '可约时间已更新' : 'Availability updated');
|
||||
});
|
||||
}
|
||||
|
||||
<div className="cf-split">
|
||||
<section className="cf-panel">
|
||||
<h2 style={{ margin: "0 0 0.75rem", fontFamily: "Syne, sans-serif", fontSize: "1.05rem" }}>
|
||||
{zh ? "可约时间(Cal availability)" : "Availability"}
|
||||
</h2>
|
||||
{!schedule ? (
|
||||
<p className="cf-hint">—</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="cf-meta" style={{ marginBottom: "0.75rem" }}>
|
||||
<span className="cf-pill">{schedule.timezone}</span>
|
||||
<span>{schedule.name}</span>
|
||||
</div>
|
||||
<div className="cf-list">
|
||||
{schedule.availability.map((w, i) => (
|
||||
<div key={i} className="cf-event" style={{ cursor: "default" }}>
|
||||
<div className="cf-meta">
|
||||
{(w.days || []).map((d) => (
|
||||
<span key={d} className="cf-pill">
|
||||
{d}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<h3>
|
||||
{minutesToHm(w.startTime)} – {minutesToHm(w.endTime)}
|
||||
</h3>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="cf-hint" style={{ marginTop: "0.85rem" }}>
|
||||
{zh
|
||||
? "演示账号 guest:公开链接可被任何人预约。后续可接登录身份。"
|
||||
: "Demo host guest — public booking link. Auth wiring later."}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
const patchWindow = (index: number, part: Partial<CoffeeAvailabilityWindow>) => setWindows(current => current.map((window, i) => i === index ? { ...window, ...part } : window));
|
||||
|
||||
<aside className="cf-panel">
|
||||
<h2 style={{ margin: "0 0 0.75rem", fontFamily: "Syne, sans-serif", fontSize: "1.05rem" }}>
|
||||
{zh ? "预约列表" : "Bookings"}
|
||||
</h2>
|
||||
<div className="cf-list">
|
||||
{!bookings.length && (
|
||||
<p className="cf-empty">{zh ? "暂无预约" : "No bookings"}</p>
|
||||
)}
|
||||
{bookings.map((b) => (
|
||||
<article key={b.id} className="cf-event" style={{ cursor: "default" }}>
|
||||
<div className="cf-meta">
|
||||
<span className={`cf-pill${b.status === "accepted" ? " ok" : ""}`}>
|
||||
{b.status}
|
||||
</span>
|
||||
<time dateTime={b.start}>{b.start}</time>
|
||||
</div>
|
||||
<h3>{b.title}</h3>
|
||||
<p className="cf-hint" style={{ margin: 0 }}>
|
||||
{b.attendee.name}
|
||||
{b.attendee.email ? ` · ${b.attendee.email}` : ""}
|
||||
</p>
|
||||
<div style={{ display: "flex", gap: 8, marginTop: 8, flexWrap: "wrap" }}>
|
||||
<Link
|
||||
className="cf-btn cf-btn-ghost"
|
||||
href={socialPath(`/coffeechat/bookings/${b.id}`)}
|
||||
>
|
||||
{zh ? "详情" : "Detail"}
|
||||
</Link>
|
||||
{b.status === "accepted" && (
|
||||
<button
|
||||
type="button"
|
||||
className="cf-btn cf-btn-ghost"
|
||||
onClick={() => void cancel(b.id)}
|
||||
>
|
||||
{zh ? "取消" : "Cancel"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
return <SiteShell title={socialTx('咖啡聊日程')}><div className="cf-root">
|
||||
<header className="cf-head"><h1>{zh ? '我的咖啡聊' : 'My coffee chats'}</h1>
|
||||
{host && <Link className="cf-btn cf-btn-ghost" href={socialPath(`/coffeechat/${host.username}`)}>{zh ? '公开预约页' : 'Public booking page'}</Link>}
|
||||
<Link className="cf-btn cf-btn-ghost" href={socialPath('/coffeechat')}>{zh ? '浏览咖啡聊' : 'Explore coffee chats'}</Link>
|
||||
</header>
|
||||
<p className="cf-hint">{zh ? '预约管理保存在当前浏览器。请使用同一浏览器和账号查看或取消预约。' : 'Booking management is linked to this browser. Use the same browser and account to view or cancel bookings.'}</p>
|
||||
{loading && <p className="cf-hint" role="status">{zh ? '加载中…' : 'Loading…'}</p>}
|
||||
{err && <p className="cf-error" role="alert">{err}</p>}
|
||||
{err && !savedProfile && <button type="button" className="cf-btn cf-btn-ghost" disabled={loading} onClick={() => void load()}>{zh ? '重新加载' : 'Retry'}</button>}
|
||||
{toast && <p className="cf-hint" role="status">{toast}</p>}
|
||||
{(profileDirty || windowsDirty) && <p className="cf-hint" role="status">{zh ? '有未保存修改' : 'You have unsaved changes'}</p>}
|
||||
{!loading && savedProfile && <>
|
||||
<div className="cf-split">
|
||||
<section className="cf-panel"><h2>{zh ? '个人资料' : 'Your profile'}</h2>
|
||||
<form className="cf-form" onSubmit={event => { event.preventDefault(); saveProfile(); }}>
|
||||
<label>{zh ? '称呼' : 'Name'}<input required maxLength={120} autoComplete="name" value={profile.name} disabled={busy} onChange={event => setProfile(d => ({ ...d, name: event.target.value }))} /></label>
|
||||
<label>{zh ? '所在城市' : 'City'}<input maxLength={120} autoComplete="address-level2" value={profile.city} disabled={busy} onChange={event => setProfile(d => ({ ...d, city: event.target.value }))} /></label>
|
||||
<label>{zh ? '聊聊什么' : 'What would you like to talk about?'}<textarea maxLength={2000} value={profile.bio} disabled={busy} onChange={event => setProfile(d => ({ ...d, bio: event.target.value }))} /></label>
|
||||
<label>{zh ? '时区' : 'Time zone'}<input required maxLength={80} value={profile.timezone} placeholder="Asia/Shanghai" disabled={busy} onChange={event => setProfile(d => ({ ...d, timezone: event.target.value }))} /></label>
|
||||
<button type="submit" className="cf-btn cf-btn-primary" disabled={busy || !profile.name.trim() || (!!host && !profileDirty)}>{busy ? (zh ? '保存中…' : 'Saving…') : host ? (zh ? '保存个人资料' : 'Save profile') : (zh ? '创建我的预约页' : 'Create my booking page')}</button>
|
||||
</form>
|
||||
</section>
|
||||
<section className="cf-panel"><h2>{zh ? '可约时间' : 'Availability'}</h2>
|
||||
{!host ? <p className="cf-hint">{zh ? '先保存个人资料,再添加可约时间。' : 'Save your profile first, then add available times.'}</p> : <>
|
||||
<p className="cf-hint">{host.timezone} · {zh ? '每次 30 分钟,已预约时段会自动排除。' : '30-minute meetings. Booked slots are excluded automatically.'}</p>
|
||||
{windows.map((window, index) => <div className="cf-event" key={index}>
|
||||
<fieldset disabled={busy} style={{ border: 0, padding: 0, margin: 0 }}><legend>{zh ? `时段 ${index + 1}` : `Window ${index + 1}`}</legend>
|
||||
<div className="cf-meta">{DAYS.map((day, i) => <label key={day}><input type="checkbox" checked={window.days.includes(day)} onChange={event => patchWindow(index, { days: event.target.checked ? [...window.days, day] : window.days.filter(value => value !== day) })} /> {zh ? DAYS_ZH[i] : day.slice(0, 3)}</label>)}</div>
|
||||
<div className="cf-form"><label>{zh ? '开始' : 'Start'}<input type="time" required value={hm(window.startTime)} onChange={event => patchWindow(index, { startTime: mins(event.target.value) })} /></label><label>{zh ? '结束' : 'End'}<input type="time" required value={hm(window.endTime)} onChange={event => patchWindow(index, { endTime: mins(event.target.value) || 1440 })} /></label></div>
|
||||
<button type="button" className="cf-btn cf-btn-ghost" onClick={() => setWindows(current => current.filter((_, i) => i !== index))}>{zh ? '移除此时段' : 'Remove window'}</button>
|
||||
</fieldset>
|
||||
</div>)}
|
||||
{!windows.length && <p className="cf-empty">{zh ? '暂无可约时间。添加时段后开放预约。' : 'No availability yet. Add a window to accept bookings.'}</p>}
|
||||
<div className="cf-cta"><button type="button" className="cf-btn cf-btn-ghost" disabled={busy || windows.length >= 20} onClick={() => setWindows(current => [...current, { days: DAYS.slice(0, 5), startTime: 600, endTime: 1080 }])}>{zh ? '添加时段' : 'Add window'}</button><button type="button" className="cf-btn cf-btn-primary" disabled={busy || !windowsDirty} onClick={saveSchedule}>{zh ? '保存可约时间' : 'Save availability'}</button></div>
|
||||
</>}
|
||||
</section>
|
||||
</div>
|
||||
</SiteShell>
|
||||
);
|
||||
<section className="cf-panel" style={{ marginTop: '1rem' }}><h2>{zh ? '我的预约' : 'My bookings'}</h2>
|
||||
{!bookings.length && <p className="cf-empty">{zh ? '暂无预约' : 'No bookings yet'}</p>}
|
||||
<div className="cf-list">{bookings.map(booking => <article key={booking.id} className="cf-event">
|
||||
<div className="cf-meta"><span className={`cf-pill${booking.status === 'accepted' ? ' ok' : ''}`}>{booking.status === 'cancelled' ? (zh ? '已取消' : 'Cancelled') : (zh ? '已确认' : 'Confirmed')}</span><time dateTime={booking.start}>{new Date(booking.start).toLocaleString(zh ? 'zh-CN' : 'en-US')}</time></div>
|
||||
<h3>{booking.title}</h3><p className="cf-hint">{booking.host?.username === host?.username ? booking.attendee.name : booking.host?.name}</p>
|
||||
<div className="cf-cta"><Link className="cf-btn cf-btn-ghost" href={socialPath(`/coffeechat/bookings/${booking.id}`)}>{zh ? '查看详情' : 'View details'}</Link>
|
||||
{booking.status === 'accepted' && <button type="button" className="cf-btn cf-btn-ghost" disabled={busy} onClick={() => { if (window.confirm(zh ? '确定取消这次预约?' : 'Cancel this booking?')) void action(async () => { const result = await coffeeApi.cancel(booking.id); setBookings(current => current.map(item => item.id === booking.id ? result.booking : item)); setToast(zh ? '预约已取消' : 'Booking cancelled'); }); }}>{zh ? '取消预约' : 'Cancel booking'}</button>}
|
||||
</div>
|
||||
</article>)}</div>
|
||||
</section>
|
||||
</>}
|
||||
</div></SiteShell>;
|
||||
}
|
||||
|
||||
@ -5,26 +5,22 @@ import type {
|
||||
CoffeeSchedule,
|
||||
CoffeeSlot,
|
||||
} from "./types";
|
||||
import { requestJson } from "~/lib/client-request";
|
||||
import { getGuestId } from '@social/lib/api';
|
||||
import { coffeeDeviceKey } from './device-key';
|
||||
|
||||
const BASE = "/api/coffee/v1";
|
||||
|
||||
async function j<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const res = await fetch(`${BASE}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(init?.headers || {}),
|
||||
},
|
||||
cache: "no-store",
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok || data?.ok === false) {
|
||||
throw new Error(data?.detail || data?.error || `http_${res.status}`);
|
||||
}
|
||||
return data as T;
|
||||
const headers = new Headers(init?.headers);
|
||||
headers.set('X-Social-Guest-Id', getGuestId());
|
||||
headers.set('X-Coffee-Key', coffeeDeviceKey(getGuestId()));
|
||||
return requestJson<T>(`${BASE}${path}`, { ...init, headers });
|
||||
}
|
||||
|
||||
export const coffeeApi = {
|
||||
me: () => j<{ ok: true; host: CoffeeHost | null; schedule: CoffeeSchedule | null }>('/me'),
|
||||
saveHost: (body: { name: string; bio: string; city: string; timezone: string }) => j<{ ok: true; host: CoffeeHost; schedule: CoffeeSchedule }>('/me', { method: 'PUT', body: JSON.stringify(body) }),
|
||||
health: () => j<{ ok: true }>("/health"),
|
||||
hosts: () => j<{ ok: true; hosts: CoffeeHost[] }>("/hosts"),
|
||||
host: (username: string) =>
|
||||
@ -33,7 +29,7 @@ export const coffeeApi = {
|
||||
j<{ ok: true; event_type: CoffeeEventType }>(
|
||||
`/hosts/${encodeURIComponent(username)}/event-types/${encodeURIComponent(slug)}`,
|
||||
),
|
||||
slots: (username: string, slug: string, day: string) =>
|
||||
slots: (username: string, slug: string, day: string, signal?: AbortSignal) =>
|
||||
j<{
|
||||
ok: true;
|
||||
day: string;
|
||||
@ -42,6 +38,7 @@ export const coffeeApi = {
|
||||
event_type: { slug: string; title: string; length_minutes: number };
|
||||
}>(
|
||||
`/hosts/${encodeURIComponent(username)}/event-types/${encodeURIComponent(slug)}/slots?day=${encodeURIComponent(day)}`,
|
||||
{ signal },
|
||||
),
|
||||
schedule: (username: string) =>
|
||||
j<{ ok: true; schedule: CoffeeSchedule }>(
|
||||
@ -71,8 +68,8 @@ export const coffeeApi = {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
booking: (id: string) =>
|
||||
j<{ ok: true; booking: CoffeeBooking }>(`/bookings/${encodeURIComponent(id)}`),
|
||||
booking: (id: string, signal?: AbortSignal) =>
|
||||
j<{ ok: true; booking: CoffeeBooking }>(`/bookings/${encodeURIComponent(id)}`, { signal }),
|
||||
bookings: (host?: string, status?: string) => {
|
||||
const q = new URLSearchParams();
|
||||
if (host) q.set("host", host);
|
||||
|
||||
42
src/modules/coffee/lib/calendar.ts
Normal file
42
src/modules/coffee/lib/calendar.ts
Normal file
@ -0,0 +1,42 @@
|
||||
import type { CoffeeBooking } from './types'
|
||||
|
||||
/** Day keys and labels must refer to the same date in the host's time zone. */
|
||||
export function upcomingDays(count = 14, timeZone = 'UTC', now = new Date()) {
|
||||
const parts = new Intl.DateTimeFormat('en-US', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(now)
|
||||
const part = (key: string) => Number(parts.find(value => value.type === key)?.value)
|
||||
const first = Date.UTC(part('year'), part('month') - 1, part('day'))
|
||||
return Array.from({ length: count }, (_, index) => {
|
||||
const date = new Date(first + index * 86400000)
|
||||
return { iso: date.toISOString().slice(0, 10), label: `${date.getUTCMonth() + 1}/${date.getUTCDate()}` }
|
||||
})
|
||||
}
|
||||
|
||||
function text(value: string) {
|
||||
return value.replace(/\\/g, '\\\\').replace(/\r\n|\r|\n/g, '\\n').replace(/;/g, '\\;').replace(/,/g, '\\,')
|
||||
}
|
||||
|
||||
function fold(line: string) {
|
||||
let current = '', length = 0
|
||||
const lines: string[] = []
|
||||
for (const char of line) {
|
||||
const bytes = new TextEncoder().encode(char).length
|
||||
if (length + bytes > 75) { lines.push(current); current = ' '; length = 1 }
|
||||
current += char; length += bytes
|
||||
}
|
||||
lines.push(current)
|
||||
return lines.join('\r\n')
|
||||
}
|
||||
|
||||
/** RFC 5545: escaped text, UTC dates, CRLF and UTF-8-safe line folding. */
|
||||
export function bookingCalendar(booking: CoffeeBooking, now = new Date()) {
|
||||
const stamp = (value: Date) => value.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z')
|
||||
const start = new Date(booking.start), end = new Date(booking.end)
|
||||
if (!Number.isFinite(start.getTime()) || !Number.isFinite(end.getTime()) || end <= start) throw new Error('Invalid booking time')
|
||||
return [
|
||||
'BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//Nomadro//Coffeechat//EN', 'CALSCALE:GREGORIAN',
|
||||
'BEGIN:VEVENT', `UID:${text(booking.uid || booking.id)}@nomadro.com`, `DTSTAMP:${stamp(now)}`,
|
||||
`DTSTART:${stamp(start)}`, `DTEND:${stamp(end)}`, `SUMMARY:${text(booking.title)}`,
|
||||
`LOCATION:${text(booking.location || '')}`, `DESCRIPTION:${text(booking.notes || '')}`,
|
||||
`STATUS:${booking.status === 'cancelled' ? 'CANCELLED' : 'CONFIRMED'}`, 'END:VEVENT', 'END:VCALENDAR',
|
||||
].map(fold).join('\r\n') + '\r\n'
|
||||
}
|
||||
10
src/modules/coffee/lib/device-key.ts
Normal file
10
src/modules/coffee/lib/device-key.ts
Normal file
@ -0,0 +1,10 @@
|
||||
/** Private booking credential. Public profile IDs are never ownership proofs. */
|
||||
export function coffeeDeviceKey(guest: string): string {
|
||||
const key = `nomadro-coffee-key:${guest}`;
|
||||
let value = localStorage.getItem(key);
|
||||
if (!value) {
|
||||
value = Array.from(crypto.getRandomValues(new Uint8Array(32)), byte => byte.toString(16).padStart(2, '0')).join('');
|
||||
localStorage.setItem(key, value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@ -1,5 +1,5 @@
|
||||
import type { Metadata, Viewport } from "next";
|
||||
import { Outfit } from "next/font/google";
|
||||
import { outfit } from "~/lib/fonts";
|
||||
import "./globals.css";
|
||||
import { AuthProvider } from "@community/lib/auth";
|
||||
import { ToastProvider } from "@community/lib/toast";
|
||||
@ -8,13 +8,6 @@ import PwaRegister from "@community/components/PwaRegister";
|
||||
|
||||
const SITE = process.env.NEXT_PUBLIC_SITE_URL || "https://nomadweb.nomadro.com";
|
||||
|
||||
const outfit = Outfit({
|
||||
subsets: ["latin"],
|
||||
weight: ["400", "500", "600", "700"],
|
||||
variable: "--font-outfit",
|
||||
display: "swap",
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
metadataBase: new URL(SITE),
|
||||
title: "nomadro · 数字游民旅居指南",
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import SiteShell from "@social/components/SiteShell";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
@ -8,24 +8,31 @@ import { socialTx } from "@social/lib/socialTx";
|
||||
import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||
import { notifyApi } from "../lib/api";
|
||||
import type { NotifyPreferences } from "../lib/types";
|
||||
import { useNotifySubscriber } from "../lib/useNotifySubscriber";
|
||||
import "./notifications.css";
|
||||
|
||||
const SUB = "guest";
|
||||
function quietFrom(prefs: NotifyPreferences) {
|
||||
return { timezone: String(prefs.channels.timezone || 'Asia/Shanghai'), quiet_start: String(prefs.channels.quiet_start || '22:00').slice(0, 5), quiet_end: String(prefs.channels.quiet_end || '08:00').slice(0, 5) };
|
||||
}
|
||||
|
||||
function Switch({
|
||||
checked,
|
||||
onChange,
|
||||
id,
|
||||
disabled,
|
||||
}: {
|
||||
checked: boolean;
|
||||
onChange: (v: boolean) => void;
|
||||
id: string;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<label className="ntf-switch" htmlFor={id}>
|
||||
<input
|
||||
id={id}
|
||||
type="checkbox"
|
||||
aria-label={id}
|
||||
disabled={disabled}
|
||||
checked={checked}
|
||||
onChange={(e) => onChange(e.target.checked)}
|
||||
/>
|
||||
@ -37,36 +44,64 @@ function Switch({
|
||||
export default function NotificationSettingsClient() {
|
||||
const { locale } = useSocialI18n();
|
||||
const zh = locale === "zh";
|
||||
const SUB = useNotifySubscriber();
|
||||
const [prefs, setPrefs] = useState<NotifyPreferences | null>(null);
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const [hint, setHint] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const saving = useRef(false);
|
||||
const identity = useRef(SUB);
|
||||
identity.current = SUB;
|
||||
const [quiet, setQuiet] = useState({ timezone: '', quiet_start: '22:00', quiet_end: '08:00' });
|
||||
const quietDirty = prefs != null && JSON.stringify(quiet) !== JSON.stringify(quietFrom(prefs));
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const load = useCallback(async (signal?: AbortSignal) => {
|
||||
if (!SUB) return;
|
||||
setErr(null);
|
||||
try {
|
||||
const res = await notifyApi.preferences(SUB);
|
||||
const res = await notifyApi.preferences(SUB, signal);
|
||||
if (signal?.aborted || identity.current !== SUB) return;
|
||||
setPrefs(res.preferences);
|
||||
setQuiet(quietFrom(res.preferences));
|
||||
} catch (e) {
|
||||
if (signal?.aborted || identity.current !== SUB) return;
|
||||
setErr(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}, []);
|
||||
}, [SUB]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
const controller = new AbortController();
|
||||
setPrefs(null); setHint(null);
|
||||
void load(controller.signal);
|
||||
return () => controller.abort();
|
||||
}, [load]);
|
||||
|
||||
async function patch(partial: Record<string, boolean | string>) {
|
||||
if (!prefs) return;
|
||||
if (!prefs || !SUB || saving.current) return false;
|
||||
saving.current = true;
|
||||
setBusy(true);
|
||||
setHint(null);
|
||||
setErr(null);
|
||||
try {
|
||||
const res = await notifyApi.setPreferences(SUB, {
|
||||
...prefs.channels,
|
||||
...partial,
|
||||
});
|
||||
const res = await notifyApi.setPreferences(SUB, partial);
|
||||
if (identity.current !== SUB) return false;
|
||||
setPrefs(res.preferences);
|
||||
if ('timezone' in partial) setQuiet(quietFrom(res.preferences));
|
||||
setHint(zh ? '偏好已保存' : 'Preferences saved');
|
||||
return true;
|
||||
} catch (e) {
|
||||
setErr(e instanceof Error ? e.message : String(e));
|
||||
if (identity.current === SUB) setErr(e instanceof Error ? e.message : String(e));
|
||||
return false;
|
||||
} finally { saving.current = false; setBusy(false); }
|
||||
}
|
||||
|
||||
async function saveQuiet() {
|
||||
try { new Intl.DateTimeFormat('en-US', { timeZone: quiet.timezone.trim() }).format(); }
|
||||
catch { setErr(zh ? '请输入有效时区,例如 Asia/Shanghai 或 America/New_York。' : 'Enter a valid time zone, such as Asia/Shanghai or America/New_York.'); return; }
|
||||
if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(quiet.quiet_start) || !/^([01]\d|2[0-3]):[0-5]\d$/.test(quiet.quiet_end)) {
|
||||
setErr(zh ? '请选择完整的开始和结束时间。' : 'Choose a valid start and end time.'); return;
|
||||
}
|
||||
await patch({ ...quiet, timezone: quiet.timezone.trim() });
|
||||
}
|
||||
|
||||
async function requestPush() {
|
||||
@ -78,11 +113,12 @@ export default function NotificationSettingsClient() {
|
||||
}
|
||||
try {
|
||||
const permission = await Notification.requestPermission();
|
||||
await patch({
|
||||
const saved = await patch({
|
||||
push_permission: permission,
|
||||
browser_push: permission === "granted",
|
||||
push: permission === "granted",
|
||||
});
|
||||
if (!saved) return;
|
||||
if (permission === "granted") {
|
||||
setHint(zh ? "已授权浏览器推送" : "Browser push granted");
|
||||
try {
|
||||
@ -116,8 +152,10 @@ export default function NotificationSettingsClient() {
|
||||
</Link>
|
||||
</header>
|
||||
|
||||
{err && <p className="ntf-error">{err}</p>}
|
||||
{hint && <p className="ntf-hint">{hint}</p>}
|
||||
{err && <p className="ntf-error" role="alert">{err}</p>}
|
||||
{err && !prefs && <button type="button" className="ntf-btn" onClick={() => void load()}>{zh ? '重试' : 'Retry'}</button>}
|
||||
{hint && <p className="ntf-hint" role="status">{hint}</p>}
|
||||
{busy && <p className="ntf-hint" role="status">{zh ? '正在保存…' : 'Saving…'}</p>}
|
||||
|
||||
{!prefs ? (
|
||||
<p className="ntf-hint">{zh ? "加载中…" : "Loading…"}</p>
|
||||
@ -134,6 +172,7 @@ export default function NotificationSettingsClient() {
|
||||
</div>
|
||||
<Switch
|
||||
id="dnd"
|
||||
disabled={busy}
|
||||
checked={dnd}
|
||||
onChange={(v) => void patch({ dnd: v })}
|
||||
/>
|
||||
@ -144,12 +183,13 @@ export default function NotificationSettingsClient() {
|
||||
<h3>{zh ? "邮件订阅" : "Email subscription"}</h3>
|
||||
<p>
|
||||
{zh
|
||||
? "工作流里的 Email 步骤是否允许投递(首期为 stub 记录)。"
|
||||
: "Allow email steps in workflows (stubbed delivery for now)."}
|
||||
? "邮件提醒偏好。邮件投递尚未开放。"
|
||||
: "Choose your email preference. Email delivery is not available yet."}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="email"
|
||||
disabled={busy}
|
||||
checked={email}
|
||||
onChange={(v) =>
|
||||
void patch({ email_subscribe: v, email: v })
|
||||
@ -162,20 +202,21 @@ export default function NotificationSettingsClient() {
|
||||
<h3>{zh ? "浏览器推送授权" : "Browser push"}</h3>
|
||||
<p>
|
||||
{zh
|
||||
? `权限状态:${prefs.push_permission || prefs.channels.push_permission || "default"}。授权后可收到系统级提醒。`
|
||||
? `权限状态:${prefs.push_permission || prefs.channels.push_permission || "default"}。允许此浏览器显示提醒。`
|
||||
: `Permission: ${prefs.push_permission || prefs.channels.push_permission || "default"}.`}
|
||||
</p>
|
||||
</div>
|
||||
<div style={{ display: "grid", gap: 8, justifyItems: "end" }}>
|
||||
<Switch
|
||||
id="push"
|
||||
disabled={busy}
|
||||
checked={pushOn}
|
||||
onChange={(v) => {
|
||||
if (v) void requestPush();
|
||||
else void patch({ browser_push: false, push: false });
|
||||
}}
|
||||
/>
|
||||
<button type="button" className="ntf-btn" onClick={() => void requestPush()}>
|
||||
<button type="button" className="ntf-btn" disabled={busy} onClick={() => void requestPush()}>
|
||||
{zh ? "请求授权" : "Request"}
|
||||
</button>
|
||||
</div>
|
||||
@ -188,6 +229,7 @@ export default function NotificationSettingsClient() {
|
||||
</div>
|
||||
<Switch
|
||||
id="in_app"
|
||||
disabled={busy}
|
||||
checked={!!prefs.channels.in_app}
|
||||
onChange={(v) => void patch({ in_app: v })}
|
||||
/>
|
||||
@ -207,12 +249,9 @@ export default function NotificationSettingsClient() {
|
||||
{zh ? "时区" : "Timezone"}
|
||||
<input
|
||||
type="text"
|
||||
value={String(
|
||||
prefs.channels.timezone ||
|
||||
(prefs as { timezone?: string }).timezone ||
|
||||
"Asia/Shanghai",
|
||||
)}
|
||||
onChange={(e) => void patch({ timezone: e.target.value })}
|
||||
value={quiet.timezone}
|
||||
disabled={busy}
|
||||
onChange={(e) => setQuiet(d => ({ ...d, timezone: e.target.value }))}
|
||||
placeholder="Asia/Shanghai"
|
||||
/>
|
||||
</label>
|
||||
@ -220,27 +259,25 @@ export default function NotificationSettingsClient() {
|
||||
{zh ? "开始" : "Start"}
|
||||
<input
|
||||
type="time"
|
||||
value={String(
|
||||
prefs.channels.quiet_start ||
|
||||
(prefs as { quiet_start?: string }).quiet_start ||
|
||||
"22:00",
|
||||
).slice(0, 5)}
|
||||
onChange={(e) => void patch({ quiet_start: e.target.value })}
|
||||
value={quiet.quiet_start}
|
||||
disabled={busy}
|
||||
onChange={(e) => setQuiet(d => ({ ...d, quiet_start: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{zh ? "结束" : "End"}
|
||||
<input
|
||||
type="time"
|
||||
value={String(
|
||||
prefs.channels.quiet_end ||
|
||||
(prefs as { quiet_end?: string }).quiet_end ||
|
||||
"08:00",
|
||||
).slice(0, 5)}
|
||||
onChange={(e) => void patch({ quiet_end: e.target.value })}
|
||||
value={quiet.quiet_end}
|
||||
disabled={busy}
|
||||
onChange={(e) => setQuiet(d => ({ ...d, quiet_end: e.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
|
||||
<button type="button" className="ntf-btn ntf-btn-primary" disabled={busy || !quietDirty} onClick={() => void saveQuiet()}>{zh ? '保存静默时段' : 'Save quiet hours'}</button>
|
||||
<button type="button" className="ntf-btn" disabled={busy || !quietDirty} onClick={() => setQuiet(quietFrom(prefs))}>{zh ? '重置' : 'Reset'}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="ntf-setting">
|
||||
@ -254,6 +291,7 @@ export default function NotificationSettingsClient() {
|
||||
</div>
|
||||
<Switch
|
||||
id="digest_daily"
|
||||
disabled={busy}
|
||||
checked={
|
||||
prefs.channels.digest_daily !== false &&
|
||||
(prefs as { digest_daily?: boolean }).digest_daily !== false
|
||||
@ -271,6 +309,7 @@ export default function NotificationSettingsClient() {
|
||||
</div>
|
||||
<Switch
|
||||
id="digest_weekly"
|
||||
disabled={busy}
|
||||
checked={
|
||||
prefs.channels.digest_weekly !== false &&
|
||||
(prefs as { digest_weekly?: boolean }).digest_weekly !== false
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import SiteShell from "@social/components/SiteShell";
|
||||
@ -10,10 +10,9 @@ import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||
import { notifyApi } from "../lib/api";
|
||||
import { NOTIFY_CATEGORIES, categoryLabel, type NotifyCategory } from "../lib/categories";
|
||||
import type { NotifyMessage } from "../lib/types";
|
||||
import { announceInboxChanged, INBOX_CHANGED, useNotifySubscriber } from "../lib/useNotifySubscriber";
|
||||
import "./notifications.css";
|
||||
|
||||
const SUB = "guest";
|
||||
|
||||
function resolveHref(m: NotifyMessage) {
|
||||
const raw = m.href || m.cta_url || "";
|
||||
if (!raw) return socialPath("/notifications");
|
||||
@ -26,35 +25,56 @@ export default function NotificationsClient() {
|
||||
const { locale } = useSocialI18n();
|
||||
const zh = locale === "zh";
|
||||
const router = useRouter();
|
||||
const subscriber = useNotifySubscriber();
|
||||
const [cat, setCat] = useState<NotifyCategory | "all">("all");
|
||||
const [messages, setMessages] = useState<NotifyMessage[]>([]);
|
||||
const [unread, setUnread] = useState(0);
|
||||
const [byCat, setByCat] = useState<Record<string, number>>({});
|
||||
const [err, setErr] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const mutating = useRef(false);
|
||||
const currentQuery = useRef('');
|
||||
currentQuery.current = `${subscriber}|${cat}`;
|
||||
const currentUnread = cat === 'all' ? unread : byCat[cat] || 0;
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const load = useCallback(async (signal?: AbortSignal) => {
|
||||
const query = `${subscriber}|${cat}`;
|
||||
if (!subscriber || currentQuery.current !== query) return;
|
||||
setLoading(true);
|
||||
setErr(null);
|
||||
try {
|
||||
const res = await notifyApi.inbox(SUB, {
|
||||
const res = await notifyApi.inbox(subscriber, {
|
||||
category: cat === "all" ? undefined : cat,
|
||||
signal,
|
||||
});
|
||||
if (signal?.aborted || currentQuery.current !== query) return;
|
||||
setMessages(res.messages);
|
||||
setUnread(res.unread);
|
||||
setByCat(res.unread_by_category || {});
|
||||
} catch (e) {
|
||||
if (signal?.aborted || currentQuery.current !== query) return;
|
||||
setErr(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}, [cat]);
|
||||
} finally { if (!signal?.aborted && currentQuery.current === query) setLoading(false); }
|
||||
}, [cat, subscriber]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
const controller = new AbortController();
|
||||
setMessages([]); setUnread(0); setByCat({});
|
||||
void load(controller.signal);
|
||||
const refresh = () => { if (!document.hidden) void load(controller.signal); };
|
||||
const timer = window.setInterval(refresh, 45000);
|
||||
window.addEventListener(INBOX_CHANGED, refresh);
|
||||
window.addEventListener('focus', refresh);
|
||||
window.addEventListener('online', refresh);
|
||||
return () => { controller.abort(); window.clearInterval(timer); window.removeEventListener(INBOX_CHANGED, refresh); window.removeEventListener('focus', refresh); window.removeEventListener('online', refresh); };
|
||||
}, [load]);
|
||||
|
||||
async function openItem(m: NotifyMessage) {
|
||||
if (!m.read) {
|
||||
try {
|
||||
await notifyApi.patchMessage(m.id, { read: true });
|
||||
announceInboxChanged();
|
||||
} catch {
|
||||
/* still navigate */
|
||||
}
|
||||
@ -64,22 +84,26 @@ export default function NotificationsClient() {
|
||||
|
||||
async function markRead(e: React.MouseEvent, id: string) {
|
||||
e.stopPropagation();
|
||||
await notifyApi.patchMessage(id, { read: true });
|
||||
await load();
|
||||
await mutate(() => notifyApi.patchMessage(id, { read: true }));
|
||||
}
|
||||
|
||||
async function remove(e: React.MouseEvent, id: string) {
|
||||
e.stopPropagation();
|
||||
await notifyApi.deleteMessage(id);
|
||||
await load();
|
||||
await mutate(() => notifyApi.deleteMessage(id));
|
||||
}
|
||||
|
||||
async function markAll() {
|
||||
async function mutate(action: () => Promise<unknown>) {
|
||||
if (mutating.current) return;
|
||||
mutating.current = true;
|
||||
setBusy(true);
|
||||
setErr(null);
|
||||
try {
|
||||
await notifyApi.markAllRead(SUB, cat === "all" ? undefined : cat);
|
||||
await load();
|
||||
await action();
|
||||
announceInboxChanged();
|
||||
} catch (e) {
|
||||
setErr(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
mutating.current = false;
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
@ -95,11 +119,12 @@ export default function NotificationsClient() {
|
||||
<button
|
||||
type="button"
|
||||
className="ntf-btn"
|
||||
disabled={busy || unread === 0}
|
||||
onClick={() => void markAll()}
|
||||
disabled={busy || loading || currentUnread === 0}
|
||||
onClick={() => void mutate(() => notifyApi.markAllRead(subscriber, cat === "all" ? undefined : cat))}
|
||||
>
|
||||
{zh ? "全部已读" : "Mark all read"}
|
||||
{busy ? (zh ? '更新中…' : 'Updating…') : cat === 'all' ? (zh ? "全部已读" : "Mark all read") : (zh ? '本类全部已读' : 'Mark category read')}
|
||||
</button>
|
||||
<button type="button" className="ntf-btn" disabled={loading || busy} onClick={() => void load()}>{zh ? '刷新' : 'Refresh'}</button>
|
||||
<Link className="ntf-btn ntf-btn-primary" href={socialPath("/notifications/settings")}>
|
||||
{zh ? "偏好设置" : "Settings"}
|
||||
</Link>
|
||||
@ -125,27 +150,20 @@ export default function NotificationsClient() {
|
||||
})}
|
||||
</div>
|
||||
|
||||
{err && <p className="ntf-error">{err}</p>}
|
||||
{!err && !messages.length && (
|
||||
{err && <p className="ntf-error" role="alert">{err}<button type="button" className="ntf-btn" disabled={loading || busy} onClick={() => void load()}>{zh ? '重试' : 'Retry'}</button></p>}
|
||||
{loading && <p className="ntf-empty" role="status">{zh ? '正在加载通知…' : 'Loading notifications…'}</p>}
|
||||
{!loading && !err && !messages.length && (
|
||||
<p className="ntf-empty">{zh ? "暂无通知" : "No notifications"}</p>
|
||||
)}
|
||||
|
||||
<div className="ntf-list">
|
||||
<div className="ntf-list" aria-busy={loading || busy}>
|
||||
{messages.map((m) => (
|
||||
<div
|
||||
key={m.id}
|
||||
className={`ntf-card${m.read ? "" : " is-unread"}`}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => void openItem(m)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
void openItem(m);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="ntf-card-main">
|
||||
<div className="ntf-card-main" role="button" tabIndex={0} onClick={() => void openItem(m)}
|
||||
onKeyDown={event => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); void openItem(m); } }}>
|
||||
<div className="ntf-card-meta">
|
||||
<span className={`ntf-pill ${m.category}`}>
|
||||
{categoryLabel(m.category, zh)}
|
||||
@ -159,6 +177,7 @@ export default function NotificationsClient() {
|
||||
{!m.read && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
className="ntf-btn"
|
||||
onClick={(e) => void markRead(e, m.id)}
|
||||
>
|
||||
@ -167,6 +186,7 @@ export default function NotificationsClient() {
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
className="ntf-btn"
|
||||
onClick={(e) => void remove(e, m.id)}
|
||||
>
|
||||
|
||||
@ -25,9 +25,10 @@ import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||
import { notifyApi } from "../lib/api";
|
||||
import { categoryLabel } from "../lib/categories";
|
||||
import type { NotifyMessage } from "../lib/types";
|
||||
import { announceInboxChanged, INBOX_CHANGED, useNotifySubscriber } from "../lib/useNotifySubscriber";
|
||||
import { getGuestId } from '@social/lib/api';
|
||||
import "./notifications.css";
|
||||
|
||||
const SUB = "guest";
|
||||
const POLL_MS = 45_000;
|
||||
const PREVIEW_LIMIT = 8;
|
||||
const STORAGE_CHANGE = "nomadro-social-storage";
|
||||
@ -85,6 +86,7 @@ export default function NotifyBell({ onNavigate }: { onNavigate?: () => void })
|
||||
const { locale } = useSocialI18n();
|
||||
const zh = locale === "zh";
|
||||
const router = useRouter();
|
||||
const SUB = useNotifySubscriber();
|
||||
const panelId = useId();
|
||||
const wrapRef = useRef<HTMLDivElement>(null);
|
||||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
@ -121,20 +123,21 @@ export default function NotifyBell({ onNavigate }: { onNavigate?: () => void })
|
||||
const badgeCount = unread + pendingCount;
|
||||
|
||||
const refreshUnread = useCallback(async () => {
|
||||
if (!loggedIn) {
|
||||
if (!loggedIn || !SUB) {
|
||||
setUnread(0);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await notifyApi.unread(SUB);
|
||||
if (getGuestId() !== SUB) return;
|
||||
setUnread(res.unread || 0);
|
||||
} catch {
|
||||
/* API down — keep local pending badge */
|
||||
}
|
||||
}, [loggedIn]);
|
||||
}, [loggedIn, SUB]);
|
||||
|
||||
const loadPreview = useCallback(async () => {
|
||||
if (!loggedIn) {
|
||||
if (!loggedIn || !SUB) {
|
||||
setMessages([]);
|
||||
setUnread(0);
|
||||
setErr(null);
|
||||
@ -145,16 +148,16 @@ export default function NotifyBell({ onNavigate }: { onNavigate?: () => void })
|
||||
setErr(null);
|
||||
try {
|
||||
const res = await notifyApi.inbox(SUB);
|
||||
if (getGuestId() !== SUB) return;
|
||||
setMessages((res.messages || []).slice(0, PREVIEW_LIMIT));
|
||||
setUnread(res.unread || 0);
|
||||
} catch {
|
||||
// 不把 fetch failed 甩给用户
|
||||
setErr(null);
|
||||
setMessages([]);
|
||||
if (getGuestId() !== SUB) return;
|
||||
setErr(zh ? '通知暂时无法加载,请重试。' : 'Notifications could not be loaded. Please retry.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
if (getGuestId() === SUB) setLoading(false);
|
||||
}
|
||||
}, [loggedIn]);
|
||||
}, [loggedIn, SUB, zh]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!loggedIn) {
|
||||
@ -168,9 +171,11 @@ export default function NotifyBell({ onNavigate }: { onNavigate?: () => void })
|
||||
const t = window.setInterval(() => void refreshUnread(), POLL_MS);
|
||||
const onFocus = () => void refreshUnread();
|
||||
window.addEventListener("focus", onFocus);
|
||||
window.addEventListener(INBOX_CHANGED, onFocus);
|
||||
return () => {
|
||||
window.clearInterval(t);
|
||||
window.removeEventListener("focus", onFocus);
|
||||
window.removeEventListener(INBOX_CHANGED, onFocus);
|
||||
};
|
||||
}, [loggedIn, refreshUnread]);
|
||||
|
||||
@ -213,6 +218,7 @@ export default function NotifyBell({ onNavigate }: { onNavigate?: () => void })
|
||||
if (!m.read) {
|
||||
try {
|
||||
await notifyApi.patchMessage(m.id, { read: true });
|
||||
announceInboxChanged();
|
||||
setUnread((n) => Math.max(0, n - 1));
|
||||
setMessages((list) =>
|
||||
list.map((item) => (item.id === m.id ? { ...item, read: true } : item)),
|
||||
@ -228,10 +234,11 @@ export default function NotifyBell({ onNavigate }: { onNavigate?: () => void })
|
||||
async function markAll() {
|
||||
try {
|
||||
await notifyApi.markAllRead(SUB);
|
||||
announceInboxChanged();
|
||||
setUnread(0);
|
||||
setMessages((list) => list.map((m) => ({ ...m, read: true })));
|
||||
} catch {
|
||||
/* ignore */
|
||||
setErr(zh ? '未能标记已读,请重试。' : 'Could not mark messages as read. Please retry.');
|
||||
}
|
||||
}
|
||||
|
||||
@ -340,7 +347,7 @@ export default function NotifyBell({ onNavigate }: { onNavigate?: () => void })
|
||||
{loading && !messages.length ? (
|
||||
<p className="nav-notify-empty">{zh ? "加载中…" : "Loading…"}</p>
|
||||
) : null}
|
||||
{err ? <p className="nav-notify-error">{err}</p> : null}
|
||||
{err ? <div role="alert"><p className="nav-notify-error">{err}</p><button type="button" className="nav-notify-text-btn" onClick={() => void loadPreview()}>{zh ? '重试' : 'Retry'}</button></div> : null}
|
||||
{!loading && !err && !messages.length && !todos.length ? (
|
||||
<p className="nav-notify-empty">
|
||||
{zh ? "暂无通知" : "No notifications"}
|
||||
|
||||
@ -184,8 +184,16 @@
|
||||
|
||||
.ntf-settings {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.ntf-setting > div { min-width: 0; }
|
||||
.ntf-setting > div:last-child { flex-shrink: 0; }
|
||||
.ntf-setting.ntf-setting-stack {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
.ntf-setting .ntf-btn { white-space: nowrap; }
|
||||
.ntf-setting {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
@ -218,9 +226,16 @@
|
||||
}
|
||||
.ntf-switch input {
|
||||
opacity: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
z-index: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.ntf-switch input:focus-visible + span { outline: 2px solid var(--nt-amber); outline-offset: 3px; }
|
||||
.ntf-switch input:disabled + span { opacity: 0.5; }
|
||||
.ntf-switch span {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
@ -505,6 +520,9 @@ html[data-theme="light"] .nav-notify-panel {
|
||||
color: var(--nt-muted);
|
||||
}
|
||||
.ntf-quiet-fields input {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
box-sizing: border-box;
|
||||
min-height: 44px;
|
||||
border-radius: 12px;
|
||||
border: 1px solid var(--nt-line);
|
||||
|
||||
@ -11,23 +11,15 @@ import type {
|
||||
NotifyTopic,
|
||||
NotifyWorkflow,
|
||||
} from "./types";
|
||||
import { requestJson } from "~/lib/client-request";
|
||||
import { getGuestId } from '@social/lib/api';
|
||||
|
||||
const BASE = "/api/notify/v1";
|
||||
|
||||
async function j<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const res = await fetch(`${BASE}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(init?.headers || {}),
|
||||
},
|
||||
cache: "no-store",
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok || data?.ok === false) {
|
||||
throw new Error(data?.detail || data?.error || `http_${res.status}`);
|
||||
}
|
||||
return data as T;
|
||||
const headers = new Headers(init?.headers);
|
||||
headers.set('X-Social-Guest-Id', getGuestId());
|
||||
return requestJson<T>(`${BASE}${path}`, { ...init, headers });
|
||||
}
|
||||
|
||||
export const notifyApi = {
|
||||
@ -84,7 +76,7 @@ export const notifyApi = {
|
||||
}>("/events/trigger", { method: "POST", body: JSON.stringify(body) }),
|
||||
inbox: (
|
||||
subscriber_id = "guest",
|
||||
opts?: { include_archived?: boolean; category?: string },
|
||||
opts?: { include_archived?: boolean; category?: string; signal?: AbortSignal },
|
||||
) => {
|
||||
const q = new URLSearchParams({ subscriber_id });
|
||||
if (opts?.include_archived) q.set("include_archived", "true");
|
||||
@ -95,7 +87,7 @@ export const notifyApi = {
|
||||
unread: number;
|
||||
unread_by_category: Record<string, number>;
|
||||
messages: NotifyMessage[];
|
||||
}>(`/inbox?${q}`);
|
||||
}>(`/inbox?${q}`, { signal: opts?.signal });
|
||||
},
|
||||
unread: (subscriber_id = "guest") =>
|
||||
j<{
|
||||
@ -118,9 +110,10 @@ export const notifyApi = {
|
||||
}),
|
||||
deleteMessage: (id: string) =>
|
||||
j<{ ok: true }>(`/inbox/${encodeURIComponent(id)}`, { method: "DELETE" }),
|
||||
preferences: (subscriber_id: string) =>
|
||||
preferences: (subscriber_id: string, signal?: AbortSignal) =>
|
||||
j<{ ok: true; preferences: NotifyPreferences }>(
|
||||
`/subscribers/${encodeURIComponent(subscriber_id)}/preferences`,
|
||||
{ signal },
|
||||
),
|
||||
setPreferences: (
|
||||
subscriber_id: string,
|
||||
|
||||
24
src/modules/notify/lib/useNotifySubscriber.ts
Normal file
24
src/modules/notify/lib/useNotifySubscriber.ts
Normal file
@ -0,0 +1,24 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { getGuestId } from '@social/lib/api';
|
||||
|
||||
export const INBOX_CHANGED = 'nomadro-inbox-changed';
|
||||
|
||||
/** Social events target guest IDs; every inbox surface must use that same ID. */
|
||||
export function useNotifySubscriber() {
|
||||
const [subscriber, setSubscriber] = useState('');
|
||||
useEffect(() => {
|
||||
const update = () => setSubscriber(getGuestId());
|
||||
update();
|
||||
window.addEventListener('nomadro-social-storage', update);
|
||||
window.addEventListener('storage', update);
|
||||
return () => {
|
||||
window.removeEventListener('nomadro-social-storage', update);
|
||||
window.removeEventListener('storage', update);
|
||||
};
|
||||
}, []);
|
||||
return subscriber;
|
||||
}
|
||||
|
||||
export function announceInboxChanged() { window.dispatchEvent(new Event(INBOX_CHANGED)); }
|
||||
@ -1069,6 +1069,21 @@
|
||||
color: #fff;
|
||||
font: inherit;
|
||||
font-weight: 500;
|
||||
color-scheme: dark;
|
||||
}
|
||||
.social-join-desk-form select {
|
||||
appearance: none;
|
||||
background-image: linear-gradient(45deg, transparent 50%, rgba(255, 255, 255, 0.55) 50%),
|
||||
linear-gradient(135deg, rgba(255, 255, 255, 0.55) 50%, transparent 50%);
|
||||
background-position: calc(100% - 18px) calc(50% - 2px), calc(100% - 12px) calc(50% - 2px);
|
||||
background-size: 6px 6px, 6px 6px;
|
||||
background-repeat: no-repeat;
|
||||
padding-right: 36px;
|
||||
}
|
||||
.social-join-desk-form select option,
|
||||
.social-join-desk-form select optgroup {
|
||||
background-color: #12141c;
|
||||
color: #f8fafc;
|
||||
}
|
||||
.social-join-desk-form textarea {
|
||||
min-height: 120px;
|
||||
@ -1082,6 +1097,45 @@
|
||||
border-color: color-mix(in srgb, var(--sx-mint, #4ecdc4) 55%, transparent);
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--sx-mint, #4ecdc4) 16%, transparent);
|
||||
}
|
||||
.social-join-gender {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
}
|
||||
.social-join-gender-label {
|
||||
color: rgba(255, 255, 255, 0.58);
|
||||
font-size: 0.86rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.social-join-gender-pills {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px;
|
||||
}
|
||||
.social-join-gender-pill {
|
||||
min-height: 48px;
|
||||
border-radius: 12px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
color: rgba(255, 255, 255, 0.78);
|
||||
font: inherit;
|
||||
font-weight: 650;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.15s, background 0.15s, color 0.15s;
|
||||
}
|
||||
.social-join-gender-pill:hover {
|
||||
border-color: rgba(255, 255, 255, 0.22);
|
||||
color: #fff;
|
||||
}
|
||||
.social-join-gender-pill.is-on {
|
||||
border-color: transparent;
|
||||
background: color-mix(in srgb, var(--sx-mint, #4ecdc4) 28%, transparent);
|
||||
color: #fff;
|
||||
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--sx-mint, #4ecdc4) 45%, transparent);
|
||||
}
|
||||
.social-join-gender-pill:focus-visible {
|
||||
outline: 2px solid var(--sx-mint, #4ecdc4);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.social-join-desk-form input::placeholder,
|
||||
.social-join-desk-form textarea::placeholder {
|
||||
color: rgba(255, 255, 255, 0.28);
|
||||
@ -1506,11 +1560,19 @@
|
||||
font-size: 25px;
|
||||
animation: none;
|
||||
}
|
||||
.social-workspace .nav-actions {
|
||||
.social-workspace .nav-actions,
|
||||
.social-immersive .nav-actions,
|
||||
.social-home .nav-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-left: auto;
|
||||
margin-left: auto; /* 汉堡/操作永远顶到最右边 */
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.social-immersive .nav-container,
|
||||
.social-home .nav-container {
|
||||
width: 100%;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
.social-lang-switch {
|
||||
display: inline-flex;
|
||||
@ -2541,7 +2603,40 @@
|
||||
.social-workspace .social-nav-desktop-cta {
|
||||
display: none;
|
||||
}
|
||||
.social-workspace .mobile-menu-btn {
|
||||
/* 登录/加入只放汉堡菜单里;顶栏右侧再露「登录」会叠在汉堡上像浮层 */
|
||||
.social-workspace .nav-actions > .social-nav-login,
|
||||
.social-immersive .nav-actions > .social-nav-login,
|
||||
.social-home .nav-actions > .social-nav-login,
|
||||
.social-immersive .social-nav-desktop-cta {
|
||||
display: none !important;
|
||||
}
|
||||
.social-immersive .nav-links:not(.open) {
|
||||
display: none;
|
||||
}
|
||||
.social-immersive .nav-links.open {
|
||||
display: flex;
|
||||
position: fixed;
|
||||
inset: 70px 0 auto;
|
||||
width: 100%;
|
||||
max-height: calc(100dvh - 100px);
|
||||
overflow: auto;
|
||||
padding: 20px;
|
||||
border: 1px solid var(--connection-border, var(--sx-line));
|
||||
border-radius: 16px;
|
||||
background: var(--bg-primary);
|
||||
gap: 8px;
|
||||
transform: none;
|
||||
flex-direction: column;
|
||||
z-index: 1200;
|
||||
}
|
||||
.social-immersive .nav-mobile-extras {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid var(--sx-line);
|
||||
}
|
||||
.social-workspace .mobile-menu-btn,
|
||||
.social-immersive .mobile-menu-btn {
|
||||
display: flex;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
|
||||
@ -1666,6 +1666,18 @@ html[data-theme="light"] .social-mobile-dock a[aria-current="page"] {
|
||||
backdrop-filter: blur(24px);
|
||||
gap: 24px;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.social-immersive .nav-container {
|
||||
padding: 0 6px 0 12px; /* 汉堡贴右 */
|
||||
gap: 8px;
|
||||
}
|
||||
.social-immersive .nav-actions {
|
||||
margin-left: auto !important;
|
||||
}
|
||||
.social-immersive .mobile-menu-btn {
|
||||
margin-left: auto;
|
||||
}
|
||||
}
|
||||
.social-immersive .navbar.scrolled .nav-container {
|
||||
box-shadow: 0 8px 32px #0002;
|
||||
}
|
||||
|
||||
@ -751,8 +751,13 @@ export function Conversation({
|
||||
}
|
||||
>
|
||||
<div className="social-message-avatar" aria-hidden="true">
|
||||
{message.avatar?.trim() ? (
|
||||
<SocialAvatar src={message.avatar} size={36} lazy />
|
||||
{message.avatar?.trim().startsWith("/api/social/") ? (
|
||||
<SocialAvatar
|
||||
src={message.avatar}
|
||||
size={36}
|
||||
lazy
|
||||
faceOk
|
||||
/>
|
||||
) : (
|
||||
message.author.slice(0, 1).toUpperCase()
|
||||
)}
|
||||
|
||||
@ -43,12 +43,10 @@ import {
|
||||
JOIN_INTENT_OPTIONS,
|
||||
JOIN_LIVENESS_RETURN,
|
||||
JOIN_PROFILE_RETURN,
|
||||
JOIN_RELATIONSHIP_OPTIONS,
|
||||
isJoinPaid,
|
||||
clearJoinProfileDone,
|
||||
isJoinProfileDone,
|
||||
markJoinProfileDone,
|
||||
type JoinOption,
|
||||
type JoinProfileDraft,
|
||||
} from "@social/lib/joinFlow";
|
||||
import { archiveJoinLead } from "@social/lib/joinArchive";
|
||||
@ -218,33 +216,6 @@ const EMPTY_JOIN_PROFILE: JoinProfileDraft = {
|
||||
bio: "",
|
||||
};
|
||||
|
||||
function JoinSelect({
|
||||
label,
|
||||
value,
|
||||
options,
|
||||
locale,
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
options: JoinOption[];
|
||||
locale: string;
|
||||
onChange: (value: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<label>
|
||||
{label}
|
||||
<select value={value} onChange={(e) => onChange(e.target.value)}>
|
||||
{options.map((opt) => (
|
||||
<option key={opt.value || "na"} value={opt.value}>
|
||||
{locale === "en" ? opt.labelEn : opt.labelZh}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
type JoinStep = "pay" | "profile" | "liveness" | "done";
|
||||
|
||||
/** URL-only — must match SSR; localStorage flags applied after mount. */
|
||||
@ -356,6 +327,8 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
loadJson<string>("nick", "") ||
|
||||
saved.name ||
|
||||
"";
|
||||
const genderRaw =
|
||||
typeof saved.gender === "string" ? saved.gender.trim() : "";
|
||||
setDraft({
|
||||
...EMPTY_JOIN_PROFILE,
|
||||
...saved,
|
||||
@ -366,6 +339,9 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
typeof saved.status === "string" && saved.status
|
||||
? saved.status
|
||||
: "online",
|
||||
// Only 男/女 — drop legacy nb / empty placeholders
|
||||
gender: genderRaw === "m" || genderRaw === "f" ? genderRaw : "",
|
||||
relationship: "",
|
||||
name: typeof nick === "string" ? nick : "",
|
||||
avatar:
|
||||
typeof saved.avatar === "string" && !saved.avatar.startsWith("blob:")
|
||||
@ -525,6 +501,10 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
nameRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
if (draft.gender !== "m" && draft.gender !== "f") {
|
||||
setErr(socialTx("请选择性别"));
|
||||
return;
|
||||
}
|
||||
if (!draft.intents.length) {
|
||||
setErr(socialTx("请至少选一个「想认识 / 想做什么」"));
|
||||
return;
|
||||
@ -634,10 +614,6 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
JOIN_GENDER_OPTIONS.find((opt) => opt.value === draft.gender)?.[
|
||||
locale === "en" ? "labelEn" : "labelZh"
|
||||
] || "";
|
||||
const summaryRel =
|
||||
JOIN_RELATIONSHIP_OPTIONS.find((opt) => opt.value === draft.relationship)?.[
|
||||
locale === "en" ? "labelEn" : "labelZh"
|
||||
] || "";
|
||||
const summaryIntents = draft.intents
|
||||
.map(
|
||||
(id) =>
|
||||
@ -702,10 +678,9 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
<p className="social-join-live-kicker">{socialTx("实时预览")}</p>
|
||||
<h2 className="social-join-live-name">{summaryName}</h2>
|
||||
<p className="social-join-live-title">{summaryTitle}</p>
|
||||
{(summaryGender && draft.gender) || (summaryRel && draft.relationship) ? (
|
||||
{summaryGender ? (
|
||||
<div className="social-join-live-meta">
|
||||
{draft.gender ? <span>{summaryGender}</span> : null}
|
||||
{draft.relationship ? <span>{summaryRel}</span> : null}
|
||||
<span>{summaryGender}</span>
|
||||
</div>
|
||||
) : null}
|
||||
{summaryIntents.length ? (
|
||||
@ -875,20 +850,32 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
onChange={(e) => update("name", e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<JoinSelect
|
||||
label={socialTx("性别(选填)")}
|
||||
value={draft.gender}
|
||||
options={JOIN_GENDER_OPTIONS}
|
||||
locale={locale}
|
||||
onChange={(value) => update("gender", value)}
|
||||
/>
|
||||
<JoinSelect
|
||||
label={socialTx("感情状态(选填)")}
|
||||
value={draft.relationship}
|
||||
options={JOIN_RELATIONSHIP_OPTIONS}
|
||||
locale={locale}
|
||||
onChange={(value) => update("relationship", value)}
|
||||
/>
|
||||
<div
|
||||
className="social-join-gender social-join-span-2"
|
||||
role="group"
|
||||
aria-label={socialTx("性别")}
|
||||
>
|
||||
<span className="social-join-gender-label">
|
||||
{socialTx("性别")}
|
||||
<span className="social-join-req">*</span>
|
||||
</span>
|
||||
<div className="social-join-gender-pills">
|
||||
{JOIN_GENDER_OPTIONS.map((opt) => {
|
||||
const on = draft.gender === opt.value;
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
className={`social-join-gender-pill${on ? " is-on" : ""}`}
|
||||
aria-pressed={on}
|
||||
onClick={() => update("gender", opt.value)}
|
||||
>
|
||||
{locale === "en" ? opt.labelEn : opt.labelZh}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="social-join-section">{socialTx("工作与背景")}</p>
|
||||
<label className="social-join-span-2">
|
||||
@ -1139,6 +1126,9 @@ export function CommunityJoin() {
|
||||
return;
|
||||
}
|
||||
setStep(next);
|
||||
if (next === "profile") {
|
||||
void archiveJoinLead("profile_started");
|
||||
}
|
||||
// Never invent "paid" here — only /paid (or localhost skip) may markJoinPaid.
|
||||
if (next === "profile") {
|
||||
if (stepParam === "profile" && isJoinPaid()) {
|
||||
|
||||
@ -13,8 +13,9 @@ const HOST = {
|
||||
name: "Alice",
|
||||
city: "清迈",
|
||||
cityId: "chiangmai",
|
||||
// Real face crop — never dicebear/initials on home modules
|
||||
avatar:
|
||||
"https://api.dicebear.com/7.x/lorelei/svg?seed=AliceHost&backgroundColor=f59e0b",
|
||||
"https://images.unsplash.com/photo-1534528741775-53994a69daeb?auto=format&fit=crop&w=400&h=400&q=80&crop=faces",
|
||||
};
|
||||
|
||||
const RAIL_IDS = ["chengdu", "dali", "chiangmai", "bali", "lisbon", "hangzhou"];
|
||||
@ -125,7 +126,7 @@ export default function HomeCoffeeEntry({
|
||||
) : null}
|
||||
|
||||
<Link href={bookHref} className="home-coffee-card reveal">
|
||||
<SocialAvatar src={HOST.avatar} size={64} />
|
||||
<SocialAvatar src={HOST.avatar} size={64} faceOk />
|
||||
<div className="home-coffee-copy">
|
||||
<em>
|
||||
{socialTx("线下主持人")} · {active?.name || HOST.city}
|
||||
|
||||
@ -109,7 +109,7 @@ export default function HomeStatusStrip() {
|
||||
>
|
||||
<div className="home-status-card">
|
||||
<span className="home-status-ava">
|
||||
<SocialAvatar src={avatarSrc} size={52} />
|
||||
<SocialAvatar src={avatarSrc} size={52} allowPlaceholder />
|
||||
</span>
|
||||
<div className="home-status-meta">
|
||||
<strong>{name}</strong>
|
||||
|
||||
@ -4,7 +4,6 @@ import {
|
||||
Suspense,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
useSyncExternalStore,
|
||||
} from "react";
|
||||
@ -27,15 +26,8 @@ import { socialApi } from "@social/lib/api";
|
||||
import { SOCIAL_CITIES } from "@social/lib/cities";
|
||||
import type { SocialMapCity } from "@social/lib/geoTypes";
|
||||
import { buildMapPersonPins, type MapPersonPin } from "@social/lib/mapPins";
|
||||
import { openSocialJoinModal } from "@social/lib/joinModal";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
import {
|
||||
canUseTrial,
|
||||
consumeTrial,
|
||||
resolveTrialLimits,
|
||||
trialPaywallHint,
|
||||
} from "@social/lib/socialTrial";
|
||||
import { getSocialLive } from "@social/lib/socialLive";
|
||||
import { useDiscoveryRoster } from "@social/lib/discoveryRoster";
|
||||
import { useSocialConfig } from "./SocialExperience";
|
||||
@ -90,25 +82,12 @@ function MapClientInner() {
|
||||
const pathname = usePathname();
|
||||
const isH5 = useIsH5();
|
||||
const config = useSocialConfig();
|
||||
const trialLimits = resolveTrialLimits(config);
|
||||
const [mapBlocked, setMapBlocked] = useState(false);
|
||||
const mapTrialTaken = useRef(false);
|
||||
const cityParam = params.get("city");
|
||||
const modeParam = params.get("mode") === "globe" ? "globe" : "flat";
|
||||
const [mode, setMode] = useState<Mode>(modeParam);
|
||||
// H5:强制沉浸立体,不要平面 / 城市目录
|
||||
const effectiveMode: Mode = isH5 ? "globe" : mode;
|
||||
|
||||
useEffect(() => {
|
||||
if (mapTrialTaken.current) return;
|
||||
mapTrialTaken.current = true;
|
||||
if (!canUseTrial("mapOpens", trialLimits)) {
|
||||
setMapBlocked(true);
|
||||
return;
|
||||
}
|
||||
consumeTrial("mapOpens", trialLimits);
|
||||
}, [trialLimits]);
|
||||
|
||||
const switchMode = (next: Mode) => {
|
||||
if (isH5) return;
|
||||
setMode(next);
|
||||
@ -198,23 +177,6 @@ function MapClientInner() {
|
||||
|
||||
const showRail = !isH5;
|
||||
|
||||
if (mapBlocked) {
|
||||
return (
|
||||
<SiteShell title={socialTx("地图")} immersive>
|
||||
<div className="container" style={{ padding: "2rem 1rem" }}>
|
||||
<p>{socialTx(trialPaywallHint("mapOpens"))}</p>
|
||||
<button
|
||||
type="button"
|
||||
className="social-btn coral"
|
||||
onClick={() => openSocialJoinModal({ reason: "gate" })}
|
||||
>
|
||||
{socialTx("加入社区")}
|
||||
</button>
|
||||
</div>
|
||||
</SiteShell>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SiteShell title={socialTx("地图")} immersive>
|
||||
<div
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { MIROTALK_URL, SEED_CHANNELS } from "@social/lib/seed";
|
||||
import { resolveMirotalkUrl, SEED_CHANNELS } from "@social/lib/seed";
|
||||
import { saveJson } from "@social/lib/storage";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { resolveSocialCatalog } from "@social/lib/resolveCatalog";
|
||||
@ -21,22 +21,41 @@ import {
|
||||
|
||||
type Layout = "split" | "video" | "chat";
|
||||
|
||||
/** 自研 MiroTalk 厅 URL;只作 iframe src,禁止整页跳二级域 */
|
||||
/**
|
||||
* 自研 MiroTalk 厅 URL;只作 iframe src。
|
||||
* 必须带 name=:跳过「进入房间」昵称弹窗,直接进语音/视频画面。
|
||||
* audio/video=1 强制开麦开摄像头(服务端 checkInitConfig 已按 URL 覆盖 mute 记忆)。
|
||||
*/
|
||||
function joinUrl(room: string, name: string) {
|
||||
const nick = (name || "guest").trim().slice(0, 32) || "guest";
|
||||
const q = new URLSearchParams({
|
||||
room,
|
||||
name,
|
||||
name: nick,
|
||||
notify: "0",
|
||||
chat: "0",
|
||||
audio: "1",
|
||||
video: "1",
|
||||
});
|
||||
return `${MIROTALK_URL.replace(/\/$/, "")}/join?${q.toString()}`;
|
||||
return `${resolveMirotalkUrl().replace(/\/$/, "")}/join?${q.toString()}`;
|
||||
}
|
||||
|
||||
/** Same-origin only: pre-fill MiroTalk init nick input. */
|
||||
function seedMirotalkNick(name: string) {
|
||||
try {
|
||||
const nick = (name || "").trim();
|
||||
if (!nick || typeof window === "undefined") return;
|
||||
const origin = new URL(resolveMirotalkUrl()).origin;
|
||||
if (origin !== window.location.origin) return;
|
||||
window.localStorage.setItem("peer_name", nick);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
function warmMirotalkOrigin() {
|
||||
try {
|
||||
const origin = new URL(MIROTALK_URL).origin;
|
||||
const origin = new URL(resolveMirotalkUrl()).origin;
|
||||
// Same-origin portal already warm; still prefetch assets path
|
||||
for (const rel of ["dns-prefetch", "preconnect"] as const) {
|
||||
if (document.querySelector(`link[rel="${rel}"][href="${origin}"]`))
|
||||
continue;
|
||||
@ -111,12 +130,14 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
const startedRef = useRef(false);
|
||||
const endedRef = useRef(false);
|
||||
|
||||
const videoSrc = useMemo(
|
||||
() => joinUrl(meetup.mirotalkRoom, joinName || ensureGuestNick()),
|
||||
[meetup.mirotalkRoom, joinName],
|
||||
);
|
||||
const videoSrc = useMemo(() => {
|
||||
const nick = joinName || ensureGuestNick();
|
||||
seedMirotalkNick(nick);
|
||||
// 必须用 roomId:线下场次 seed 里 mirotalkRoom="" 时不能塞空 room(iframe 黑屏 + 乱提示)
|
||||
return joinUrl(roomId, nick);
|
||||
}, [roomId, joinName]);
|
||||
|
||||
// 防止厅内跳到门户首页(同域 /join 挂断曾会变成首页嵌套)
|
||||
// 同域 /join 挂断会跳到门户 `/`,必须立刻拉回厅,避免黑屏嵌首页
|
||||
const guardIframeHome = useCallback(() => {
|
||||
const frame = iframeRef.current;
|
||||
if (!frame) return;
|
||||
@ -126,7 +147,7 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
const isJoin = href.includes("/join");
|
||||
const isPortalHome =
|
||||
/nomadro\.(com|cn)\/?(\?|$)/.test(href) ||
|
||||
href.includes("/social") && !href.includes("/join");
|
||||
(href.includes("/social") && !href.includes("/join"));
|
||||
if (!isJoin && isPortalHome) {
|
||||
frame.src = videoSrc;
|
||||
}
|
||||
@ -215,6 +236,7 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
const name = ensureGuestNick();
|
||||
chat.setNick(name);
|
||||
saveJson("nick", name);
|
||||
seedMirotalkNick(name);
|
||||
warmMirotalkOrigin();
|
||||
setJoinName(name);
|
||||
setIframeLoading(true);
|
||||
@ -241,6 +263,7 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
const name = ensureGuestNick();
|
||||
chat.setNick(name);
|
||||
saveJson("nick", name);
|
||||
seedMirotalkNick(name);
|
||||
setJoinName(name);
|
||||
setVideoReady(true);
|
||||
// 进厅埋点抢先落库(不依赖摄像头),后台立刻有「待上传」
|
||||
@ -328,7 +351,8 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
<div>
|
||||
<strong>{meetup.title}</strong>
|
||||
<p className="social-muted">
|
||||
{meetup.date} {meetup.time} · {channel.name}
|
||||
{[meetup.date, meetup.time].filter(Boolean).join(" ")}
|
||||
{channel.topic ? ` · ${channel.topic}` : ""}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
@ -448,8 +472,9 @@ export default function MeetupLiveClient({ meetupId }: { meetupId: string }) {
|
||||
ref={iframeRef}
|
||||
title={meetup.title}
|
||||
src={videoSrc}
|
||||
allow="camera; microphone; display-capture; autoplay; fullscreen"
|
||||
allow="camera; microphone; speaker-selection; display-capture; autoplay; fullscreen; clipboard-read; clipboard-write"
|
||||
allowFullScreen
|
||||
referrerPolicy="origin"
|
||||
className="social-live-iframe"
|
||||
onLoad={() => {
|
||||
setIframeLoading(false);
|
||||
|
||||
@ -127,7 +127,7 @@ export default function NavAccountMenu({
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
>
|
||||
{profile.avatar ? (
|
||||
<SocialAvatar src={profile.avatar} size={36} />
|
||||
<SocialAvatar src={profile.avatar} size={36} allowPlaceholder />
|
||||
) : (
|
||||
<span className="social-nav-avatar-fallback" aria-hidden>
|
||||
{initial}
|
||||
@ -169,7 +169,7 @@ export default function NavAccountMenu({
|
||||
<div className="social-nav-account-body" role="tabpanel">
|
||||
<div className="social-nav-account-hero">
|
||||
{profile.avatar ? (
|
||||
<SocialAvatar src={profile.avatar} size={56} />
|
||||
<SocialAvatar src={profile.avatar} size={56} allowPlaceholder />
|
||||
) : (
|
||||
<span className="social-nav-avatar-fallback is-lg" aria-hidden>
|
||||
{initial}
|
||||
|
||||
@ -140,9 +140,8 @@ export default function PeopleProfileClient({ id }: { id: string }) {
|
||||
<SocialAvatar
|
||||
src={member.avatar}
|
||||
size={96}
|
||||
faceOk={
|
||||
member.id === SELF_MEMBER_ID ? undefined : member.faceOk
|
||||
}
|
||||
faceOk={member.faceOk}
|
||||
allowPlaceholder={member.id === SELF_MEMBER_ID}
|
||||
/>
|
||||
<div>
|
||||
<p className="social-profile-kicker">
|
||||
@ -282,9 +281,8 @@ export default function PeopleProfileClient({ id }: { id: string }) {
|
||||
<SocialAvatar
|
||||
src={member.avatar}
|
||||
size={120}
|
||||
faceOk={
|
||||
member.id === SELF_MEMBER_ID ? undefined : member.faceOk
|
||||
}
|
||||
faceOk={member.faceOk}
|
||||
allowPlaceholder={member.id === SELF_MEMBER_ID}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -268,7 +268,7 @@ export default function ProfileStudio() {
|
||||
</div>
|
||||
{profile.avatar?.trim() ? (
|
||||
<div className="social-profile-face">
|
||||
<SocialAvatar src={profile.avatar.trim()} size={88} />
|
||||
<SocialAvatar src={profile.avatar.trim()} size={88} allowPlaceholder />
|
||||
</div>
|
||||
) : (
|
||||
<div className="social-profile-monogram">
|
||||
|
||||
@ -343,6 +343,8 @@ export default function SiteShell({
|
||||
{t.skipToMain}
|
||||
</a>
|
||||
{nav}
|
||||
{/* home: heartbeat only, no presence strip on blog/policy */}
|
||||
<SocialLiveShell home />
|
||||
<div className="social-editorial-frame">
|
||||
<main
|
||||
className="social-main social-main--editorial"
|
||||
|
||||
@ -4,22 +4,38 @@ import Image from "next/image";
|
||||
|
||||
const PLACEHOLDER = "/icons/nomadro.webp";
|
||||
|
||||
/** Unoptimized keeps external/profile/API avatar URLs working offline & cross-host. */
|
||||
/**
|
||||
* Public faces: only render when faceOk === true.
|
||||
* Self/account/studio: pass allowPlaceholder (may show empty → brand mark).
|
||||
* Never paint no-face album shots or nomadro.webp as a "person" on public surfaces.
|
||||
*/
|
||||
export default function SocialAvatar({
|
||||
src,
|
||||
size,
|
||||
lazy = false,
|
||||
faceOk,
|
||||
allowPlaceholder = false,
|
||||
}: {
|
||||
src: string;
|
||||
size: number;
|
||||
lazy?: boolean;
|
||||
/** When false, never paint the raw album URL (no-face photos stay hidden). */
|
||||
/** Public: must be true. Omitted/false → nothing (unless allowPlaceholder). */
|
||||
faceOk?: boolean;
|
||||
/** Account / studio / own chrome only. */
|
||||
allowPlaceholder?: boolean;
|
||||
}) {
|
||||
const raw = (src || "").trim();
|
||||
const url = faceOk === false ? "" : raw;
|
||||
// Relative social API / blob: use plain <img> — next/image remotePatterns skip these.
|
||||
if (!allowPlaceholder && faceOk !== true) return null;
|
||||
|
||||
const url = (src || "").trim();
|
||||
if (!url && !allowPlaceholder) return null;
|
||||
// Public: never treat brand logo / data URI as a face
|
||||
if (
|
||||
!allowPlaceholder &&
|
||||
(url.includes("nomadro.webp") || url.startsWith("data:"))
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
!url ||
|
||||
url.startsWith("/api/") ||
|
||||
@ -38,6 +54,10 @@ export default function SocialAvatar({
|
||||
style={{ width: size, height: size, objectFit: "cover" }}
|
||||
onError={(event) => {
|
||||
const img = event.currentTarget;
|
||||
if (!allowPlaceholder) {
|
||||
img.style.display = "none";
|
||||
return;
|
||||
}
|
||||
if (!img.src.endsWith(PLACEHOLDER)) img.src = PLACEHOLDER;
|
||||
}}
|
||||
/>
|
||||
@ -53,6 +73,10 @@ export default function SocialAvatar({
|
||||
loading={lazy ? "lazy" : "eager"}
|
||||
onError={(event) => {
|
||||
const img = event.currentTarget;
|
||||
if (!allowPlaceholder) {
|
||||
img.style.display = "none";
|
||||
return;
|
||||
}
|
||||
if (!img.src.endsWith(PLACEHOLDER)) img.src = PLACEHOLDER;
|
||||
}}
|
||||
/>
|
||||
|
||||
@ -1,73 +1,29 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* Social Live UX — heartbeat always; chrome only when it earns the pixel.
|
||||
* Never paste landing copy into presence. Never sticky-bar the home hero.
|
||||
* Social Live UX — heartbeat only; no「N 人在线」strip chrome.
|
||||
*/
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useRemoteConfig } from "~/lib/use-remote-config";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
import {
|
||||
getSocialLive,
|
||||
type SocialLiveFlags,
|
||||
} from "@social/lib/socialLive";
|
||||
import { socialTrack } from "@social/lib/socialTrack";
|
||||
import { useSocialPresence } from "@social/lib/useSocialPresence";
|
||||
import SocialAvatar from "./SocialAvatar";
|
||||
|
||||
function LiveToast({
|
||||
text,
|
||||
onDone,
|
||||
}: {
|
||||
text: string;
|
||||
onDone: () => void;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
const t = setTimeout(onDone, 3200);
|
||||
return () => clearTimeout(t);
|
||||
}, [onDone, text]);
|
||||
return (
|
||||
<div className="social-live-toast" role="status" aria-live="polite">
|
||||
{text}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SocialLiveShell({
|
||||
/** Home hero: never sticky-strip under nav */
|
||||
home = false,
|
||||
}: {
|
||||
home?: boolean;
|
||||
}) {
|
||||
const pathname = usePathname();
|
||||
const { config } = useRemoteConfig();
|
||||
const live = getSocialLive(config);
|
||||
const presence = useSocialPresence(config);
|
||||
const [toast, setToast] = useState("");
|
||||
const [navOffline, setNavOffline] = useState(false);
|
||||
// Keep presence effect mounted (silent heartbeat).
|
||||
useSocialPresence(config);
|
||||
const lastVersion = useRef<number>(Number(config.version) || 0);
|
||||
const booted = useRef(false);
|
||||
|
||||
const isHome =
|
||||
home ||
|
||||
pathname === socialPath("/") ||
|
||||
pathname === socialPath("") ||
|
||||
pathname === "/social" ||
|
||||
pathname === "/social/";
|
||||
|
||||
useEffect(() => {
|
||||
const sync = () =>
|
||||
setNavOffline(typeof navigator !== "undefined" && !navigator.onLine);
|
||||
sync();
|
||||
window.addEventListener("online", sync);
|
||||
window.addEventListener("offline", sync);
|
||||
return () => {
|
||||
window.removeEventListener("online", sync);
|
||||
window.removeEventListener("offline", sync);
|
||||
};
|
||||
}, []);
|
||||
void home;
|
||||
|
||||
useEffect(() => {
|
||||
const v = Number(config.version) || 0;
|
||||
@ -79,90 +35,10 @@ export default function SocialLiveShell({
|
||||
if (v && v !== lastVersion.current) {
|
||||
lastVersion.current = v;
|
||||
socialTrack(live, "social_config_hot", { version: v });
|
||||
if (live.configHotReloadToast) {
|
||||
setToast(
|
||||
socialTx("社区配置已更新") +
|
||||
(live.configVersionChip ? ` · v${v}` : ""),
|
||||
);
|
||||
}
|
||||
}
|
||||
}, [config.version, live]);
|
||||
|
||||
// Only real browser offline — never flash on first-paint config seed.
|
||||
const showOffline = live.offlineFallbackShell && navOffline;
|
||||
|
||||
const peers =
|
||||
live.presenceCityScope && presence.cityPeers.length
|
||||
? presence.cityPeers
|
||||
: presence.peers;
|
||||
const count =
|
||||
live.presenceCityScope && presence.cityOnline > 0
|
||||
? presence.cityOnline
|
||||
: presence.online;
|
||||
|
||||
// Home: never float / never strip — heartbeat still runs, zero chrome.
|
||||
const showStrip =
|
||||
!isHome &&
|
||||
live.presenceStrip &&
|
||||
live.presenceEnabled &&
|
||||
count > 0 &&
|
||||
!presence.fromOffline;
|
||||
|
||||
if (!showStrip && !showOffline && !toast) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`social-live-shell${isHome ? " is-home" : ""}`}
|
||||
aria-live="polite"
|
||||
>
|
||||
{showOffline ? (
|
||||
<div className="social-live-offline" role="status">
|
||||
<span className="social-live-dot is-warn" aria-hidden />
|
||||
<div>
|
||||
<strong>{socialTx("网络已断开")}</strong>
|
||||
<p>{socialTx("仍可浏览本地数据,连上后自动刷新。")}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{showStrip ? (
|
||||
<div
|
||||
className={`social-live-strip${isHome ? " is-float" : ""}`}
|
||||
data-offline="0"
|
||||
>
|
||||
<span className="social-live-dot is-ok" aria-hidden />
|
||||
<strong>
|
||||
{live.onlineCountBadge ? (
|
||||
<em className="social-live-count">{count}</em>
|
||||
) : null}
|
||||
{socialTx("人在线")}
|
||||
</strong>
|
||||
{peers.length ? (
|
||||
<div className="social-live-avs" aria-hidden>
|
||||
{peers.slice(0, 6).map((p) => (
|
||||
<SocialAvatar
|
||||
key={p.guestId}
|
||||
src={p.avatar || ""}
|
||||
size={20}
|
||||
lazy
|
||||
faceOk={
|
||||
live.hideNoFaceAvatar ? Boolean(p.avatar) : undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{live.configVersionChip ? (
|
||||
<span className="social-live-ver">v{config.version || "—"}</span>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{toast ? <LiveToast text={toast} onDone={() => setToast("")} /> : null}
|
||||
</div>
|
||||
);
|
||||
return <div className="social-live-shell is-silent" aria-hidden />;
|
||||
}
|
||||
|
||||
export function readLiveFlags(
|
||||
|
||||
@ -25,6 +25,8 @@ export default function TrialNudgeBanner() {
|
||||
const limits = useMemo(() => resolveTrialLimits(config), [config]);
|
||||
|
||||
if (!pathNeedsLiveness(pathname)) return null;
|
||||
// 地图沉浸页禁止顶栏试用横幅——会顶开地球/底图,看起来像花屏叠导航
|
||||
if ((pathname || "").includes("/map")) return null;
|
||||
if (unlockSnap === "1") return null;
|
||||
if (!limits.enabled) return null;
|
||||
|
||||
|
||||
@ -555,7 +555,12 @@ export const socialApi = {
|
||||
throw new Error(lastErr || "反馈提交失败");
|
||||
},
|
||||
|
||||
/** Join funnel archive — try portal + social (local rewrite often 404s old social). */
|
||||
/**
|
||||
* Join funnel archive.
|
||||
* Prefer portal (local file + server-side forward to SOCIAL_API_URL).
|
||||
* Never hard-hit production from localhost — that polluted admin.nomadro.com
|
||||
* and created duplicate leads during local QA.
|
||||
*/
|
||||
postJoinLead: async (payload: {
|
||||
email: string;
|
||||
stage?: string;
|
||||
@ -571,14 +576,9 @@ export const socialApi = {
|
||||
"Content-Type": "application/json",
|
||||
"X-Social-Guest-Id": getGuestId(),
|
||||
};
|
||||
const urls = [
|
||||
"/api/portal/join-leads",
|
||||
`${BASE}/join/leads`,
|
||||
"https://nomadro.com/api/social/v1/join/leads",
|
||||
];
|
||||
// Portal first (server forwards via SOCIAL_API_URL); social rewrite as fallback.
|
||||
const urls = ["/api/portal/join-leads", `${BASE}/join/leads`];
|
||||
let lastErr = "";
|
||||
let lastOk: { ok: boolean; id?: string; email?: string; stage?: string } | null =
|
||||
null;
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
@ -592,18 +592,17 @@ export const socialApi = {
|
||||
lastErr = await res.text().catch(() => `HTTP ${res.status}`);
|
||||
continue;
|
||||
}
|
||||
lastOk = (await res.json()) as {
|
||||
const data = (await res.json()) as {
|
||||
ok: boolean;
|
||||
id?: string;
|
||||
email?: string;
|
||||
stage?: string;
|
||||
};
|
||||
// keep trying US so admin.nomadro.com sees the lead
|
||||
if (data?.ok !== false) return data;
|
||||
} catch (e) {
|
||||
lastErr = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
}
|
||||
if (lastOk) return lastOk;
|
||||
throw new Error(lastErr || "join lead failed");
|
||||
},
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user