From 499f2d3e26f49e3f939869afc44be97bc4444335 Mon Sep 17 00:00:00 2001 From: Eric Date: Thu, 5 Nov 2026 18:19:37 +0800 Subject: [PATCH] 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 --- README.md | 2 + apps/api/run.py | 9 + apps/api/services/coffee_svc/pb_store.py | 79 ++++-- apps/api/services/coffee_svc/routers/api.py | 150 +++++++++-- apps/api/services/coffee_svc/scheduling.py | 37 +++ apps/api/services/coffee_svc/store.py | 1 + .../ebook_svc/routers/audience_admin.py | 3 +- .../ebook_svc/routers/social_blog_admin.py | 21 +- .../ebook_svc/routers/social_ugc_admin.py | 81 ++++++ .../ebook_svc/services/audience_config.py | 26 +- .../ebook_svc/services/social_blog_ops.py | 5 +- .../services/ebook_svc/services/social_ugc.py | 4 + apps/api/services/nomadro_pb/config.py | 11 + apps/api/services/nomadro_pb/ensure.py | 43 ++- apps/api/services/nomadro_pb/schemas.py | 4 +- apps/api/services/notify_svc/access.py | 33 +++ apps/api/services/notify_svc/pb_store.py | 28 +- apps/api/services/notify_svc/routers/api.py | 5 +- apps/api/services/notify_svc/store.py | 1 + apps/api/services/social_svc/face_check.py | 18 +- apps/api/services/social_svc/notify_bridge.py | 2 + apps/api/services/social_svc/onboarding.py | 2 +- apps/api/services/social_svc/pb_data.py | 203 ++++++++++++-- apps/api/services/social_svc/routers/api.py | 2 +- apps/api/services/social_svc/store.py | 2 +- apps/api/tests/pb_fixture.py | 2 + apps/api/tests/test_coffee_notify_api.py | 117 +++++++++ apps/api/tests/test_coffee_scheduling.py | 50 ++++ apps/api/tests/test_scoped_schema.py | 40 +++ apps/api/tests/test_uiux_config.py | 79 ++++++ apps/com/admin/src/api/client.ts | 11 +- .../src/components/PresenceLivePulse.tsx | 70 +++++ .../admin/src/components/UnsavedChanges.tsx | 36 +++ apps/com/admin/src/components/WebLayout.tsx | 18 +- .../admin/src/lib/SocialPresenceContext.tsx | 31 +++ apps/com/admin/src/lib/useDraft.ts | 26 ++ .../admin/src/lib/useSocialPresenceLive.ts | 97 +++++++ apps/com/admin/src/main.tsx | 8 +- apps/com/admin/src/pages/Blog.tsx | 62 +++-- apps/com/admin/src/pages/LaneHub.tsx | 36 ++- apps/com/admin/src/pages/Login.tsx | 5 +- apps/com/admin/src/pages/Pricing.tsx | 101 +++---- apps/com/admin/src/pages/Social.tsx | 96 ++++++- apps/com/admin/src/pages/SocialDetail.tsx | 11 +- apps/com/admin/src/pages/Switches.tsx | 47 ++-- apps/com/admin/src/pages/socialMeta.ts | 13 + apps/com/admin/src/upgrade.css | 170 ++++++++++++ apps/com/deploy/install-uiux-services.py | 80 ++++++ data/remote-config.json | 23 +- deploy/social/mirotalk/nomadro-embed.css | 138 +++++++++- docs/uiux-upgrade-2026-11-05.md | 62 +++++ next.config.ts | 18 +- scripts/audit_uiux_runtime_com.py | 18 ++ scripts/check-admin-editing.py | 196 ++++++++++++++ scripts/check-live-uiux-com.py | 38 +++ scripts/check-portal-uiux.py | 189 +++++++++++++ scripts/check-services-pocketbase.py | 98 +++++++ scripts/deploy_platform_upgrade_com.py | 10 +- scripts/deploy_portal_upgrade_com.py | 11 + scripts/deploy_uiux_services_com.py | 99 +++++++ src/app/api/portal/join-leads/route.ts | 42 ++- src/app/layout.tsx | 10 +- src/lib/client-request.ts | 52 ++++ src/lib/fonts.ts | 9 + src/lib/fonts/OFL.txt | 93 +++++++ src/lib/fonts/Outfit.ttf | Bin 0 -> 110884 bytes src/lib/remote-config.ts | 4 +- src/lib/service-proxy.ts | 9 +- src/lib/use-remote-config.ts | 13 +- .../coffee/components/CoffeeBookPage.tsx | 113 +++++--- .../coffee/components/CoffeeBookingDetail.tsx | 74 ++++-- .../coffee/components/CoffeeHostPage.tsx | 15 +- .../coffee/components/CoffeeLanding.tsx | 21 +- .../coffee/components/CoffeeManagePage.tsx | 248 ++++++++---------- src/modules/coffee/lib/api.ts | 29 +- src/modules/coffee/lib/calendar.ts | 42 +++ src/modules/coffee/lib/device-key.ts | 10 + src/modules/community/app/layout.tsx | 9 +- .../components/NotificationSettingsClient.tsx | 113 +++++--- .../notify/components/NotificationsClient.tsx | 82 +++--- src/modules/notify/components/NotifyBell.tsx | 29 +- .../notify/components/notifications.css | 22 +- src/modules/notify/lib/api.ts | 25 +- src/modules/notify/lib/useNotifySubscriber.ts | 24 ++ src/modules/social/app/experience.css | 101 ++++++- src/modules/social/app/h5.css | 12 + .../social/components/ChatWorkspace.tsx | 9 +- .../social/components/CommunityWelcome.tsx | 90 +++---- .../social/components/HomeCoffeeEntry.tsx | 5 +- .../social/components/HomeStatusStrip.tsx | 2 +- src/modules/social/components/MapClient.tsx | 38 --- .../social/components/MeetupLiveClient.tsx | 51 +++- .../social/components/NavAccountMenu.tsx | 4 +- .../social/components/PeopleProfileClient.tsx | 10 +- .../social/components/ProfileStudio.tsx | 2 +- src/modules/social/components/SiteShell.tsx | 2 + .../social/components/SocialAvatar.tsx | 34 ++- .../social/components/SocialLiveShell.tsx | 136 +--------- .../social/components/TrialNudgeBanner.tsx | 2 + src/modules/social/lib/api.ts | 21 +- src/modules/social/lib/discoveryRoster.ts | 21 +- src/modules/social/lib/joinFlow.ts | 5 +- src/modules/social/lib/mapPins.ts | 3 +- src/modules/social/lib/phrases.ts | 2 + src/modules/social/lib/resolveCatalog.ts | 8 +- src/modules/social/lib/rosterAvatars.ts | 1 + src/modules/social/lib/rosterMock.ts | 8 +- src/modules/social/lib/seed.ts | 35 ++- src/modules/social/lib/useAudienceRoster.ts | 6 +- src/modules/social/lib/useSocialPresence.ts | 19 +- src/modules/work/lib/api.ts | 16 +- src/modules/work/micro/custom-elements.d.ts | 16 ++ 112 files changed, 3729 insertions(+), 896 deletions(-) create mode 100644 apps/api/services/coffee_svc/scheduling.py create mode 100644 apps/api/services/notify_svc/access.py create mode 100644 apps/api/tests/test_coffee_notify_api.py create mode 100644 apps/api/tests/test_coffee_scheduling.py create mode 100644 apps/api/tests/test_scoped_schema.py create mode 100644 apps/api/tests/test_uiux_config.py create mode 100644 apps/com/admin/src/components/PresenceLivePulse.tsx create mode 100644 apps/com/admin/src/components/UnsavedChanges.tsx create mode 100644 apps/com/admin/src/lib/SocialPresenceContext.tsx create mode 100644 apps/com/admin/src/lib/useDraft.ts create mode 100644 apps/com/admin/src/lib/useSocialPresenceLive.ts create mode 100644 apps/com/deploy/install-uiux-services.py create mode 100644 docs/uiux-upgrade-2026-11-05.md create mode 100644 scripts/audit_uiux_runtime_com.py create mode 100644 scripts/check-admin-editing.py create mode 100644 scripts/check-live-uiux-com.py create mode 100644 scripts/check-portal-uiux.py create mode 100644 scripts/check-services-pocketbase.py create mode 100644 scripts/deploy_uiux_services_com.py create mode 100644 src/lib/client-request.ts create mode 100644 src/lib/fonts.ts create mode 100644 src/lib/fonts/OFL.txt create mode 100644 src/lib/fonts/Outfit.ttf create mode 100644 src/modules/coffee/lib/calendar.ts create mode 100644 src/modules/coffee/lib/device-key.ts create mode 100644 src/modules/notify/lib/useNotifySubscriber.ts create mode 100644 src/modules/work/micro/custom-elements.d.ts diff --git a/README.md b/README.md index 9133a1e..68d3854 100644 --- a/README.md +++ b/README.md @@ -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` 未同步本次发版。 diff --git a/apps/api/run.py b/apps/api/run.py index a35ccdc..b13b9ce 100644 --- a/apps/api/run.py +++ b/apps/api/run.py @@ -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 diff --git a/apps/api/services/coffee_svc/pb_store.py b/apps/api/services/coffee_svc/pb_store.py index f5ea64c..5c37c7c 100644 --- a/apps/api/services/coffee_svc/pb_store.py +++ b/apps/api/services/coffee_svc/pb_store.py @@ -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: diff --git a/apps/api/services/coffee_svc/routers/api.py b/apps/api/services/coffee_svc/routers/api.py index 8451896..4e194ad 100644 --- a/apps/api/services/coffee_svc/routers/api.py +++ b/apps/api/services/coffee_svc/routers/api.py @@ -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") diff --git a/apps/api/services/coffee_svc/scheduling.py b/apps/api/services/coffee_svc/scheduling.py new file mode 100644 index 0000000..2a54ff1 --- /dev/null +++ b/apps/api/services/coffee_svc/scheduling.py @@ -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)] diff --git a/apps/api/services/coffee_svc/store.py b/apps/api/services/coffee_svc/store.py index e6d6448..d8d8bc2 100644 --- a/apps/api/services/coffee_svc/store.py +++ b/apps/api/services/coffee_svc/store.py @@ -14,4 +14,5 @@ from coffee_svc.pb_store import ( # noqa: F401 list_hosts, update_schedule, upsert_event_type, + upsert_host, ) diff --git a/apps/api/services/ebook_svc/routers/audience_admin.py b/apps/api/services/ebook_svc/routers/audience_admin.py index f024831..969230f 100644 --- a/apps/api/services/ebook_svc/routers/audience_admin.py +++ b/apps/api/services/ebook_svc/routers/audience_admin.py @@ -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 diff --git a/apps/api/services/ebook_svc/routers/social_blog_admin.py b/apps/api/services/ebook_svc/routers/social_blog_admin.py index 9884c41..7a88943 100644 --- a/apps/api/services/ebook_svc/routers/social_blog_admin.py +++ b/apps/api/services/ebook_svc/routers/social_blog_admin.py @@ -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") diff --git a/apps/api/services/ebook_svc/routers/social_ugc_admin.py b/apps/api/services/ebook_svc/routers/social_ugc_admin.py index e003e06..5d55f37 100644 --- a/apps/api/services/ebook_svc/routers/social_ugc_admin.py +++ b/apps/api/services/ebook_svc/routers/social_ugc_admin.py @@ -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 = "", diff --git a/apps/api/services/ebook_svc/services/audience_config.py b/apps/api/services/ebook_svc/services/audience_config.py index 0268454..cdc0b28 100644 --- a/apps/api/services/ebook_svc/services/audience_config.py +++ b/apps/api/services/ebook_svc/services/audience_config.py @@ -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 = { diff --git a/apps/api/services/ebook_svc/services/social_blog_ops.py b/apps/api/services/ebook_svc/services/social_blog_ops.py index 88fb8dd..8bb9069 100644 --- a/apps/api/services/ebook_svc/services/social_blog_ops.py +++ b/apps/api/services/ebook_svc/services/social_blog_ops.py @@ -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) diff --git a/apps/api/services/ebook_svc/services/social_ugc.py b/apps/api/services/ebook_svc/services/social_ugc.py index 6b4adc0..c0810dc 100644 --- a/apps/api/services/ebook_svc/services/social_ugc.py +++ b/apps/api/services/ebook_svc/services/social_ugc.py @@ -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) diff --git a/apps/api/services/nomadro_pb/config.py b/apps/api/services/nomadro_pb/config.py index 3d6e6f3..a59cb2f 100644 --- a/apps/api/services/nomadro_pb/config.py +++ b/apps/api/services/nomadro_pb/config.py @@ -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 = ( diff --git a/apps/api/services/nomadro_pb/ensure.py b/apps/api/services/nomadro_pb/ensure.py index b51a94a..e92d526 100644 --- a/apps/api/services/nomadro_pb/ensure.py +++ b/apps/api/services/nomadro_pb/ensure.py @@ -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: diff --git a/apps/api/services/nomadro_pb/schemas.py b/apps/api/services/nomadro_pb/schemas.py index e0e2ce3..28ed0c8 100644 --- a/apps/api/services/nomadro_pb/schemas.py +++ b/apps/api/services/nomadro_pb/schemas.py @@ -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"), ], diff --git a/apps/api/services/notify_svc/access.py b/apps/api/services/notify_svc/access.py new file mode 100644 index 0000000..dc5a90f --- /dev/null +++ b/apps/api/services/notify_svc/access.py @@ -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') diff --git a/apps/api/services/notify_svc/pb_store.py b/apps/api/services/notify_svc/pb_store.py index 84dae02..9b41bec 100644 --- a/apps/api/services/notify_svc/pb_store.py +++ b/apps/api/services/notify_svc/pb_store.py @@ -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) diff --git a/apps/api/services/notify_svc/routers/api.py b/apps/api/services/notify_svc/routers/api.py index 8ef869d..6230d2c 100644 --- a/apps/api/services/notify_svc/routers/api.py +++ b/apps/api/services/notify_svc/routers/api.py @@ -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): diff --git a/apps/api/services/notify_svc/store.py b/apps/api/services/notify_svc/store.py index d0463ab..36bd8ce 100644 --- a/apps/api/services/notify_svc/store.py +++ b/apps/api/services/notify_svc/store.py @@ -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, diff --git a/apps/api/services/social_svc/face_check.py b/apps/api/services/social_svc/face_check.py index 18f4fe6..dda7c52 100644 --- a/apps/api/services/social_svc/face_check.py +++ b/apps/api/services/social_svc/face_check.py @@ -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( diff --git a/apps/api/services/social_svc/notify_bridge.py b/apps/api/services/social_svc/notify_bridge.py index c52f43b..b8584ca 100644 --- a/apps/api/services/social_svc/notify_bridge.py +++ b/apps/api/services/social_svc/notify_bridge.py @@ -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) diff --git a/apps/api/services/social_svc/onboarding.py b/apps/api/services/social_svc/onboarding.py index bedd796..96b30db 100644 --- a/apps/api/services/social_svc/onboarding.py +++ b/apps/api/services/social_svc/onboarding.py @@ -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: diff --git a/apps/api/services/social_svc/pb_data.py b/apps/api/services/social_svc/pb_data.py index 412abab..5901d58 100644 --- a/apps/api/services/social_svc/pb_data.py +++ b/apps/api/services/social_svc/pb_data.py @@ -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: diff --git a/apps/api/services/social_svc/routers/api.py b/apps/api/services/social_svc/routers/api.py index 033de44..7d7d152 100644 --- a/apps/api/services/social_svc/routers/api.py +++ b/apps/api/services/social_svc/routers/api.py @@ -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), ): diff --git a/apps/api/services/social_svc/store.py b/apps/api/services/social_svc/store.py index 9906d6a..6d4901a 100644 --- a/apps/api/services/social_svc/store.py +++ b/apps/api/services/social_svc/store.py @@ -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 diff --git a/apps/api/tests/pb_fixture.py b/apps/api/tests/pb_fixture.py index 241c675..b23b9ee 100644 --- a/apps/api/tests/pb_fixture.py +++ b/apps/api/tests/pb_fixture.py @@ -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() diff --git a/apps/api/tests/test_coffee_notify_api.py b/apps/api/tests/test_coffee_notify_api.py new file mode 100644 index 0000000..3066be4 --- /dev/null +++ b/apps/api/tests/test_coffee_notify_api.py @@ -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() diff --git a/apps/api/tests/test_coffee_scheduling.py b/apps/api/tests/test_coffee_scheduling.py new file mode 100644 index 0000000..e367a95 --- /dev/null +++ b/apps/api/tests/test_coffee_scheduling.py @@ -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() diff --git a/apps/api/tests/test_scoped_schema.py b/apps/api/tests/test_scoped_schema.py new file mode 100644 index 0000000..a0d164c --- /dev/null +++ b/apps/api/tests/test_scoped_schema.py @@ -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'}]})) diff --git a/apps/api/tests/test_uiux_config.py b/apps/api/tests/test_uiux_config.py new file mode 100644 index 0000000..fdbcf17 --- /dev/null +++ b/apps/api/tests/test_uiux_config.py @@ -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() diff --git a/apps/com/admin/src/api/client.ts b/apps/com/admin/src/api/client.ts index 167d845..0e267cb 100644 --- a/apps/com/admin/src/api/client.ts +++ b/apps/com/admin/src/api/client.ts @@ -30,26 +30,31 @@ export async function api(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) diff --git a/apps/com/admin/src/components/PresenceLivePulse.tsx b/apps/com/admin/src/components/PresenceLivePulse.tsx new file mode 100644 index 0000000..ad74dc0 --- /dev/null +++ b/apps/com/admin/src/components/PresenceLivePulse.tsx @@ -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 ( + <> + p.nick) + .join(' · ') + : snap.fromOffline + ? '在线心跳暂时连不上' + : '暂无访客心跳' + } + > + + {count} + + {live ? '人在线' : snap.fromOffline ? '心跳离线' : '等待访客'} + + {live && snap.peers.length ? ( + + {snap.peers.slice(0, 4).map((p) => ( + + {(p.nick || '?').slice(0, 1)} + + ))} + + ) : null} + + + {toast ? ( +
+ + {toast} + 实时 +
+ ) : null} + + ) +} diff --git a/apps/com/admin/src/components/UnsavedChanges.tsx b/apps/com/admin/src/components/UnsavedChanges.tsx new file mode 100644 index 0000000..c212b1c --- /dev/null +++ b/apps/com/admin/src/components/UnsavedChanges.tsx @@ -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(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 &&
有未保存修改
} + { event.preventDefault(); if (blocker.state === 'blocked') blocker.reset() }}> +

保留当前修改?

+

当前修改尚未保存。你可以继续编辑,或放弃修改后离开。

+
+ + +
+
+ +} diff --git a/apps/com/admin/src/components/WebLayout.tsx b/apps/com/admin/src/components/WebLayout.tsx index 20a277a..9fce530 100644 --- a/apps/com/admin/src/components/WebLayout.tsx +++ b/apps/com/admin/src/components/WebLayout.tsx @@ -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 ( + - - - {online ? '网络已连接' : '网络已断开'} - +
+ + + + {online ? '网络已连接' : '网络已断开'} + +
{!online ? (
@@ -366,5 +369,6 @@ export default function WebLayout() {
+
) } diff --git a/apps/com/admin/src/lib/SocialPresenceContext.tsx b/apps/com/admin/src/lib/SocialPresenceContext.tsx new file mode 100644 index 0000000..7ae09b9 --- /dev/null +++ b/apps/com/admin/src/lib/SocialPresenceContext.tsx @@ -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(EMPTY) + +export function SocialPresenceProvider({ children }: { children: ReactNode }) { + const snap = useSocialPresenceLive() + return {children} +} + +export function useSharedSocialPresence(): PresenceSnap { + return useContext(Ctx) +} diff --git a/apps/com/admin/src/lib/useDraft.ts b/apps/com/admin/src/lib/useDraft.ts new file mode 100644 index 0000000..3564b3d --- /dev/null +++ b/apps/com/admin/src/lib/useDraft.ts @@ -0,0 +1,26 @@ +import { useState } from 'react' + +/** Rebase untouched fields after a partial save without losing other edits. */ +export function useDraft>(initial: T) { + const [draft, setDraft] = useState(initial) + const [baseline, setBaseline] = useState(initial) + const dirty = (Object.keys(draft) as Array).some(key => draft[key] !== baseline[key]) + + function accept(next: T, savedFields: Array = []) { + setDraft(current => { + const rebased = { ...current } + for (const key of Object.keys(next) as Array) { + 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 } +} diff --git a/apps/com/admin/src/lib/useSocialPresenceLive.ts b/apps/com/admin/src/lib/useSocialPresenceLive.ts new file mode 100644 index 0000000..ddc7a63 --- /dev/null +++ b/apps/com/admin/src/lib/useSocialPresenceLive.ts @@ -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(EMPTY) + const seen = useRef>(new Set()) + const booted = useRef(false) + + useEffect(() => { + let cancelled = false + let timer: ReturnType | 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 +} diff --git a/apps/com/admin/src/main.tsx b/apps/com/admin/src/main.tsx index 6235cfe..e69c6b1 100644 --- a/apps/com/admin/src/main.tsx +++ b/apps/com/admin/src/main.tsx @@ -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: }]) + ReactDOM.createRoot(document.getElementById('root')!).render( - - - + , ) diff --git a/apps/com/admin/src/pages/Blog.tsx b/apps/com/admin/src/pages/Blog.tsx index b949b02..e984e8c 100644 --- a/apps/com/admin/src/pages/Blog.tsx +++ b/apps/com/admin/src/pages/Blog.tsx @@ -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('posts') const [ov, setOv] = useState(null) const [posts, setPosts] = useState([]) @@ -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, 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('/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) 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() { 打开博客 ↗ ) : null} - - {msg ?
{msg}
: null} - {err ?
{err}
: null} + + {msg ?
{msg}
: null} + {err ?
{err}
: null} + {stale &&
线上配置已更新,当前草稿已保留。请使用刷新按钮加载最新配置后再保存。
}
@@ -228,6 +254,8 @@ export default function Blog() {
setQ(e.target.value)} @@ -308,6 +336,7 @@ export default function Blog() {