Compare commits
111 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5b0506a663 | |||
| efb5e426b7 | |||
| d0e1bea941 | |||
| 346836f561 | |||
| 2b5d2cd801 | |||
| 6139960a9e | |||
| cbb704577a | |||
| 0c8ad54780 | |||
| 98bcfe2a21 | |||
| e32cfd8015 | |||
| 7237278f5a | |||
| 15a452dd49 | |||
| 2007ded86d | |||
| 1ab7db065c | |||
| 436afe121a | |||
| 88b355e9de | |||
| b146c637b6 | |||
| 7caae4dceb | |||
| 28db3ed428 | |||
| 306d701a2d | |||
| 54c93db483 | |||
| 961451aeff | |||
| a584da83f7 | |||
| 443540c27e | |||
| ab5c5cfb23 | |||
| 7de31ec429 | |||
| 7589fd74bf | |||
| fd210ac730 | |||
| 2b0e6a6f67 | |||
| b1ce479909 | |||
| 6d20d51bb9 | |||
| 4e0ddfa771 | |||
| b866ebf6e3 | |||
| afffbb852b | |||
| 69ea686750 | |||
| b7a72bd9ff | |||
| 77f2b6ac07 | |||
| 1dfdd18421 | |||
| 67e691ed95 | |||
| 1461d02488 | |||
| 54acfc05aa | |||
| bbc5dbb8d6 | |||
| 29f6542a72 | |||
| 05184cb2ad | |||
| b365155622 | |||
| fc72b3539d | |||
| 5796d380c5 | |||
| 58a09fe6fe | |||
| 4ac690228e | |||
| 90822c81d4 | |||
| 5e83a5cca3 | |||
| 578e50b2da | |||
| 5ac5caf3ef | |||
| 7adec4e17c | |||
| 354d55f752 | |||
| 6feb4ff489 | |||
| fcaa9d5c7f | |||
| b1102400f6 | |||
| 5e31bc9ea3 | |||
| ff7d77ef06 | |||
| ce22752ccc | |||
| 8a091fd7cc | |||
| 06b1e1b9fe | |||
| 21a42af01c | |||
| ace9c71743 | |||
| 7cdd6102c6 | |||
| f8b17d16ea | |||
| e2c51f5125 | |||
| 60785471e2 | |||
| d2b27b1020 | |||
| 7171192ea6 | |||
| e8a39000b9 | |||
| 4519af0c6c | |||
| 3cb5d2e8fc | |||
| 2ba680954c | |||
| 33385c3dda | |||
| 3c950956e3 | |||
| 2eb46853bf | |||
| c795d90993 | |||
| 7fe89e097b | |||
| bddcd434da | |||
| 6aa3a7dda8 | |||
| dd720582d5 | |||
| adf2924a1c | |||
| e662ef7d3b | |||
| 0425c237b1 | |||
| 13cd176449 | |||
| 49d883e3a2 | |||
| 75c2baf1d1 | |||
| b11836a378 | |||
| f7c5a2f443 | |||
| 290dd2b3cf | |||
| ac03fb74be | |||
| 4413b31396 | |||
| a19925fe7a | |||
| 8959faac91 | |||
| e7e52c0da7 | |||
| 345c56c4f4 | |||
| e4b8d71653 | |||
| ddf909f690 | |||
| 98d36a9174 | |||
| a0b8a3595c | |||
| 7225b8bcc7 | |||
| 43749fff7c | |||
| 6b76290cff | |||
| 48619830a5 | |||
| 74e35b990b | |||
| f6771247a6 | |||
| 3196552c78 | |||
| 03dcb4329b | |||
| 1c84893bed |
+81
-85
@@ -1,75 +1,85 @@
|
||||
# Telegram Bot
|
||||
TELEGRAM_BOT_TOKEN=your_bot_token_here
|
||||
TELEGRAM_CHAT_ID=your_chat_id_here
|
||||
# Optional multi-chat target (comma-separated). If set, it will be merged with TELEGRAM_CHAT_ID.
|
||||
# Example: TELEGRAM_CHAT_IDS=-1003586303099,-1003539418691
|
||||
# PolyWeather backend/bot minimal reproducible config
|
||||
# Full configuration guide:
|
||||
# docs/CONFIGURATION_ZH.md
|
||||
# Sensitive-only template:
|
||||
# .env.secrets.example
|
||||
|
||||
########################################
|
||||
# 1) Runtime paths and base behavior
|
||||
########################################
|
||||
ENV=production
|
||||
LOG_LEVEL=INFO
|
||||
POLYWEATHER_MAP_URL=https://polyweather-pro.vercel.app/
|
||||
POLYWEATHER_RUNTIME_DATA_DIR=/var/lib/polyweather
|
||||
POLYWEATHER_DB_PATH=/var/lib/polyweather/polyweather.db
|
||||
OPEN_METEO_DISK_CACHE_PATH=/var/lib/polyweather/open_meteo_cache.json
|
||||
# Optional: host user/group mapping for Docker on Linux.
|
||||
# Windows / macOS can usually keep the defaults.
|
||||
UID=1000
|
||||
GID=1000
|
||||
POLYWEATHER_STATE_STORAGE_MODE=dual
|
||||
|
||||
########################################
|
||||
# 2) Telegram bot minimal
|
||||
########################################
|
||||
TELEGRAM_BOT_TOKEN=
|
||||
TELEGRAM_CHAT_ID=
|
||||
TELEGRAM_CHAT_IDS=
|
||||
# Optional: route /city and /deb outputs to a fixed forum topic.
|
||||
# If TELEGRAM_QUERY_TOPIC_CHAT_ID is empty, fallback to command source chat.
|
||||
TELEGRAM_QUERY_TOPIC_CHAT_ID=
|
||||
TELEGRAM_QUERY_TOPIC_ID=
|
||||
# Optional per-group topic routing (higher priority than fixed topic above):
|
||||
# format: chat_id:topic_id,chat_id:topic_id
|
||||
# Example: TELEGRAM_QUERY_TOPIC_MAP=-1003586303099:25513,-1003539418691:25514
|
||||
TELEGRAM_QUERY_TOPIC_MAP=
|
||||
TELEGRAM_ALERT_PUSH_ENABLED=true
|
||||
TELEGRAM_ALERT_PUSH_INTERVAL_SEC=300
|
||||
TELEGRAM_ALERT_PUSH_COOLDOWN_SEC=1800
|
||||
TELEGRAM_ALERT_MIN_TRIGGER_COUNT=2
|
||||
TELEGRAM_ALERT_MIN_SEVERITY=medium
|
||||
# Mispricing radar: skip push when YES buy price is above this cap (10c = 0.10)
|
||||
TELEGRAM_ALERT_MISPRICING_MAX_YES_BUY=0.10
|
||||
TELEGRAM_ALERT_CITIES=ankara,london,paris,seoul,hong kong,shanghai,singapore,tokyo,tel aviv,toronto,buenos aires,wellington,new york,chicago,dallas,miami,atlanta,seattle,lucknow,sao paulo,munich
|
||||
POLYWEATHER_BOT_GROUP_INVITE_URL=
|
||||
|
||||
# Open-Meteo (forecast data changes ~hourly, no need to refresh more often)
|
||||
########################################
|
||||
# 3) Weather + cache
|
||||
########################################
|
||||
OPEN_METEO_CACHE_TTL_SEC=7200
|
||||
OPEN_METEO_ENSEMBLE_CACHE_TTL_SEC=7200
|
||||
OPEN_METEO_MULTI_MODEL_CACHE_TTL_SEC=7200
|
||||
OPEN_METEO_MULTI_MODEL_CACHE_VERSION=v2
|
||||
OPEN_METEO_RATE_LIMIT_COOLDOWN_SEC=900
|
||||
OPEN_METEO_RATE_CACHE_TTL_SEC=3600
|
||||
OPEN_METEO_MIN_CALL_INTERVAL_SEC=3
|
||||
METAR_CACHE_TTL_SEC=600
|
||||
METEOBLUE_CACHE_TTL_SEC=7200
|
||||
|
||||
# Proxy Setting (optional)
|
||||
HTTPS_PROXY=http://127.0.0.1:7890
|
||||
HTTP_PROXY=http://127.0.0.1:7890
|
||||
|
||||
# Other Settings
|
||||
LOG_LEVEL=INFO
|
||||
ENV=production
|
||||
POLYWEATHER_MAP_URL=https://polyweather-pro.vercel.app/
|
||||
# Runtime data directory (host path mounted into container at /var/lib/polyweather and /app/data)
|
||||
POLYWEATHER_RUNTIME_DATA_DIR=/var/lib/polyweather
|
||||
# Recommended: keep SQLite outside repository workspace
|
||||
POLYWEATHER_DB_PATH=/var/lib/polyweather/polyweather.db
|
||||
# Recommended disk cache/state paths (optional; defaults are still /app/data/*)
|
||||
OPEN_METEO_DISK_CACHE_PATH=/var/lib/polyweather/open_meteo_cache.json
|
||||
# Unified Auth (Supabase + Google/Email)
|
||||
########################################
|
||||
# 4) Auth / entitlement
|
||||
########################################
|
||||
POLYWEATHER_AUTH_ENABLED=false
|
||||
# If true: website APIs require login; if false: guest access, login optional.
|
||||
POLYWEATHER_AUTH_REQUIRED=false
|
||||
# If true, authenticated users must also have an active row in `subscriptions`.
|
||||
POLYWEATHER_AUTH_REQUIRE_SUBSCRIPTION=false
|
||||
POLYWEATHER_REQUIRE_ENTITLEMENT=false
|
||||
SUPABASE_URL=
|
||||
SUPABASE_ANON_KEY=
|
||||
SUPABASE_SERVICE_ROLE_KEY=
|
||||
SUPABASE_HTTP_TIMEOUT_SEC=8
|
||||
SUPABASE_AUTH_CACHE_TTL_SEC=30
|
||||
SUPABASE_SUB_CACHE_TTL_SEC=60
|
||||
# Frontend wallet connection (WalletConnect v2)
|
||||
# Apply in Vercel env as NEXT_PUBLIC_*
|
||||
POLYWEATHER_BACKEND_ENTITLEMENT_TOKEN=
|
||||
|
||||
########################################
|
||||
# 5) Alerts / operations
|
||||
########################################
|
||||
TELEGRAM_ALERT_PUSH_ENABLED=true
|
||||
TELEGRAM_ALERT_PUSH_INTERVAL_SEC=300
|
||||
TELEGRAM_ALERT_PUSH_COOLDOWN_SEC=1800
|
||||
TELEGRAM_ALERT_MIN_TRIGGER_COUNT=2
|
||||
TELEGRAM_ALERT_MIN_SEVERITY=medium
|
||||
TELEGRAM_ALERT_MISPRICING_MAX_YES_BUY=0.10
|
||||
TELEGRAM_ALERT_CITIES=ankara,london,paris,seoul,hong kong,shanghai,singapore,tokyo,tel aviv,toronto,buenos aires,wellington,new york,chicago,dallas,miami,atlanta,seattle,lucknow,sao paulo,munich
|
||||
|
||||
########################################
|
||||
# 6) Frontend-facing shared values
|
||||
########################################
|
||||
NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID=
|
||||
NEXT_PUBLIC_WALLETCONNECT_POLYGON_RPC_URL=https://polygon-bor-rpc.publicnode.com
|
||||
# Bot command access guard (/city, /deb):
|
||||
# - Pro entitlement removed
|
||||
# - user only needs to be a member of any configured group (TELEGRAM_CHAT_IDS / TELEGRAM_CHAT_ID)
|
||||
POLYWEATHER_BOT_GROUP_INVITE_URL=
|
||||
# Group message points (anti-spam + ranking)
|
||||
POLYWEATHER_BOT_MESSAGE_POINTS=4
|
||||
POLYWEATHER_BOT_MESSAGE_DAILY_CAP=40
|
||||
POLYWEATHER_BOT_MESSAGE_MIN_LENGTH=3
|
||||
POLYWEATHER_BOT_MESSAGE_COOLDOWN_SEC=30
|
||||
POLYWEATHER_BOT_CITY_QUERY_COST=1
|
||||
POLYWEATHER_BOT_DEB_QUERY_COST=1
|
||||
# Weekly leaderboard reward settlement
|
||||
# settle_weekday: 1=Mon ... 7=Sun
|
||||
|
||||
########################################
|
||||
# 7) Optional modules
|
||||
########################################
|
||||
|
||||
# Weekly reward / leaderboard
|
||||
POLYWEATHER_WEEKLY_REWARD_ENABLED=true
|
||||
POLYWEATHER_WEEKLY_REWARD_TIMEZONE=Asia/Shanghai
|
||||
POLYWEATHER_WEEKLY_REWARD_SETTLE_WEEKDAY=1
|
||||
@@ -78,24 +88,23 @@ POLYWEATHER_WEEKLY_REWARD_SETTLE_MINUTE=5
|
||||
POLYWEATHER_WEEKLY_REWARD_CHECK_INTERVAL_SEC=300
|
||||
POLYWEATHER_WEEKLY_REWARD_HTTP_TIMEOUT_SEC=10
|
||||
POLYWEATHER_WEEKLY_REWARD_ANNOUNCE_ENABLED=true
|
||||
# Backend entitlement guard (for /api/cities, /api/city/*, /api/history/*)
|
||||
POLYWEATHER_REQUIRE_ENTITLEMENT=false
|
||||
POLYWEATHER_BACKEND_ENTITLEMENT_TOKEN=
|
||||
|
||||
# P1 Contract Checkout (MetaMask + Polygon USDC)
|
||||
# Group message points
|
||||
POLYWEATHER_BOT_MESSAGE_POINTS=4
|
||||
POLYWEATHER_BOT_MESSAGE_DAILY_CAP=40
|
||||
POLYWEATHER_BOT_MESSAGE_MIN_LENGTH=3
|
||||
POLYWEATHER_BOT_MESSAGE_COOLDOWN_SEC=30
|
||||
POLYWEATHER_BOT_CITY_QUERY_COST=1
|
||||
POLYWEATHER_BOT_DEB_QUERY_COST=1
|
||||
|
||||
# Payments
|
||||
POLYWEATHER_PAYMENT_ENABLED=false
|
||||
POLYWEATHER_PAYMENT_CHAIN_ID=137
|
||||
POLYWEATHER_PAYMENT_RPC_URL=https://polygon-rpc.com
|
||||
# Legacy single-token fallback (still supported)
|
||||
POLYWEATHER_PAYMENT_RPC_URLS=https://polygon-rpc.com
|
||||
POLYWEATHER_PAYMENT_RECEIVER_CONTRACT=
|
||||
POLYWEATHER_PAYMENT_TOKEN_ADDRESS=0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174
|
||||
POLYWEATHER_PAYMENT_TOKEN_DECIMALS=6
|
||||
# Recommended multi-token config (supports USDC.e + Native USDC at the same time)
|
||||
# Example:
|
||||
# [
|
||||
# {"code":"usdc_e","symbol":"USDC.e","name":"USDC.e (PoS)","address":"0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174","decimals":6,"receiver_contract":"0xYourCheckoutContract","is_default":true},
|
||||
# {"code":"usdc","symbol":"USDC","name":"Native USDC","address":"0x3c499c542cef5e3811e1192ce70d8cc03d5c3359","decimals":6,"receiver_contract":"0xYourCheckoutContract"}
|
||||
# ]
|
||||
POLYWEATHER_PAYMENT_ACCEPTED_TOKENS_JSON=
|
||||
POLYWEATHER_PAYMENT_CONFIRMATIONS=2
|
||||
POLYWEATHER_PAYMENT_INTENT_TTL_SEC=1800
|
||||
@@ -104,18 +113,13 @@ POLYWEATHER_PAYMENT_HTTP_TIMEOUT_SEC=10
|
||||
POLYWEATHER_PAYMENT_POLL_INTERVAL_SEC=4
|
||||
POLYWEATHER_PAYMENT_MAX_WAIT_SEC=50
|
||||
POLYWEATHER_PAYMENT_TELEGRAM_NOTIFY_ENABLED=true
|
||||
# Payment points redemption
|
||||
POLYWEATHER_PAYMENT_POINTS_ENABLED=true
|
||||
POLYWEATHER_PAYMENT_POINTS_PER_USDC=500
|
||||
POLYWEATHER_PAYMENT_POINTS_MAX_DISCOUNT_USDC=3
|
||||
# Comma-separated allowed plans for checkout UI + backend validation.
|
||||
# Default is monthly-only launch.
|
||||
POLYWEATHER_PAYMENT_ALLOWED_PLAN_CODES=pro_monthly
|
||||
# JSON object
|
||||
# Example: {"pro_monthly":{"plan_id":101,"amount_usdc":"5","duration_days":30}}
|
||||
POLYWEATHER_PAYMENT_PLAN_CATALOG_JSON=
|
||||
|
||||
# Polymarket P0 Read-Only Market Layer
|
||||
# Polymarket market scan
|
||||
POLYMARKET_MARKET_SCAN_ENABLED=true
|
||||
POLYMARKET_GAMMA_URL=https://gamma-api.polymarket.com
|
||||
POLYMARKET_CLOB_URL=https://clob.polymarket.com
|
||||
@@ -128,10 +132,10 @@ POLYMARKET_DISCOVERY_LIMIT=200
|
||||
POLYMARKET_SIGNAL_MIN_LIQUIDITY=500
|
||||
POLYMARKET_SIGNAL_EDGE_PCT=2
|
||||
|
||||
# Polygon Wallet Watcher (Single Chain P0)
|
||||
# Polygon watcher
|
||||
POLYGON_WALLET_WATCH_ENABLED=false
|
||||
POLYGON_RPC_URL=https://polygon-rpc.com
|
||||
POLYGON_WALLET_WATCH_ADDRESSES=0x0000000000000000000000000000000000000000
|
||||
POLYGON_WALLET_WATCH_ADDRESSES=
|
||||
POLYGON_WALLET_WATCH_INTERVAL_SEC=8
|
||||
POLYGON_WALLET_WATCH_CONFIRMATIONS=2
|
||||
POLYGON_WALLET_WATCH_MAX_BLOCKS_PER_CYCLE=30
|
||||
@@ -141,24 +145,15 @@ POLYGON_WALLET_WATCH_TX_BASE=https://polygonscan.com/tx
|
||||
POLYGON_WALLET_WATCH_ADDR_BASE=https://polygonscan.com/address
|
||||
POLYGON_WALLET_WATCH_POLYMARKET_ONLY=true
|
||||
POLYGON_WALLET_WATCH_INCLUDE_DEFAULT_PM_CONTRACTS=true
|
||||
# Optional custom Polymarket contracts, format: LABEL:0x...,LABEL2:0x...
|
||||
POLYGON_WALLET_WATCH_POLYMARKET_CONTRACTS=
|
||||
|
||||
# Polymarket Wallet Activity Watcher (all markets, not weather-only)
|
||||
# Polymarket wallet activity
|
||||
POLYMARKET_WALLET_ACTIVITY_ENABLED=false
|
||||
POLYMARKET_WALLET_ACTIVITY_USERS=0x0000000000000000000000000000000000000000
|
||||
# Optional dedicated chat targets for wallet activity push (recommended)
|
||||
# If unset, fallback to TELEGRAM_CHAT_IDS / TELEGRAM_CHAT_ID.
|
||||
POLYMARKET_WALLET_ACTIVITY_USERS=
|
||||
POLYMARKET_WALLET_ACTIVITY_CHAT_ID=
|
||||
POLYMARKET_WALLET_ACTIVITY_CHAT_IDS=
|
||||
# Optional: mirror wallet activity push to a forum topic, while keeping existing chat targets unchanged.
|
||||
POLYMARKET_WALLET_ACTIVITY_TOPIC_CHAT_ID=
|
||||
POLYMARKET_WALLET_ACTIVITY_TOPIC_ID=
|
||||
# Optional wallet nicknames:
|
||||
# - CSV: 0xabc...=Whale_A,0xdef...=Main_Account
|
||||
# - JSON: {"0xabc...":"Whale A","0xdef...":"Main Account"}
|
||||
# - Env key: POLYMARKET_WALLET_ACTIVITY_USER_ALIASES
|
||||
# (legacy typo POLYMARKET_WALLET_ACTIVITY_USERS_ALIASES is also accepted)
|
||||
POLYMARKET_WALLET_ACTIVITY_USER_ALIASES=
|
||||
POLYMARKET_WALLET_ACTIVITY_DATA_API_URL=https://data-api.polymarket.com
|
||||
POLYMARKET_WALLET_ACTIVITY_INTERVAL_SEC=20
|
||||
@@ -177,10 +172,11 @@ POLYMARKET_WALLET_ACTIVITY_UPDATE_DEBOUNCE_SEC=30
|
||||
POLYMARKET_WALLET_ACTIVITY_UPDATE_MAX_HOLD_SEC=120
|
||||
POLYMARKET_WALLET_ACTIVITY_AVG_PRICE_SHOW_MIN=0.01
|
||||
POLYMARKET_WALLET_ACTIVITY_AVG_PRICE_SHOW_MAX=0.99
|
||||
# Skip wallet activity pushes when position value is below this floor (USD).
|
||||
# Set 0 to disable.
|
||||
POLYMARKET_WALLET_ACTIVITY_MIN_POSITION_VALUE_USD=0
|
||||
# Comma-separated wallet addresses exempt from min value floor.
|
||||
# Example: 0x849d9a4dd64829b8b0141ea53e7caca7e99529ec
|
||||
POLYMARKET_WALLET_ACTIVITY_MIN_VALUE_EXEMPT_USERS=
|
||||
|
||||
########################################
|
||||
# 8) Optional proxies
|
||||
########################################
|
||||
HTTPS_PROXY=
|
||||
HTTP_PROXY=
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# PolyWeather secrets-only template
|
||||
# Copy the required lines into your real `.env` / platform secret manager.
|
||||
# Never commit actual values.
|
||||
|
||||
########################################
|
||||
# Telegram
|
||||
########################################
|
||||
TELEGRAM_BOT_TOKEN=
|
||||
|
||||
########################################
|
||||
# Supabase
|
||||
########################################
|
||||
SUPABASE_URL=
|
||||
SUPABASE_ANON_KEY=
|
||||
SUPABASE_SERVICE_ROLE_KEY=
|
||||
NEXT_PUBLIC_SUPABASE_URL=
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=
|
||||
|
||||
########################################
|
||||
# Entitlement / dashboard
|
||||
########################################
|
||||
POLYWEATHER_BACKEND_ENTITLEMENT_TOKEN=
|
||||
POLYWEATHER_DASHBOARD_ACCESS_TOKEN=
|
||||
|
||||
########################################
|
||||
# Meteoblue / third-party APIs
|
||||
########################################
|
||||
METEOBLUE_API_KEY=
|
||||
|
||||
########################################
|
||||
# Wallet / payments
|
||||
########################################
|
||||
NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID=
|
||||
POLYWEATHER_PAYMENT_RECEIVER_CONTRACT=
|
||||
POLYWEATHER_PAYMENT_ACCEPTED_TOKENS_JSON=
|
||||
POLYWEATHER_PAYMENT_PLAN_CATALOG_JSON=
|
||||
|
||||
########################################
|
||||
# Optional exchange / market secrets
|
||||
########################################
|
||||
POLYMARKET_API_KEY=
|
||||
POLYMARKET_SECRET_KEY=
|
||||
POLYMARKET_PASSPHRASE=
|
||||
POLYMARKET_WALLET_ADDRESS=
|
||||
@@ -0,0 +1,61 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
python-quality:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.11"
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements.txt -r requirements-dev.txt
|
||||
|
||||
- name: Ruff
|
||||
run: python -m ruff check .
|
||||
|
||||
- name: Pytest
|
||||
run: python -m pytest
|
||||
|
||||
frontend-quality:
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: frontend
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: "npm"
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
docker-build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Build Docker image
|
||||
run: docker build -t polyweather-ci .
|
||||
@@ -33,6 +33,7 @@ Thumbs.db
|
||||
frontend/node_modules/
|
||||
frontend/.next/
|
||||
frontend/.vercel/
|
||||
frontend/*.tsbuildinfo
|
||||
|
||||
.npm-cache/
|
||||
.env.local
|
||||
|
||||
@@ -1,5 +1,50 @@
|
||||
# Changelog
|
||||
|
||||
## 1.5.1 - 2026-03-23
|
||||
|
||||
- `/ops` 页面增加管理员守卫,前后端双层限制管理员访问
|
||||
- `/ops` 支持会员列表、支付异常单、用户查询、周榜和手动补分
|
||||
- `/ops` 支付异常单支持按原因筛选、标记已处理,并补充支付异常审计视图
|
||||
- 会员列表支持按 `user_id` 去重,并优先回补 Supabase Auth 邮箱/注册时间
|
||||
- 新增按邮箱补跑订阅恢复脚本 `scripts/reconcile_subscription_by_email.py`
|
||||
- 支付确认失败(如 `receiver_mismatch`)现在会明确落 `failed`,并写入 SQLite 审计事件
|
||||
- 支付前强制重新拉取 `/api/payments/config`,并校验最新地址、允许域名和当前支付上下文
|
||||
- 浏览器钱包选择补齐 EIP-6963 发现、稳定去重和绑定后账户状态即时刷新
|
||||
- 城市详情页新增 `官方参考 / Official Sources` 区块,覆盖主要城市的官方机构/机场/METAR 链接
|
||||
- “今日日内分析”结构解读改为后端同源动态短评,并统一网页与 Bot 解释口径
|
||||
- 台北主结算源切换到 `NOAA RCTP`,按最终质控后的最高整度摄氏值展示和说明
|
||||
- 浏览器插件同步台北 `NOAA RCTP` 结算参考标签和说明
|
||||
- `/ops` 手机端收口为卡片化视图,保留桌面表格
|
||||
- 账户中心补充本周积分显示,`weekly_points` 与周排行同屏展示
|
||||
- Dashboard 历史对账补充“峰值前 12 小时 DEB 参考(近似)”卡片
|
||||
- 历史图不再错误混入 `settlement_history` 实测,历史样本仅按可比较样本统计
|
||||
- 新增 `scripts/backfill_recent_daily_actuals_from_metar.py`,支持为缺失 `daily_records` 的 METAR 城市补最近 14 天 `actual_high`
|
||||
- 历史接口对新接入的 METAR 城市增加自动 bootstrap,避免新增城市历史页整块空白
|
||||
- 香港历史/日内展示继续坚持 `HKO` 官方口径,不再 fallback 到 `VHHH METAR` 连续线
|
||||
- 香港 HKO 当天官方点位不再落单独 JSON,统一写入 runtime state
|
||||
- 今日日内结构信号按城市本地时间与峰值窗口分析,不再只看固定下午时段
|
||||
- 新增高空结构信号:冲高环境、压温风险、午后扰动、冲高效率,并提供中英文说明
|
||||
- 新增交易动作卡:结合高空结构、市场拥挤度与 `edge_percent` 输出 `偏暖侧 / 偏谨慎 / 先观察`
|
||||
- 非香港机场城市新增 `TAF` 接入,支持 `FM / TEMPO / BECMG / PROB30/40` 时间片解析
|
||||
- 温度走势图新增 `TAF 时段 / TAF Timing` 标记,并在 tooltip 中显示对应时段摘要
|
||||
- `TAF` 信号与 `market_signal / edge_percent` 联动进入交易动作,提示更贴近交易语境
|
||||
- `TAF` 展示词已改成普通用户可读版本:`基础时段 / 明确切换 / 临时波动 / 逐步转变`
|
||||
- 日内结构总摘要补充“TAF 未新增压温不等于继续升温”的解释,避免误读
|
||||
- 浏览器插件多日预报改为 `DEB` 优先,基础判断卡补充方向、置信度与原因,并统一引流到主站首页
|
||||
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 1.5.0 - 2026-03-21
|
||||
|
||||
- 运行态状态与缓存支持 SQLite 渐进迁移,新增 `POLYWEATHER_STATE_STORAGE_MODE=file|dual|sqlite`
|
||||
- 新增 `/healthz`、`/api/system/status`、`/metrics`
|
||||
- 新增支付运行态接口 `/api/payments/runtime`
|
||||
- 支付侧新增 SQLite 审计事件、事件重放脚本与多 RPC 容灾支持
|
||||
- 新增支付静态审计脚本与 V2 合约升级草案
|
||||
- 统一周积分显示口径,`/top` 中“我的状态”改为累计发言/本周排名/本周积分
|
||||
- 文档同步更新为 2026-03-20 当前状态
|
||||
|
||||
## 1.4.0 - 2026-03-14
|
||||
|
||||
- 统一收费阶段产品口径,发布 PolyWeather Pro `v1.4.0`
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# 前端交付与重构报告(v1.4.0)
|
||||
# 前端交付与重构报告(v1.5.1)
|
||||
|
||||
最后更新:`2026-03-14`
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ Production weather-intelligence stack for temperature settlement markets.
|
||||
|
||||
Official dashboard: [polyweather-pro.vercel.app](https://polyweather-pro.vercel.app/)
|
||||
|
||||
Public docs center: `/docs/intro` on the main site (bilingual product documentation, including intraday signals, TAF, settlement sources, history, and extension).
|
||||
|
||||
## Product Screenshots
|
||||
|
||||
### Global Dashboard
|
||||
@@ -14,12 +16,21 @@ Official dashboard: [polyweather-pro.vercel.app](https://polyweather-pro.vercel.
|
||||
|
||||

|
||||
|
||||
## Product Status (2026-03)
|
||||
## Product Status (2026-03-24)
|
||||
|
||||
- Subscription live: `Pro Monthly 5 USDC`.
|
||||
- Points redemption live: `500 points = 1 USDC`, max `3 USDC` off.
|
||||
- Onchain checkout live: Polygon contract checkout (USDC / USDC.e).
|
||||
- Auto-reconciliation live: event listener + periodic confirm loop.
|
||||
- Ops dashboard live: `/ops` for memberships, leaderboard, manual point grants, and payment incident triage.
|
||||
- Lightweight observability live: `/healthz`, `/api/system/status`, `/metrics`.
|
||||
- Runtime state supports gradual SQLite migration (`file / dual / sqlite`).
|
||||
- EMOS/CRPS pipeline is integrated in `shadow` mode with rollout gating.
|
||||
- Intraday structural signal is now peak-window aware and bilingual (`zh-CN` / `en-US`).
|
||||
- Non-Hong Kong airport cities now ingest `TAF` and parse `FM / TEMPO / BECMG / PROB30/40`.
|
||||
- Temperature chart now overlays `TAF Timing` markers near the expected peak window.
|
||||
- Trade cue now combines upper-air structure, `TAF`, market crowding, and `edge_percent`.
|
||||
- Browser extension now uses `DEB` for multi-day forecast and stays positioned as a lightweight lead-in to the main site.
|
||||
|
||||
## Open-Core Boundary (Important)
|
||||
|
||||
@@ -32,11 +43,14 @@ See: [Open-Core & Commercial Boundary](docs/OPEN_CORE_POLICY.md)
|
||||
|
||||
## Core Capabilities
|
||||
|
||||
- Aggregates observations and forecasts for 20 monitored cities.
|
||||
- Aggregates observations and forecasts for 30 monitored cities.
|
||||
- Uses DEB (Dynamic Error Balancing) to blend multi-model highs.
|
||||
- Generates settlement-oriented probability buckets (`mu` + bucket distribution).
|
||||
- Maps weather view to Polymarket quotes for mispricing scan.
|
||||
- Reuses one analysis core across web dashboard and Telegram bot.
|
||||
- Adds payment audit trails, replay tooling, and incident visibility in ops.
|
||||
- Adds peak-window-oriented intraday structure cards for surface + upper-air analysis.
|
||||
- Adds airport-side `TAF` timing overlays and airport suppression/disruption interpretation for non-Hong Kong airport cities.
|
||||
|
||||
## Reference Architecture
|
||||
|
||||
@@ -49,20 +63,23 @@ flowchart LR
|
||||
|
||||
API --> WX["Weather Collector"]
|
||||
WX --> METAR["Aviation Weather (METAR)"]
|
||||
WX --> TAF["Aviation Weather (TAF)"]
|
||||
WX --> MGM["MGM (Turkey station network)"]
|
||||
WX --> OM["Open-Meteo"]
|
||||
WX --> HKO["HKO / NOAA / Official settlement sources"]
|
||||
|
||||
API --> ANA["DEB + Trend + Probability + Market Scan"]
|
||||
ANA --> PAY["Payment State (Intent + Event + Confirm Loop)"]
|
||||
ANA --> PM["Polymarket Read-only Layer"]
|
||||
```
|
||||
|
||||
## Monitored Cities (20)
|
||||
## Monitored Cities (30)
|
||||
|
||||
- Europe / Middle East: Ankara, London, Paris, Munich
|
||||
- APAC: Seoul, Hong Kong, Shanghai, Singapore, Tokyo, Wellington
|
||||
- Europe / Middle East: Ankara, London, Paris, Munich, Tel Aviv, Milan, Warsaw, Madrid
|
||||
- APAC: Seoul, Hong Kong, Taipei, Shanghai, Singapore, Tokyo, Wellington
|
||||
- Americas: Toronto, New York, Chicago, Dallas, Miami, Atlanta, Seattle, Buenos Aires, Sao Paulo
|
||||
- South Asia: Lucknow
|
||||
- China extension: Chengdu, Chongqing, Shenzhen, Beijing, Wuhan
|
||||
|
||||
## Quick Start
|
||||
|
||||
@@ -80,6 +97,17 @@ npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## Recent Highlights
|
||||
|
||||
- Taipei settlement is aligned to `NOAA RCTP` and rounded whole-degree Celsius logic.
|
||||
- Hong Kong keeps `HKO` official readings in dashboard and history, without falling back to airport METAR lines.
|
||||
- Intraday analysis now separates:
|
||||
- `Surface Structure`
|
||||
- `Upper-Air Structure`
|
||||
- `Trade cue`
|
||||
- `TAF` is used as an airport-side confirmation layer, not as the main temperature model.
|
||||
- Browser extension remains a lightweight monitoring + basic-bias product, while the site holds the full analysis experience.
|
||||
|
||||
## Runtime Data (Recommended on VPS)
|
||||
|
||||
Use external runtime storage to avoid SQLite/git conflicts:
|
||||
@@ -91,6 +119,14 @@ POLYWEATHER_DB_PATH=/var/lib/polyweather/polyweather.db
|
||||
|
||||
## Ops Verification
|
||||
|
||||
### Health / system status / metrics
|
||||
|
||||
```bash
|
||||
curl http://127.0.0.1:8000/healthz
|
||||
curl http://127.0.0.1:8000/api/system/status
|
||||
curl http://127.0.0.1:8000/metrics
|
||||
```
|
||||
|
||||
### Frontend cache headers
|
||||
|
||||
```bash
|
||||
@@ -103,6 +139,12 @@ POLYWEATHER_DB_PATH=/var/lib/polyweather/polyweather.db
|
||||
docker compose logs -f polyweather | egrep "payment event loop started|payment confirm loop started|payment auto-confirmed"
|
||||
```
|
||||
|
||||
### Payment runtime
|
||||
|
||||
```bash
|
||||
curl http://127.0.0.1:8000/api/payments/runtime
|
||||
```
|
||||
|
||||
### Wallet activity logs
|
||||
|
||||
```bash
|
||||
@@ -124,17 +166,24 @@ docker compose logs -f polyweather | egrep "polymarket wallet activity watcher s
|
||||
|
||||
- Chinese overview: [README_ZH.md](README_ZH.md)
|
||||
- Chinese API guide: [docs/API_ZH.md](docs/API_ZH.md)
|
||||
- TAF signal guide (ZH): [docs/TAF_SIGNAL_ZH.md](docs/TAF_SIGNAL_ZH.md)
|
||||
- Commercialization: [docs/COMMERCIALIZATION.md](docs/COMMERCIALIZATION.md)
|
||||
- Open-Core policy: [docs/OPEN_CORE_POLICY.md](docs/OPEN_CORE_POLICY.md)
|
||||
- Supabase setup (ZH): [docs/SUPABASE_SETUP_ZH.md](docs/SUPABASE_SETUP_ZH.md)
|
||||
- Configuration & secrets (ZH): [docs/CONFIGURATION_ZH.md](docs/CONFIGURATION_ZH.md)
|
||||
- Frontend deployment (ZH): [docs/FRONTEND_DEPLOYMENT_ZH.md](docs/FRONTEND_DEPLOYMENT_ZH.md)
|
||||
- Tech debt (EN): [docs/TECH_DEBT.md](docs/TECH_DEBT.md)
|
||||
- Tech debt (ZH): [docs/TECH_DEBT_ZH.md](docs/TECH_DEBT_ZH.md)
|
||||
- Payment verification: [docs/payments/POLYGONSCAN_VERIFY.md](docs/payments/POLYGONSCAN_VERIFY.md)
|
||||
- Payment audit: [docs/payments/PAYMENT_AUDIT_ZH.md](docs/payments/PAYMENT_AUDIT_ZH.md)
|
||||
- Payment V2 upgrade: [docs/payments/PAYMENT_UPGRADE_V2_ZH.md](docs/payments/PAYMENT_UPGRADE_V2_ZH.md)
|
||||
- Ops admin guide: [docs/OPS_ADMIN_ZH.md](docs/OPS_ADMIN_ZH.md)
|
||||
- Deep research report: [docs/deep-research-report.md](docs/deep-research-report.md)
|
||||
- Frontend report: [FRONTEND_REDESIGN_REPORT.md](FRONTEND_REDESIGN_REPORT.md)
|
||||
- Release process: [RELEASE.md](RELEASE.md)
|
||||
- Changelog: [CHANGELOG.md](CHANGELOG.md)
|
||||
|
||||
## Version
|
||||
|
||||
- Version: `v1.4.0`
|
||||
- Last Updated: `2026-03-14`
|
||||
- Version: `v1.5.1`
|
||||
- Last Updated: `2026-03-24`
|
||||
|
||||
+48
-7
@@ -14,12 +14,17 @@
|
||||
|
||||

|
||||
|
||||
## 当前产品状态(2026-03)
|
||||
## 当前产品状态(2026-03-21)
|
||||
|
||||
- 已上线订阅制:`Pro 月付 5 USDC`。
|
||||
- 已上线积分抵扣:`500 积分 = 1 USDC`,最多抵扣 `3 USDC`。
|
||||
- 已上线链上支付:Polygon 合约支付(USDC / USDC.e)。
|
||||
- 已上线自动补单:事件监听 + 周期确认双链路。
|
||||
- 已上线支付运行态与审计接口:`/api/payments/runtime`。
|
||||
- 已上线轻量运营后台:`/ops`(会员、周榜、补分、支付异常单)。
|
||||
- 已上线轻量可观测性:`/healthz`、`/api/system/status`、`/metrics`。
|
||||
- 运行态状态与缓存已支持 SQLite 渐进迁移:`file / dual / sqlite`。
|
||||
- 已接入 EMOS/CRPS 校准链路,但当前仍保持 `emos_shadow`。
|
||||
|
||||
## 开源边界(重要)
|
||||
|
||||
@@ -32,11 +37,12 @@
|
||||
|
||||
## 核心能力
|
||||
|
||||
- 聚合 20 个监控城市的实测与预报数据。
|
||||
- 聚合 30 个监控城市的实测与预报数据。
|
||||
- DEB(Dynamic Error Balancing)融合多模型最高温。
|
||||
- 输出结算导向概率分布(`mu` + 温度桶)。
|
||||
- 将模型观点映射到 Polymarket 行情,做错价扫描。
|
||||
- Web 仪表盘与 Telegram Bot 复用同一分析内核。
|
||||
- 支付链路具备事件重放、SQLite 审计事件与 RPC 容灾能力。
|
||||
|
||||
## 参考架构
|
||||
|
||||
@@ -55,14 +61,17 @@ flowchart LR
|
||||
API --> ANA["DEB + 趋势 + 概率 + 市场扫描"]
|
||||
ANA --> PAY["支付状态(Intent + Event + Confirm Loop)"]
|
||||
ANA --> PM["Polymarket 只读层"]
|
||||
API --> OBS["healthz / system status / metrics"]
|
||||
ANA --> STATE["SQLite runtime state + dual fallback"]
|
||||
```
|
||||
|
||||
## 监控城市(20)
|
||||
## 监控城市(30)
|
||||
|
||||
- 欧洲/中东:Ankara、London、Paris、Munich
|
||||
- 亚太:Seoul、Hong Kong、Shanghai、Singapore、Tokyo、Wellington
|
||||
- 欧洲/中东:Ankara、London、Paris、Munich、Tel Aviv、Milan、Warsaw、Madrid
|
||||
- 亚太:Seoul、Hong Kong、Taipei、Shanghai、Singapore、Tokyo、Wellington
|
||||
- 美洲:Toronto、New York、Chicago、Dallas、Miami、Atlanta、Seattle、Buenos Aires、Sao Paulo
|
||||
- 南亚:Lucknow
|
||||
- 中国扩展:Chengdu、Chongqing、Shenzhen、Beijing、Wuhan
|
||||
|
||||
## 快速启动
|
||||
|
||||
@@ -87,10 +96,19 @@ npm run dev
|
||||
```env
|
||||
POLYWEATHER_RUNTIME_DATA_DIR=/var/lib/polyweather
|
||||
POLYWEATHER_DB_PATH=/var/lib/polyweather/polyweather.db
|
||||
POLYWEATHER_STATE_STORAGE_MODE=dual
|
||||
```
|
||||
|
||||
## 运维验收
|
||||
|
||||
### 健康与系统状态
|
||||
|
||||
```bash
|
||||
curl http://127.0.0.1:8000/healthz
|
||||
curl http://127.0.0.1:8000/api/system/status
|
||||
curl http://127.0.0.1:8000/metrics
|
||||
```
|
||||
|
||||
### 前端缓存头
|
||||
|
||||
```bash
|
||||
@@ -103,6 +121,21 @@ POLYWEATHER_DB_PATH=/var/lib/polyweather/polyweather.db
|
||||
docker compose logs -f polyweather | egrep "payment event loop started|payment confirm loop started|payment auto-confirmed"
|
||||
```
|
||||
|
||||
### 支付运行态
|
||||
|
||||
```bash
|
||||
curl http://127.0.0.1:8000/api/payments/runtime
|
||||
```
|
||||
|
||||
### 运营后台
|
||||
|
||||
- 前端入口:`https://polyweather-pro.vercel.app/ops`
|
||||
- 后端需配置:
|
||||
|
||||
```env
|
||||
POLYWEATHER_OPS_ADMIN_EMAILS=yhrsc30@gmail.com
|
||||
```
|
||||
|
||||
### 钱包异动监听日志
|
||||
|
||||
```bash
|
||||
@@ -127,14 +160,22 @@ docker compose logs -f polyweather | egrep "polymarket wallet activity watcher s
|
||||
- 商业化说明:[docs/COMMERCIALIZATION.md](docs/COMMERCIALIZATION.md)
|
||||
- Open-Core 边界:[docs/OPEN_CORE_POLICY.md](docs/OPEN_CORE_POLICY.md)
|
||||
- Supabase 接入:[docs/SUPABASE_SETUP_ZH.md](docs/SUPABASE_SETUP_ZH.md)
|
||||
- 配置与密钥管理:[docs/CONFIGURATION_ZH.md](docs/CONFIGURATION_ZH.md)
|
||||
- 前端部署(Vercel):[docs/FRONTEND_DEPLOYMENT_ZH.md](docs/FRONTEND_DEPLOYMENT_ZH.md)
|
||||
- EMOS 训练报告:[docs/EMOS_TRAINING_REPORT_ZH.md](docs/EMOS_TRAINING_REPORT_ZH.md)
|
||||
- 概率快照归档:[docs/PROBABILITY_SNAPSHOT_ARCHIVE_ZH.md](docs/PROBABILITY_SNAPSHOT_ARCHIVE_ZH.md)
|
||||
- 技术债(中文镜像):[docs/TECH_DEBT_ZH.md](docs/TECH_DEBT_ZH.md)
|
||||
- 技术债(主文档):[docs/TECH_DEBT.md](docs/TECH_DEBT.md)
|
||||
- 支付合约验证:[docs/payments/POLYGONSCAN_VERIFY.md](docs/payments/POLYGONSCAN_VERIFY.md)
|
||||
- 支付审计说明:[docs/payments/PAYMENT_AUDIT_ZH.md](docs/payments/PAYMENT_AUDIT_ZH.md)
|
||||
- 支付 V2 升级方案:[docs/payments/PAYMENT_UPGRADE_V2_ZH.md](docs/payments/PAYMENT_UPGRADE_V2_ZH.md)
|
||||
- 运营后台说明:[docs/OPS_ADMIN_ZH.md](docs/OPS_ADMIN_ZH.md)
|
||||
- 深度评估报告:[docs/deep-research-report.md](docs/deep-research-report.md)
|
||||
- 前端报告:[FRONTEND_REDESIGN_REPORT.md](FRONTEND_REDESIGN_REPORT.md)
|
||||
- 发布流程:[RELEASE.md](RELEASE.md)
|
||||
- 变更记录:[CHANGELOG.md](CHANGELOG.md)
|
||||
|
||||
## 当前版本
|
||||
|
||||
- 版本:`v1.4.0`
|
||||
- 最后更新:`2026-03-14`
|
||||
- 版本:`v1.5.1`
|
||||
- 文档最后更新:`2026-03-21`
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
{
|
||||
"version": "emos-20260320132525",
|
||||
"trained_at": "2026-03-20T13:25:25.836021+00:00",
|
||||
"global": {
|
||||
"mu": {
|
||||
"intercept": -1.57406048,
|
||||
"raw_mu_coef": 2.80583627,
|
||||
"deb_coef": -0.06819634,
|
||||
"ens_median_coef": -1.81560215,
|
||||
"max_so_far_gap_coef": 0.0
|
||||
},
|
||||
"sigma": {
|
||||
"intercept": 0.67509915,
|
||||
"raw_sigma_coef": 0.14431833,
|
||||
"spread_coef": 0.14431833,
|
||||
"peak_flag_coef": 0.0,
|
||||
"max_so_far_gap_coef": 0.0
|
||||
}
|
||||
},
|
||||
"sigma_constraints": {
|
||||
"min_ratio": 0.85,
|
||||
"max_ratio": 1.35,
|
||||
"absolute_min": 0.25,
|
||||
"absolute_max": 3.0
|
||||
},
|
||||
"selection_guardrails": {
|
||||
"max_mae_increase": 0.02,
|
||||
"max_bucket_hit_drop": 0.01,
|
||||
"max_bucket_brier_increase": 0.05
|
||||
},
|
||||
"blending": {
|
||||
"alpha_mu": 0.0,
|
||||
"alpha_sigma": 0.0
|
||||
},
|
||||
"cities": {
|
||||
"ankara": {
|
||||
"samples": 7,
|
||||
"mu_bias": 0.566273,
|
||||
"sigma_scale": 2.0,
|
||||
"confidence": 0.875
|
||||
},
|
||||
"london": {
|
||||
"samples": 6,
|
||||
"mu_bias": 0.489961,
|
||||
"sigma_scale": 2.0,
|
||||
"confidence": 0.75
|
||||
},
|
||||
"new york": {
|
||||
"samples": 4,
|
||||
"mu_bias": 1.852451,
|
||||
"sigma_scale": 0.830444,
|
||||
"confidence": 0.5
|
||||
},
|
||||
"paris": {
|
||||
"samples": 7,
|
||||
"mu_bias": 0.308599,
|
||||
"sigma_scale": 2.0,
|
||||
"confidence": 0.875
|
||||
},
|
||||
"seoul": {
|
||||
"samples": 6,
|
||||
"mu_bias": -1.486024,
|
||||
"sigma_scale": 1.569585,
|
||||
"confidence": 0.75
|
||||
},
|
||||
"toronto": {
|
||||
"samples": 5,
|
||||
"mu_bias": -0.734395,
|
||||
"sigma_scale": 1.656751,
|
||||
"confidence": 0.625
|
||||
},
|
||||
"buenos aires": {
|
||||
"samples": 5,
|
||||
"mu_bias": -1.753334,
|
||||
"sigma_scale": 1.831739,
|
||||
"confidence": 0.625
|
||||
},
|
||||
"wellington": {
|
||||
"samples": 6,
|
||||
"mu_bias": 0.350757,
|
||||
"sigma_scale": 1.377974,
|
||||
"confidence": 0.75
|
||||
},
|
||||
"chicago": {
|
||||
"samples": 4,
|
||||
"mu_bias": 3.01062,
|
||||
"sigma_scale": 0.825575,
|
||||
"confidence": 0.5
|
||||
},
|
||||
"sao paulo": {
|
||||
"samples": 5,
|
||||
"mu_bias": 1.632457,
|
||||
"sigma_scale": 2.0,
|
||||
"confidence": 0.625
|
||||
},
|
||||
"dallas": {
|
||||
"samples": 4,
|
||||
"mu_bias": 3.77714,
|
||||
"sigma_scale": 0.796874,
|
||||
"confidence": 0.5
|
||||
},
|
||||
"miami": {
|
||||
"samples": 5,
|
||||
"mu_bias": -4.868741,
|
||||
"sigma_scale": 2.0,
|
||||
"confidence": 0.625
|
||||
},
|
||||
"atlanta": {
|
||||
"samples": 5,
|
||||
"mu_bias": -7.648823,
|
||||
"sigma_scale": 2.0,
|
||||
"confidence": 0.625
|
||||
},
|
||||
"seattle": {
|
||||
"samples": 4,
|
||||
"mu_bias": 4.058619,
|
||||
"sigma_scale": 2.0,
|
||||
"confidence": 0.5
|
||||
},
|
||||
"lucknow": {
|
||||
"samples": 4,
|
||||
"mu_bias": 3.257609,
|
||||
"sigma_scale": 2.0,
|
||||
"confidence": 0.5
|
||||
},
|
||||
"munich": {
|
||||
"samples": 6,
|
||||
"mu_bias": -0.780811,
|
||||
"sigma_scale": 2.0,
|
||||
"confidence": 0.75
|
||||
},
|
||||
"hong kong": {
|
||||
"samples": 3,
|
||||
"mu_bias": -0.492675,
|
||||
"sigma_scale": 2.0,
|
||||
"confidence": 0.375
|
||||
},
|
||||
"taipei": {
|
||||
"samples": 3,
|
||||
"mu_bias": 1.462462,
|
||||
"sigma_scale": 1.132834,
|
||||
"confidence": 0.375
|
||||
},
|
||||
"milan": {
|
||||
"samples": 3,
|
||||
"mu_bias": -2.729203,
|
||||
"sigma_scale": 2.0,
|
||||
"confidence": 0.375
|
||||
},
|
||||
"warsaw": {
|
||||
"samples": 3,
|
||||
"mu_bias": 0.349319,
|
||||
"sigma_scale": 1.337949,
|
||||
"confidence": 0.375
|
||||
}
|
||||
},
|
||||
"metrics": {
|
||||
"sample_count": 105,
|
||||
"mean_crps": 2.923823,
|
||||
"legacy_mean_crps": 2.793938,
|
||||
"legacy_mean_mae": 2.721143,
|
||||
"legacy_bucket_hit_rate": 0.695238,
|
||||
"legacy_bucket_brier": 0.775463,
|
||||
"selected_mean_crps": 2.700275,
|
||||
"selected_mean_mae": 2.721143,
|
||||
"selected_bucket_hit_rate": 0.695238,
|
||||
"selected_bucket_brier": 0.765459,
|
||||
"selected_score": 4.003626,
|
||||
"legacy_score": 4.104792,
|
||||
"filled_actual_from_history": 2,
|
||||
"settlement_history_city_count": 30
|
||||
},
|
||||
"source": "artifacts\\probability_calibration\\default.json"
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
{
|
||||
"summary": {
|
||||
"sample_count": 105,
|
||||
"filled_actual_from_history": 2,
|
||||
"legacy": {
|
||||
"mean_crps": 2.793938,
|
||||
"mean_mae": 2.721143,
|
||||
"bucket_hit_rate": 0.695238
|
||||
},
|
||||
"emos": {
|
||||
"mean_crps": 2.700275,
|
||||
"mean_mae": 2.721143,
|
||||
"bucket_hit_rate": 0.695238
|
||||
},
|
||||
"delta": {
|
||||
"crps": -0.093663,
|
||||
"mae": 0.0,
|
||||
"bucket_hit_rate": 0.0
|
||||
}
|
||||
},
|
||||
"by_city": {
|
||||
"ankara": {
|
||||
"samples": 7,
|
||||
"legacy_mean_crps": 2.023242,
|
||||
"emos_mean_crps": 2.023242,
|
||||
"legacy_mean_mae": 1.984286,
|
||||
"emos_mean_mae": 1.984286,
|
||||
"legacy_bucket_hit_rate": 0.714286,
|
||||
"emos_bucket_hit_rate": 0.714286
|
||||
},
|
||||
"atlanta": {
|
||||
"samples": 5,
|
||||
"legacy_mean_crps": 12.792034,
|
||||
"emos_mean_crps": 12.694543,
|
||||
"legacy_mean_mae": 12.806,
|
||||
"emos_mean_mae": 12.806,
|
||||
"legacy_bucket_hit_rate": 0.6,
|
||||
"emos_bucket_hit_rate": 0.6
|
||||
},
|
||||
"buenos aires": {
|
||||
"samples": 5,
|
||||
"legacy_mean_crps": 3.846144,
|
||||
"emos_mean_crps": 3.846144,
|
||||
"legacy_mean_mae": 4.168,
|
||||
"emos_mean_mae": 4.168,
|
||||
"legacy_bucket_hit_rate": 0.6,
|
||||
"emos_bucket_hit_rate": 0.6
|
||||
},
|
||||
"chicago": {
|
||||
"samples": 4,
|
||||
"legacy_mean_crps": 1.346667,
|
||||
"emos_mean_crps": 0.601765,
|
||||
"legacy_mean_mae": 0.0,
|
||||
"emos_mean_mae": 0.0,
|
||||
"legacy_bucket_hit_rate": 1.0,
|
||||
"emos_bucket_hit_rate": 1.0
|
||||
},
|
||||
"dallas": {
|
||||
"samples": 4,
|
||||
"legacy_mean_crps": 1.256111,
|
||||
"emos_mean_crps": 0.651425,
|
||||
"legacy_mean_mae": 0.0,
|
||||
"emos_mean_mae": 0.0,
|
||||
"legacy_bucket_hit_rate": 1.0,
|
||||
"emos_bucket_hit_rate": 1.0
|
||||
},
|
||||
"hong kong": {
|
||||
"samples": 3,
|
||||
"legacy_mean_crps": 0.261027,
|
||||
"emos_mean_crps": 0.261027,
|
||||
"legacy_mean_mae": 0.1,
|
||||
"emos_mean_mae": 0.1,
|
||||
"legacy_bucket_hit_rate": 1.0,
|
||||
"emos_bucket_hit_rate": 0.666667
|
||||
},
|
||||
"london": {
|
||||
"samples": 6,
|
||||
"legacy_mean_crps": 2.079624,
|
||||
"emos_mean_crps": 2.079624,
|
||||
"legacy_mean_mae": 2.451667,
|
||||
"emos_mean_mae": 2.451667,
|
||||
"legacy_bucket_hit_rate": 0.166667,
|
||||
"emos_bucket_hit_rate": 0.166667
|
||||
},
|
||||
"lucknow": {
|
||||
"samples": 4,
|
||||
"legacy_mean_crps": 1.468528,
|
||||
"emos_mean_crps": 1.468528,
|
||||
"legacy_mean_mae": 1.6025,
|
||||
"emos_mean_mae": 1.6025,
|
||||
"legacy_bucket_hit_rate": 0.5,
|
||||
"emos_bucket_hit_rate": 0.5
|
||||
},
|
||||
"madrid": {
|
||||
"samples": 2,
|
||||
"legacy_mean_crps": 6.27726,
|
||||
"emos_mean_crps": 6.27726,
|
||||
"legacy_mean_mae": 7.33,
|
||||
"emos_mean_mae": 7.33,
|
||||
"legacy_bucket_hit_rate": 0.0,
|
||||
"emos_bucket_hit_rate": 0.0
|
||||
},
|
||||
"miami": {
|
||||
"samples": 5,
|
||||
"legacy_mean_crps": 11.665378,
|
||||
"emos_mean_crps": 11.665378,
|
||||
"legacy_mean_mae": 12.07,
|
||||
"emos_mean_mae": 12.07,
|
||||
"legacy_bucket_hit_rate": 0.6,
|
||||
"emos_bucket_hit_rate": 0.6
|
||||
},
|
||||
"milan": {
|
||||
"samples": 3,
|
||||
"legacy_mean_crps": 4.401392,
|
||||
"emos_mean_crps": 3.928883,
|
||||
"legacy_mean_mae": 4.06,
|
||||
"emos_mean_mae": 4.06,
|
||||
"legacy_bucket_hit_rate": 0.666667,
|
||||
"emos_bucket_hit_rate": 0.666667
|
||||
},
|
||||
"munich": {
|
||||
"samples": 6,
|
||||
"legacy_mean_crps": 2.988583,
|
||||
"emos_mean_crps": 2.988583,
|
||||
"legacy_mean_mae": 3.143333,
|
||||
"emos_mean_mae": 3.143333,
|
||||
"legacy_bucket_hit_rate": 0.5,
|
||||
"emos_bucket_hit_rate": 0.5
|
||||
},
|
||||
"new york": {
|
||||
"samples": 4,
|
||||
"legacy_mean_crps": 1.861101,
|
||||
"emos_mean_crps": 1.409393,
|
||||
"legacy_mean_mae": 1.3725,
|
||||
"emos_mean_mae": 1.3725,
|
||||
"legacy_bucket_hit_rate": 0.75,
|
||||
"emos_bucket_hit_rate": 0.75
|
||||
},
|
||||
"paris": {
|
||||
"samples": 7,
|
||||
"legacy_mean_crps": 2.430082,
|
||||
"emos_mean_crps": 2.430082,
|
||||
"legacy_mean_mae": 2.518571,
|
||||
"emos_mean_mae": 2.518571,
|
||||
"legacy_bucket_hit_rate": 0.571429,
|
||||
"emos_bucket_hit_rate": 0.571429
|
||||
},
|
||||
"sao paulo": {
|
||||
"samples": 5,
|
||||
"legacy_mean_crps": 2.454756,
|
||||
"emos_mean_crps": 2.454756,
|
||||
"legacy_mean_mae": 2.628,
|
||||
"emos_mean_mae": 2.628,
|
||||
"legacy_bucket_hit_rate": 0.6,
|
||||
"emos_bucket_hit_rate": 0.6
|
||||
},
|
||||
"seattle": {
|
||||
"samples": 4,
|
||||
"legacy_mean_crps": 0.531656,
|
||||
"emos_mean_crps": 0.452784,
|
||||
"legacy_mean_mae": 0.0,
|
||||
"emos_mean_mae": 0.0,
|
||||
"legacy_bucket_hit_rate": 1.0,
|
||||
"emos_bucket_hit_rate": 1.0
|
||||
},
|
||||
"seoul": {
|
||||
"samples": 6,
|
||||
"legacy_mean_crps": 0.328088,
|
||||
"emos_mean_crps": 0.328088,
|
||||
"legacy_mean_mae": 0.2,
|
||||
"emos_mean_mae": 0.2,
|
||||
"legacy_bucket_hit_rate": 1.0,
|
||||
"emos_bucket_hit_rate": 1.0
|
||||
},
|
||||
"shanghai": {
|
||||
"samples": 2,
|
||||
"legacy_mean_crps": 0.250034,
|
||||
"emos_mean_crps": 0.250034,
|
||||
"legacy_mean_mae": 0.15,
|
||||
"emos_mean_mae": 0.15,
|
||||
"legacy_bucket_hit_rate": 1.0,
|
||||
"emos_bucket_hit_rate": 1.0
|
||||
},
|
||||
"singapore": {
|
||||
"samples": 2,
|
||||
"legacy_mean_crps": 0.281993,
|
||||
"emos_mean_crps": 0.281993,
|
||||
"legacy_mean_mae": 0.15,
|
||||
"emos_mean_mae": 0.15,
|
||||
"legacy_bucket_hit_rate": 1.0,
|
||||
"emos_bucket_hit_rate": 1.0
|
||||
},
|
||||
"taipei": {
|
||||
"samples": 3,
|
||||
"legacy_mean_crps": 0.356996,
|
||||
"emos_mean_crps": 0.356996,
|
||||
"legacy_mean_mae": 0.1,
|
||||
"emos_mean_mae": 0.1,
|
||||
"legacy_bucket_hit_rate": 1.0,
|
||||
"emos_bucket_hit_rate": 1.0
|
||||
},
|
||||
"tel aviv": {
|
||||
"samples": 2,
|
||||
"legacy_mean_crps": 0.446758,
|
||||
"emos_mean_crps": 0.446758,
|
||||
"legacy_mean_mae": 0.3,
|
||||
"emos_mean_mae": 0.3,
|
||||
"legacy_bucket_hit_rate": 1.0,
|
||||
"emos_bucket_hit_rate": 1.0
|
||||
},
|
||||
"tokyo": {
|
||||
"samples": 2,
|
||||
"legacy_mean_crps": 0.450128,
|
||||
"emos_mean_crps": 0.450128,
|
||||
"legacy_mean_mae": 0.25,
|
||||
"emos_mean_mae": 0.25,
|
||||
"legacy_bucket_hit_rate": 0.5,
|
||||
"emos_bucket_hit_rate": 1.0
|
||||
},
|
||||
"toronto": {
|
||||
"samples": 5,
|
||||
"legacy_mean_crps": 2.647861,
|
||||
"emos_mean_crps": 2.566068,
|
||||
"legacy_mean_mae": 2.532,
|
||||
"emos_mean_mae": 2.532,
|
||||
"legacy_bucket_hit_rate": 0.6,
|
||||
"emos_bucket_hit_rate": 0.6
|
||||
},
|
||||
"warsaw": {
|
||||
"samples": 3,
|
||||
"legacy_mean_crps": 1.618875,
|
||||
"emos_mean_crps": 1.618875,
|
||||
"legacy_mean_mae": 2.056667,
|
||||
"emos_mean_mae": 2.056667,
|
||||
"legacy_bucket_hit_rate": 0.333333,
|
||||
"emos_bucket_hit_rate": 0.333333
|
||||
},
|
||||
"wellington": {
|
||||
"samples": 6,
|
||||
"legacy_mean_crps": 0.266349,
|
||||
"emos_mean_crps": 0.266349,
|
||||
"legacy_mean_mae": 0.2,
|
||||
"emos_mean_mae": 0.2,
|
||||
"legacy_bucket_hit_rate": 1.0,
|
||||
"emos_bucket_hit_rate": 1.0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
{
|
||||
"evaluation_report_path": "E:\\web\\PolyWeather\\artifacts\\probability_calibration\\evaluation_report.json",
|
||||
"shadow_report_path": "E:\\web\\PolyWeather\\artifacts\\probability_calibration\\shadow_report.json",
|
||||
"evaluation_report_exists": true,
|
||||
"shadow_report_exists": true,
|
||||
"decision": {
|
||||
"decision": "hold",
|
||||
"ready_for_primary": false,
|
||||
"summary": "当前指标不足以切换 emos_primary,应继续保持 shadow。",
|
||||
"thresholds": {
|
||||
"evaluation_min_samples": 80,
|
||||
"shadow_min_samples": 50,
|
||||
"max_delta_mae": 0.05,
|
||||
"min_delta_crps": -0.02,
|
||||
"min_delta_bucket_hit_rate": 0.0,
|
||||
"max_delta_bucket_brier_promote": 0.02,
|
||||
"max_delta_bucket_brier_observe": 0.15
|
||||
},
|
||||
"evaluation": {
|
||||
"sample_count": 105,
|
||||
"delta_crps": -0.093663,
|
||||
"delta_mae": 0.0,
|
||||
"delta_bucket_hit_rate": 0.0
|
||||
},
|
||||
"shadow": {
|
||||
"sample_count": 103,
|
||||
"delta_mae": 0.012708,
|
||||
"delta_bucket_hit_rate": 0.009709,
|
||||
"delta_bucket_brier": 0.293835
|
||||
},
|
||||
"blocking_reasons": [
|
||||
"shadow bucket brier 退化超限:delta=0.293835"
|
||||
],
|
||||
"worst_shadow_regressions": [
|
||||
{
|
||||
"city": "dallas",
|
||||
"samples": 4,
|
||||
"delta_mae": 0.114807,
|
||||
"delta_bucket_hit_rate": 0.0,
|
||||
"delta_bucket_brier": 0.778678
|
||||
},
|
||||
{
|
||||
"city": "chicago",
|
||||
"samples": 4,
|
||||
"delta_mae": 0.075265,
|
||||
"delta_bucket_hit_rate": 0.0,
|
||||
"delta_bucket_brier": 0.746156
|
||||
},
|
||||
{
|
||||
"city": "seattle",
|
||||
"samples": 4,
|
||||
"delta_mae": 0.11262,
|
||||
"delta_bucket_hit_rate": 0.0,
|
||||
"delta_bucket_brier": 0.692003
|
||||
},
|
||||
{
|
||||
"city": "atlanta",
|
||||
"samples": 4,
|
||||
"delta_mae": 0.293028,
|
||||
"delta_bucket_hit_rate": -0.25,
|
||||
"delta_bucket_brier": 0.601425
|
||||
},
|
||||
{
|
||||
"city": "miami",
|
||||
"samples": 4,
|
||||
"delta_mae": 0.241559,
|
||||
"delta_bucket_hit_rate": -0.5,
|
||||
"delta_bucket_brier": 0.478245
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,267 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.24;
|
||||
|
||||
interface IERC20 {
|
||||
function transferFrom(address from, address to, uint256 value) external returns (bool);
|
||||
function transfer(address to, uint256 value) external returns (bool);
|
||||
}
|
||||
|
||||
library Address {
|
||||
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
|
||||
(bool success, bytes memory returndata) = target.call(data);
|
||||
require(success, errorMessage);
|
||||
return returndata;
|
||||
}
|
||||
}
|
||||
|
||||
library SafeERC20 {
|
||||
using Address for address;
|
||||
|
||||
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
|
||||
bytes memory returndata = address(token).functionCall(
|
||||
abi.encodeWithSelector(token.transferFrom.selector, from, to, value),
|
||||
"SAFE_TRANSFER_FROM_FAILED"
|
||||
);
|
||||
if (returndata.length > 0) {
|
||||
require(abi.decode(returndata, (bool)), "SAFE_TRANSFER_FROM_FALSE");
|
||||
}
|
||||
}
|
||||
|
||||
function safeTransfer(IERC20 token, address to, uint256 value) internal {
|
||||
bytes memory returndata = address(token).functionCall(
|
||||
abi.encodeWithSelector(token.transfer.selector, to, value),
|
||||
"SAFE_TRANSFER_FAILED"
|
||||
);
|
||||
if (returndata.length > 0) {
|
||||
require(abi.decode(returndata, (bool)), "SAFE_TRANSFER_FALSE");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
abstract contract Ownable {
|
||||
address public owner;
|
||||
|
||||
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
|
||||
|
||||
modifier onlyOwner() {
|
||||
require(msg.sender == owner, "ONLY_OWNER");
|
||||
_;
|
||||
}
|
||||
|
||||
constructor(address initialOwner) {
|
||||
require(initialOwner != address(0), "ZERO_OWNER");
|
||||
owner = initialOwner;
|
||||
emit OwnershipTransferred(address(0), initialOwner);
|
||||
}
|
||||
|
||||
function transferOwnership(address newOwner) external onlyOwner {
|
||||
require(newOwner != address(0), "ZERO_OWNER");
|
||||
emit OwnershipTransferred(owner, newOwner);
|
||||
owner = newOwner;
|
||||
}
|
||||
}
|
||||
|
||||
abstract contract Pausable {
|
||||
bool public paused;
|
||||
|
||||
event Paused(address indexed account);
|
||||
event Unpaused(address indexed account);
|
||||
|
||||
modifier whenNotPaused() {
|
||||
require(!paused, "PAUSED");
|
||||
_;
|
||||
}
|
||||
|
||||
function _pause() internal {
|
||||
require(!paused, "PAUSED");
|
||||
paused = true;
|
||||
emit Paused(msg.sender);
|
||||
}
|
||||
|
||||
function _unpause() internal {
|
||||
require(paused, "NOT_PAUSED");
|
||||
paused = false;
|
||||
emit Unpaused(msg.sender);
|
||||
}
|
||||
}
|
||||
|
||||
abstract contract ReentrancyGuard {
|
||||
uint256 private _status = 1;
|
||||
|
||||
modifier nonReentrant() {
|
||||
require(_status == 1, "REENTRANT");
|
||||
_status = 2;
|
||||
_;
|
||||
_status = 1;
|
||||
}
|
||||
}
|
||||
|
||||
contract PolyWeatherCheckoutV2 is Ownable, Pausable, ReentrancyGuard {
|
||||
using SafeERC20 for IERC20;
|
||||
|
||||
struct PlanConfig {
|
||||
uint256 amount;
|
||||
bool active;
|
||||
}
|
||||
|
||||
bytes32 public constant AUTHORIZED_PAYMENT_TYPEHASH =
|
||||
keccak256(
|
||||
"AuthorizedPayment(bytes32 orderId,address payer,uint256 planId,address token,uint256 amount,uint256 nonce,uint256 deadline)"
|
||||
);
|
||||
|
||||
bytes32 public immutable DOMAIN_SEPARATOR;
|
||||
|
||||
address public treasury;
|
||||
address public signer;
|
||||
mapping(address => bool) public allowedToken;
|
||||
mapping(bytes32 => bool) public paidOrder;
|
||||
mapping(uint256 => mapping(address => PlanConfig)) public planConfig;
|
||||
mapping(address => uint256) public payerNonce;
|
||||
|
||||
event OrderPaid(
|
||||
bytes32 indexed orderId,
|
||||
address indexed payer,
|
||||
uint256 indexed planId,
|
||||
address token,
|
||||
uint256 amount
|
||||
);
|
||||
event TreasuryUpdated(address indexed treasury);
|
||||
event SignerUpdated(address indexed signer);
|
||||
event TokenAllowedUpdated(address indexed token, bool allowed);
|
||||
event PlanConfigured(uint256 indexed planId, address indexed token, uint256 amount, bool active);
|
||||
|
||||
constructor(address initialOwner, address initialTreasury, address initialSigner)
|
||||
Ownable(initialOwner)
|
||||
{
|
||||
require(initialTreasury != address(0), "ZERO_TREASURY");
|
||||
treasury = initialTreasury;
|
||||
signer = initialSigner;
|
||||
|
||||
uint256 chainId;
|
||||
assembly {
|
||||
chainId := chainid()
|
||||
}
|
||||
DOMAIN_SEPARATOR = keccak256(
|
||||
abi.encode(
|
||||
keccak256(
|
||||
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
|
||||
),
|
||||
keccak256(bytes("PolyWeatherCheckoutV2")),
|
||||
keccak256(bytes("1")),
|
||||
chainId,
|
||||
address(this)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function setTreasury(address newTreasury) external onlyOwner {
|
||||
require(newTreasury != address(0), "ZERO_ADDR");
|
||||
treasury = newTreasury;
|
||||
emit TreasuryUpdated(newTreasury);
|
||||
}
|
||||
|
||||
function setSigner(address newSigner) external onlyOwner {
|
||||
signer = newSigner;
|
||||
emit SignerUpdated(newSigner);
|
||||
}
|
||||
|
||||
function setTokenAllowed(address token, bool allowed) external onlyOwner {
|
||||
require(token != address(0), "ZERO_ADDR");
|
||||
allowedToken[token] = allowed;
|
||||
emit TokenAllowedUpdated(token, allowed);
|
||||
}
|
||||
|
||||
function setPlan(uint256 planId, address token, uint256 amount, bool active) external onlyOwner {
|
||||
require(planId > 0, "PLAN_ZERO");
|
||||
require(token != address(0), "ZERO_ADDR");
|
||||
require(amount > 0 || !active, "AMOUNT_ZERO");
|
||||
planConfig[planId][token] = PlanConfig({amount: amount, active: active});
|
||||
emit PlanConfigured(planId, token, amount, active);
|
||||
}
|
||||
|
||||
function pause() external onlyOwner {
|
||||
_pause();
|
||||
}
|
||||
|
||||
function unpause() external onlyOwner {
|
||||
_unpause();
|
||||
}
|
||||
|
||||
function payPlan(bytes32 orderId, uint256 planId, address token)
|
||||
external
|
||||
whenNotPaused
|
||||
nonReentrant
|
||||
{
|
||||
require(allowedToken[token], "TOKEN_NOT_ALLOWED");
|
||||
PlanConfig memory config = planConfig[planId][token];
|
||||
require(config.active, "PLAN_NOT_ACTIVE");
|
||||
require(config.amount > 0, "PLAN_AMOUNT_ZERO");
|
||||
_collect(orderId, msg.sender, planId, token, config.amount);
|
||||
}
|
||||
|
||||
function payAuthorized(
|
||||
bytes32 orderId,
|
||||
uint256 planId,
|
||||
address token,
|
||||
uint256 amount,
|
||||
uint256 deadline,
|
||||
bytes calldata signature
|
||||
) external whenNotPaused nonReentrant {
|
||||
require(allowedToken[token], "TOKEN_NOT_ALLOWED");
|
||||
require(amount > 0, "AMOUNT_ZERO");
|
||||
require(deadline >= block.timestamp, "AUTH_EXPIRED");
|
||||
require(signer != address(0), "SIGNER_NOT_SET");
|
||||
|
||||
uint256 nonce = payerNonce[msg.sender];
|
||||
bytes32 structHash = keccak256(
|
||||
abi.encode(
|
||||
AUTHORIZED_PAYMENT_TYPEHASH,
|
||||
orderId,
|
||||
msg.sender,
|
||||
planId,
|
||||
token,
|
||||
amount,
|
||||
nonce,
|
||||
deadline
|
||||
)
|
||||
);
|
||||
bytes32 digest = keccak256(
|
||||
abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash)
|
||||
);
|
||||
require(_recover(digest, signature) == signer, "BAD_SIGNATURE");
|
||||
payerNonce[msg.sender] = nonce + 1;
|
||||
|
||||
_collect(orderId, msg.sender, planId, token, amount);
|
||||
}
|
||||
|
||||
function rescueToken(address token, address to, uint256 amount) external onlyOwner nonReentrant {
|
||||
require(token != address(0) && to != address(0), "ZERO_ADDR");
|
||||
IERC20(token).safeTransfer(to, amount);
|
||||
}
|
||||
|
||||
function _collect(bytes32 orderId, address payer, uint256 planId, address token, uint256 amount) internal {
|
||||
require(!paidOrder[orderId], "ORDER_PAID");
|
||||
paidOrder[orderId] = true;
|
||||
IERC20(token).safeTransferFrom(payer, treasury, amount);
|
||||
emit OrderPaid(orderId, payer, planId, token, amount);
|
||||
}
|
||||
|
||||
function _recover(bytes32 digest, bytes calldata signature) internal pure returns (address) {
|
||||
require(signature.length == 65, "BAD_SIG_LEN");
|
||||
bytes32 r;
|
||||
bytes32 s;
|
||||
uint8 v;
|
||||
assembly {
|
||||
r := calldataload(signature.offset)
|
||||
s := calldataload(add(signature.offset, 32))
|
||||
v := byte(0, calldataload(add(signature.offset, 64)))
|
||||
}
|
||||
if (v < 27) {
|
||||
v += 27;
|
||||
}
|
||||
require(v == 27 || v == 28, "BAD_SIG_V");
|
||||
address recovered = ecrecover(digest, v, r, s);
|
||||
require(recovered != address(0), "BAD_SIG");
|
||||
return recovered;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
{"city": "ankara", "timestamp": "2026-03-20T12:00:00+03:00", "date": "2026-03-20", "temp_symbol": "°C", "raw_mu": 15.2, "raw_sigma": 1.2, "deb_prediction": 15.4, "ensemble": {"p10": 14.8, "median": 15.8, "p90": 17.9}, "multi_model": {"ECMWF": 15.8, "GFS": 14.1, "ICON": 15.9}, "max_so_far": 15.0, "peak_status": "before", "prob_snapshot": [{"v": 15, "p": 0.552}, {"v": 16, "p": 0.377}], "shadow_prob_snapshot": [{"v": 15, "p": 0.324}, {"v": 16, "p": 0.238}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320130245", "calibration_source": "artifacts/probability_calibration/default.json", "calibrated_mu": 15.1, "calibrated_sigma": 1.25}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 10:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.5625, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 26.0, "peak_status": "before", "prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "shadow_prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.5625}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 33.3, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 33.0, "peak_status": "in_window", "prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "shadow_prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 33.3, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 22:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 16:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.85, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.5, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 29.5, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "shadow_prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.85, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:30", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 10:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.5625, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 26.0, "peak_status": "before", "prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "shadow_prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.5625}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 33.3, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 33.0, "peak_status": "in_window", "prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "shadow_prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 33.3, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 22:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 16:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.85, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.5, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 29.5, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "shadow_prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.85, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:30", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 10:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.5625, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 26.0, "peak_status": "before", "prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "shadow_prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.5625}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 33.3, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 33.0, "peak_status": "in_window", "prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "shadow_prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 33.3, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 22:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 16:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.85, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.5, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 29.5, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "shadow_prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.85, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:30", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 10:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.5625, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 26.0, "peak_status": "before", "prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "shadow_prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.5625}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 33.3, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 33.0, "peak_status": "in_window", "prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "shadow_prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 33.3, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 22:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 16:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.85, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.5, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 29.5, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "shadow_prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.85, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:30", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 10:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.5625, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 26.0, "peak_status": "before", "prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "shadow_prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.5625}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 33.3, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 33.0, "peak_status": "in_window", "prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "shadow_prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 33.3, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 22:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 16:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.85, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.5, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 29.5, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "shadow_prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.85, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:30", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 10:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.5625, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 26.0, "peak_status": "before", "prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "shadow_prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.5625}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 33.3, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 33.0, "peak_status": "in_window", "prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "shadow_prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 33.3, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 22:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 16:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.85, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.5, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 29.5, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "shadow_prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.85, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:30", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 10:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.5625, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 26.0, "peak_status": "before", "prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "shadow_prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.5625}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 33.3, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 33.0, "peak_status": "in_window", "prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "shadow_prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 33.3, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 22:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 16:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.85, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.5, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 29.5, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "shadow_prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.85, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:30", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 10:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.5625, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 26.0, "peak_status": "before", "prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "shadow_prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.5625}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 33.3, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 33.0, "peak_status": "in_window", "prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "shadow_prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 33.3, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 22:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 16:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.85, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.5, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 29.5, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "shadow_prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.85, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:30", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 10:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.5625, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 26.0, "peak_status": "before", "prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "shadow_prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.5625}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 33.3, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 33.0, "peak_status": "in_window", "prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "shadow_prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 33.3, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 22:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 16:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.85, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.5, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 29.5, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "shadow_prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.85, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:30", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 10:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.5625, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 26.0, "peak_status": "before", "prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "shadow_prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.5625}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 33.3, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 33.0, "peak_status": "in_window", "prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "shadow_prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 33.3, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 22:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 16:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.85, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.5, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 29.5, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "shadow_prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.85, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:30", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 10:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.5625, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 26.0, "peak_status": "before", "prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "shadow_prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.5625}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 33.3, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 33.0, "peak_status": "in_window", "prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "shadow_prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 33.3, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 22:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 16:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.85, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.5, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 29.5, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "shadow_prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.85, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:30", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 10:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.5625, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 26.0, "peak_status": "before", "prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "shadow_prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.5625}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 33.3, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 33.0, "peak_status": "in_window", "prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "shadow_prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 33.3, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 22:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 16:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.85, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.5, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 29.5, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "shadow_prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.85, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:30", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 10:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.5625, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 26.0, "peak_status": "before", "prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "shadow_prob_snapshot": [{"v": 30, "p": 0.254}, {"v": 29, "p": 0.234}, {"v": 31, "p": 0.185}, {"v": 28, "p": 0.146}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.5625}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 33.3, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 33.0, "peak_status": "in_window", "prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "shadow_prob_snapshot": [{"v": 33, "p": 0.456}, {"v": 34, "p": 0.391}, {"v": 35, "p": 0.153}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 33.3, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 17:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 22:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 16:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 23.0, "raw_sigma": 0.46875, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 23.0, "peak_status": "past", "prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "shadow_prob_snapshot": [{"v": 23, "p": 0.834}, {"v": 24, "p": 0.166}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 23.0, "calibrated_sigma": 0.46875}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:00", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.85, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.5, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 29.5, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "shadow_prob_snapshot": [{"v": 30, "p": 0.565}, {"v": 31, "p": 0.341}, {"v": 32, "p": 0.094}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.85, "calibrated_sigma": 1.09375}
|
||||
{"city": "test_city", "timestamp": "2026-03-04 14:30", "date": "2026-03-04", "temp_symbol": "°C", "raw_mu": 29.7, "raw_sigma": 1.09375, "deb_prediction": null, "ensemble": {"p10": 27.0, "median": 29.0, "p90": 31.0}, "multi_model": {"Open-Meteo": 30.0}, "max_so_far": 28.0, "peak_status": "in_window", "prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "shadow_prob_snapshot": [{"v": 30, "p": 0.35}, {"v": 29, "p": 0.299}, {"v": 31, "p": 0.187}, {"v": 28, "p": 0.117}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 29.7, "calibrated_sigma": 1.09375}
|
||||
{"city": "hong kong", "timestamp": "2026-03-23T21:10:00+08:00", "date": "2026-03-23", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.6806250000000001, "deb_prediction": 25.2, "ensemble": {"p10": 26.3, "median": 26.4, "p90": 26.6}, "multi_model": {"Open-Meteo": 24.8, "HKO(港天文)": 27.0, "ECMWF": 25.4, "GFS": 25.1, "ICON": 24.8, "GEM": 25.3, "JMA": 23.6}, "max_so_far": 27.4, "peak_status": "past", "prob_snapshot": [{"v": 27, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "shenzhen", "timestamp": "2026-03-25T08:43:15.528748+00:00", "date": "2026-03-25", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.18016764322916676, "deb_prediction": 28.1, "ensemble": {"p10": 30.5, "median": 31.4, "p90": 31.8}, "multi_model": {"Open-Meteo": 26.6, "ECMWF": 28.8, "GFS": 30.3, "ICON": 26.6, "GEM": 30.7, "JMA": 25.5}, "max_so_far": 29.0, "peak_status": "past", "prob_snapshot": [{"v": 29, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "shenzhen", "timestamp": "2026-03-25T08:57:11.783182+00:00", "date": "2026-03-25", "temp_symbol": "°C", "raw_mu": 26.7, "raw_sigma": 0.18016764322916676, "deb_prediction": 28.1, "ensemble": {"p10": 30.5, "median": 31.4, "p90": 31.8}, "multi_model": {"Open-Meteo": 26.6, "ECMWF": 28.8, "GFS": 30.3, "ICON": 26.6, "GEM": 30.7, "JMA": 25.5}, "max_so_far": 26.7, "peak_status": "past", "prob_snapshot": [{"v": 27, "p": 1.0}], "shadow_prob_snapshot": [{"v": 27, "p": 1.0}], "probability_engine": "legacy", "probability_mode": "emos_shadow", "calibration_version": "emos-20260320132525", "calibration_source": "artifacts\\probability_calibration\\default.json", "calibrated_mu": 26.7, "calibrated_sigma": 0.24322631835937514}
|
||||
{"city": "shenzhen", "timestamp": "2026-03-25T09:32:32+00:00", "date": "2026-03-25", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.16637912326388898, "deb_prediction": 28.1, "ensemble": {"p10": 30.5, "median": 31.4, "p90": 31.8}, "multi_model": {"Open-Meteo": 26.6, "ECMWF": 28.8, "GFS": 30.3, "ICON": 26.6, "GEM": 30.7, "JMA": 25.5}, "max_so_far": 28.9, "peak_status": "past", "prob_snapshot": [{"v": 29, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
{"city": "shenzhen", "timestamp": "2026-03-25T10:02:35+00:00", "date": "2026-03-25", "temp_symbol": "°C", "raw_mu": null, "raw_sigma": 0.15911458333333342, "deb_prediction": 28.2, "ensemble": {"p10": 30.5, "median": 31.4, "p90": 31.8}, "multi_model": {"Open-Meteo": 26.5, "ECMWF": 28.8, "GFS": 30.3, "ICON": 26.5, "GEM": 30.7, "JMA": 26.2}, "max_so_far": 28.9, "peak_status": "past", "prob_snapshot": [{"v": 28, "p": 1.0}], "shadow_prob_snapshot": [], "probability_engine": "legacy", "probability_mode": "legacy", "calibration_version": null, "calibration_source": null, "calibrated_mu": null, "calibrated_sigma": null}
|
||||
+5
-1
@@ -7,11 +7,13 @@ services:
|
||||
- .env
|
||||
volumes:
|
||||
# Persist runtime data outside git workspace.
|
||||
# Host path defaults to /var/lib/polyweather and can be overridden by POLYWEATHER_RUNTIME_DATA_DIR.
|
||||
# Host path defaults to /var/lib/polyweather and can be overridden in .env.
|
||||
- ${POLYWEATHER_RUNTIME_DATA_DIR:-/var/lib/polyweather}:/var/lib/polyweather
|
||||
# Keep /app/data compatibility for existing cache/state defaults.
|
||||
- ${POLYWEATHER_RUNTIME_DATA_DIR:-/var/lib/polyweather}:/app/data
|
||||
- ./bot.log:/app/bot.log # 挂载日志文件
|
||||
# UID/GID are mainly useful on Linux hosts to avoid root-owned output files.
|
||||
# Windows / macOS can usually keep the fallback values.
|
||||
user: "${UID:-1000}:${GID:-1000}"
|
||||
|
||||
polyweather_web:
|
||||
@@ -22,8 +24,10 @@ services:
|
||||
env_file:
|
||||
- .env
|
||||
volumes:
|
||||
# Web service shares the same runtime data directory as bot/state tasks.
|
||||
- ${POLYWEATHER_RUNTIME_DATA_DIR:-/var/lib/polyweather}:/var/lib/polyweather
|
||||
- ${POLYWEATHER_RUNTIME_DATA_DIR:-/var/lib/polyweather}:/app/data
|
||||
ports:
|
||||
- "8000:8000"
|
||||
# UID/GID are mainly useful on Linux hosts to avoid root-owned output files.
|
||||
user: "${UID:-1000}:${GID:-1000}"
|
||||
|
||||
+134
-8
@@ -1,8 +1,8 @@
|
||||
# PolyWeather API 文档(v1.4.0)
|
||||
# PolyWeather API 文档(v1.5.1)
|
||||
|
||||
最后更新:`2026-03-14`
|
||||
最后更新:`2026-03-24`
|
||||
|
||||
本文档描述当前对外可用 API 口径(`web/app.py` + `frontend/app/api/*`)。
|
||||
本文档描述当前对外可用 API 口径(`web/app.py` + `web/routes.py` + `frontend/app/api/*`)。
|
||||
|
||||
## 1. 基础信息
|
||||
|
||||
@@ -15,10 +15,11 @@
|
||||
```mermaid
|
||||
flowchart LR
|
||||
FE["Browser / Dashboard"] --> BFF["Next.js Route Handlers (/api/*)"]
|
||||
BFF --> API["FastAPI (/web/app.py)"]
|
||||
BFF --> API["FastAPI (/web/app.py + /web/routes.py)"]
|
||||
API --> WX["Weather Collector"]
|
||||
API --> ANA["DEB + Trend + Probability + Market Scan"]
|
||||
API --> PAY["Payment Intent + Event + Confirm Loops"]
|
||||
API --> OBS["healthz / system status / metrics"]
|
||||
```
|
||||
|
||||
## 3. 天气分析接口
|
||||
@@ -43,9 +44,70 @@ flowchart LR
|
||||
|
||||
- `market_scan.available`
|
||||
- `market_scan.signal_label`
|
||||
- `market_scan.edge_percent`
|
||||
- `market_scan.anchor_model / anchor_high / anchor_settlement`
|
||||
- `market_scan.yes_buy / no_buy`
|
||||
- `market_scan.primary_market.tradable`
|
||||
- `peak.first_h / peak.last_h / peak.status`
|
||||
- `vertical_profile_signal.heating_setup / suppression_risk / trigger_risk / mixing_strength`
|
||||
- `taf.signal.peak_window / suppression_level / disruption_level / markers`
|
||||
|
||||
### `detail` 新增结构信号说明
|
||||
|
||||
`/api/city/{name}/detail` 现在会返回一组更偏交易场景的结构字段:
|
||||
|
||||
#### 1. `peak`
|
||||
|
||||
- `first_h`:预计峰值窗口起始小时
|
||||
- `last_h`:预计峰值窗口结束小时
|
||||
- `status`:`before_peak | near_peak | after_peak`
|
||||
|
||||
这组字段用于让日内结构信号围绕真实峰值窗口分析,而不是固定只看下午。
|
||||
|
||||
#### 2. `vertical_profile_signal`
|
||||
|
||||
重点字段:
|
||||
|
||||
- `source`
|
||||
- `window`
|
||||
- `cape_max`
|
||||
- `cin_min`
|
||||
- `lifted_index_min`
|
||||
- `boundary_layer_height_max`
|
||||
- `shear_10m_180m_max`
|
||||
- `suppression_risk`
|
||||
- `trigger_risk`
|
||||
- `mixing_strength`
|
||||
- `shear_risk`
|
||||
- `heating_setup`
|
||||
- `heating_score`
|
||||
- `summary_zh`
|
||||
- `summary_en`
|
||||
|
||||
这组字段对应前端“高空结构信号 / Upper-Air Structure”卡片。
|
||||
|
||||
#### 3. `taf.signal`
|
||||
|
||||
仅对**非香港机场城市**启用。当前已支持解析:
|
||||
|
||||
- `FM`
|
||||
- `TEMPO`
|
||||
- `BECMG`
|
||||
- `PROB30`
|
||||
- `PROB40`
|
||||
|
||||
重点字段:
|
||||
|
||||
- `peak_window`
|
||||
- `segments`
|
||||
- `markers`
|
||||
- `suppression_level`
|
||||
- `disruption_level`
|
||||
- `wind_shift`
|
||||
- `summary_zh`
|
||||
- `summary_en`
|
||||
|
||||
`markers` 会被前端温度走势图拿来做 `TAF 时段 / TAF Timing` 标记。
|
||||
|
||||
## 4. 鉴权与账户接口
|
||||
|
||||
@@ -60,11 +122,12 @@ flowchart LR
|
||||
- `points`, `weekly_points`, `weekly_rank`
|
||||
- `subscription_active`, `subscription_plan_code`, `subscription_expires_at`
|
||||
|
||||
## 5. 支付接口(P1)
|
||||
## 5. 支付接口
|
||||
|
||||
| 接口 | 方法 | 用途 |
|
||||
| :-- | :-- | :-- |
|
||||
| `/api/payments/config` | GET | 支付配置、代币列表、套餐、积分抵扣规则 |
|
||||
| `/api/payments/runtime` | GET | 支付运行态、RPC 状态、event loop 状态、最近审计事件 |
|
||||
| `/api/payments/wallets` | GET | 当前用户已绑定钱包 |
|
||||
| `/api/payments/wallets/challenge` | POST | 获取绑定签名 challenge |
|
||||
| `/api/payments/wallets/verify` | POST | 提交签名并绑定钱包 |
|
||||
@@ -72,6 +135,7 @@ flowchart LR
|
||||
| `/api/payments/intents/{intent_id}` | GET | 查询 intent 最新状态 |
|
||||
| `/api/payments/intents/{intent_id}/submit` | POST | 提交交易哈希 |
|
||||
| `/api/payments/intents/{intent_id}/confirm` | POST | 手动触发确认 |
|
||||
| `/api/payments/reconcile-latest` | POST | 对当前登录用户最近一笔 intent 做恢复性确认 |
|
||||
|
||||
### 支付状态建议
|
||||
|
||||
@@ -83,13 +147,57 @@ flowchart LR
|
||||
4. `POST /confirm`
|
||||
5. 若 pending,轮询 `GET /intents/{id}` 直到 `confirmed`
|
||||
|
||||
## 6. 缓存策略(当前)
|
||||
## 6. 运维与观测接口
|
||||
|
||||
| 接口 | 方法 | 用途 |
|
||||
| :-- | :-- | :-- |
|
||||
| `/healthz` | GET | 基础健康检查 |
|
||||
| `/api/system/status` | GET | 系统状态、功能开关、rollout 状态、轻量指标摘要 |
|
||||
| `/metrics` | GET | Prometheus 风格指标导出 |
|
||||
|
||||
`/api/system/status` 当前会包含:
|
||||
|
||||
- `features.state_storage_mode`
|
||||
- `probability.decision`
|
||||
- `probability.ready_for_primary`
|
||||
- `metrics`
|
||||
|
||||
`/metrics` 当前会导出:
|
||||
|
||||
- `polyweather_http_requests_total`
|
||||
- `polyweather_http_request_duration_ms_*`
|
||||
- `polyweather_source_requests_total`
|
||||
- `polyweather_source_request_duration_ms_*`
|
||||
|
||||
## 7. Ops 管理接口
|
||||
|
||||
这些接口主要给 `/ops` 管理后台使用,默认要求:
|
||||
|
||||
- 已登录
|
||||
- 当前邮箱位于 `POLYWEATHER_OPS_ADMIN_EMAILS`
|
||||
|
||||
| 接口 | 方法 | 用途 |
|
||||
| :-- | :-- | :-- |
|
||||
| `/api/ops/users` | GET | 按 Telegram ID / 用户名 / 邮箱查询用户 |
|
||||
| `/api/ops/leaderboard/weekly` | GET | 本周积分榜 |
|
||||
| `/api/ops/memberships` | GET | 当前有效会员(已按用户去重,保留最晚到期) |
|
||||
| `/api/ops/users/grant-points` | POST | 手动补分 |
|
||||
| `/api/ops/payments/incidents` | GET | 支付异常单(仅 `payment_intent_failed`) |
|
||||
| `/api/ops/payments/incidents/{event_id}/resolve` | POST | 标记支付异常单已处理 |
|
||||
|
||||
`/api/ops/payments/incidents` 当前支持:
|
||||
|
||||
- `reason=<receiver_mismatch|sender_mismatch|event_mismatch|tx_reverted>`
|
||||
- 默认不返回已标记处理的记录
|
||||
- 重点用于排查“已付款未开通”“打到旧收款地址”等事故
|
||||
## 8. 缓存策略(当前)
|
||||
|
||||
- `cities` / `summary` / `history`:BFF 支持 `ETag + 304`
|
||||
- `summary?force_refresh=true`:`Cache-Control: no-store`
|
||||
- 详情接口与支付接口:`no-store`
|
||||
- `METAR` / `TAF` / settlement current 由后端各自维护短 TTL 缓存
|
||||
|
||||
## 7. 调试示例
|
||||
## 9. 调试示例
|
||||
|
||||
### 查询未来日期 market_scan
|
||||
|
||||
@@ -103,13 +211,31 @@ curl -s "http://127.0.0.1:8000/api/city/ankara/detail?force_refresh=true&target_
|
||||
curl -s http://127.0.0.1:8000/api/payments/config | python3 -m json.tool
|
||||
```
|
||||
|
||||
### 查看支付运行态
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:8000/api/payments/runtime | python3 -m json.tool
|
||||
```
|
||||
|
||||
### 查看支付异常单
|
||||
|
||||
```bash
|
||||
curl -s "http://127.0.0.1:8000/api/ops/payments/incidents?reason=receiver_mismatch" | python3 -m json.tool
|
||||
```
|
||||
|
||||
### 查看系统状态
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:8000/api/system/status | python3 -m json.tool
|
||||
```
|
||||
|
||||
### 观察支付自动补单
|
||||
|
||||
```bash
|
||||
docker compose logs -f polyweather | egrep "payment event loop started|payment confirm loop started|payment auto-confirmed"
|
||||
```
|
||||
|
||||
## 8. 开源口径说明
|
||||
## 10. 开源口径说明
|
||||
|
||||
对外公开文档仅覆盖通用 API 契约。生产商业策略参数不在公开文档披露。
|
||||
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
# 配置与密钥管理(中文)
|
||||
|
||||
## 1. 目标
|
||||
|
||||
PolyWeather 的环境变量很多,但不是所有变量都属于同一层级。
|
||||
|
||||
当前推荐做法是把配置拆成三类:
|
||||
|
||||
1. 可复现基础配置
|
||||
放在:[.env.example](/E:/web/PolyWeather/.env.example)
|
||||
|
||||
2. 敏感密钥模板
|
||||
放在:[.env.secrets.example](/E:/web/PolyWeather/.env.secrets.example)
|
||||
|
||||
3. 平台侧真实密钥
|
||||
放在:
|
||||
- VPS / Docker `.env`
|
||||
- Vercel Environment Variables
|
||||
- GitHub Secrets(如需要)
|
||||
|
||||
## 2. 为什么要拆
|
||||
|
||||
如果把所有变量都平铺在一个 `.env` 里,会有三个问题:
|
||||
|
||||
1. 新环境很难知道“最小启动到底需要哪些变量”
|
||||
2. 敏感密钥和普通开关混在一起,容易误泄露
|
||||
3. 调优参数太多时,团队很难区分“必须填”和“保持默认即可”
|
||||
|
||||
所以正确做法不是“减少变量数量”,而是:
|
||||
|
||||
- 保留变量能力
|
||||
- 按职责分层
|
||||
- 给出最小启动路径
|
||||
|
||||
## 3. 文件职责
|
||||
|
||||
### 3.1 根 `.env.example`
|
||||
|
||||
文件:
|
||||
|
||||
- [.env.example](/E:/web/PolyWeather/.env.example)
|
||||
|
||||
用途:
|
||||
|
||||
- 后端 / Bot / Docker 的可复现配置模板
|
||||
- 只放变量名、默认值、开关与非敏感示例
|
||||
|
||||
### 3.2 根 `.env.secrets.example`
|
||||
|
||||
文件:
|
||||
|
||||
- [.env.secrets.example](/E:/web/PolyWeather/.env.secrets.example)
|
||||
|
||||
用途:
|
||||
|
||||
- 只列敏感项
|
||||
- 帮助运维明确哪些值必须从密钥系统注入
|
||||
|
||||
### 3.3 前端 `.env.example`
|
||||
|
||||
文件:
|
||||
|
||||
- [frontend/.env.example](/E:/web/PolyWeather/frontend/.env.example)
|
||||
|
||||
用途:
|
||||
|
||||
- 前端本地开发与 Vercel 环境变量模板
|
||||
|
||||
## 4. 配置分级
|
||||
|
||||
### 4.1 L1:最小启动必需项
|
||||
|
||||
这是“服务能跑起来”的最小集合。
|
||||
|
||||
后端 / Bot:
|
||||
|
||||
- `TELEGRAM_BOT_TOKEN`
|
||||
- `TELEGRAM_CHAT_ID`
|
||||
- `POLYWEATHER_RUNTIME_DATA_DIR`
|
||||
- `POLYWEATHER_DB_PATH`
|
||||
- `POLYWEATHER_STATE_STORAGE_MODE`
|
||||
|
||||
前端:
|
||||
|
||||
- `POLYWEATHER_API_BASE_URL`
|
||||
- `POLYWEATHER_OPS_ADMIN_EMAILS`(如果启用 `/ops` 页面级管理员守卫)
|
||||
|
||||
如果启用登录:
|
||||
|
||||
- `NEXT_PUBLIC_SUPABASE_URL`
|
||||
- `NEXT_PUBLIC_SUPABASE_ANON_KEY`
|
||||
- `SUPABASE_URL`
|
||||
- `SUPABASE_ANON_KEY`
|
||||
- `SUPABASE_SERVICE_ROLE_KEY`
|
||||
|
||||
### 4.2 L2:功能开关
|
||||
|
||||
这些变量一般不敏感,但会决定功能是否启用。
|
||||
|
||||
例如:
|
||||
|
||||
- `POLYWEATHER_AUTH_ENABLED`
|
||||
- `POLYWEATHER_AUTH_REQUIRED`
|
||||
- `POLYWEATHER_AUTH_REQUIRE_SUBSCRIPTION`
|
||||
- `POLYWEATHER_OPS_ADMIN_EMAILS`
|
||||
- `POLYWEATHER_STATE_STORAGE_MODE`
|
||||
- `POLYWEATHER_PAYMENT_ENABLED`
|
||||
- `POLYMARKET_MARKET_SCAN_ENABLED`
|
||||
- `POLYGON_WALLET_WATCH_ENABLED`
|
||||
- `POLYMARKET_WALLET_ACTIVITY_ENABLED`
|
||||
|
||||
### 4.3 L3:运行调优项
|
||||
|
||||
这些一般不需要在第一天就改。
|
||||
|
||||
例如:
|
||||
|
||||
- 各类 `*_TTL_SEC`
|
||||
- 各类 `*_TIMEOUT_SEC`
|
||||
- 各类 `*_COOLDOWN_SEC`
|
||||
- 各类 `*_INTERVAL_SEC`
|
||||
- `POLYWEATHER_PAYMENT_RPC_URLS`
|
||||
- `TAF_CACHE_TTL_SEC`
|
||||
|
||||
策略:
|
||||
|
||||
- 先用默认值
|
||||
- 出现性能或运维问题时再调
|
||||
|
||||
### 4.4 L4:敏感项
|
||||
|
||||
这些变量不应写进公开文档截图,也不应提交到仓库。
|
||||
|
||||
例如:
|
||||
|
||||
- `TELEGRAM_BOT_TOKEN`
|
||||
- `SUPABASE_SERVICE_ROLE_KEY`
|
||||
- `POLYWEATHER_BACKEND_ENTITLEMENT_TOKEN`
|
||||
- `POLYWEATHER_DASHBOARD_ACCESS_TOKEN`
|
||||
- `METEOBLUE_API_KEY`
|
||||
- `NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID`
|
||||
- `POLYMARKET_SECRET_KEY`
|
||||
|
||||
## 5. 推荐部署矩阵
|
||||
|
||||
### 5.1 VPS / Docker(后端 + Bot)
|
||||
|
||||
建议放这些:
|
||||
|
||||
- 根 `.env` 的后端项
|
||||
- 所有 secrets
|
||||
- Bot / 支付 / watcher 配置
|
||||
|
||||
### 5.2 Vercel(前端)
|
||||
|
||||
建议只放前端真正需要的变量:
|
||||
|
||||
- `POLYWEATHER_API_BASE_URL`
|
||||
- `NEXT_PUBLIC_SUPABASE_URL`
|
||||
- `NEXT_PUBLIC_SUPABASE_ANON_KEY`
|
||||
- `POLYWEATHER_AUTH_ENABLED`
|
||||
- `POLYWEATHER_AUTH_REQUIRED`
|
||||
- `POLYWEATHER_OPS_ADMIN_EMAILS`
|
||||
- `POLYWEATHER_DASHBOARD_ACCESS_TOKEN`
|
||||
- `POLYWEATHER_BACKEND_ENTITLEMENT_TOKEN`
|
||||
- `NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID`
|
||||
- `NEXT_PUBLIC_WALLETCONNECT_POLYGON_RPC_URL`
|
||||
|
||||
说明:
|
||||
|
||||
- `/ops` 现在是前后端双层限制:
|
||||
- 前端页面入口读取 `POLYWEATHER_OPS_ADMIN_EMAILS`
|
||||
- 后端写接口同样读取 `POLYWEATHER_OPS_ADMIN_EMAILS`
|
||||
- 因此,Vercel 和 VPS / Docker 两侧都应配置相同的管理员邮箱白名单。
|
||||
|
||||
不要把后端专用密钥全搬进 Vercel。
|
||||
|
||||
### 5.3 GitHub Actions
|
||||
|
||||
当前 CI 不需要大规模 secrets。
|
||||
|
||||
如果未来要做自动部署,再考虑:
|
||||
|
||||
- `VERCEL_TOKEN`
|
||||
- `VERCEL_ORG_ID`
|
||||
- `VERCEL_PROJECT_ID`
|
||||
|
||||
## 6. 最小部署示例
|
||||
|
||||
### 6.1 前端最小变量
|
||||
|
||||
```env
|
||||
POLYWEATHER_API_BASE_URL=https://your-backend.example.com
|
||||
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_anon_key
|
||||
POLYWEATHER_AUTH_ENABLED=true
|
||||
POLYWEATHER_AUTH_REQUIRED=true
|
||||
```
|
||||
|
||||
### 6.2 后端最小变量
|
||||
|
||||
```env
|
||||
TELEGRAM_BOT_TOKEN=...
|
||||
TELEGRAM_CHAT_ID=...
|
||||
POLYWEATHER_RUNTIME_DATA_DIR=/var/lib/polyweather
|
||||
POLYWEATHER_DB_PATH=/var/lib/polyweather/polyweather.db
|
||||
POLYWEATHER_STATE_STORAGE_MODE=dual
|
||||
UID=1000
|
||||
GID=1000
|
||||
POLYWEATHER_AUTH_ENABLED=true
|
||||
POLYWEATHER_AUTH_REQUIRED=false
|
||||
POLYWEATHER_OPS_ADMIN_EMAILS=yhrsc30@gmail.com
|
||||
TAF_CACHE_TTL_SEC=900
|
||||
SUPABASE_URL=https://your-project.supabase.co
|
||||
SUPABASE_ANON_KEY=...
|
||||
SUPABASE_SERVICE_ROLE_KEY=...
|
||||
POLYWEATHER_BACKEND_ENTITLEMENT_TOKEN=...
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
- `UID` / `GID` 主要给 Linux Docker 主机用,避免容器把运行文件写成 root 所有。
|
||||
- Windows / macOS 一般可以直接保留默认值。
|
||||
- `POLYWEATHER_RUNTIME_DATA_DIR` 建议放在仓库外,例如 `/var/lib/polyweather`。
|
||||
- `docker-compose.yml` 会把这个目录同时挂载到容器内的 `/var/lib/polyweather` 和 `/app/data`,兼容现有缓存与 SQLite 路径。
|
||||
- `POLYWEATHER_STATE_STORAGE_MODE` 当前推荐先用 `dual`,验证后再切 `sqlite`。
|
||||
- `POLYWEATHER_PAYMENT_RPC_URLS` 支持逗号分隔多个 RPC;如果暂时只用单 RPC,也可以继续只配 `POLYWEATHER_PAYMENT_RPC_URL`。
|
||||
|
||||
## 7. 当前建议的运维规则
|
||||
|
||||
### 7.1 仓库中允许存在
|
||||
|
||||
- `.env.example`
|
||||
- `.env.secrets.example`
|
||||
- `frontend/.env.example`
|
||||
|
||||
### 7.2 仓库中不应提交
|
||||
|
||||
- `.env`
|
||||
- `.env.local`
|
||||
- 任何带真实 token / key 的配置文件
|
||||
|
||||
### 7.3 截图与共享规则
|
||||
|
||||
以下值一旦出现在截图或聊天里,建议视为泄露并轮换:
|
||||
|
||||
- `SUPABASE_SERVICE_ROLE_KEY`
|
||||
- `POLYWEATHER_BACKEND_ENTITLEMENT_TOKEN`
|
||||
- `TELEGRAM_BOT_TOKEN`
|
||||
- 第三方私有 API Key
|
||||
|
||||
## 8. 如何收口配置复杂度
|
||||
|
||||
如果你觉得变量仍然太多,正确的做法不是一刀删掉,而是:
|
||||
|
||||
1. 把“功能开关”和“调优参数”分开看
|
||||
2. 保持 `.env.example` 中:
|
||||
- 最小启动项
|
||||
- 常用功能开关
|
||||
- 默认调优值
|
||||
3. 让不常改的高阶参数继续留默认
|
||||
|
||||
也就是说:
|
||||
|
||||
- 使用者只需要先关心 10-20 个关键变量
|
||||
- 其余变量保持默认即可
|
||||
|
||||
## 9. 当前已经完成的配置治理
|
||||
|
||||
1. 根 `.env.example` 收口
|
||||
2. `.env.secrets.example` 新增
|
||||
3. 前端 `.env.example` 收口
|
||||
4. 运行时配置校验脚本新增
|
||||
5. `/ops` 管理员白名单与前后端职责边界已明确
|
||||
5. 支付运行态与多 RPC 配置支持
|
||||
6. 运行态 SQLite 迁移配置支持
|
||||
|
||||
## 10. 配置校验命令
|
||||
|
||||
在不启动服务的情况下,你可以直接检查配置:
|
||||
|
||||
```bash
|
||||
python scripts/validate_runtime_env.py --component web
|
||||
python scripts/validate_runtime_env.py --component bot
|
||||
```
|
||||
@@ -0,0 +1,311 @@
|
||||
# EMOS 训练报告(2026-03-20)
|
||||
|
||||
## 1. 报告目的
|
||||
|
||||
本文档用于记录当前 PolyWeather 概率校准引擎(EMOS)的训练结果、离线评估结果、线上 shadow 观测结果,以及是否具备切换为主路径的条件。
|
||||
|
||||
当前结论先写在前面:
|
||||
|
||||
- `EMOS` 已完成接入、训练、离线评估、shadow 落盘与滚动报表。
|
||||
- 当前默认运行模式应继续保持 `emos_shadow`。
|
||||
- 现阶段 **不建议切换到 `emos_primary`**。
|
||||
|
||||
## 2. 本次训练版本
|
||||
|
||||
- 校准版本:`emos-20260320130245`
|
||||
- 训练时间:`2026-03-20T13:02:45.903772+00:00`
|
||||
- 参数文件:[default.json](/E:/web/PolyWeather/artifacts/probability_calibration/default.json)
|
||||
- 离线评估报告:[evaluation_report.json](/E:/web/PolyWeather/artifacts/probability_calibration/evaluation_report.json)
|
||||
- 线上 shadow 报表:[shadow_report.json](/E:/web/PolyWeather/artifacts/probability_calibration/shadow_report.json)
|
||||
|
||||
## 3. 训练数据概况
|
||||
|
||||
### 3.1 数据来源
|
||||
|
||||
当前训练主要使用两类数据:
|
||||
|
||||
1. 项目历史日记录
|
||||
文件:[daily_records.json](/E:/web/PolyWeather/data/daily_records.json)
|
||||
|
||||
2. 历史天气 CSV 构建出的结算标签
|
||||
文件:[settlement_history.json](/E:/web/PolyWeather/artifacts/probability_calibration/settlement_history.json)
|
||||
|
||||
### 3.2 样本规模
|
||||
|
||||
- 总训练样本数:`105`
|
||||
- 通过历史天气 CSV 补回的缺失 `actual_high`:`2`
|
||||
- 历史结算标签覆盖城市数:`30`
|
||||
|
||||
说明:
|
||||
|
||||
- 当前样本已覆盖 30 个城市,但有效监督样本量仍偏小。
|
||||
- 部分城市样本数只有 `2-7` 条,城市级参数容易波动。
|
||||
|
||||
## 4. 模型结构
|
||||
|
||||
### 4.1 当前实现
|
||||
|
||||
EMOS 属于统计后处理层,不是数值天气模型本身。当前结构位于:
|
||||
|
||||
- [probability_calibration.py](/E:/web/PolyWeather/src/analysis/probability_calibration.py)
|
||||
|
||||
当前目标是对原有概率引擎输出进行校准:
|
||||
|
||||
- 输入:`raw_mu`、`raw_sigma`、`DEB`、`ensemble median/spread`、`peak_status` 等特征
|
||||
- 输出:校准后的 `mu / sigma / distribution`
|
||||
|
||||
### 4.2 当前运行模式
|
||||
|
||||
支持三种模式:
|
||||
|
||||
- `legacy`
|
||||
- `emos_shadow`
|
||||
- `emos_primary`
|
||||
|
||||
当前建议默认模式:
|
||||
|
||||
- `emos_shadow`
|
||||
|
||||
即:
|
||||
|
||||
- 对外仍展示 legacy 结果
|
||||
- 后台并行计算 EMOS 结果
|
||||
- 用于持续评估,不直接影响用户
|
||||
|
||||
## 5. 本次训练参数摘要
|
||||
|
||||
### 5.1 全局约束
|
||||
|
||||
本次训练已加入两类约束:
|
||||
|
||||
1. `sigma_constraints`
|
||||
- `min_ratio = 0.85`
|
||||
- `max_ratio = 1.35`
|
||||
- `absolute_min = 0.25`
|
||||
- `absolute_max = 3.0`
|
||||
|
||||
2. `selection_guardrails`
|
||||
- `max_mae_increase = 0.02`
|
||||
- `max_bucket_hit_drop = 0.01`
|
||||
- `max_bucket_brier_increase = 0.05`
|
||||
|
||||
这两类约束的目的不是追求“更激进的拟合”,而是防止 EMOS 为了降低 CRPS 而把分布摊得过平,导致业务上更关键的顶桶命中和概率质量变差。
|
||||
|
||||
### 5.2 当前选中的 blending
|
||||
|
||||
本次训练产物中最终选择:
|
||||
|
||||
- `alpha_mu = 0.0`
|
||||
- `alpha_sigma = 0.0`
|
||||
|
||||
含义是:
|
||||
|
||||
- 训练器在护栏约束下,没有找到足够安全的候选方案可以替代 legacy 主路径
|
||||
- 因此当前正式选中的可用结果,本质上仍然锚定在 legacy
|
||||
|
||||
这是一种正确的保护行为,不是失败。说明门禁已经起作用,避免了坏校准进入主路径。
|
||||
|
||||
## 6. 离线评估结果
|
||||
|
||||
评估报告来源:
|
||||
|
||||
- [evaluation_report.json](/E:/web/PolyWeather/artifacts/probability_calibration/evaluation_report.json)
|
||||
|
||||
### 6.1 总体结果
|
||||
|
||||
Legacy:
|
||||
|
||||
- `mean_crps = 2.793938`
|
||||
- `mean_mae = 2.721143`
|
||||
- `bucket_hit_rate = 0.695238`
|
||||
|
||||
EMOS(强制 primary 评估):
|
||||
|
||||
- `mean_crps = 2.650216`
|
||||
- `mean_mae = 2.722829`
|
||||
- `bucket_hit_rate = 0.666667`
|
||||
|
||||
Delta:
|
||||
|
||||
- `CRPS = -0.143722`
|
||||
- `MAE = +0.001686`
|
||||
- `bucket_hit_rate = -0.028571`
|
||||
|
||||
### 6.2 解读
|
||||
|
||||
这组结果说明:
|
||||
|
||||
1. `CRPS` 有改善
|
||||
说明从“分布整体平滑度”角度看,EMOS 有一定价值。
|
||||
|
||||
2. `MAE` 基本持平但略差
|
||||
不是大问题,但也不能算改善。
|
||||
|
||||
3. `bucket_hit_rate` 明显下降
|
||||
这是当前最大阻塞项。对 PolyWeather 这种结算桶业务来说,顶桶命中率比单纯 CRPS 更关键。
|
||||
|
||||
因此,离线结论是:
|
||||
|
||||
- `EMOS` 有研究价值
|
||||
- 但 **离线强切 primary 仍然不合格**
|
||||
|
||||
## 7. 线上 Shadow 观测结果
|
||||
|
||||
线上 shadow 报表来源:
|
||||
|
||||
- [shadow_report.json](/E:/web/PolyWeather/artifacts/probability_calibration/shadow_report.json)
|
||||
|
||||
### 7.1 总体结果
|
||||
|
||||
- `samples = 103`
|
||||
- `legacy_mean_mae = 1.839223`
|
||||
- `shadow_mean_mae = 1.851931`
|
||||
- `delta_mae = +0.012708`
|
||||
|
||||
- `legacy_bucket_hit_rate = 0.669903`
|
||||
- `shadow_bucket_hit_rate = 0.679612`
|
||||
- `delta_bucket_hit_rate = +0.009709`
|
||||
|
||||
- `legacy_bucket_brier = 0.462814`
|
||||
- `shadow_bucket_brier = 0.756649`
|
||||
- `delta_bucket_brier = +0.293835`
|
||||
|
||||
### 7.2 解读
|
||||
|
||||
线上 shadow 结果和离线强制 primary 结果不完全相同,这是正常的。原因是:
|
||||
|
||||
- `shadow_report` 反映的是历史记录中实际落盘的 shadow 输出
|
||||
- `evaluation_report` 反映的是离线脚本在强制 `emos_primary` 下重新计算的效果
|
||||
|
||||
当前线上 shadow 的含义是:
|
||||
|
||||
1. 顶桶命中率略有提升
|
||||
`+0.97%`
|
||||
|
||||
2. 但 `MAE` 轻微变差
|
||||
虽然幅度不大,但没有形成明确优势
|
||||
|
||||
3. `bucket_brier` 明显更差
|
||||
说明 shadow 分布仍然偏“摊平”,概率质量不足
|
||||
|
||||
这是当前最重要的信号:
|
||||
|
||||
- EMOS 在“顶桶命中”上偶尔能赢
|
||||
- 但在“概率质量”上还不够好
|
||||
|
||||
## 8. 城市级观察
|
||||
|
||||
从当前城市级结果看,EMOS 并不是“全城市统一改善”,而是明显分化:
|
||||
|
||||
### 8.1 相对改善较明显的城市
|
||||
|
||||
- `London`
|
||||
- `Hong Kong`
|
||||
- `Tokyo`
|
||||
- `New York`
|
||||
|
||||
这些城市在部分指标上看到一定改善,说明当前校准特征在这些城市上更有效。
|
||||
|
||||
### 8.2 风险较高的城市
|
||||
|
||||
- `Atlanta`
|
||||
- `Miami`
|
||||
- `Chicago`
|
||||
- `Dallas`
|
||||
- `Seattle`
|
||||
|
||||
这些城市常见现象是:
|
||||
|
||||
- 顶桶命中没有显著提高
|
||||
- 或 `bucket_brier` 明显恶化
|
||||
- 或者 `MAE` 出现不必要抬升
|
||||
|
||||
这说明当前 EMOS 还没有形成稳定的全局校准能力,城市间异质性很强。
|
||||
|
||||
## 9. 当前判断
|
||||
|
||||
### 9.1 能不能上线为主路径
|
||||
|
||||
当前答案:
|
||||
|
||||
- **不能**
|
||||
|
||||
原因:
|
||||
|
||||
1. 离线强制 primary 时,`bucket_hit_rate` 下降
|
||||
2. 线上 shadow 时,`bucket_brier` 明显变差
|
||||
3. 样本量依然偏小,城市样本不均衡
|
||||
4. 城市级表现分化明显
|
||||
|
||||
### 9.2 当前应该怎么运行
|
||||
|
||||
当前最合理的运行方式:
|
||||
|
||||
1. 保持 `emos_shadow`
|
||||
2. 继续落盘 `shadow_prob_snapshot`
|
||||
3. 继续维护滚动报表
|
||||
4. 不修改机器人和网页的正式对外概率展示
|
||||
|
||||
## 10. 已完成的工程能力
|
||||
|
||||
目前已经具备以下能力:
|
||||
|
||||
1. 可离线训练
|
||||
脚本:[fit_probability_calibration.py](/E:/web/PolyWeather/scripts/fit_probability_calibration.py)
|
||||
|
||||
2. 可离线评估
|
||||
脚本:[evaluate_probability_calibration.py](/E:/web/PolyWeather/scripts/evaluate_probability_calibration.py)
|
||||
|
||||
3. 可导出训练样本
|
||||
脚本:[export_probability_training_dataset.py](/E:/web/PolyWeather/scripts/export_probability_training_dataset.py)
|
||||
|
||||
4. 可历史回填 shadow 结果
|
||||
脚本:[backfill_probability_shadow_history.py](/E:/web/PolyWeather/scripts/backfill_probability_shadow_history.py)
|
||||
|
||||
5. 可生成滚动 shadow 报表
|
||||
脚本:[build_probability_shadow_report.py](/E:/web/PolyWeather/scripts/build_probability_shadow_report.py)
|
||||
|
||||
6. CI 已接入
|
||||
包含 `ruff / pytest / frontend build / docker build workflow`
|
||||
|
||||
## 11. 下一步建议
|
||||
|
||||
### 11.1 必做
|
||||
|
||||
1. 扩大监督样本量
|
||||
重点不是继续堆原始天气 CSV,而是补更多带 forecast snapshot 的历史样本。
|
||||
|
||||
2. 继续按版本沉淀训练报告
|
||||
每次重训后都更新本报告或新增版本报告,避免只看单次结果。
|
||||
|
||||
3. 保持 `shadow` 连续观测
|
||||
至少持续一段时间观察滚动指标是否稳定。
|
||||
|
||||
### 11.2 再做
|
||||
|
||||
1. 细分城市组建模
|
||||
比如按气候区、结算规则、温度单位分组,而不是完全全局一套参数。
|
||||
|
||||
2. 优化训练目标
|
||||
目前已经把 `bucket_brier` 纳入目标,但仍需进一步靠近 PolyWeather 的业务目标。
|
||||
|
||||
3. 补更严格的切换门槛
|
||||
只有在同时满足以下条件时,才考虑切 `emos_primary`:
|
||||
- `CRPS` 下降
|
||||
- `MAE` 不上升
|
||||
- `bucket_hit_rate` 不下降
|
||||
- `bucket_brier` 不上升
|
||||
|
||||
## 12. 结论
|
||||
|
||||
当前 EMOS 状态可以概括为:
|
||||
|
||||
- 工程上:已经完整接入,具备训练、评估、shadow 观测能力
|
||||
- 模型上:有一定价值,但还不稳定
|
||||
- 产品上:适合继续做 shadow,不适合切主路径
|
||||
|
||||
最终结论:
|
||||
|
||||
- **继续使用 `emos_shadow`**
|
||||
- **暂不切 `emos_primary`**
|
||||
- **继续积累样本并按版本跟踪训练结果**
|
||||
@@ -0,0 +1,211 @@
|
||||
# 前端部署配置(Vercel)
|
||||
|
||||
本文只覆盖 `frontend` 目录对应的 Next.js 前端部署。
|
||||
|
||||
## 一、部署目标
|
||||
|
||||
推荐方案:
|
||||
|
||||
1. GitHub Actions 负责 `CI`
|
||||
2. Vercel 负责前端 `CD`
|
||||
3. FastAPI 后端单独部署在 VPS / Docker 主机
|
||||
|
||||
前端本身不直接访问天气源,而是通过 Next Route Handlers 转发到后端:
|
||||
|
||||
1. 浏览器 -> Vercel 上的 Next.js 前端
|
||||
2. Next `/api/*` -> `POLYWEATHER_API_BASE_URL`
|
||||
3. FastAPI 后端 -> 分析 / 支付 / 鉴权服务
|
||||
|
||||
## 二、Vercel 项目设置
|
||||
|
||||
在 Vercel 导入 GitHub 仓库后,使用下面的设置:
|
||||
|
||||
- Framework Preset: `Next.js`
|
||||
- Root Directory: `frontend`
|
||||
- Build Command: `npm run build`
|
||||
- Install Command: `npm install`
|
||||
|
||||
如果仓库已经连接过 Vercel,通常只需要确认 `Root Directory` 仍然是 `frontend`。
|
||||
|
||||
## 三、最小必填环境变量
|
||||
|
||||
只部署天气看板和基础登录时,先填下面 4 项:
|
||||
|
||||
```env
|
||||
POLYWEATHER_API_BASE_URL=https://<your-fastapi-host>
|
||||
NEXT_PUBLIC_SUPABASE_URL=https://<your-project>.supabase.co
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=<your-anon-key>
|
||||
POLYWEATHER_AUTH_ENABLED=true
|
||||
```
|
||||
|
||||
建议显式补:
|
||||
|
||||
```env
|
||||
POLYWEATHER_AUTH_REQUIRED=true
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
- `POLYWEATHER_API_BASE_URL`:前端所有 `/api/*` Route Handler 转发时依赖它,没填会直接返回 500。
|
||||
- `NEXT_PUBLIC_SUPABASE_URL` / `NEXT_PUBLIC_SUPABASE_ANON_KEY`:Supabase 客户端依赖它们。
|
||||
- `POLYWEATHER_AUTH_ENABLED`:关闭时,前端不会启用登录能力。
|
||||
- `POLYWEATHER_AUTH_REQUIRED`:控制 middleware 是否强制登录。
|
||||
|
||||
## 四、按功能启用的可选环境变量
|
||||
|
||||
### 1. 分享式看板
|
||||
|
||||
```env
|
||||
POLYWEATHER_DASHBOARD_ACCESS_TOKEN=
|
||||
```
|
||||
|
||||
设置后,可通过 `/?access_token=<token>` 打开带令牌的看板入口。
|
||||
|
||||
### 2. 前后端 entitlement 校验
|
||||
|
||||
```env
|
||||
POLYWEATHER_BACKEND_ENTITLEMENT_TOKEN=
|
||||
```
|
||||
|
||||
仅当后端开启 entitlement / 订阅校验时需要。
|
||||
|
||||
### 3. 钱包支付
|
||||
|
||||
```env
|
||||
NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID=
|
||||
NEXT_PUBLIC_WALLETCONNECT_POLYGON_RPC_URL=https://polygon-bor-rpc.publicnode.com
|
||||
```
|
||||
|
||||
如果不启用钱包支付,可以留空。
|
||||
|
||||
### 4. `/ops` 管理员页面守卫
|
||||
|
||||
```env
|
||||
POLYWEATHER_OPS_ADMIN_EMAILS=yhrsc30@gmail.com
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
- `/ops` 现在不是只有后端接口限制,前端页面入口也会读取管理员邮箱白名单。
|
||||
- 因此前端部署到 Vercel 时,也应配置 `POLYWEATHER_OPS_ADMIN_EMAILS`。
|
||||
|
||||
### 5. Telegram 入口
|
||||
|
||||
```env
|
||||
NEXT_PUBLIC_TELEGRAM_GROUP_URL=https://t.me/<your_group>
|
||||
NEXT_PUBLIC_TELEGRAM_BOT_URL=https://t.me/WeatherQuant_bot
|
||||
```
|
||||
|
||||
只影响按钮跳转,不影响核心页面加载。
|
||||
|
||||
## 五、支付配置与旧部署治理
|
||||
|
||||
支付区现在有一层额外防护:
|
||||
|
||||
1. 用户点击支付前,前端会重新请求 `/api/payments/config`
|
||||
2. 若发现 `receiver_contract` 与页面旧状态不一致,会自动切换到最新地址
|
||||
3. 若后端返回的 `tx_payload.to` 与最新 `receiver_contract` 不一致,会直接阻断支付
|
||||
|
||||
这层防护的目的,是降低以下事故概率:
|
||||
|
||||
- 用户使用长期未刷新的旧标签页
|
||||
- 命中旧 deployment URL
|
||||
- 页面本地状态残留旧收款地址
|
||||
|
||||
如果你变更过支付收款地址,建议同步执行:
|
||||
|
||||
1. 在 Vercel 对当前 production 做一次 redeploy
|
||||
2. 删除明显过期、可能还带旧支付配置的旧 deployment
|
||||
3. 在 `Settings -> Security -> Deployment Retention Policy` 中收紧旧部署保留周期
|
||||
|
||||
## 六、推荐的三套配置口径
|
||||
|
||||
### 1. 公开游客模式
|
||||
|
||||
```env
|
||||
POLYWEATHER_API_BASE_URL=https://api.example.com
|
||||
POLYWEATHER_AUTH_ENABLED=false
|
||||
POLYWEATHER_AUTH_REQUIRED=false
|
||||
```
|
||||
|
||||
适合公开演示站。
|
||||
|
||||
### 2. 正常登录模式
|
||||
|
||||
```env
|
||||
POLYWEATHER_API_BASE_URL=https://api.example.com
|
||||
NEXT_PUBLIC_SUPABASE_URL=https://<project>.supabase.co
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=<anon-key>
|
||||
POLYWEATHER_AUTH_ENABLED=true
|
||||
POLYWEATHER_AUTH_REQUIRED=true
|
||||
```
|
||||
|
||||
适合正式前端站点。
|
||||
|
||||
### 3. 登录 + entitlement 联动
|
||||
|
||||
```env
|
||||
POLYWEATHER_API_BASE_URL=https://api.example.com
|
||||
NEXT_PUBLIC_SUPABASE_URL=https://<project>.supabase.co
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=<anon-key>
|
||||
POLYWEATHER_AUTH_ENABLED=true
|
||||
POLYWEATHER_AUTH_REQUIRED=true
|
||||
POLYWEATHER_BACKEND_ENTITLEMENT_TOKEN=<shared-token>
|
||||
```
|
||||
|
||||
适合前后端都启用了会员/订阅保护的生产环境。
|
||||
|
||||
## 七、不要放进 Vercel 的变量
|
||||
|
||||
这些属于后端私密配置,不应该放到前端项目:
|
||||
|
||||
- `SUPABASE_SERVICE_ROLE_KEY`
|
||||
- `TELEGRAM_BOT_TOKEN`
|
||||
- `POLYWEATHER_BACKEND_ENTITLEMENT_TOKEN` 以外的后端 secret
|
||||
- 支付签名私钥 / 交易私钥 / 任何 bot 凭据
|
||||
|
||||
特别注意:
|
||||
|
||||
- `NEXT_PUBLIC_*` 会暴露给浏览器
|
||||
- 只有明确允许前端公开使用的值,才应加 `NEXT_PUBLIC_`
|
||||
|
||||
## 八、上线前检查
|
||||
|
||||
Vercel 部署前至少确认:
|
||||
|
||||
1. `POLYWEATHER_API_BASE_URL` 指向可访问的后端生产地址
|
||||
2. `frontend/.env.example` 和 Vercel Project Settings 中的实际值一致
|
||||
3. GitHub Actions 中 `frontend-quality` 已通过
|
||||
4. 如果启用鉴权,Supabase redirect URL 已包含前端域名
|
||||
5. `GET /api/payments/config` 返回的是当前最新地址,而不是旧收款合约
|
||||
6. 如果启用了 `/ops`,确认 `POLYWEATHER_OPS_ADMIN_EMAILS` 已在 Vercel 与后端同时配置
|
||||
|
||||
## 九、常见问题
|
||||
|
||||
### 1. 页面打开后 API 全部 500
|
||||
|
||||
先检查:
|
||||
|
||||
```env
|
||||
POLYWEATHER_API_BASE_URL
|
||||
```
|
||||
|
||||
这是最常见原因。
|
||||
|
||||
### 2. Vercel 构建通过,但登录失败
|
||||
|
||||
先检查:
|
||||
|
||||
- `NEXT_PUBLIC_SUPABASE_URL`
|
||||
- `NEXT_PUBLIC_SUPABASE_ANON_KEY`
|
||||
- Supabase 项目里的站点 URL / redirect URL
|
||||
|
||||
### 3. 钱包入口显示未配置
|
||||
|
||||
先检查:
|
||||
|
||||
```env
|
||||
NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID
|
||||
```
|
||||
|
||||
这是钱包连接的必需项。
|
||||
@@ -0,0 +1,104 @@
|
||||
# Ops 运营后台说明
|
||||
|
||||
最后更新:`2026-03-21`
|
||||
|
||||
## 1. 入口
|
||||
|
||||
前端入口:
|
||||
|
||||
- `https://polyweather-pro.vercel.app/ops`
|
||||
|
||||
## 2. 权限
|
||||
|
||||
`/ops` 的写接口由后端白名单控制:
|
||||
|
||||
```env
|
||||
POLYWEATHER_OPS_ADMIN_EMAILS=yhrsc30@gmail.com
|
||||
```
|
||||
|
||||
可配置多个邮箱,逗号分隔。
|
||||
|
||||
## 3. 当前能力
|
||||
|
||||
### 只读能力
|
||||
|
||||
- 系统健康
|
||||
- SQLite / rollout / metrics 摘要
|
||||
- 支付运行态
|
||||
- 当前会员
|
||||
- 周榜
|
||||
- 支付异常单
|
||||
|
||||
### 写能力
|
||||
|
||||
- 手动补分
|
||||
- 标记支付异常单“已处理”
|
||||
|
||||
## 4. 当前会员
|
||||
|
||||
会员列表来自:
|
||||
|
||||
1. `subscriptions` 中的有效订阅
|
||||
2. 本地 `users` / `supabase_bindings`
|
||||
3. 若本地缺邮箱或注册时间,再回补 Supabase Auth 用户信息
|
||||
|
||||
去重规则:
|
||||
|
||||
- 同一个 `user_id` 只保留最晚到期那条
|
||||
|
||||
## 5. 支付异常单
|
||||
|
||||
当前异常单来源:
|
||||
|
||||
- `payment_audit_events`
|
||||
- 仅筛 `payment_intent_failed`
|
||||
|
||||
当前支持的典型失败原因:
|
||||
|
||||
- `receiver_mismatch`
|
||||
- `sender_mismatch`
|
||||
- `event_mismatch`
|
||||
- `tx_reverted`
|
||||
|
||||
默认只显示未处理项。
|
||||
|
||||
## 6. 典型处理流程
|
||||
|
||||
### 6.1 钱已到账但没开订阅
|
||||
|
||||
先看 `/ops` 的支付异常单:
|
||||
|
||||
- 如果是 `receiver_mismatch`
|
||||
- 优先判定为支付打到了旧收款地址
|
||||
- 不是缓存问题
|
||||
|
||||
然后执行:
|
||||
|
||||
1. 查 `payment_intents`
|
||||
2. 查 `payment_transactions`
|
||||
3. 查 `subscriptions`
|
||||
4. 跑恢复脚本:
|
||||
|
||||
```bash
|
||||
python scripts/reconcile_subscription_by_email.py --email <user_email>
|
||||
```
|
||||
|
||||
如果仍然失败,再人工补订阅。
|
||||
|
||||
### 6.2 已人工处理
|
||||
|
||||
在 `/ops` 里直接点:
|
||||
|
||||
- `标记已处理`
|
||||
|
||||
这不会删除审计事件,只会给原事件写:
|
||||
|
||||
- `resolved_at`
|
||||
- `resolved_by`
|
||||
|
||||
## 7. 备注
|
||||
|
||||
`/ops` 是运营后台最小版,不是完整 Admin 平台。当前目标是:
|
||||
|
||||
- 让会员、积分、支付事故、系统状态可查
|
||||
- 让常见人工操作不必再直接写 SQL
|
||||
@@ -0,0 +1,324 @@
|
||||
# 概率训练样本归档说明(中文)
|
||||
|
||||
## 1. 目的
|
||||
|
||||
这份文档说明两件事:
|
||||
|
||||
1. 为什么 `EMOS` 训练不能只依赖历史实测天气
|
||||
2. 未来如何持续沉淀“历史预测记录”,让概率引擎越训越稳
|
||||
|
||||
一句话结论:
|
||||
|
||||
- 历史实测天气只能补 `actual_high`
|
||||
- 真正决定 `EMOS` 训练质量的是“当时那一刻的预测快照”
|
||||
|
||||
## 2. 什么是“历史预测记录”
|
||||
|
||||
对 PolyWeather 来说,一条可训练的历史预测记录,至少应该包含这些字段:
|
||||
|
||||
- `city`
|
||||
- `timestamp`
|
||||
- `date`
|
||||
- `raw_mu`
|
||||
- `raw_sigma`
|
||||
- `deb_prediction`
|
||||
- `ensemble p10 / p50 / p90`
|
||||
- `multi-model forecasts`
|
||||
- `max_so_far`
|
||||
- `peak_status`
|
||||
- `prob_snapshot`
|
||||
- 当天最终 `actual_high`
|
||||
- 当天最终 `settlement bucket`
|
||||
|
||||
这类记录的核心价值是:
|
||||
|
||||
- 还原“当时系统实际看到什么”
|
||||
- 再对照“后来真实发生了什么”
|
||||
|
||||
只有这两者成对,`EMOS` 才能学习偏差。
|
||||
|
||||
## 3. 为什么不能只用历史天气实测
|
||||
|
||||
历史天气 CSV 只能告诉你:
|
||||
|
||||
- 当天最高温是多少
|
||||
- 某小时温度是多少
|
||||
|
||||
但它不能告诉你:
|
||||
|
||||
- 当天早上 09:00 时,系统的 `mu` 是多少
|
||||
- 当时的 `ensemble spread` 是多少
|
||||
- 当时 `DEB` 怎么看
|
||||
- 当时的 top bucket 是什么
|
||||
|
||||
所以:
|
||||
|
||||
- 历史实测天气是标签
|
||||
- 历史预测记录才是训练输入
|
||||
|
||||
缺少后者,EMOS 只能学到很有限的东西。
|
||||
|
||||
## 4. 当前项目里已经有的基础
|
||||
|
||||
### 4.1 已有历史日记录
|
||||
|
||||
文件:
|
||||
|
||||
- [daily_records.json](/E:/web/PolyWeather/data/daily_records.json)
|
||||
|
||||
当前已经保存了一部分训练相关字段,例如:
|
||||
|
||||
- `forecasts`
|
||||
- `actual_high`
|
||||
- `deb_prediction`
|
||||
- `mu`
|
||||
- `prob_snapshot`
|
||||
- `shadow_prob_snapshot`
|
||||
- `probability_calibration`
|
||||
- `probability_features`
|
||||
|
||||
这已经是“历史预测记录”的雏形。
|
||||
|
||||
### 4.2 已有历史天气 CSV
|
||||
|
||||
目录:
|
||||
|
||||
- [data/historical](/E:/web/PolyWeather/data/historical)
|
||||
|
||||
它们可以帮助补:
|
||||
|
||||
- `actual_high`
|
||||
- `settlement history`
|
||||
|
||||
但不能替代预测快照归档。
|
||||
|
||||
## 5. 未来应该怎么存历史预测记录
|
||||
|
||||
推荐做法是:
|
||||
|
||||
### 5.1 固定时点归档
|
||||
|
||||
每天为每个重点城市固定存几次快照,例如:
|
||||
|
||||
- 当地 `09:00`
|
||||
- 当地 `12:00`
|
||||
- 当地 `15:00`
|
||||
|
||||
这样能确保每个交易日都有稳定可比样本。
|
||||
|
||||
### 5.2 关键变化时补充归档
|
||||
|
||||
除了固定时点,还应该在以下情况额外存一次:
|
||||
|
||||
- `max_so_far` 创新高
|
||||
- `mu` 变化超过阈值
|
||||
- `top bucket` 发生变化
|
||||
- `shadow top bucket` 发生变化
|
||||
|
||||
这样能捕捉真正有训练价值的转折点。
|
||||
|
||||
### 5.3 建议的存储格式
|
||||
|
||||
建议新增一个文件,例如:
|
||||
|
||||
- `data/probability_training_snapshots.jsonl`
|
||||
|
||||
每一行保存一条 JSON 记录。
|
||||
|
||||
优点:
|
||||
|
||||
- 追加写入简单
|
||||
- 后续导出训练集方便
|
||||
- 不容易因为单个大 JSON 文件损坏而全盘受影响
|
||||
|
||||
## 6. 一条建议的快照结构
|
||||
|
||||
示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"city": "ankara",
|
||||
"timestamp": "2026-03-20T12:00:00+03:00",
|
||||
"date": "2026-03-20",
|
||||
"raw_mu": 15.2,
|
||||
"raw_sigma": 1.2,
|
||||
"deb_prediction": 15.4,
|
||||
"ensemble": {
|
||||
"p10": 14.8,
|
||||
"median": 15.8,
|
||||
"p90": 17.9
|
||||
},
|
||||
"multi_model": {
|
||||
"ECMWF": 15.8,
|
||||
"GFS": 14.1,
|
||||
"ICON": 15.9,
|
||||
"GEM": 16.5,
|
||||
"JMA": 14.5
|
||||
},
|
||||
"max_so_far": 15.0,
|
||||
"peak_status": "before",
|
||||
"prob_snapshot": [
|
||||
{"v": 15, "p": 0.552},
|
||||
{"v": 16, "p": 0.377}
|
||||
],
|
||||
"shadow_prob_snapshot": [
|
||||
{"v": 15, "p": 0.324},
|
||||
{"v": 16, "p": 0.238}
|
||||
],
|
||||
"probability_engine": "legacy",
|
||||
"probability_mode": "emos_shadow",
|
||||
"calibration_version": "emos-20260320130245"
|
||||
}
|
||||
```
|
||||
|
||||
当天结束后,再由后处理脚本回填:
|
||||
|
||||
- `actual_high`
|
||||
- `settlement_bucket`
|
||||
|
||||
## 7. 现阶段你可以执行的命令
|
||||
|
||||
### 7.1 回填历史天气 CSV
|
||||
|
||||
```bash
|
||||
python scripts/backfill_historical_weather.py
|
||||
```
|
||||
|
||||
作用:
|
||||
|
||||
- 补全 30 城市历史天气时序 CSV
|
||||
|
||||
### 7.2 从历史 CSV 构建日级结算标签
|
||||
|
||||
```bash
|
||||
python scripts/build_settlement_history_from_csv.py
|
||||
```
|
||||
|
||||
作用:
|
||||
|
||||
- 生成 [settlement_history.json](/E:/web/PolyWeather/artifacts/probability_calibration/settlement_history.json)
|
||||
|
||||
### 7.3 导出当前训练样本
|
||||
|
||||
```bash
|
||||
python scripts/export_probability_training_dataset.py
|
||||
```
|
||||
|
||||
作用:
|
||||
|
||||
- 生成 [training_samples.json](/E:/web/PolyWeather/artifacts/probability_calibration/training_samples.json)
|
||||
|
||||
### 7.4 重训 EMOS
|
||||
|
||||
```bash
|
||||
python scripts/fit_probability_calibration.py
|
||||
```
|
||||
|
||||
作用:
|
||||
|
||||
- 生成新的 [default.json](/E:/web/PolyWeather/artifacts/probability_calibration/default.json)
|
||||
|
||||
### 7.5 离线评估训练效果
|
||||
|
||||
```bash
|
||||
python scripts/evaluate_probability_calibration.py
|
||||
```
|
||||
|
||||
作用:
|
||||
|
||||
- 生成 [evaluation_report.json](/E:/web/PolyWeather/artifacts/probability_calibration/evaluation_report.json)
|
||||
|
||||
### 7.6 回填 shadow 结果到历史记录
|
||||
|
||||
```bash
|
||||
python scripts/backfill_probability_shadow_history.py
|
||||
```
|
||||
|
||||
作用:
|
||||
|
||||
- 把 `shadow_prob_snapshot` 和 `probability_calibration` 回填到 [daily_records.json](/E:/web/PolyWeather/data/daily_records.json)
|
||||
|
||||
### 7.7 生成线上 shadow 滚动报表
|
||||
|
||||
```bash
|
||||
python scripts/build_probability_shadow_report.py
|
||||
```
|
||||
|
||||
作用:
|
||||
|
||||
- 生成 [shadow_report.json](/E:/web/PolyWeather/artifacts/probability_calibration/shadow_report.json)
|
||||
|
||||
## 8. 推荐的一整套重训流程
|
||||
|
||||
如果过了十天、半个月,想重新训练一次,建议按这个顺序执行:
|
||||
|
||||
```bash
|
||||
python scripts/build_settlement_history_from_csv.py
|
||||
python scripts/export_probability_training_dataset.py
|
||||
python scripts/fit_probability_calibration.py
|
||||
python scripts/evaluate_probability_calibration.py
|
||||
python scripts/backfill_probability_shadow_history.py
|
||||
python scripts/build_probability_shadow_report.py
|
||||
```
|
||||
|
||||
如果历史天气 CSV 还没补全,再先执行:
|
||||
|
||||
```bash
|
||||
python scripts/backfill_historical_weather.py
|
||||
```
|
||||
|
||||
## 9. 怎么判断这次训练有没有进步
|
||||
|
||||
重训后,不要只看一个指标。
|
||||
|
||||
至少看这 4 个:
|
||||
|
||||
1. `CRPS`
|
||||
- 越低越好
|
||||
|
||||
2. `MAE`
|
||||
- 越低越好
|
||||
- 至少不要明显变差
|
||||
|
||||
3. `Bucket Hit Rate`
|
||||
- 越高越好
|
||||
- 这是业务上非常关键的指标
|
||||
|
||||
4. `Bucket Brier`
|
||||
- 越低越好
|
||||
- 反映概率分布质量
|
||||
|
||||
只有同时满足下面条件,才可以说训练效果真的进步:
|
||||
|
||||
- `CRPS` 下降
|
||||
- `MAE` 不上升
|
||||
- `Bucket Hit Rate` 不下降
|
||||
- `Bucket Brier` 不上升
|
||||
|
||||
## 10. 当前最重要的现实判断
|
||||
|
||||
过去的“完整历史预测记录”通常没法完全补出来,除非:
|
||||
|
||||
1. 你之前就存过
|
||||
2. 你接入了支持 forecast archive 的商业数据源
|
||||
|
||||
所以现实里最重要的不是“把过去全补齐”,而是:
|
||||
|
||||
- 从现在开始系统化归档
|
||||
- 每天稳定沉淀可训练样本
|
||||
- 定期离线重训
|
||||
|
||||
## 11. 推荐的下一步
|
||||
|
||||
最值得做的改造是:
|
||||
|
||||
1. 新增 `probability_training_snapshots.jsonl`
|
||||
2. 每次分析时自动追加一条快照
|
||||
3. 当天结束后自动回填 `actual_high`
|
||||
4. 每 1-2 周重新训练一次
|
||||
|
||||
## 12. 总结
|
||||
|
||||
如果只记住一句话,就记这个:
|
||||
|
||||
**EMOS 要想越训越好,关键不是多下载一点历史天气,而是持续保存“当时系统看到的预测快照”。**
|
||||
@@ -1,4 +1,4 @@
|
||||
# Supabase + 登录 + 支付接入说明(v1.4.0)
|
||||
# Supabase + 登录 + 支付接入说明(v1.5.1)
|
||||
|
||||
最后更新:`2026-03-14`
|
||||
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
# PolyWeather TAF 信号说明(TAF_SIGNAL_ZH)
|
||||
|
||||
本文档说明 PolyWeather 当前如何把 `TAF`(机场终端预报)接入“今日日内分析”,以及这些信号在交易判断里到底代表什么。
|
||||
|
||||
本文档只描述**当前实现**,不夸大、不脑补。
|
||||
|
||||
---
|
||||
|
||||
## 一、TAF 在项目中的定位
|
||||
|
||||
在 PolyWeather 里,`TAF` 不是主温度模型,也不是结算源。
|
||||
|
||||
它的定位是:
|
||||
|
||||
1. **机场侧确认层**
|
||||
- 用来补充说明机场在峰值窗口附近会不会出现云、雨、雷暴或风向切换。
|
||||
|
||||
2. **压温 / 扰动风险提示层**
|
||||
- 用来判断“机场最高温是否可能因为天气扰动被压低”。
|
||||
|
||||
3. **走势图时间轴联动层**
|
||||
- 用来在温度走势图上标出 `FM / TEMPO / BECMG / PROB30/40` 对应的时段。
|
||||
|
||||
它**不负责**:
|
||||
|
||||
1. 直接提供多模型最高温数值
|
||||
2. 替代 `DEB`
|
||||
3. 替代机场实况 `METAR`
|
||||
4. 替代官方结算源
|
||||
|
||||
---
|
||||
|
||||
## 二、后端当前怎么解析 TAF
|
||||
|
||||
后端入口在:
|
||||
|
||||
- [web/analysis_service.py](/E:/web/PolyWeather/web/analysis_service.py)
|
||||
|
||||
核心函数:
|
||||
|
||||
- `_build_taf_signal(...)`
|
||||
|
||||
当前会解析这些时间片:
|
||||
|
||||
1. `BASE`
|
||||
2. `FM`
|
||||
3. `TEMPO`
|
||||
4. `BECMG`
|
||||
5. `PROB30`
|
||||
6. `PROB40`
|
||||
7. `PROB30 TEMPO`
|
||||
8. `PROB40 TEMPO`
|
||||
|
||||
并且只聚焦于:
|
||||
|
||||
- **峰值窗口前后**
|
||||
|
||||
当前窗口定义是:
|
||||
|
||||
- `peak.first_h - 2h`
|
||||
- 到
|
||||
- `peak.last_h + 1h`
|
||||
|
||||
也就是说,TAF 不是整段报文全量平铺,而是会优先关注**和今天高温兑现最相关的时段**。
|
||||
|
||||
---
|
||||
|
||||
## 三、当前后端真正产出的核心字段
|
||||
|
||||
### 1. `suppression_level`
|
||||
|
||||
表示机场端的**压温风险等级**。
|
||||
|
||||
当前逻辑来自:
|
||||
|
||||
1. 降水 / 雷暴关键词
|
||||
- `TSRA`
|
||||
- `TS`
|
||||
- `VCTS`
|
||||
- `SHRA`
|
||||
- `SHSN`
|
||||
- `SHGS`
|
||||
- `RA`
|
||||
- `DZ`
|
||||
- `SN`
|
||||
|
||||
2. 低云底
|
||||
- 只对 `BKN / OVC` 生效
|
||||
- 如果最低云底 `<= 4000 ft`
|
||||
- 会把原本 `low` 的压温风险至少抬到 `medium`
|
||||
|
||||
注意:
|
||||
|
||||
- 不是所有 `FEW / SCT / BKN / OVC` 都会直接把风险打到 `high`
|
||||
- 当前实现里,**低云主要是把风险从 `low` 抬到 `medium`**
|
||||
- 真正更容易触发 `high` 的,还是阵雨 / 雷暴类关键词
|
||||
|
||||
### 2. `disruption_level`
|
||||
|
||||
表示峰值窗口附近的**扰动程度**。
|
||||
|
||||
当前逻辑:
|
||||
|
||||
1. 这些时间片会至少把扰动抬到 `medium`
|
||||
- `TEMPO`
|
||||
- `BECMG`
|
||||
- `PROB30`
|
||||
- `PROB40`
|
||||
- `PROB30 TEMPO`
|
||||
- `PROB40 TEMPO`
|
||||
|
||||
2. 这些情况会把扰动抬到 `high`
|
||||
- `PROB30 TEMPO`
|
||||
- `PROB40 TEMPO`
|
||||
- 或者该时段本身就出现强降水/雷暴类关键词
|
||||
|
||||
注意:
|
||||
|
||||
- **`TEMPO` 本身不等于 `high`**
|
||||
- **`PROB40` 也不等于“确定发生”**
|
||||
|
||||
---
|
||||
|
||||
## 四、前端怎么展示
|
||||
|
||||
前端主要在:
|
||||
|
||||
- [frontend/components/dashboard/FutureForecastModal.tsx](/E:/web/PolyWeather/frontend/components/dashboard/FutureForecastModal.tsx)
|
||||
- [frontend/lib/dashboard-utils.ts](/E:/web/PolyWeather/frontend/lib/dashboard-utils.ts)
|
||||
|
||||
当前会通过三种方式展示 TAF:
|
||||
|
||||
### 1. 图表时间轴标记
|
||||
|
||||
在日内温度走势图上,当前会显示:
|
||||
|
||||
- `TAF 时段 / TAF Timing`
|
||||
|
||||
tooltip 会显示该时段摘要,例如:
|
||||
|
||||
- `基础时段 13:00-19:00 以稳定为主`
|
||||
- `明确切换 15:00-21:00 以稳定为主`
|
||||
- `临时波动 14:00-17:00 有云雨扰动`
|
||||
|
||||
### 2. 今日日内结构信号里的 `机场预报`
|
||||
|
||||
会显示类似:
|
||||
|
||||
- `防压温`
|
||||
- `看云雨`
|
||||
- `暂稳`
|
||||
|
||||
### 3. 顶部摘要与交易动作
|
||||
|
||||
系统会把:
|
||||
|
||||
1. 近地面结构
|
||||
2. 高空结构
|
||||
3. `TAF`
|
||||
4. `market_signal / edge_percent / bucket crowding`
|
||||
|
||||
合并成更贴近交易的提示,例如:
|
||||
|
||||
- `偏暖侧`
|
||||
- `偏谨慎`
|
||||
- `先观察`
|
||||
|
||||
---
|
||||
|
||||
## 五、TAF 关键词当前在项目里的真实含义
|
||||
|
||||
| TAF 关键词 | 当前展示词 | 当前项目含义 |
|
||||
| :-- | :-- | :-- |
|
||||
| `BASE` | 基础时段 | 在第一个显式变化组出现前的默认背景天气段 |
|
||||
| `FM` | 明确切换 | 从某个明确时刻开始,机场预报进入一套新的天气阶段 |
|
||||
| `TEMPO` | 临时波动 | 一段短时、非整段主导的扰动窗口 |
|
||||
| `BECMG` | 逐步转变 | 天气在该窗口内逐步过渡,不是立刻硬切 |
|
||||
| `PROB30/40` | 30% / 40% 风险窗 | 有概率触发的扰动窗口,不等于确定发生 |
|
||||
|
||||
注意:
|
||||
|
||||
- `FM` 不是由 `valid_match` 触发,它是按 `FMddhhmm` 独立解析出来的明确切换段
|
||||
- `PROB40` 不是“确定性信号”,仍然只是概率窗口
|
||||
|
||||
---
|
||||
|
||||
## 六、怎么理解“机场端压温风险偏高”
|
||||
|
||||
这句话的意思不是:
|
||||
|
||||
- 城区一定更冷
|
||||
- 一定会结算更低
|
||||
|
||||
真正意思是:
|
||||
|
||||
**在机场这个结算相关站点上,峰值窗口附近更容易因为云、阵雨或雷暴,导致最终最高温冲不上去。**
|
||||
|
||||
对于很多按机场报文或机场相关站点结算的市场,这一点很关键。
|
||||
|
||||
一句话:
|
||||
|
||||
- `TAF` 提示压温高
|
||||
- 不代表一定下雨
|
||||
- 但代表“机场高温可能被压低”的概率更值得防
|
||||
|
||||
---
|
||||
|
||||
## 七、怎么和图表一起看
|
||||
|
||||
### 情况 A:模型还偏热,但 TAF 给出压温高
|
||||
|
||||
这表示:
|
||||
|
||||
1. 数值模型仍给出较高高温
|
||||
2. 但机场端预报提示云雨/雷暴会打断峰值兑现
|
||||
|
||||
这种情况下,更适合理解成:
|
||||
|
||||
- **机场侧高温兑现有风险**
|
||||
- 追更高温区间要谨慎
|
||||
|
||||
### 情况 B:TAF 没有新增压温,但总判断仍偏降温
|
||||
|
||||
这表示:
|
||||
|
||||
1. `TAF` 没有提供新的云雨压温利空
|
||||
2. 但近地面窗口本身已经在走弱
|
||||
|
||||
比如:
|
||||
|
||||
- 温度走弱
|
||||
- 风场切换
|
||||
- 气压回升
|
||||
- 露点回落
|
||||
|
||||
所以:
|
||||
|
||||
- `TAF 无压温`
|
||||
- **不等于**
|
||||
- `一定继续升温`
|
||||
|
||||
当前系统已经会在摘要里把这层关系解释清楚。
|
||||
|
||||
---
|
||||
|
||||
## 八、当前实现边界
|
||||
|
||||
这套 `TAF` 逻辑当前是**交易导向的轻量解码**,不是完整航空专业解码器。
|
||||
|
||||
当前做得到:
|
||||
|
||||
1. 识别主要时间片
|
||||
2. 找出峰值窗口附近的扰动
|
||||
3. 识别云雨压温和风向切换
|
||||
4. 联动图表时间轴
|
||||
5. 联动交易动作
|
||||
|
||||
当前还没有做:
|
||||
|
||||
1. 对全部 TAF 语法做完整航空级严格解释
|
||||
2. 对每个时段都做完整的逐字段人工预报学解释
|
||||
3. 把 TAF 当成温度主预测模型
|
||||
|
||||
---
|
||||
|
||||
## 九、产品口径总结
|
||||
|
||||
最重要的一句:
|
||||
|
||||
**在 PolyWeather 里,TAF 是“机场侧扰动确认层”,不是主模型,也不是结算源。**
|
||||
|
||||
它最值钱的地方是:
|
||||
|
||||
- 帮你判断峰值窗口附近,机场高温会不会被云雨、雷暴、低云或风向切换打断。
|
||||
|
||||
对交易来说,更适合把它理解成:
|
||||
|
||||
- “机场这边有没有额外的压温风险”
|
||||
|
||||
而不是:
|
||||
|
||||
- “TAF 直接告诉我今天结算温度是多少”
|
||||
|
||||
---
|
||||
|
||||
_PolyWeather 文档中心_
|
||||
+29
-18
@@ -1,62 +1,73 @@
|
||||
# 技术债与工程待办(v1.4.0)
|
||||
# 技术债与工程待办(v1.5.1)
|
||||
|
||||
最后更新:`2026-03-14`
|
||||
最后更新:`2026-03-20`
|
||||
|
||||
目标:在收费上线后,优先保证支付可靠性、权限一致性和运营可追溯性。
|
||||
目标:在收费上线后,优先保证状态一致性、支付可靠性、可观测性和概率引擎发布可控。
|
||||
|
||||
## 1. 债务快照
|
||||
|
||||
当前估计:**93% 稳定 / 7% 技术债**。
|
||||
当前估计:**95% 稳定 / 5% 技术债**。
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["技术债"]
|
||||
|
||||
subgraph P["支付与订阅"]
|
||||
P1["异常交易自动重放策略"]
|
||||
P1["合约 V2 升级(SafeERC20 / Pausable)"]
|
||||
P2["退款与工单流程"]
|
||||
P3["多链结算对账"]
|
||||
P3["多 RPC 与链上对账面板"]
|
||||
end
|
||||
|
||||
subgraph E["权限与运营"]
|
||||
E1["前后端/Bot 权限矩阵回归"]
|
||||
E2["积分与订阅冲突策略"]
|
||||
E2["积分来源明细与补分审计"]
|
||||
end
|
||||
|
||||
subgraph O["可观测性"]
|
||||
O1["支付失败原因分层指标"]
|
||||
O1["外部监控抓取与告警阈值"]
|
||||
O2["业务监控看板"]
|
||||
end
|
||||
|
||||
subgraph S["状态与概率"]
|
||||
S1["SQLite dual -> sqlite 切换验收"]
|
||||
S2["EMOS shadow -> primary 门禁稳定化"]
|
||||
end
|
||||
|
||||
A --> P
|
||||
A --> E
|
||||
A --> O
|
||||
A --> S
|
||||
```
|
||||
|
||||
## 2. 近期已关闭
|
||||
|
||||
- P1 支付主链路已上线(intent -> submit -> confirm)。
|
||||
- 支付主链路已上线(intent -> submit -> confirm)。
|
||||
- 支付自动补单已上线(Event Loop + Confirm Loop)。
|
||||
- 支付事件重放脚本已补齐。
|
||||
- 支付运行态 API 与 SQLite 审计事件已补齐。
|
||||
- 钱包绑定支持浏览器钱包 + WalletConnect。
|
||||
- 账户中心与 Pro 权限展示链路打通。
|
||||
- 钱包异动支持独立频道路由。
|
||||
- 运行态状态/缓存已支持 SQLite 渐进迁移。
|
||||
- 轻量可观测性已上线(`/healthz`、`/api/system/status`、`/metrics`)。
|
||||
- EMOS/CRPS 校准链路已上线 shadow 模式。
|
||||
|
||||
## 3. 高优先级技术债
|
||||
|
||||
| 项目 | 影响 | 建议动作 |
|
||||
| :-- | :-- | :-- |
|
||||
| 支付异常重放策略标准化 | 偶发确认失败需人工介入 | 建立 tx hash 自动回放 + 降级路径 |
|
||||
| SQLite 主读切换验收 | 仍处于 dual 过渡期 | 线上跑满 24-48 小时后切到 `sqlite` |
|
||||
| EMOS 上线门禁 | 当前 `hold`,不能切 primary | 继续积累样本,重点压 `bucket_brier` |
|
||||
| 外部监控与告警 | 只有轻量指标,无外部抓取 | 接 Prometheus/Grafana 或最小巡检 |
|
||||
| 退款与售后链路 | 商业闭环不完整 | 增加退款状态机与工单系统 |
|
||||
| 订阅审计可视化 | 排障效率受限 | 建立订阅事件时间线视图 |
|
||||
| 多邮箱绑定同 TG 账户策略 | 积分归属易混淆 | 引入主账号绑定策略与迁移工具 |
|
||||
|
||||
## 4. 中优先级技术债
|
||||
|
||||
| 项目 | 影响 | 建议动作 |
|
||||
| :-- | :-- | :-- |
|
||||
| 积分发放可解释性 | 用户理解成本高 | 输出积分来源明细(发言/签到/奖励) |
|
||||
| 积分发放可解释性 | 用户理解成本高 | 输出积分来源明细(发言/奖励/手动补分) |
|
||||
| 支付合约 V2 升级 | 当前仍是最小可用合约 | 升级到 SafeERC20 + Pausable + plan 绑定 |
|
||||
| 支付失败文案标准化 | 转化率受影响 | 建立错误码 -> 文案映射表 |
|
||||
| 配置收敛 | 运维出错概率高 | 将支付/推送配置集中分组管理 |
|
||||
|
||||
## 5. 低优先级技术债
|
||||
|
||||
@@ -67,7 +78,7 @@ flowchart TD
|
||||
|
||||
## 6. 下阶段里程碑
|
||||
|
||||
1. 完成支付异常自动重放与告警分层。
|
||||
2. 上线退款/售后后台最小版。
|
||||
3. 建立商业化运营看板(支付、续费、留存)。
|
||||
4. 完成权限矩阵自动化回归测试。
|
||||
1. 完成 SQLite 从 `dual` 到 `sqlite` 的主读切换。
|
||||
2. 稳定 EMOS shadow,达到 rollout `observe/promote` 条件。
|
||||
3. 补外部监控抓取与告警阈值。
|
||||
4. 评估并推进支付合约 V2 升级。
|
||||
|
||||
+29
-18
@@ -1,62 +1,73 @@
|
||||
# 技术债与工程待办(v1.4.0)
|
||||
# 技术债与工程待办(v1.5.1)
|
||||
|
||||
最后更新:`2026-03-14`
|
||||
最后更新:`2026-03-20`
|
||||
|
||||
目标:在收费上线后,优先保证支付可靠性、权限一致性和运营可追溯性。
|
||||
目标:在收费上线后,优先保证状态一致性、支付可靠性、可观测性和概率引擎发布可控。
|
||||
|
||||
## 1. 债务快照
|
||||
|
||||
当前估计:**93% 稳定 / 7% 技术债**。
|
||||
当前估计:**95% 稳定 / 5% 技术债**。
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["技术债"]
|
||||
|
||||
subgraph P["支付与订阅"]
|
||||
P1["异常交易自动重放策略"]
|
||||
P1["合约 V2 升级(SafeERC20 / Pausable)"]
|
||||
P2["退款与工单流程"]
|
||||
P3["多链结算对账"]
|
||||
P3["多 RPC 与链上对账面板"]
|
||||
end
|
||||
|
||||
subgraph E["权限与运营"]
|
||||
E1["前后端/Bot 权限矩阵回归"]
|
||||
E2["积分与订阅冲突策略"]
|
||||
E2["积分来源明细与补分审计"]
|
||||
end
|
||||
|
||||
subgraph O["可观测性"]
|
||||
O1["支付失败原因分层指标"]
|
||||
O1["外部监控抓取与告警阈值"]
|
||||
O2["业务监控看板"]
|
||||
end
|
||||
|
||||
subgraph S["状态与概率"]
|
||||
S1["SQLite dual -> sqlite 切换验收"]
|
||||
S2["EMOS shadow -> primary 门禁稳定化"]
|
||||
end
|
||||
|
||||
A --> P
|
||||
A --> E
|
||||
A --> O
|
||||
A --> S
|
||||
```
|
||||
|
||||
## 2. 近期已关闭
|
||||
|
||||
- P1 支付主链路已上线(intent -> submit -> confirm)。
|
||||
- 支付主链路已上线(intent -> submit -> confirm)。
|
||||
- 支付自动补单已上线(Event Loop + Confirm Loop)。
|
||||
- 支付事件重放脚本已补齐。
|
||||
- 支付运行态 API 与 SQLite 审计事件已补齐。
|
||||
- 钱包绑定支持浏览器钱包 + WalletConnect。
|
||||
- 账户中心与 Pro 权限展示链路打通。
|
||||
- 钱包异动支持独立频道路由。
|
||||
- 运行态状态/缓存已支持 SQLite 渐进迁移。
|
||||
- 轻量可观测性已上线(`/healthz`、`/api/system/status`、`/metrics`)。
|
||||
- EMOS/CRPS 校准链路已上线 shadow 模式。
|
||||
|
||||
## 3. 高优先级技术债
|
||||
|
||||
| 项目 | 影响 | 建议动作 |
|
||||
| :-- | :-- | :-- |
|
||||
| 支付异常重放策略标准化 | 偶发确认失败需人工介入 | 建立 tx hash 自动回放 + 降级路径 |
|
||||
| SQLite 主读切换验收 | 仍处于 dual 过渡期 | 线上跑满 24-48 小时后切到 `sqlite` |
|
||||
| EMOS 上线门禁 | 当前 `hold`,不能切 primary | 继续积累样本,重点压 `bucket_brier` |
|
||||
| 外部监控与告警 | 只有轻量指标,无外部抓取 | 接 Prometheus/Grafana 或最小巡检 |
|
||||
| 退款与售后链路 | 商业闭环不完整 | 增加退款状态机与工单系统 |
|
||||
| 订阅审计可视化 | 排障效率受限 | 建立订阅事件时间线视图 |
|
||||
| 多邮箱绑定同 TG 账户策略 | 积分归属易混淆 | 引入主账号绑定策略与迁移工具 |
|
||||
|
||||
## 4. 中优先级技术债
|
||||
|
||||
| 项目 | 影响 | 建议动作 |
|
||||
| :-- | :-- | :-- |
|
||||
| 积分发放可解释性 | 用户理解成本高 | 输出积分来源明细(发言/签到/奖励) |
|
||||
| 积分发放可解释性 | 用户理解成本高 | 输出积分来源明细(发言/奖励/手动补分) |
|
||||
| 支付合约 V2 升级 | 当前仍是最小可用合约 | 升级到 SafeERC20 + Pausable + plan 绑定 |
|
||||
| 支付失败文案标准化 | 转化率受影响 | 建立错误码 -> 文案映射表 |
|
||||
| 配置收敛 | 运维出错概率高 | 将支付/推送配置集中分组管理 |
|
||||
|
||||
## 5. 低优先级技术债
|
||||
|
||||
@@ -67,7 +78,7 @@ flowchart TD
|
||||
|
||||
## 6. 下阶段里程碑
|
||||
|
||||
1. 完成支付异常自动重放与告警分层。
|
||||
2. 上线退款/售后后台最小版。
|
||||
3. 建立商业化运营看板(支付、续费、留存)。
|
||||
4. 完成权限矩阵自动化回归测试。
|
||||
1. 完成 SQLite 从 `dual` 到 `sqlite` 的主读切换。
|
||||
2. 稳定 EMOS shadow,达到 rollout `observe/promote` 条件。
|
||||
3. 补外部监控抓取与告警阈值。
|
||||
4. 评估并推进支付合约 V2 升级。
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
## 执行摘要
|
||||
|
||||
PolyWeather(仓库:`yangyuan-zhen/PolyWeather`)定位为**面向温度类结算预测市场(如 Polymarket 的温度结算合约)**的“生产级气象情报系统”,核心在于把多源天气观测/预报转化为**结算导向的概率桶(μ + bucket distribution)**,并进一步映射到市场报价完成**错价扫描**;同时提供 Web 仪表盘与 Telegram Bot 两套交互入口,并包含 Polygon 链上 USDC/USDC.e 支付、自动补单与订阅/积分体系。项目 README 明确其“Open-Core”边界:仓库公开天气聚合、基础分析、看板、Bot、标准支付流程;生产私有部分包含商业风控、阈值与运营工具等。
|
||||
从工程实现看,当前版本(README 标注 `v1.4.0`,最后更新 `2026-03-14`)已经落地关键业务闭环:多源天气采集(Open-Meteo、AviationWeather METAR、土耳其 MGM、香港 HKO、台湾 CWA、美国 NWS 等)、DEB 动态融合、趋势/概率引擎、Polymarket 只读行情层、前端缓存策略(ETag/304、force_refresh no-store)、以及支付事件监听与确认循环。
|
||||
但它也暴露出典型的“从快速迭代走向稳态生产”的结构性问题:核心模块(如 `src/data_collection/weather_sources.py`、`web/app.py`)体量巨大、职责耦合;配置/依赖/可复现性仍偏脚本化;测试覆盖存在但 CI/CD 缺失;多处自定义缓存与状态文件并发一致性风险;以及对第三方 API(Open-Meteo、AviationWeather、Supabase、Polymarket)在**配额、变更、SLA、合规**方面需要更系统的治理。
|
||||
本报告给出的改进方向按收益/风险/工作量分级,优先建议聚焦三条主线:
|
||||
第一,**模块化与工程化**:将采集/分析/市场层/支付/鉴权拆成清晰边界,补齐 CI、测试、类型与规范化配置;第二,**可观测性与可靠性**:统一缓存与状态管理、增加限流与退避策略、建立指标与告警;第三,**模型与评测体系**:围绕“结算命中率 + 偏差(MAE/RMSE)+ 概率校准(Brier/CRPS)+ 错价信号有效性(Edge/PnL 模拟)”建立基准与回归测试,并可在合规前提下评估引入更先进的气象后处理(如 EMOS)或外部 AI 预报(GraphCast/FourCastNet/Pangu-Weather 的商业许可限制需特别注意)。
|
||||
从工程实现看,截至 `2026-03-21`,项目已经完成一轮明确的工程化收口:多源天气采集仍保持现有业务能力,同时已完成采集层与 Web API 大文件拆分、CI 质量门禁、配置分级(`.env.example` / `.env.secrets.example` / 中文部署文档)、EMOS/CRPS 校准链路、运行态状态与缓存向 SQLite 的渐进迁移,以及基础可观测性接口(`/healthz`、`/api/system/status`、`/metrics`)。
|
||||
这意味着报告里最初最突出的“工程地基缺失”问题,已经有一部分被关闭:`src/data_collection/weather_sources.py` 与 `web/app.py` 不再是原来的超大单文件;GitHub Actions 已覆盖 Python、前端和 Docker build;配置与密钥治理已成体系;运行态状态不再只能依赖 JSON/JSONL 文件;EMOS 也不再只是概念,而是进入了可训练、可评估、可 shadow、可门禁判断的阶段。
|
||||
但项目仍处在“从可用走向稳态”的中段,而不是终局。当前真正的高优先级问题已收敛为三类:第一,**SQLite 迁移仍处于推荐的 dual 过渡模式**,线上真正切主读路径前仍需跑一段时间验证;第二,**可观测性只完成了轻量级指标层**,还没有形成完整的外部监控、阈值告警与趋势面板;第三,**EMOS 仍未达到生产切换标准**,当前门禁结论明确为 `hold`,阻塞原因是 shadow bucket brier 明显退化。支付链路方面,链下审计与容灾已明显增强:事件重放、SQLite 审计事件、RPC 多节点容灾、合约静态检查、`/ops` 支付异常单、按邮箱恢复脚本都已补齐;当前剩余风险主要集中在**链上合约本身仍是最小实现**,尚未升级到 SafeERC20、Pausable、链上套餐绑定等更强防护版本。
|
||||
因此,当前阶段最正确的策略已经不是继续做“大范围基础重构”,而是围绕**迁移验收、可观测性补全、EMOS 上线门禁稳定化**这三条线持续收口。短中期内更高 ROI 的方向依然不是引入新的大模型,而是把现有“采集→后处理→市场映射→支付/订阅”的链路做成**状态一致、指标可见、发布可控、回退明确**的生产平台。
|
||||
## 项目概览
|
||||
|
||||
PolyWeather 的目标与范围在 README/README_ZH 中定义得较清楚:为温度结算市场提供气象情报(多源采集→融合→概率→对照市场报价),并提供“官方看板(Vercel 前端)+ VPS 后端 + Telegram Bot”。
|
||||
@@ -30,13 +30,15 @@ DEB(Dynamic Error Balancing)基于过去 N 天模型误差(MAE)倒数加
|
||||
| 层级 | 目录/文件 | 角色定位 | 关键说明 |
|
||||
| ------------- | ------------------------------------------------------------------------ | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 运行时组件 | `frontend/` | Next.js 前端(Vercel) | 前端重构报告提到 App Router、Route Handlers(BFF)、缓存策略、支付与账户中心等。 |
|
||||
| 运行时组件 | `web/app.py` | FastAPI 后端 API | 作为前端 BFF 与 Telegram Bot 的共同 API。 |
|
||||
| 运行时组件 | `web/app.py` + `web/core.py` + `web/routes.py` + `web/analysis_service.py` | FastAPI 后端 API | 已从单文件入口拆为启动入口、核心上下文、路由层、分析服务层。 |
|
||||
| 运行时组件 | `bot_listener.py` + `src/bot/*` | Telegram Bot | 入口 `bot_listener.py` 调 `start_bot()`,并由 `StartupCoordinator` 启动多个后台 loop。 |
|
||||
| Python 域模块 | `src/data_collection/*` | 天气采集 + 城市注册 + 市场读取 | `WeatherDataCollector`、`CITY_REGISTRY`、`PolymarketReadOnlyLayer` 等。 |
|
||||
| Python 域模块 | `src/data_collection/*` | 天气采集 + 城市注册 + 市场读取 | 采集层已拆为 `weather_sources.py` 编排层 + `open_meteo_cache.py`、`settlement_sources.py`、`metar_sources.py`、`mgm_sources.py`、`nws_open_meteo_sources.py`。 |
|
||||
| Python 域模块 | `src/analysis/*` | DEB/趋势/概率/结算口径 | `deb_algorithm.py`、`trend_engine.py`、`settlement_rounding.py`。 |
|
||||
| Python 域模块 | `src/payments/*` + `contracts/*` | 支付合约 + 事件监听/补单 | Solidity 合约 + Python 侧事件扫描与确认循环。 |
|
||||
| Python 域模块 | `src/analysis/probability_calibration.py` + `src/analysis/probability_rollout.py` | 概率校准与上线门禁 | 已支持 `legacy / emos_shadow / emos_primary`,并可产出 rollout 判断。 |
|
||||
| Python 域模块 | `src/payments/*` + `contracts/*` | 支付合约 + 事件监听/补单 | Solidity 合约 + Python 侧事件扫描/确认循环 + SQLite 审计事件 + RPC 多节点容灾 + 合约静态检查。 |
|
||||
| Python 域模块 | `src/auth/*`、`docs/SUPABASE_SETUP_ZH.md`、`scripts/supabase/schema.sql` | Supabase 鉴权/订阅/积分 | 使用 `/auth/v1/user` 校验 JWT、`/rest/v1/subscriptions` 查订阅(服务端角色 key 必须保密)。 |
|
||||
| 工程与运维 | `docker-compose.yml`、`Dockerfile`、`update.sh`、`scripts/*` | 部署/验证脚本 | Compose 启两个容器(bot 与 web),脚本校验 ETag/缓存、更新重启等。 |
|
||||
| Python 域模块 | `src/database/runtime_state.py` | 运行态状态与缓存仓储 | 已接入 `daily_records`、`telegram_alert_state`、`probability_training_snapshots`、`open_meteo` 持久缓存。 |
|
||||
| 工程与运维 | `docker-compose.yml`、`Dockerfile`、`.github/workflows/ci.yml`、`scripts/*` | 部署/验证脚本 | 现已具备 CI 门禁、迁移脚本、状态校验脚本、配置校验脚本与 rollout 报告脚本。 |
|
||||
|
||||
### 参考架构与关键工作流
|
||||
|
||||
@@ -55,8 +57,8 @@ flowchart TB
|
||||
subgraph Data
|
||||
WX[WeatherDataCollector]
|
||||
CITY[CITY_REGISTRY]
|
||||
HIST[daily_records.json<br/>DEB history]
|
||||
CACHE[open_meteo_cache.json<br/>disk cache]
|
||||
HIST[(SQLite runtime state<br/>daily_records / cache / snapshots)]
|
||||
JSON[Legacy JSON files<br/>dual-mode fallback]
|
||||
end
|
||||
|
||||
subgraph ExternalAPIs
|
||||
@@ -99,7 +101,8 @@ flowchart TB
|
||||
CF --> RPC
|
||||
RPC --> SOL
|
||||
|
||||
WX --> CACHE
|
||||
WX --> HIST
|
||||
WX --> JSON
|
||||
FAST --> HIST
|
||||
WX --> CITY
|
||||
```
|
||||
@@ -118,13 +121,13 @@ flowchart TB
|
||||
**概率引擎**:`trend_engine.py` 以集合预报的 p10/p90 推 σ(并考虑历史 MAE floor、风向/云量/压强的 shock_score、以及峰值窗口 time-decay),再用正态近似把连续分布映射为 WU 整数“温度桶概率”。
|
||||
**推理流水线(在线)**:
|
||||
Web/Telegram 请求 → FastAPI 调用采集器抓取/复用缓存 → 分析引擎输出结构化结果(μ、概率桶、趋势、死盘/窗口判定、DEB 预测、市场扫描)→ 前端渲染或 bot 消息格式化。
|
||||
**检查点(checkpoints)**:传统 ML checkpoint 不适用;但项目存在两类“业务状态 checkpoint”:
|
||||
`daily_records.json`(DEB 历史与评测快照)与 `open_meteo_cache.json`(Open-Meteo 预报磁盘缓存)。
|
||||
**检查点(checkpoints)**:传统 ML checkpoint 不适用;但项目现已形成两类“业务状态 checkpoint”:
|
||||
(a)SQLite 运行态存储(推荐主路径);(b)legacy JSON/JSONL 文件(迁移期回退路径)。当前设计是 `POLYWEATHER_STATE_STORAGE_MODE=file|dual|sqlite`,建议先以 `dual` 运行,再切到 `sqlite`。
|
||||
### 测试、CI/CD 与运维验证
|
||||
|
||||
**测试**:仓库存在 `tests/test_trend_engine.py`,覆盖 μ 计算、死盘判定、预报崩盘提示、趋势方向等核心逻辑(通过 patch 隔离外部依赖)。
|
||||
**CI/CD**:从仓库检索结果看,未发现公开的 GitHub Actions 工作流(`.github/workflows` 搜索为空),需要补齐自动化质量门禁。
|
||||
**运维验收**:提供 `scripts/validate_frontend_cache.sh` 校验 `/api/cities`、`/api/city/<city>/summary`、`/api/history/<city>` 的 ETag/Cache-Control,并对 `force_refresh` 期望 `no-store`。
|
||||
**CI/CD**:已补齐 GitHub Actions 工作流,至少覆盖 Python lint/test、前端 build、Docker build 三条门禁;当前缺口不再是“有没有 CI”,而是“是否已在 GitHub 分支保护中强制执行”。
|
||||
**运维验收**:除 `scripts/validate_frontend_cache.sh` 外,现已新增配置校验、运行态迁移/核验、EMOS rollout 判断等脚本,并提供 `/healthz`、`/api/system/status`、`/metrics` 作为基础观测入口。
|
||||
**部署/更新**:Compose 用于启动服务;另有 `update.sh` 通过 `pkill` + `nohup` 重启 bot 与 web。
|
||||
## 优势与薄弱点
|
||||
|
||||
@@ -136,12 +139,14 @@ Web/Telegram 请求 → FastAPI 调用采集器抓取/复用缓存 → 分析引
|
||||
**支付侧有“事件监听 + 确认补单”的双通路**:支付链路天然存在“交易 pending / RPC 延迟 / 日志索引不完整”等问题,项目通过 event loop 与 confirm loop 双机制提升最终一致性。
|
||||
### 薄弱点与风险
|
||||
|
||||
**核心文件过大导致可维护性下降**:`WeatherDataCollector` 集“多源采集 + 缓存 + 限流 + 解析 + 部分业务逻辑(城市/单位/回退策略)”于一体,规模继续增长会显著提高回归风险与重构成本。 同类问题往往也会出现在“单文件 FastAPI 应用”形态(`web/app.py`)。
|
||||
**可复现性仍偏“脚本+隐式约定”**:
|
||||
虽然给了 Docker/Compose 快速启动,但缺少一份稳定的 `.env.example` / 配置 schema(哪些变量必需、默认值、敏感级别、环境分层),导致他人复现时容易踩坑;此外 `update.sh` 以 `pkill` 强杀进程方式更新,存在误杀与状态丢失风险,建议迁移到 systemd/容器滚动更新/健康检查。
|
||||
**测试存在但依赖与 CI 缺失**:有 pytest 单测文件,但 `requirements.txt` 未体现 dev 依赖与一键运行指令,且缺少 CI 自动运行,容易出现“本地能跑、线上漂移”。
|
||||
**核心文件过大问题已明显缓解,但边界仍需继续稳定**:`WeatherDataCollector` 与 `web/app.py` 的超大文件问题已完成第一阶段拆分;当前风险已从“文件过大”转为“跨模块兼容与边界稳定性”,例如旧调用路径、兼容导出、跨层 helper 仍需持续清理。
|
||||
**可复现性已从“缺模板”进入“模板与生产对齐”的阶段**:`.env.example`、`.env.secrets.example`、中文配置文档、前端部署文档、运行时配置校验器都已存在;当前风险主要在于线上历史 `.env` 与新模板并存、旧变量命名残留、以及密钥轮换与分层是否真正落实。
|
||||
**CI 已建立,但组织级质量门禁未必完全收口**:CI 现已覆盖 Python、前端与 Docker build。当前问题不再是“缺 CI”,而是是否把这些 status check 绑定到 `main` 保护策略,以及是否逐步引入更严格的 pre-merge 审查。
|
||||
**运行态状态/缓存迁移仍处于过渡期**:`daily_records`、`telegram_alert_state`、`probability_training_snapshots`、`open_meteo` 缓存已经支持 SQLite,并有迁移/校验脚本;但在正式切到 `sqlite` 主读路径前,仍需经历一段 dual 双写验证期。这是当前最需要谨慎处理的工程性风险之一。
|
||||
**第三方服务合规与稳定性风险**:
|
||||
项目强依赖外部 API(Open-Meteo、AviationWeather、NWS、HKO、CWA、Polymarket、Supabase)。其中 AviationWeather Data API 有明确速率限制;Polymarket 官方说明 Gamma/Data/CLOB 三套 API 分属不同域,CLOB 交易端点需鉴权且策略可能变化;Supabase 明确强调 `service_role`/secret keys 绝不可暴露。若缺乏集中治理(重试/退避/熔断/降级/配额监控/密钥轮换),稳定性与合规不可控。
|
||||
**可观测性已起步,但仍不构成完整监控体系**:项目现在已有 `/healthz`、`/api/system/status`、`/metrics`,并为 HTTP 与关键第三方源增加了轻量指标;但仍缺少 Prometheus/Grafana 级别的外部抓取、告警阈值、趋势面板和运行日报。这部分现在属于“已开始,不算完成”。
|
||||
**EMOS 已完成工程接入,但未完成生产发布**:EMOS/CRPS 校准、shadow 观测、rollout report、上线门禁都已实现;当前真实门禁结果为 `hold`,阻塞原因是 shadow bucket brier 明显退化。因此概率引擎标准化并非未做,而是“工程完成、发布未通过”。
|
||||
**许可证/商业使用的潜在冲突点**:仓库自身是 MIT,但如果未来尝试引入外部 AI 预报模型,需要非常谨慎:GraphCast 仓库代码 Apache-2.0,但权重使用 CC BY-NC-SA 4.0(非商业),Pangu-Weather 权重同样 BY-NC-SA 且明确禁止商业用途;不加区分地把这些模型用于付费产品会留下法律风险。
|
||||
## 对标分析
|
||||
|
||||
@@ -164,17 +169,15 @@ Web/Telegram 请求 → FastAPI 调用采集器抓取/复用缓存 → 分析引
|
||||
**对标结论**:PolyWeather 与这类“全球 AI 预报模型”不在同一层级:PolyWeather 是“面向结算市场的产品化情报系统”,其价值核心是**将预测转成可交易/可结算的决策信息**。短中期内更高 ROI 的方向不是“自训大模型”,而是把现有“采集+后处理+市场映射”的链路做成**可复现、可观测、可评测、可扩展**的工程平台;在许可合规前提下,再评估引入外部模型推理作为额外信号源。
|
||||
## 优先级改进建议
|
||||
|
||||
下表给出“高/中/低”优先级的具体改进清单,包含工作量估计、主要风险与可执行步骤(假设“无特定部署约束/性能指标约束”)。
|
||||
下表按截至 `2026-03-21` 的真实状态重排优先级。已完成项不再继续列为“待做”,只保留当前仍需推进的事项。
|
||||
| 优先级 | 改进项 | 预估工作量 | 主要收益 | 主要风险 | 可执行步骤(建议顺序) |
|
||||
| ------ | --------------------------------------------------------------------------------------------------------------------------------- | -------------------: | ------------------------------------------------------------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 高 | **拆分 `WeatherDataCollector` 为可插拔 Provider 架构**(OpenMeteoProvider / MetarProvider / NwsProvider / SettlementProvider 等) | 1–2 周 | 降低耦合、提高可测性,便于加入新城市/新源;减少回归面 | 重构期间线上行为漂移 | 1) 定义统一接口(输入:city/lat/lon/date;输出:标准 schema)→ 2) 把缓存/限流抽为中间层(decorator)→ 3) 用现有测试补齐 provider 单测 → 4) 灰度开启(仅部分城市走新链路) |
|
||||
| 高 | **拆分 `web/app.py`:路由层/服务层/DTO/依赖注入** | 1–2 周 | API 可维护性、鉴权/限流/缓存策略更清晰;更易做 OpenAPI 文档与版本化 | 改路由可能影响前端 | 1) 抽出 `services/analysis_service.py`、`services/market_service.py`、`services/payment_service.py` → 2) 引入 Pydantic models 作为响应 schema → 3) 保持 URL 不变,先做内部重构 |
|
||||
| 高 | **建立 CI(Python + Frontend)与质量门禁**:lint/format/typecheck/test/docker build | 3–5 天 | 防回归、提高贡献效率;让 `v1.4` 之后迭代更稳 | 初期会暴露大量历史问题 | 1) Python:ruff + mypy + pytest;Node:eslint + typecheck + build → 2) GitHub Actions 两条 pipeline → 3) 给出“允许失败→逐步收紧”的迁移策略 |
|
||||
| 高 | **补齐可复现配置与密钥分级**:`.env.example` + 配置文档 + 敏感项隔离 | 2–4 天 | 新环境搭建更快、减少误配置;降低密钥泄露风险 | 需要梳理现有 env 变量 | 1) 盘点 env(Open-Meteo、Polymarket、Supabase、RPC、支付等)→ 2) `.env.example` 提供默认与说明 → 3) 标注敏感等级(尤其 `SUPABASE_SERVICE_ROLE_KEY`)并禁止前端/日志输出 |
|
||||
| 高 | **统一“状态与缓存”方案**:把 JSON 文件状态迁移到 SQLite/Postgres/Redis(至少做到原子/锁一致) | 1–2 周 | 降低并发一致性 bug(多进程/多容器)、便于观测与回放 | 迁移会引入数据兼容与历史清理问题 | 1) 为 `daily_records` 与 `open_meteo_cache` 定义表结构 → 2) 先实现写入双写(JSON+DB)→ 3) 校验一致后切换读取 → 4) 下线 JSON 文件 |
|
||||
| 高 | **完成 SQLite 迁移切换与验收**:从 `dual` 过渡到 `sqlite` 主读路径 | 2–5 天 | 真正关闭 JSON/JSONL 并发一致性风险;状态/缓存统一入库 | 迁移校验不充分会导致线上行为漂移 | 1) 线上部署新代码 → 2) 执行迁移与校验脚本 → 3) `dual` 运行至少 24–48 小时 → 4) 校验 `/api/history`、bot 告警、snapshot、缓存都正常 → 5) 再切 `POLYWEATHER_STATE_STORAGE_MODE=sqlite` |
|
||||
| 高 | **把轻量可观测性接入外部监控与告警**:围绕 `/metrics` 建立抓取、阈值与巡检 | 3–7 天 | 不再只靠日志定位问题;可以监控第三方源错误率、缓存命中与 HTTP 延迟 | 指标不分层会导致噪音高、告警无用 | 1) 抓取 `/metrics` → 2) 先围绕 HTTP、Open-Meteo、MGM、METAR 建立最小仪表板 → 3) 为 429/403/error/stale_cache 设阈值 → 4) 增加巡检脚本或告警通道 |
|
||||
| 高 | **稳定 EMOS shadow 并收紧上线门禁** | 1–2 周 | 让概率引擎升级具备明确发布条件,避免拍脑袋切换 | 当前 shadow bucket brier 退化明显,存在误上线风险 | 1) 持续积累 snapshot 样本 → 2) 定期重训与生成 `evaluation_report` / `shadow_report` / `rollout_report` → 3) 重点压 `bucket_brier` 退化 → 4) 只有门禁从 `hold` 进入 `observe/promote` 后才考虑上线 |
|
||||
| 中 | **市场层升级为 async + 类型安全**:引入 `aiopolymarket` 或在现有层加重试/backoff/连接池 | 4–7 天 | 行情层更稳,减少短时网络抖动;更易扩展更多市场/分页 | 依赖升级带来的行为差异 | 1) 把 requests.Session 替换为 aiohttp/httpx → 2) 在 Gamma/CLOB 调用侧实现指数退避 → 3) 引入 typed models,减少解析失败 |
|
||||
| 中 | **概率引擎更标准化:引入 EMOS/CRPS 拟合做校准**(替换/增强当前正态近似与规则 σ) | 1–2 周 | 概率输出更可解释、可校准;适合做长期回归评测 | 需要足够历史样本;可能改变用户体验 | 1) 以 `daily_records` 为训练集(模型预报均值/方差→实际)→ 2) 先离线拟合并与现模型对比 → 3) 线上 shadow 输出(不影响主显示)→ 4) 达标后切换 |
|
||||
| 中 | **支付合约/链上交互加强审计与防护**:事件重放、重入/授权边界、RPC 多节点容灾 | 1 周 | 提升资金链路可信度;减少链上卡单 | 合约升级需要迁移/再验证 | 1) 为 event loop 增加“最后处理区块高度”持久化与重放工具 → 2) RPC 端支持多 URL fallback → 3) 合约侧考虑 OpenZeppelin Ownable/SafeERC20(如升级)并更新验证流程 |
|
||||
| 中 | **支付合约从“最小可用”升级到“更强合约防护”** | 1–2 周 | 在已完成的链下审计与容灾之上,进一步收紧链上授权边界 | 合约升级需要重新部署、迁移配置并再次验证 | 1) 维持现有事件重放、SQLite 审计、多 RPC fallback → 2) 升级合约到 SafeERC20 + Pausable → 3) 评估链上 plan/amount/token 绑定或 EIP-712 签名校验 → 4) 迁移后更新 PolygonScan 验证与支付审计文档 |
|
||||
| 中 | **将 CI 与分支保护/发布流程真正绑定** | 1–3 天 | 让现有 CI 从“存在”变成“强制门禁” | 历史分支/热修流程可能受影响 | 1) GitHub `main` 开启 required checks → 2) 把 release/tag 流程绑定 CI → 3) 明确热修例外流程 |
|
||||
| 低 | **引入外部 AI 预报模型作为附加信号**(GraphCast/FourCastNet/Pangu-Weather 等) | 2–6 周(取决于范围) | 可能提升极端/中期预测能力与差异化 | **商业许可限制**(多为 CC BY-NC-SA/禁止商业)与算力成本 | 1) 先做合规评审(权重许可/数据条款)→ 2) 仅在研究/非商业环境评估 → 3) 若要商用,优先选择可商用权重或自研/购买授权 |
|
||||
|
||||
### 文档、测试与贡献流程的具体补强建议(落到仓库层面)
|
||||
@@ -239,7 +242,7 @@ PolyWeather 的评测应围绕“结算场景”而非传统数值天气预报
|
||||
|
||||
**外部 API 速率限制/格式变更**:AviationWeather 明确 rate limit 与建议使用 cache 文件;Open-Meteo 也可能在不同端点策略上变化。缓解:统一“请求预算”与退避/熔断;关键响应做 schema 校验与回放测试;对高频数据优先拉取官方 cache/批量接口(若可用)。
|
||||
**密钥泄露与权限滥用**:Supabase 明确强调 `service_role` 属高权限密钥,绝不可出现在前端或公开环境。缓解:密钥分级、CI secret scan、运行时最小权限、日志脱敏。
|
||||
**支付链路最终一致性与链上不确定性**:链上事件索引延迟、RPC 不稳定、交易确认数不足都会导致误判。缓解:保持“事件监听 + 确认补单”双路径,并增加“事件重放/对账工具”、多 RPC fallback、以及链上高度持久化。
|
||||
**支付链路最终一致性与链上不确定性**:链上事件索引延迟、RPC 不稳定、交易确认数不足都会导致误判。当前项目已经补齐“事件监听 + 确认补单”双路径、事件重放脚本、SQLite 审计事件与多 RPC fallback;现阶段的主要剩余风险不再是“没有防护”,而是链上合约仍为最小实现,owner 为单地址管理,且没有 pause 开关与 SafeERC20。
|
||||
**引入外部 AI 预报模型的商业合规风险**:GraphCast/Pangu-Weather 的权重许可均带非商业限制(CC BY-NC-SA/BY-NC-SA);若 PolyWeather 是付费产品,必须先做法务与授权评审。缓解:只在研究环境评估;商用优先选择可商用权重/购买授权/自研。
|
||||
**Open-Core 边界导致的“公开仓库与生产行为不一致”**:README 明确生产存在私有风控与阈值。缓解:把“公开核心”的可复现与评测做扎实(接口/数据 schema/测试/评测),私有策略只作为可插拔 policy layer 接入。
|
||||
## 参考链接
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
# PolyWeather 支付审计与防护说明
|
||||
|
||||
最后更新:`2026-03-21`
|
||||
|
||||
## 1. 当前已落地的防护
|
||||
|
||||
### 链下运行态
|
||||
|
||||
- 支付事件扫描与确认循环已把运行态写入 SQLite:
|
||||
- `payment_runtime_state`
|
||||
- `payment_audit_events`
|
||||
- 关键循环现在会记录:
|
||||
- `event_loop_started`
|
||||
- `event_loop_cycle`
|
||||
- `event_loop_error`
|
||||
- `confirm_loop_started`
|
||||
- `confirm_loop_cycle`
|
||||
- `confirm_loop_error`
|
||||
|
||||
### 事件确认边界
|
||||
|
||||
- 后端只认链上 `OrderPaid` 事件。
|
||||
- 前端提交 intent 不会直接视为支付完成。
|
||||
- `confirm_loop` 会再次按链上交易与确认数校验 intent。
|
||||
- 若确认失败,当前会明确把 intent / transaction 落为失败态,而不是长期停留在 `submitted`。
|
||||
|
||||
当前已显式识别的失败原因包括:
|
||||
|
||||
- `receiver_mismatch`
|
||||
- `sender_mismatch`
|
||||
- `event_mismatch`
|
||||
- `tx_reverted`
|
||||
|
||||
### RPC 多节点容灾
|
||||
|
||||
- 支持 `POLYWEATHER_PAYMENT_RPC_URLS`
|
||||
- 格式示例:
|
||||
|
||||
```env
|
||||
POLYWEATHER_PAYMENT_RPC_URLS=https://polygon-rpc.com,https://polygon-bor-rpc.publicnode.com
|
||||
```
|
||||
|
||||
- 启动时按顺序探活。
|
||||
- 当前节点断连或收据查询失败时,会自动切换到下一个可用 RPC。
|
||||
|
||||
### 事件重放
|
||||
|
||||
- 已提供脚本:
|
||||
- [replay_payment_events.py](/E:/web/PolyWeather/scripts/replay_payment_events.py)
|
||||
|
||||
用途:
|
||||
- 审计某个区块范围内的 `OrderPaid`
|
||||
- 事后补查漏单
|
||||
- 排查 RPC 抖动导致的监听遗漏
|
||||
|
||||
命令示例:
|
||||
|
||||
```bash
|
||||
python scripts/replay_payment_events.py --from-block 10000000 --to-block 10001000
|
||||
```
|
||||
|
||||
### 运行态检查
|
||||
|
||||
- 已提供接口:
|
||||
- `GET /api/payments/runtime`
|
||||
|
||||
可查看:
|
||||
- checkout 配置摘要
|
||||
- 当前活跃 RPC
|
||||
- 候选 RPC 列表
|
||||
- event loop 最新状态
|
||||
- 最近审计事件
|
||||
|
||||
### Ops 事故单
|
||||
|
||||
现在 `/ops` 已提供单独的支付异常单列表,默认展示:
|
||||
|
||||
- `payment_intent_failed`
|
||||
|
||||
支持:
|
||||
|
||||
- 按 `reason` 过滤
|
||||
- 标记已处理
|
||||
|
||||
这让下面这类事故不再需要翻日志定位:
|
||||
|
||||
- 已付款但未开通
|
||||
- 打到旧收款地址
|
||||
- 交易事件不匹配
|
||||
|
||||
## 2. 当前合约的授权边界
|
||||
|
||||
合约源码:
|
||||
- [PolyWeatherCheckout.sol](/E:/web/PolyWeather/contracts/PolyWeatherCheckout.sol)
|
||||
|
||||
当前边界:
|
||||
|
||||
1. `owner`
|
||||
- 可执行:
|
||||
- `setTreasury`
|
||||
- `setTokenAllowed`
|
||||
|
||||
2. 普通用户
|
||||
- 只能调用:
|
||||
- `pay(orderId, planId, amount, token)`
|
||||
|
||||
3. 代币边界
|
||||
- 只有 `allowedToken[token] == true` 的 token 可支付
|
||||
|
||||
4. 订单边界
|
||||
- 同一个 `orderId` 只能成功支付一次
|
||||
|
||||
## 3. 重入与重复支付判断
|
||||
|
||||
当前合约的 `pay` 逻辑顺序是:
|
||||
|
||||
1. 检查 token allowlist
|
||||
2. 检查 `amount > 0`
|
||||
3. 检查 `paidOrder[orderId] == false`
|
||||
4. 先写入 `paidOrder[orderId] = true`
|
||||
5. 再执行 `transferFrom`
|
||||
6. 发出 `OrderPaid`
|
||||
|
||||
这意味着:
|
||||
|
||||
- 同一 `orderId` 的重复支付会被拦住
|
||||
- 典型“转账外部调用后再回调重复执行同订单”的路径会被 `paidOrder` 状态挡住
|
||||
|
||||
但要注意:
|
||||
|
||||
- 当前合约没有 `Pausable`
|
||||
- 当前合约没有 `SafeERC20`
|
||||
- 当前合约没有在链上校验 `planId -> amount`
|
||||
|
||||
所以它属于:
|
||||
- **最小可用支付合约**
|
||||
- 不是“全功能强防护合约”
|
||||
|
||||
## 4. 当前静态审计结论
|
||||
|
||||
已提供脚本:
|
||||
- [check_payment_contract_security.py](/E:/web/PolyWeather/scripts/check_payment_contract_security.py)
|
||||
|
||||
命令:
|
||||
|
||||
```bash
|
||||
python scripts/check_payment_contract_security.py
|
||||
```
|
||||
|
||||
输出会检查这些项目:
|
||||
|
||||
- 是否有 `onlyOwner`
|
||||
- `setTreasury` / `setTokenAllowed` 是否受 owner 保护
|
||||
- constructor / setter 是否检查零地址
|
||||
- 是否校验 allowlist
|
||||
- 是否校验 `amount > 0`
|
||||
- 是否校验重复订单
|
||||
- 是否在 `transferFrom` 前写入 `paidOrder`
|
||||
- 是否有 pause 开关
|
||||
- 是否使用 SafeERC20
|
||||
- 是否在链上绑定套餐价格
|
||||
|
||||
## 5. 当前主要剩余风险
|
||||
|
||||
1. 单地址 owner
|
||||
- 建议把 `owner` 迁移到多签钱包
|
||||
|
||||
2. 无暂停开关
|
||||
- 发现紧急问题时,无法直接暂停 `pay`
|
||||
|
||||
3. 金额校验主要在链下
|
||||
- 当前 `planId / amount / token` 绑定主要靠后端 intent 和确认逻辑
|
||||
|
||||
4. ERC20 兼容性假设
|
||||
- 当前使用 `IERC20.transferFrom`
|
||||
- 升级版合约更建议改为 OpenZeppelin `SafeERC20`
|
||||
|
||||
## 6. 推荐操作
|
||||
|
||||
### 每次支付配置变更后
|
||||
|
||||
执行:
|
||||
|
||||
```bash
|
||||
python scripts/check_payment_contract_security.py
|
||||
python scripts/replay_payment_events.py --from-block <from> --to-block <to>
|
||||
```
|
||||
|
||||
### 线上巡检
|
||||
|
||||
执行:
|
||||
|
||||
```bash
|
||||
curl http://127.0.0.1:8000/api/payments/runtime
|
||||
```
|
||||
|
||||
重点看:
|
||||
|
||||
- `rpc.active_rpc_url`
|
||||
- `rpc.configured_rpc_count`
|
||||
- `event_loop_state.last_scanned_block`
|
||||
- `recent_audit_events`
|
||||
|
||||
如果你在 `/ops` 或脚本里看到:
|
||||
|
||||
- `receiver_mismatch`
|
||||
|
||||
其含义通常不是“缓存没刷新”,而是:
|
||||
|
||||
- 用户这笔交易的 `to` 地址不是当前生产收款合约
|
||||
- 常见原因是旧页面、旧 deployment、旧钱包会话,或历史收款地址仍被命中
|
||||
|
||||
此时应优先做:
|
||||
|
||||
1. 确认链上真实 `to` 地址
|
||||
2. 确认当前 `/api/payments/config` 返回的 `receiver_contract`
|
||||
3. 如确已收款,再走人工恢复或补开订阅
|
||||
|
||||
### 按邮箱恢复最近支付
|
||||
|
||||
已提供脚本:
|
||||
|
||||
- [reconcile_subscription_by_email.py](/E:/web/PolyWeather/scripts/reconcile_subscription_by_email.py)
|
||||
|
||||
命令:
|
||||
|
||||
```bash
|
||||
docker compose exec polyweather_web python scripts/reconcile_subscription_by_email.py --email user@example.com
|
||||
```
|
||||
|
||||
适用场景:
|
||||
|
||||
- 用户声称已付费但未开通
|
||||
- 需要快速确认最近一笔 intent 是否能自动恢复
|
||||
|
||||
## 7. 下一版合约建议
|
||||
|
||||
如果后续升级合约,优先级建议:
|
||||
|
||||
1. `Ownable` -> 多签 owner
|
||||
2. `SafeERC20`
|
||||
3. `Pausable`
|
||||
4. 链上 plan/amount/token 绑定
|
||||
5. 必要时增加 rescue/sweep 能力
|
||||
@@ -0,0 +1,197 @@
|
||||
# PolyWeather 支付合约升级方案(V2)
|
||||
|
||||
最后更新:`2026-03-20`
|
||||
|
||||
## 1. 目标
|
||||
|
||||
本次 V2 方案对应三个明确目标:
|
||||
|
||||
1. 把 `owner` 迁到多签地址
|
||||
2. 升级到 `SafeERC20 + Pausable + ReentrancyGuard`
|
||||
3. 把“链上 plan 绑定”和“EIP-712 授权支付”都纳入设计,而不是只在链下校验
|
||||
|
||||
合约草案:
|
||||
- [PolyWeatherCheckoutV2.sol](/E:/web/PolyWeather/contracts/PolyWeatherCheckoutV2.sol)
|
||||
|
||||
构造参数编码脚本:
|
||||
- [encode_checkout_v2_constructor.py](/E:/web/PolyWeather/scripts/encode_checkout_v2_constructor.py)
|
||||
|
||||
## 2. V2 新增能力
|
||||
|
||||
### 多签 owner
|
||||
|
||||
V2 constructor 不再默认 `msg.sender` 作为唯一 owner,而是显式传入:
|
||||
|
||||
- `initialOwner`
|
||||
- `initialTreasury`
|
||||
- `initialSigner`
|
||||
|
||||
这意味着:
|
||||
- 部署后可直接把多签地址设为 `owner`
|
||||
- 不需要先单签部署再补 transfer
|
||||
|
||||
### SafeERC20
|
||||
|
||||
V2 内置最小 `SafeERC20` 封装:
|
||||
|
||||
- `safeTransferFrom`
|
||||
- `safeTransfer`
|
||||
|
||||
相比直接依赖 `IERC20.transferFrom -> bool`:
|
||||
- 对非标准 ERC20 的兼容性更稳
|
||||
- 出错边界更明确
|
||||
|
||||
### Pausable
|
||||
|
||||
V2 增加:
|
||||
|
||||
- `pause()`
|
||||
- `unpause()`
|
||||
|
||||
支付入口:
|
||||
|
||||
- `payPlan(...)`
|
||||
- `payAuthorized(...)`
|
||||
|
||||
都受 `whenNotPaused` 保护。
|
||||
|
||||
一旦发现:
|
||||
- treasury 配置错误
|
||||
- token allowlist 配置错误
|
||||
- 签名器异常
|
||||
- 链上风控问题
|
||||
|
||||
可以直接暂停支付入口。
|
||||
|
||||
### ReentrancyGuard
|
||||
|
||||
V2 增加 `nonReentrant`,保护:
|
||||
|
||||
- `payPlan`
|
||||
- `payAuthorized`
|
||||
- `rescueToken`
|
||||
|
||||
虽然当前订单去重已经能挡住典型重复支付路径,但 `ReentrancyGuard` 仍然是更稳的防线。
|
||||
|
||||
### 链上套餐绑定
|
||||
|
||||
V2 新增:
|
||||
|
||||
- `setPlan(planId, token, amount, active)`
|
||||
- `planConfig[planId][token]`
|
||||
|
||||
正式支付入口 `payPlan` 会:
|
||||
|
||||
1. 校验 token 已 allowed
|
||||
2. 校验 `planId + token` 的 plan 已 active
|
||||
3. 从链上读取 amount
|
||||
4. 按链上配置收款
|
||||
|
||||
这意味着:
|
||||
- `planId / amount / token` 绑定不再完全依赖链下
|
||||
|
||||
### EIP-712 授权支付
|
||||
|
||||
V2 同时保留第二条入口:
|
||||
|
||||
- `payAuthorized(...)`
|
||||
|
||||
它适合:
|
||||
- 临时折扣
|
||||
- 特殊活动价
|
||||
- 不想每次都上链改 `setPlan`
|
||||
|
||||
校验字段包括:
|
||||
|
||||
- `orderId`
|
||||
- `payer`
|
||||
- `planId`
|
||||
- `token`
|
||||
- `amount`
|
||||
- `nonce`
|
||||
- `deadline`
|
||||
|
||||
签名人地址由:
|
||||
|
||||
- `signer`
|
||||
|
||||
统一控制。
|
||||
|
||||
## 3. 两条支付路径怎么选
|
||||
|
||||
### 路线 A:链上套餐绑定优先
|
||||
|
||||
优点:
|
||||
- 最直观
|
||||
- 合约级约束最强
|
||||
- 更容易审计
|
||||
|
||||
缺点:
|
||||
- 套餐改价需要 owner 交易
|
||||
|
||||
适合:
|
||||
- 月付/季付/年付这类稳定商品
|
||||
|
||||
### 路线 B:EIP-712 授权优先
|
||||
|
||||
优点:
|
||||
- 活动价灵活
|
||||
- 不必每次改链上 plan
|
||||
|
||||
缺点:
|
||||
- 需要管理 signer 密钥
|
||||
- 风险从 owner 单点,部分转移到 signer 运维
|
||||
|
||||
适合:
|
||||
- 促销
|
||||
- 临时折扣
|
||||
- 白名单价格
|
||||
|
||||
### 当前建议
|
||||
|
||||
生产建议不是二选一,而是:
|
||||
|
||||
1. **稳定套餐** 走 `payPlan`
|
||||
2. **特殊场景** 走 `payAuthorized`
|
||||
|
||||
这样:
|
||||
- 主流程更稳
|
||||
- 特殊价仍保留灵活性
|
||||
|
||||
## 4. 推荐迁移步骤
|
||||
|
||||
1. 先部署 V2 到测试环境
|
||||
2. `owner` 直接用多签地址
|
||||
3. 配置 `treasury`
|
||||
4. 配置 `allowedToken`
|
||||
5. 配置 `planId/token/amount`
|
||||
6. 仅在需要活动价时再配置 `signer`
|
||||
7. 用事件重放脚本和运行态接口验证
|
||||
8. 再切生产前端/后端配置到新 `receiver_contract`
|
||||
|
||||
## 5. 构造参数编码
|
||||
|
||||
示例:
|
||||
|
||||
```bash
|
||||
python scripts/encode_checkout_v2_constructor.py \
|
||||
--owner 0xYourMultiSig \
|
||||
--treasury 0xYourTreasury \
|
||||
--signer 0xYourBackendSigner
|
||||
```
|
||||
|
||||
## 6. 当前判断
|
||||
|
||||
V2 已经把这三件事做成了明确方案:
|
||||
|
||||
1. 多签 owner
|
||||
2. SafeERC20 + Pausable + ReentrancyGuard
|
||||
3. 链上 plan 绑定 + EIP-712 授权
|
||||
|
||||
它现在是**升级草案**,不是现网已部署合约。
|
||||
|
||||
如果要真正上线,下一步就是:
|
||||
|
||||
1. 做一次测试网或本地链验证
|
||||
2. 更新 PolygonScan 验证文档
|
||||
3. 修改后端 `receiver_contract` 配置
|
||||
@@ -1,11 +1,17 @@
|
||||
# PolyWeatherCheckout PolygonScan 验证(v1.4.0)
|
||||
# PolyWeatherCheckout PolygonScan 验证(v1.5.1)
|
||||
|
||||
最后更新:`2026-03-14`
|
||||
最后更新:`2026-03-20`
|
||||
|
||||
## 1. 目标
|
||||
|
||||
对生产收款合约完成源码验证,降低钱包风控误报并提升用户信任。
|
||||
|
||||
当前说明:
|
||||
|
||||
- **现网合约仍为 V1**:`contracts/PolyWeatherCheckout.sol`
|
||||
- **V2 只是升级草案**:`contracts/PolyWeatherCheckoutV2.sol`
|
||||
- 当前 PolygonScan 验证流程默认针对 V1
|
||||
|
||||
## 2. 当前部署参数(示例)
|
||||
|
||||
- 链:Polygon Mainnet(`chainId=137`)
|
||||
@@ -48,7 +54,23 @@ python scripts/encode_checkout_constructor.py \
|
||||
- USDC.e: `0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174`
|
||||
- Native USDC: `0x3c499c542cef5e3811e1192ce70d8cc03d5c3359`
|
||||
|
||||
## 7. 说明
|
||||
## 7. V2 说明(尚未部署)
|
||||
|
||||
如果后续升级到 V2,请改用:
|
||||
|
||||
```bash
|
||||
python scripts/encode_checkout_v2_constructor.py \
|
||||
--owner 0xYourMultiSig \
|
||||
--treasury 0xYourTreasury \
|
||||
--signer 0xYourBackendSigner
|
||||
```
|
||||
|
||||
V2 相关文档:
|
||||
|
||||
- [PAYMENT_UPGRADE_V2_ZH.md](/E:/web/PolyWeather/docs/payments/PAYMENT_UPGRADE_V2_ZH.md)
|
||||
- [PAYMENT_AUDIT_ZH.md](/E:/web/PolyWeather/docs/payments/PAYMENT_AUDIT_ZH.md)
|
||||
|
||||
## 8. 说明
|
||||
|
||||
- 源码验证能显著降低“欺诈/不可信”误报,但钱包风险缓存更新存在延迟。
|
||||
- 生产商用环境可使用私有升级版合约;公开仓库保留标准实现与验证流程。
|
||||
|
||||
+6
-3
@@ -9,11 +9,12 @@
|
||||
- 风险徽章
|
||||
- 城市档案(结算源 / 距离 / 观测更新时间 / 周边站点)
|
||||
- 今日日内走势(简版 Canvas)
|
||||
- 多日预报
|
||||
- 多日预报(`DEB` 优先)
|
||||
- 基础判断卡(方向 / 置信度 / 原因)
|
||||
- 快捷按钮:
|
||||
- 今日日内分析
|
||||
- 历史对账
|
||||
- 打开完整网站分析
|
||||
- 打开网站查看更多
|
||||
- 自动识别城市:
|
||||
- 监听当前激活标签页 URL(例如 Polymarket `.../event/highest-temperature-in-ankara-...`)
|
||||
- 自动将侧边栏城市切换为 URL 对应城市
|
||||
@@ -42,5 +43,7 @@
|
||||
|
||||
## 说明
|
||||
|
||||
- 当前版本是 MVP,重点是“导流回站”,未接入支付链路。
|
||||
- 当前版本仍是轻量 MVP,重点是“监控 + 基础判断 + 导流回站”,未接入支付链路。
|
||||
- 若你的 API 做了严格鉴权,请先在设置页填写 token 再使用。
|
||||
- 台北现在按 `NOAA RCTP` 结算参考展示。
|
||||
- 插件不会承载完整分析;完整结构判断、历史对账和更多信号仍以主站为准。
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"manifest_version": 3,
|
||||
"name": "PolyWeather Side Panel",
|
||||
"description": "PolyWeather 右侧城市卡片(浏览器侧边栏)",
|
||||
"version": "0.1.1",
|
||||
"version": "0.1.5",
|
||||
"icons": {
|
||||
"16": "icon-16.png",
|
||||
"32": "icon-32.png",
|
||||
|
||||
@@ -66,6 +66,23 @@ body {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.freshness-hint {
|
||||
margin: -2px 0 12px;
|
||||
padding: 8px 10px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid rgba(245, 158, 11, 0.28);
|
||||
background: rgba(245, 158, 11, 0.08);
|
||||
color: #fcd34d;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.freshness-hint.stale {
|
||||
border-color: rgba(248, 113, 113, 0.38);
|
||||
background: rgba(248, 113, 113, 0.1);
|
||||
color: #fecaca;
|
||||
}
|
||||
|
||||
.risk-badge {
|
||||
padding: 5px 9px;
|
||||
border-radius: 10px;
|
||||
@@ -236,6 +253,84 @@ body {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.decision-card {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.decision-top {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.decision-direction {
|
||||
font-size: 16px;
|
||||
font-weight: 800;
|
||||
line-height: 1.2;
|
||||
color: #f8fbff;
|
||||
}
|
||||
|
||||
.decision-window {
|
||||
margin-top: 4px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.decision-confidence {
|
||||
flex: 0 0 auto;
|
||||
padding: 5px 9px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid transparent;
|
||||
font-size: 11px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.decision-confidence.high {
|
||||
color: #86efac;
|
||||
border-color: rgba(52, 211, 153, 0.45);
|
||||
background: rgba(52, 211, 153, 0.12);
|
||||
}
|
||||
|
||||
.decision-confidence.medium {
|
||||
color: #fcd34d;
|
||||
border-color: rgba(245, 158, 11, 0.45);
|
||||
background: rgba(245, 158, 11, 0.12);
|
||||
}
|
||||
|
||||
.decision-confidence.low,
|
||||
.decision-confidence.neutral {
|
||||
color: #cbd5e1;
|
||||
border-color: rgba(148, 163, 184, 0.28);
|
||||
background: rgba(148, 163, 184, 0.1);
|
||||
}
|
||||
|
||||
.decision-summary {
|
||||
color: #dbeafe;
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.decision-reasons {
|
||||
margin: 0;
|
||||
padding-left: 18px;
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.decision-reasons li {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.forecast-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
@@ -276,6 +371,13 @@ body {
|
||||
background: rgba(59, 130, 246, 0.15);
|
||||
}
|
||||
|
||||
.open-full-hint {
|
||||
margin-bottom: 10px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.error {
|
||||
border: 1px solid rgba(248, 113, 113, 0.45);
|
||||
border-radius: 12px;
|
||||
|
||||
@@ -26,6 +26,8 @@
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div id="freshnessHint" class="freshness-hint hidden"></div>
|
||||
|
||||
<section class="section">
|
||||
<h3 id="profileTitle">城市档案</h3>
|
||||
<div class="grid2">
|
||||
@@ -57,12 +59,28 @@
|
||||
<div id="chartLegend" class="legend-text">--</div>
|
||||
</section>
|
||||
|
||||
<section class="section">
|
||||
<h3 id="decisionTitle">方向判断</h3>
|
||||
<div class="decision-card">
|
||||
<div class="decision-top">
|
||||
<div>
|
||||
<div id="decisionDirection" class="decision-direction">--</div>
|
||||
<div id="decisionWindow" class="decision-window">--</div>
|
||||
</div>
|
||||
<div id="decisionConfidence" class="decision-confidence neutral">--</div>
|
||||
</div>
|
||||
<div id="decisionSummary" class="decision-summary">--</div>
|
||||
<ul id="decisionReasons" class="decision-reasons"></ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="section">
|
||||
<h3 id="forecastTitle">多日预报</h3>
|
||||
<div id="forecastRow" class="forecast-row"></div>
|
||||
</section>
|
||||
|
||||
<section class="section">
|
||||
<div id="openFullHint" class="open-full-hint"></div>
|
||||
<button id="openFullBtn" class="btn btn-open-full">打开完整网站分析</button>
|
||||
</section>
|
||||
|
||||
|
||||
+269
-16
@@ -20,6 +20,7 @@ const I18N = {
|
||||
settlementAirport: "结算机场",
|
||||
hko: "香港天文台 (HKO)",
|
||||
cwa: "交通部中央气象署 (CWA)",
|
||||
noaa: "NOAA RCTP(台湾桃园国际机场)",
|
||||
city: "城市",
|
||||
refresh: "刷新数据",
|
||||
cityProfile: "城市档案",
|
||||
@@ -27,19 +28,47 @@ const I18N = {
|
||||
obsUpdate: "观测更新",
|
||||
nearbyStations: "周边站点",
|
||||
intradayTrend: "今日日内走势(简版)",
|
||||
directionTitle: "方向判断",
|
||||
forecast: "多日预报",
|
||||
openFull: "打开完整网站分析",
|
||||
openFull: "打开网站查看更多",
|
||||
openFullHint: "插件只提供基础判断;更多分析请到网站查看。",
|
||||
noTrendData: "暂无趋势数据",
|
||||
noForecast: "暂无多日预报",
|
||||
noContinuousObs: "暂无连续观测",
|
||||
nearbyMonitoringSuffix: "个参与监控",
|
||||
today: "今天",
|
||||
debSeries: "DEB",
|
||||
omSeries: "OM预测",
|
||||
noaaSettlementRef: "NOAA RCTP 结算参考",
|
||||
noaaSettlementLegend:
|
||||
"台北按 NOAA RCTP 最终完成质控后的最高整度摄氏值结算;图中曲线仅作结算参考。",
|
||||
loadCityDetailFailed: "加载城市详情失败",
|
||||
refreshFailed: "刷新温度数据失败",
|
||||
initFailed: "初始化失败",
|
||||
publicReadHint: "当前插件是公开读模式,Token 可留空。请检查后端是否仍开启了接口鉴权。",
|
||||
publicModeHint: "公开模式只需配置 API Base;Token 可留空。"
|
||||
publicModeHint: "公开模式只需配置 API Base;Token 可留空。",
|
||||
freshnessRecent: "数据约 {minutes} 分钟前更新。",
|
||||
freshnessWarn: "数据已 {minutes} 分钟未更新,建议点右上角刷新。",
|
||||
freshnessStale: "数据已 {minutes} 分钟未更新,当前结果可能偏旧,请立即刷新。",
|
||||
directionWarmer: "未来偏升温",
|
||||
directionCooler: "未来偏降温",
|
||||
directionFlat: "方向不清",
|
||||
confidenceHigh: "高置信",
|
||||
confidenceMedium: "中置信",
|
||||
confidenceLow: "低置信",
|
||||
confidenceNeutral: "待观察",
|
||||
decisionWindow: "未来约 {hours} 小时",
|
||||
reasonDebAbove: "DEB 路径高于当前实测,未来窗口上沿约 {delta}{symbol}。",
|
||||
reasonDebBelow: "DEB 路径低于当前实测,未来窗口下沿约 {delta}{symbol}。",
|
||||
reasonObsAboveOm: "当前实测高于 OM 基线约 {delta}{symbol},短时偏暖。",
|
||||
reasonObsBelowOm: "当前实测低于 OM 基线约 {delta}{symbol},短时偏冷。",
|
||||
reasonNearPeak: "当前已接近日内高点,继续上冲空间有限。",
|
||||
reasonRoomToPeak: "当前距日内预测高点仍有约 {delta}{symbol} 空间。",
|
||||
reasonRangeWide: "未来窗口振幅偏大,波动仍可能反复。",
|
||||
reasonRangeTight: "未来窗口振幅较小,更像缓慢推进而非急变。",
|
||||
reasonNoObs: "当前连续实测偏少,方向判断主要依赖短窗预测。",
|
||||
decisionSummaryWarmer: "未来几小时更可能缓慢抬升,板面更容易向高温侧移动。",
|
||||
decisionSummaryCooler: "未来几小时更可能回落,板面更容易向低温侧移动。",
|
||||
decisionSummaryFlat: "未来几小时更像震荡整理,短时升降温方向不够清晰。"
|
||||
},
|
||||
en: {
|
||||
loadingWeather: "Loading weather data...",
|
||||
@@ -52,6 +81,7 @@ const I18N = {
|
||||
settlementAirport: "Settlement Airport",
|
||||
hko: "Hong Kong Observatory (HKO)",
|
||||
cwa: "Central Weather Administration (CWA)",
|
||||
noaa: "NOAA RCTP (Taiwan Taoyuan International Airport)",
|
||||
city: "City",
|
||||
refresh: "Refresh data",
|
||||
cityProfile: "City Profile",
|
||||
@@ -59,19 +89,47 @@ const I18N = {
|
||||
obsUpdate: "Observation Update",
|
||||
nearbyStations: "Nearby Stations",
|
||||
intradayTrend: "Today's Intraday Trend",
|
||||
directionTitle: "Direction Bias",
|
||||
forecast: "Forecast",
|
||||
openFull: "Open Full Site Analysis",
|
||||
openFull: "Open Website for More",
|
||||
openFullHint: "The extension only provides a basic bias. Visit the site for more analysis.",
|
||||
noTrendData: "No trend data available",
|
||||
noForecast: "No multi-day forecast",
|
||||
noContinuousObs: "No continuous observations",
|
||||
nearbyMonitoringSuffix: " stations monitored",
|
||||
today: "Today",
|
||||
debSeries: "DEB",
|
||||
omSeries: "OM Forecast",
|
||||
noaaSettlementRef: "NOAA RCTP Settlement Reference",
|
||||
noaaSettlementLegend:
|
||||
"Taipei settles on NOAA RCTP using the finalized highest rounded whole-degree Celsius reading; the plotted line is only a settlement reference.",
|
||||
loadCityDetailFailed: "Failed to load city detail",
|
||||
refreshFailed: "Failed to refresh weather data",
|
||||
initFailed: "Initialization failed",
|
||||
publicReadHint: "The extension is in public read mode. Token can be empty. Check whether the backend still requires auth.",
|
||||
publicModeHint: "In public mode only API Base is required; Token can be empty."
|
||||
publicModeHint: "In public mode only API Base is required; Token can be empty.",
|
||||
freshnessRecent: "Data updated about {minutes} min ago.",
|
||||
freshnessWarn: "Data is {minutes} min old. Consider refreshing.",
|
||||
freshnessStale: "Data is {minutes} min old and may be stale. Refresh now.",
|
||||
directionWarmer: "Bias Warmer",
|
||||
directionCooler: "Bias Cooler",
|
||||
directionFlat: "Direction Unclear",
|
||||
confidenceHigh: "High Conviction",
|
||||
confidenceMedium: "Medium Conviction",
|
||||
confidenceLow: "Low Conviction",
|
||||
confidenceNeutral: "Watch",
|
||||
decisionWindow: "Next ~{hours}h",
|
||||
reasonDebAbove: "DEB path sits above current observation, with about {delta}{symbol} upside in the window.",
|
||||
reasonDebBelow: "DEB path sits below current observation, with about {delta}{symbol} downside in the window.",
|
||||
reasonObsAboveOm: "Current observation runs about {delta}{symbol} above the OM baseline, keeping the short-term tone warmer.",
|
||||
reasonObsBelowOm: "Current observation runs about {delta}{symbol} below the OM baseline, keeping the short-term tone cooler.",
|
||||
reasonNearPeak: "Current temperature is already close to the intraday peak, limiting further upside.",
|
||||
reasonRoomToPeak: "There is still about {delta}{symbol} room to the projected intraday peak.",
|
||||
reasonRangeWide: "The next-window range is wide, so the path can still swing around.",
|
||||
reasonRangeTight: "The next-window range is tight, pointing to a gradual move rather than a sharp break.",
|
||||
reasonNoObs: "Continuous observations are sparse, so the bias relies more on the short-window forecast.",
|
||||
decisionSummaryWarmer: "The next few hours are more likely to drift warmer, so the board should lean toward the hotter side.",
|
||||
decisionSummaryCooler: "The next few hours are more likely to ease lower, so the board should lean toward the cooler side.",
|
||||
decisionSummaryFlat: "The next few hours look more range-bound, so there is no clear temperature direction yet."
|
||||
}
|
||||
};
|
||||
|
||||
@@ -107,6 +165,7 @@ const els = {
|
||||
forecastRow: document.getElementById("forecastRow"),
|
||||
errorBox: document.getElementById("errorBox"),
|
||||
openFullBtn: document.getElementById("openFullBtn"),
|
||||
openFullHint: document.getElementById("openFullHint"),
|
||||
loadingOverlay: document.getElementById("loadingOverlay"),
|
||||
loadingText: document.getElementById("loadingText"),
|
||||
cityLabel: document.getElementById("cityLabel"),
|
||||
@@ -115,7 +174,14 @@ const els = {
|
||||
obsTimeLabel: document.getElementById("obsTimeLabel"),
|
||||
nearbyLabel: document.getElementById("nearbyLabel"),
|
||||
trendTitle: document.getElementById("trendTitle"),
|
||||
forecastTitle: document.getElementById("forecastTitle")
|
||||
decisionTitle: document.getElementById("decisionTitle"),
|
||||
decisionDirection: document.getElementById("decisionDirection"),
|
||||
decisionWindow: document.getElementById("decisionWindow"),
|
||||
decisionConfidence: document.getElementById("decisionConfidence"),
|
||||
decisionSummary: document.getElementById("decisionSummary"),
|
||||
decisionReasons: document.getElementById("decisionReasons"),
|
||||
forecastTitle: document.getElementById("forecastTitle"),
|
||||
freshnessHint: document.getElementById("freshnessHint")
|
||||
};
|
||||
|
||||
function normalizeBase(url) {
|
||||
@@ -258,6 +324,14 @@ function showError(message) {
|
||||
els.errorBox.classList.remove("hidden");
|
||||
}
|
||||
|
||||
function tf(key, params = {}) {
|
||||
let text = t(key);
|
||||
for (const [name, value] of Object.entries(params)) {
|
||||
text = text.replace(`{${name}}`, String(value));
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function clearError() {
|
||||
els.errorBox.textContent = "";
|
||||
els.errorBox.classList.add("hidden");
|
||||
@@ -378,6 +452,12 @@ function getSettlementSourceDisplay(detail) {
|
||||
value: t("cwa")
|
||||
};
|
||||
}
|
||||
if (source === "noaa") {
|
||||
return {
|
||||
label: t("settlementSource"),
|
||||
value: t("noaa")
|
||||
};
|
||||
}
|
||||
const airport = detail?.risk?.airport || "--";
|
||||
const icao = detail?.risk?.icao ? ` (${detail.risk.icao})` : "";
|
||||
return {
|
||||
@@ -400,6 +480,44 @@ function formatForecastDate(day, index) {
|
||||
return `${m[2]}/${m[3]}`;
|
||||
}
|
||||
|
||||
function parseIsoDate(value) {
|
||||
const text = String(value || "").trim();
|
||||
if (!text) return null;
|
||||
const date = new Date(text);
|
||||
if (Number.isNaN(date.getTime())) return null;
|
||||
return date;
|
||||
}
|
||||
|
||||
function renderFreshness(detail) {
|
||||
if (!els.freshnessHint) return;
|
||||
const updatedAt = parseIsoDate(detail?.updated_at);
|
||||
if (!updatedAt) {
|
||||
els.freshnessHint.classList.add("hidden");
|
||||
els.freshnessHint.classList.remove("stale");
|
||||
els.freshnessHint.textContent = "";
|
||||
return;
|
||||
}
|
||||
|
||||
const minutes = Math.max(
|
||||
0,
|
||||
Math.round((Date.now() - updatedAt.getTime()) / 60000)
|
||||
);
|
||||
|
||||
if (minutes < 8) {
|
||||
els.freshnessHint.classList.add("hidden");
|
||||
els.freshnessHint.classList.remove("stale");
|
||||
els.freshnessHint.textContent = "";
|
||||
return;
|
||||
}
|
||||
|
||||
const isStale = minutes >= 20;
|
||||
els.freshnessHint.classList.remove("hidden");
|
||||
els.freshnessHint.classList.toggle("stale", isStale);
|
||||
els.freshnessHint.textContent = isStale
|
||||
? tf("freshnessStale", { minutes })
|
||||
: tf("freshnessWarn", { minutes });
|
||||
}
|
||||
|
||||
function parseTimeToMinute(value) {
|
||||
const text = String(value || "");
|
||||
const m = text.match(/(\d{1,2}):(\d{2})/);
|
||||
@@ -575,7 +693,10 @@ function drawTrendChart(detail) {
|
||||
const points = [...trend, ...obs];
|
||||
const hoverPoints = [];
|
||||
const tempSymbol = detail?.temp_symbol || "°C";
|
||||
const obsSeriesLabel = String(detail?.current?.settlement_source_label || "OBS").toUpperCase();
|
||||
const sourceCode = String(detail?.current?.settlement_source || "").toLowerCase();
|
||||
const obsSeriesLabel = sourceCode === "noaa"
|
||||
? t("noaaSettlementRef")
|
||||
: String(detail?.current?.settlement_source_label || "OBS").toUpperCase();
|
||||
if (!points.length) {
|
||||
setChartHover([], tempSymbol);
|
||||
ctx.fillStyle = "#8ba0be";
|
||||
@@ -635,7 +756,7 @@ function drawTrendChart(detail) {
|
||||
trend.forEach((p, idx) => {
|
||||
const x = canUseMinuteAxis ? xFromMinute(p.m) : xFromIndex(idx, trend.length);
|
||||
const y = yFromValue(p.v);
|
||||
hoverPoints.push({ x, y, time: p.t, value: p.v, series: t("debSeries") });
|
||||
hoverPoints.push({ x, y, time: p.t, value: p.v, series: t("omSeries") });
|
||||
if (idx === 0) ctx.moveTo(x, y);
|
||||
else ctx.lineTo(x, y);
|
||||
});
|
||||
@@ -688,12 +809,129 @@ function drawTrendChart(detail) {
|
||||
setChartHover(hoverPoints, tempSymbol);
|
||||
}
|
||||
|
||||
function renderDecision(detail) {
|
||||
if (!els.decisionDirection || !els.decisionConfidence || !els.decisionSummary || !els.decisionReasons) {
|
||||
return;
|
||||
}
|
||||
|
||||
const symbol = detail?.temp_symbol || "°C";
|
||||
const currentTemp = Number(detail?.current?.temp);
|
||||
const maxSoFar = Number(detail?.current?.max_temp_so_far);
|
||||
const trendRows = extractTrendSeries(detail).trend;
|
||||
const obsRows = getObservationRows(detail);
|
||||
const obsLatest = obsRows.length ? obsRows[obsRows.length - 1] : null;
|
||||
const currentMinute = Number.isFinite(obsLatest?.minute)
|
||||
? obsLatest.minute
|
||||
: parseTimeToMinute(detail?.current?.obs_time);
|
||||
const futureRows = trendRows.filter((row) => Number.isFinite(row.m) && Number.isFinite(currentMinute) ? row.m >= currentMinute : true);
|
||||
const shortWindow = futureRows.slice(0, 4);
|
||||
const hours = Math.max(1, Math.min(4, shortWindow.length || 4));
|
||||
const baseTemp = Number.isFinite(currentTemp)
|
||||
? currentTemp
|
||||
: (obsLatest && Number.isFinite(obsLatest.temp) ? obsLatest.temp : NaN);
|
||||
|
||||
let directionKey = "directionFlat";
|
||||
let summaryKey = "decisionSummaryFlat";
|
||||
let confidenceKey = "confidenceNeutral";
|
||||
let confidenceClass = "neutral";
|
||||
const reasons = [];
|
||||
|
||||
const futureTemps = shortWindow.map((row) => Number(row.v)).filter(Number.isFinite);
|
||||
const futureMax = futureTemps.length ? Math.max(...futureTemps) : Number.NaN;
|
||||
const futureMin = futureTemps.length ? Math.min(...futureTemps) : Number.NaN;
|
||||
const futureEnd = futureTemps.length ? futureTemps[futureTemps.length - 1] : Number.NaN;
|
||||
const projectedDelta = Number.isFinite(baseTemp) && Number.isFinite(futureEnd)
|
||||
? futureEnd - baseTemp
|
||||
: Number.NaN;
|
||||
const windowAmplitude = Number.isFinite(futureMax) && Number.isFinite(futureMin)
|
||||
? futureMax - futureMin
|
||||
: Number.NaN;
|
||||
|
||||
if (Number.isFinite(projectedDelta)) {
|
||||
if (projectedDelta >= 0.8) {
|
||||
directionKey = "directionWarmer";
|
||||
summaryKey = "decisionSummaryWarmer";
|
||||
confidenceKey = projectedDelta >= 1.8 ? "confidenceHigh" : projectedDelta >= 1.2 ? "confidenceMedium" : "confidenceLow";
|
||||
confidenceClass = projectedDelta >= 1.8 ? "high" : projectedDelta >= 1.2 ? "medium" : "low";
|
||||
} else if (projectedDelta <= -0.8) {
|
||||
directionKey = "directionCooler";
|
||||
summaryKey = "decisionSummaryCooler";
|
||||
const absDelta = Math.abs(projectedDelta);
|
||||
confidenceKey = absDelta >= 1.8 ? "confidenceHigh" : absDelta >= 1.2 ? "confidenceMedium" : "confidenceLow";
|
||||
confidenceClass = absDelta >= 1.8 ? "high" : absDelta >= 1.2 ? "medium" : "low";
|
||||
} else {
|
||||
confidenceKey = Math.abs(projectedDelta) >= 0.4 ? "confidenceLow" : "confidenceNeutral";
|
||||
confidenceClass = Math.abs(projectedDelta) >= 0.4 ? "low" : "neutral";
|
||||
}
|
||||
}
|
||||
|
||||
if (Number.isFinite(baseTemp) && Number.isFinite(futureMax)) {
|
||||
const upside = futureMax - baseTemp;
|
||||
const downside = baseTemp - futureMin;
|
||||
if (directionKey === "directionWarmer" && upside > 0.3) {
|
||||
reasons.push(tf("reasonDebAbove", { delta: upside.toFixed(1), symbol }));
|
||||
} else if (directionKey === "directionCooler" && downside > 0.3) {
|
||||
reasons.push(tf("reasonDebBelow", { delta: downside.toFixed(1), symbol }));
|
||||
}
|
||||
}
|
||||
|
||||
if (Number.isFinite(baseTemp) && trendRows.length) {
|
||||
const nearest = trendRows.reduce((best, row) => {
|
||||
if (!Number.isFinite(row.m) || !Number.isFinite(currentMinute)) return best;
|
||||
if (!best) return row;
|
||||
return Math.abs(row.m - currentMinute) < Math.abs(best.m - currentMinute) ? row : best;
|
||||
}, null);
|
||||
if (nearest && Number.isFinite(nearest.v)) {
|
||||
const omGap = baseTemp - nearest.v;
|
||||
if (omGap >= 0.8) {
|
||||
reasons.push(tf("reasonObsAboveOm", { delta: omGap.toFixed(1), symbol }));
|
||||
} else if (omGap <= -0.8) {
|
||||
reasons.push(tf("reasonObsBelowOm", { delta: Math.abs(omGap).toFixed(1), symbol }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Number.isFinite(baseTemp) && Number.isFinite(maxSoFar)) {
|
||||
const gapToPeak = maxSoFar - baseTemp;
|
||||
if (gapToPeak <= 0.6) {
|
||||
reasons.push(t("reasonNearPeak"));
|
||||
} else if (gapToPeak >= 1.2) {
|
||||
reasons.push(tf("reasonRoomToPeak", { delta: gapToPeak.toFixed(1), symbol }));
|
||||
}
|
||||
}
|
||||
|
||||
if (Number.isFinite(windowAmplitude)) {
|
||||
if (windowAmplitude >= 2.2) reasons.push(t("reasonRangeWide"));
|
||||
else if (windowAmplitude <= 1.0) reasons.push(t("reasonRangeTight"));
|
||||
}
|
||||
|
||||
if (!obsRows.length) {
|
||||
reasons.push(t("reasonNoObs"));
|
||||
}
|
||||
|
||||
els.decisionDirection.textContent = t(directionKey);
|
||||
els.decisionWindow.textContent = tf("decisionWindow", { hours });
|
||||
els.decisionConfidence.textContent = t(confidenceKey);
|
||||
els.decisionConfidence.classList.remove("high", "medium", "low", "neutral");
|
||||
els.decisionConfidence.classList.add(confidenceClass);
|
||||
els.decisionSummary.textContent = t(summaryKey);
|
||||
els.decisionReasons.innerHTML = "";
|
||||
for (const reason of reasons.slice(0, 3)) {
|
||||
const li = document.createElement("li");
|
||||
li.textContent = reason;
|
||||
els.decisionReasons.appendChild(li);
|
||||
}
|
||||
}
|
||||
|
||||
function renderForecast(detail) {
|
||||
const symbol = detail?.temp_symbol || "°C";
|
||||
const daily = Array.isArray(detail?.forecast?.daily) ? detail.forecast.daily : [];
|
||||
const dailyDeb = detail?.multi_model_daily || {};
|
||||
els.forecastRow.innerHTML = "";
|
||||
for (let i = 0; i < Math.min(daily.length, 6); i += 1) {
|
||||
const day = daily[i];
|
||||
const debValue = dailyDeb?.[day?.date]?.deb?.prediction;
|
||||
const displayTemp = debValue ?? day?.max_temp;
|
||||
const card = document.createElement("div");
|
||||
card.className = `forecast-card ${i === 0 ? "today" : ""}`;
|
||||
|
||||
@@ -704,7 +942,7 @@ function renderForecast(detail) {
|
||||
|
||||
const v = document.createElement("div");
|
||||
v.className = "f-temp";
|
||||
v.textContent = formatTemp(day?.max_temp, symbol);
|
||||
v.textContent = formatTemp(displayTemp, symbol);
|
||||
card.appendChild(v);
|
||||
|
||||
els.forecastRow.appendChild(card);
|
||||
@@ -717,6 +955,7 @@ function renderForecast(detail) {
|
||||
function renderDetail(detail) {
|
||||
state.detail = detail;
|
||||
renderRiskBadge(detail);
|
||||
renderFreshness(detail);
|
||||
|
||||
const profile = getSettlementSourceDisplay(detail);
|
||||
els.settlementLabel.textContent = profile.label;
|
||||
@@ -731,16 +970,26 @@ function renderDetail(detail) {
|
||||
: `${nearby}${t("nearbyMonitoringSuffix")}`;
|
||||
|
||||
drawTrendChart(detail);
|
||||
renderDecision(detail);
|
||||
renderForecast(detail);
|
||||
|
||||
const sourceTag = String(detail?.current?.settlement_source_label || "").toUpperCase() || "OBS";
|
||||
const sourceCode = String(detail?.current?.settlement_source || "").toLowerCase();
|
||||
const sourceTag = sourceCode === "noaa"
|
||||
? t("noaaSettlementRef")
|
||||
: String(detail?.current?.settlement_source_label || "").toUpperCase() || "OBS";
|
||||
const obs = getObservationRows(detail);
|
||||
if (obs.length >= 2) {
|
||||
const first = obs[0];
|
||||
const last = obs[obs.length - 1];
|
||||
els.chartLegend.textContent = `${sourceTag}: ${first.temp}°C@${first.time} -> ${last.temp}°C@${last.time}`;
|
||||
els.chartLegend.textContent =
|
||||
sourceCode === "noaa"
|
||||
? `${sourceTag}: ${first.temp}°C@${first.time} -> ${last.temp}°C@${last.time} | ${t("noaaSettlementLegend")}`
|
||||
: `${sourceTag}: ${first.temp}°C@${first.time} -> ${last.temp}°C@${last.time}`;
|
||||
} else {
|
||||
els.chartLegend.textContent = `${sourceTag}: ${t("noContinuousObs")}`;
|
||||
els.chartLegend.textContent =
|
||||
sourceCode === "noaa"
|
||||
? `${sourceTag}: ${t("noContinuousObs")} | ${t("noaaSettlementLegend")}`
|
||||
: `${sourceTag}: ${t("noContinuousObs")}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -777,6 +1026,10 @@ function normalizeAggregateDetail(payload) {
|
||||
forecast: {
|
||||
daily: Array.isArray(timeseries.forecast_daily) ? timeseries.forecast_daily : []
|
||||
},
|
||||
multi_model_daily:
|
||||
timeseries.multi_model_daily && typeof timeseries.multi_model_daily === "object"
|
||||
? timeseries.multi_model_daily
|
||||
: {},
|
||||
hourly: timeseries.hourly || { times: [], temps: [] },
|
||||
metar_today_obs: timeseries.metar_today_obs || [],
|
||||
settlement_today_obs: timeseries.settlement_today_obs || [],
|
||||
@@ -793,8 +1046,10 @@ function applyStaticTranslations() {
|
||||
if (els.obsTimeLabel) els.obsTimeLabel.textContent = t("obsUpdate");
|
||||
if (els.nearbyLabel) els.nearbyLabel.textContent = t("nearbyStations");
|
||||
if (els.trendTitle) els.trendTitle.textContent = t("intradayTrend");
|
||||
if (els.decisionTitle) els.decisionTitle.textContent = t("directionTitle");
|
||||
if (els.forecastTitle) els.forecastTitle.textContent = t("forecast");
|
||||
if (els.openFullBtn) els.openFullBtn.textContent = t("openFull");
|
||||
if (els.openFullHint) els.openFullHint.textContent = t("openFullHint");
|
||||
if (els.refreshBtn) {
|
||||
els.refreshBtn.title = t("refresh");
|
||||
els.refreshBtn.setAttribute("aria-label", t("refresh"));
|
||||
@@ -944,10 +1199,8 @@ function bindUrlSync() {
|
||||
}
|
||||
|
||||
function openMainSite(view) {
|
||||
const city = encodeURIComponent(state.config.selectedCity || "");
|
||||
const siteBase = normalizeBase(state.config.siteBase || state.config.apiBase);
|
||||
const url = `${siteBase}/?city=${city}&view=${encodeURIComponent(view || "dashboard")}`;
|
||||
chrome.tabs.create({ url });
|
||||
chrome.tabs.create({ url: siteBase });
|
||||
}
|
||||
|
||||
function bindEvents() {
|
||||
|
||||
+28
-5
@@ -1,12 +1,35 @@
|
||||
# PolyWeather 前端最小配置(本地 / Vercel)
|
||||
# 只部署天气看板时,先填下面 4 项即可。
|
||||
|
||||
# 必填:后端 FastAPI 基础地址
|
||||
POLYWEATHER_API_BASE_URL=http://127.0.0.1:8000
|
||||
# Supabase Auth (Google + Email)
|
||||
|
||||
# 必填:Supabase 前端公钥(鉴权开启时必须)
|
||||
NEXT_PUBLIC_SUPABASE_URL=
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=
|
||||
|
||||
# 常用:前端鉴权开关
|
||||
# true: 启用 Supabase 登录
|
||||
# false: 关闭登录能力,访客模式
|
||||
POLYWEATHER_AUTH_ENABLED=false
|
||||
# If true: middleware forces login; if false: optional login mode (guests allowed).
|
||||
|
||||
# 常用:是否强制登录
|
||||
# true: middleware 强制登录后才能访问主页面
|
||||
# false: 登录可选,访客可浏览
|
||||
POLYWEATHER_AUTH_REQUIRED=false
|
||||
# Optional dashboard guard (Next.js middleware)
|
||||
# If set, open dashboard with: /?access_token=<token>
|
||||
|
||||
# 可选:分享式看板访问令牌
|
||||
# 设置后,可通过 /?access_token=<token> 打开受保护看板
|
||||
POLYWEATHER_DASHBOARD_ACCESS_TOKEN=
|
||||
# Shared secret forwarded by Next API routes to backend
|
||||
|
||||
# 可选:前端 API Route 转发到后端时附带的共享令牌
|
||||
# 仅当后端启用了 entitlement / 订阅校验时需要
|
||||
POLYWEATHER_BACKEND_ENTITLEMENT_TOKEN=
|
||||
|
||||
# 可选:钱包支付 / Telegram 入口
|
||||
NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID=
|
||||
NEXT_PUBLIC_WALLETCONNECT_POLYGON_RPC_URL=https://polygon-bor-rpc.publicnode.com
|
||||
NEXT_PUBLIC_PAYMENT_ALLOWED_HOSTS=polyweather-pro.vercel.app
|
||||
POLYWEATHER_OPS_ADMIN_EMAILS=yhrsc30@gmail.com
|
||||
NEXT_PUBLIC_TELEGRAM_GROUP_URL=https://t.me/your_group
|
||||
NEXT_PUBLIC_TELEGRAM_BOT_URL=https://t.me/WeatherQuant_bot
|
||||
|
||||
+98
-11
@@ -19,6 +19,20 @@ PolyWeather Pro 的生产前端工程。
|
||||
2. Next Route Handlers(`/api/*`)-> FastAPI 后端
|
||||
3. FastAPI -> 分析服务 / 支付服务
|
||||
|
||||
## 当前前端能力
|
||||
|
||||
- 主站 Dashboard 支持地图、城市详情、今日日内分析、历史准确率对账和账户中心
|
||||
- `/docs` 已提供公开双语产品文档中心,解释日内结构信号、TAF、结算来源和历史对账
|
||||
- 今日日内分析支持:
|
||||
- 峰值窗口感知的近地面结构信号
|
||||
- 高空结构信号
|
||||
- 交易动作卡
|
||||
- 非香港机场城市的 `TAF` 时段提示与走势图联动
|
||||
- 历史对账支持:
|
||||
- `DEB / 最佳单模型 / 实测最高温` 对比
|
||||
- 峰值前 12 小时 `DEB` 参考(近似)
|
||||
- `/ops` 已支持桌面表格 + 手机端卡片化视图
|
||||
|
||||
## 本地开发
|
||||
|
||||
```bash
|
||||
@@ -28,30 +42,55 @@ npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## 必需环境变量
|
||||
## Vercel 最小部署配置
|
||||
|
||||
只跑看板和基础鉴权时,先填这 4 项:
|
||||
|
||||
```env
|
||||
POLYWEATHER_API_BASE_URL=https://<your-fastapi-host>
|
||||
NEXT_PUBLIC_SUPABASE_URL=
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=
|
||||
NEXT_PUBLIC_SUPABASE_URL=https://<your-supabase-project>.supabase.co
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY=<your-anon-key>
|
||||
POLYWEATHER_AUTH_ENABLED=true
|
||||
POLYWEATHER_AUTH_REQUIRED=false
|
||||
POLYWEATHER_BACKEND_ENTITLEMENT_TOKEN=
|
||||
```
|
||||
|
||||
WalletConnect:
|
||||
建议显式补:
|
||||
|
||||
```env
|
||||
POLYWEATHER_AUTH_REQUIRED=true
|
||||
```
|
||||
|
||||
如果你只是开放游客浏览,可改成:
|
||||
|
||||
```env
|
||||
POLYWEATHER_AUTH_ENABLED=false
|
||||
POLYWEATHER_AUTH_REQUIRED=false
|
||||
```
|
||||
|
||||
## 可选环境变量
|
||||
|
||||
仅在对应功能启用时填写:
|
||||
|
||||
```env
|
||||
# 看板分享令牌
|
||||
POLYWEATHER_DASHBOARD_ACCESS_TOKEN=
|
||||
|
||||
# 前端 API 转发到后端时使用的共享令牌
|
||||
POLYWEATHER_BACKEND_ENTITLEMENT_TOKEN=
|
||||
|
||||
# 钱包支付
|
||||
NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID=
|
||||
NEXT_PUBLIC_WALLETCONNECT_POLYGON_RPC_URL=https://polygon-bor-rpc.publicnode.com
|
||||
```
|
||||
NEXT_PUBLIC_PAYMENT_ALLOWED_HOSTS=polyweather-pro.vercel.app
|
||||
POLYWEATHER_OPS_ADMIN_EMAILS=yhrsc30@gmail.com
|
||||
|
||||
浮层链接:
|
||||
|
||||
```env
|
||||
# 社群入口
|
||||
NEXT_PUBLIC_TELEGRAM_GROUP_URL=https://t.me/<your_group>
|
||||
NEXT_PUBLIC_TELEGRAM_BOT_URL=https://t.me/WeatherQuant_bot
|
||||
```
|
||||
|
||||
更完整的 Vercel 配置说明见:
|
||||
- [docs/FRONTEND_DEPLOYMENT_ZH.md](/E:/web/PolyWeather/docs/FRONTEND_DEPLOYMENT_ZH.md)
|
||||
|
||||
## 路由处理器
|
||||
|
||||
天气:
|
||||
@@ -77,6 +116,54 @@ NEXT_PUBLIC_TELEGRAM_GROUP_URL=https://t.me/<your_group>
|
||||
- `POST /api/payments/intents/[intentId]/submit`
|
||||
- `POST /api/payments/intents/[intentId]/confirm`
|
||||
|
||||
Ops:
|
||||
|
||||
- `GET /ops`
|
||||
- `GET /api/ops/users`
|
||||
- `GET /api/ops/leaderboard/weekly`
|
||||
- `GET /api/ops/memberships`
|
||||
- `GET /api/ops/payments/incidents`
|
||||
- `POST /api/ops/users/grant-points`
|
||||
- `POST /api/ops/payments/incidents/[eventId]/resolve`
|
||||
|
||||
## Ops 管理后台
|
||||
|
||||
当前前端已内置轻量管理页:
|
||||
|
||||
- [https://polyweather-pro.vercel.app/ops](https://polyweather-pro.vercel.app/ops)
|
||||
|
||||
页面当前支持:
|
||||
|
||||
- 系统状态
|
||||
- SQLite / rollout / 支付运行态
|
||||
- 用户查询
|
||||
- 当前会员
|
||||
- 本周积分榜
|
||||
- 手动补分
|
||||
- 支付异常单筛选与标记已处理
|
||||
- 手机端卡片化视图
|
||||
|
||||
注意:
|
||||
|
||||
- `/ops` 现在是前后端双层管理员限制
|
||||
- Vercel 前端和后端都应配置相同的 `POLYWEATHER_OPS_ADMIN_EMAILS`
|
||||
- 前端登录邮箱本身不会自动获得管理员权限
|
||||
|
||||
## 支付安全补充
|
||||
|
||||
为降低“旧页面/旧配置导致打到旧收款地址”的风险,支付区现在会:
|
||||
|
||||
1. 点击支付前重新请求 `/api/payments/config`
|
||||
2. 若 `receiver_contract` 已更新,先切到最新地址
|
||||
3. 若后端返回的 `tx_payload.to` 与最新地址不一致,直接阻断支付
|
||||
4. 仅允许在 `NEXT_PUBLIC_PAYMENT_ALLOWED_HOSTS` 白名单域名上创建 payment intent
|
||||
5. 支付区会明确显示当前账号、付款钱包和收款合约,避免账号/钱包/地址混淆
|
||||
|
||||
这意味着:
|
||||
|
||||
- 旧标签页风险已明显降低
|
||||
- 但支付地址变更后,仍建议在 Vercel 上 redeploy 当前 production,并清理明显过期 deployment
|
||||
|
||||
## 缓存行为
|
||||
|
||||
- `cities` / `summary` / `history`:`ETag + Cache-Control`
|
||||
@@ -90,4 +177,4 @@ NEXT_PUBLIC_TELEGRAM_GROUP_URL=https://t.me/<your_group>
|
||||
|
||||
详见根目录策略文档:`docs/OPEN_CORE_POLICY.md`
|
||||
|
||||
最后更新:`2026-03-14`
|
||||
最后更新:`2026-03-24`
|
||||
|
||||
@@ -20,6 +20,14 @@ export async function GET(req: NextRequest) {
|
||||
headers: auth.headers,
|
||||
cache: "no-store",
|
||||
});
|
||||
if (res.status === 401 || res.status === 403) {
|
||||
const response = NextResponse.json({
|
||||
authenticated: false,
|
||||
subscription_active: false,
|
||||
points: 0,
|
||||
});
|
||||
return applyAuthResponseCookies(response, auth.response);
|
||||
}
|
||||
if (!res.ok) {
|
||||
const raw = await res.text();
|
||||
const response = NextResponse.json(
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
applyAuthResponseCookies,
|
||||
buildBackendRequestHeaders,
|
||||
} from "@/lib/backend-auth";
|
||||
|
||||
const API_BASE = process.env.POLYWEATHER_API_BASE_URL;
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
if (!API_BASE) {
|
||||
return NextResponse.json(
|
||||
{ error: "POLYWEATHER_API_BASE_URL is not configured" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await buildBackendRequestHeaders(req);
|
||||
const res = await fetch(`${API_BASE}/healthz`, {
|
||||
headers: auth.headers,
|
||||
cache: "no-store",
|
||||
});
|
||||
const raw = await res.text();
|
||||
const response = new NextResponse(raw, {
|
||||
status: res.status,
|
||||
headers: {
|
||||
"Content-Type": res.headers.get("content-type") || "application/json",
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
});
|
||||
return applyAuthResponseCookies(response, auth.response);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch healthz", detail: String(error) },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
applyAuthResponseCookies,
|
||||
buildBackendRequestHeaders,
|
||||
} from "@/lib/backend-auth";
|
||||
|
||||
const API_BASE = process.env.POLYWEATHER_API_BASE_URL;
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
if (!API_BASE) {
|
||||
return NextResponse.json(
|
||||
{ error: "POLYWEATHER_API_BASE_URL is not configured" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await buildBackendRequestHeaders(req);
|
||||
const url = new URL(`${API_BASE}/api/ops/leaderboard/weekly`);
|
||||
const limit = req.nextUrl.searchParams.get("limit");
|
||||
if (limit) url.searchParams.set("limit", limit);
|
||||
|
||||
const res = await fetch(url.toString(), {
|
||||
headers: auth.headers,
|
||||
cache: "no-store",
|
||||
});
|
||||
const raw = await res.text();
|
||||
const response = new NextResponse(raw, {
|
||||
status: res.status,
|
||||
headers: {
|
||||
"Content-Type": res.headers.get("content-type") || "application/json",
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
});
|
||||
return applyAuthResponseCookies(response, auth.response);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch weekly leaderboard", detail: String(error) },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
applyAuthResponseCookies,
|
||||
buildBackendRequestHeaders,
|
||||
} from "@/lib/backend-auth";
|
||||
|
||||
const API_BASE = process.env.POLYWEATHER_API_BASE_URL;
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
if (!API_BASE) {
|
||||
return NextResponse.json(
|
||||
{ error: "POLYWEATHER_API_BASE_URL is not configured" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await buildBackendRequestHeaders(req);
|
||||
const url = new URL(`${API_BASE}/api/ops/memberships`);
|
||||
const limit = req.nextUrl.searchParams.get("limit");
|
||||
if (limit) url.searchParams.set("limit", limit);
|
||||
|
||||
const res = await fetch(url.toString(), {
|
||||
headers: auth.headers,
|
||||
cache: "no-store",
|
||||
});
|
||||
const raw = await res.text();
|
||||
const response = new NextResponse(raw, {
|
||||
status: res.status,
|
||||
headers: {
|
||||
"Content-Type": res.headers.get("content-type") || "application/json",
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
});
|
||||
return applyAuthResponseCookies(response, auth.response);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch memberships", detail: String(error) },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
applyAuthResponseCookies,
|
||||
buildBackendRequestHeaders,
|
||||
} from "@/lib/backend-auth";
|
||||
|
||||
const API_BASE = process.env.POLYWEATHER_API_BASE_URL;
|
||||
|
||||
type RouteContext = {
|
||||
params: Promise<{ eventId: string }>;
|
||||
};
|
||||
|
||||
export async function POST(req: NextRequest, context: RouteContext) {
|
||||
if (!API_BASE) {
|
||||
return NextResponse.json(
|
||||
{ error: "POLYWEATHER_API_BASE_URL is not configured" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await buildBackendRequestHeaders(req);
|
||||
const { eventId } = await context.params;
|
||||
const res = await fetch(`${API_BASE}/api/ops/payments/incidents/${eventId}/resolve`, {
|
||||
method: "POST",
|
||||
headers: auth.headers,
|
||||
cache: "no-store",
|
||||
});
|
||||
const raw = await res.text();
|
||||
const response = new NextResponse(raw, {
|
||||
status: res.status,
|
||||
headers: {
|
||||
"Content-Type": res.headers.get("content-type") || "application/json",
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
});
|
||||
return applyAuthResponseCookies(response, auth.response);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to resolve payment incident", detail: String(error) },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
applyAuthResponseCookies,
|
||||
buildBackendRequestHeaders,
|
||||
} from "@/lib/backend-auth";
|
||||
|
||||
const API_BASE = process.env.POLYWEATHER_API_BASE_URL;
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
if (!API_BASE) {
|
||||
return NextResponse.json(
|
||||
{ error: "POLYWEATHER_API_BASE_URL is not configured" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await buildBackendRequestHeaders(req);
|
||||
const url = new URL(`${API_BASE}/api/ops/payments/incidents`);
|
||||
const limit = req.nextUrl.searchParams.get("limit");
|
||||
if (limit) url.searchParams.set("limit", limit);
|
||||
|
||||
const res = await fetch(url.toString(), {
|
||||
headers: auth.headers,
|
||||
cache: "no-store",
|
||||
});
|
||||
const raw = await res.text();
|
||||
const response = new NextResponse(raw, {
|
||||
status: res.status,
|
||||
headers: {
|
||||
"Content-Type": res.headers.get("content-type") || "application/json",
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
});
|
||||
return applyAuthResponseCookies(response, auth.response);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch payment incidents", detail: String(error) },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
applyAuthResponseCookies,
|
||||
buildBackendRequestHeaders,
|
||||
} from "@/lib/backend-auth";
|
||||
|
||||
const API_BASE = process.env.POLYWEATHER_API_BASE_URL;
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
if (!API_BASE) {
|
||||
return NextResponse.json(
|
||||
{ error: "POLYWEATHER_API_BASE_URL is not configured" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await buildBackendRequestHeaders(req);
|
||||
const body = await req.text();
|
||||
const res = await fetch(`${API_BASE}/api/ops/users/grant-points`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
...auth.headers,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body,
|
||||
cache: "no-store",
|
||||
});
|
||||
const raw = await res.text();
|
||||
const response = new NextResponse(raw, {
|
||||
status: res.status,
|
||||
headers: {
|
||||
"Content-Type": res.headers.get("content-type") || "application/json",
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
});
|
||||
return applyAuthResponseCookies(response, auth.response);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to grant points", detail: String(error) },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
applyAuthResponseCookies,
|
||||
buildBackendRequestHeaders,
|
||||
} from "@/lib/backend-auth";
|
||||
|
||||
const API_BASE = process.env.POLYWEATHER_API_BASE_URL;
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
if (!API_BASE) {
|
||||
return NextResponse.json(
|
||||
{ error: "POLYWEATHER_API_BASE_URL is not configured" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await buildBackendRequestHeaders(req);
|
||||
const url = new URL(`${API_BASE}/api/ops/users`);
|
||||
const q = req.nextUrl.searchParams.get("q");
|
||||
const limit = req.nextUrl.searchParams.get("limit");
|
||||
if (q) url.searchParams.set("q", q);
|
||||
if (limit) url.searchParams.set("limit", limit);
|
||||
|
||||
const res = await fetch(url.toString(), {
|
||||
headers: auth.headers,
|
||||
cache: "no-store",
|
||||
});
|
||||
const raw = await res.text();
|
||||
const response = new NextResponse(raw, {
|
||||
status: res.status,
|
||||
headers: {
|
||||
"Content-Type": res.headers.get("content-type") || "application/json",
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
});
|
||||
return applyAuthResponseCookies(response, auth.response);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch ops users", detail: String(error) },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
applyAuthResponseCookies,
|
||||
buildBackendRequestHeaders,
|
||||
} from "@/lib/backend-auth";
|
||||
import { isPaymentHostAllowed } from "@/lib/payment-host";
|
||||
|
||||
const API_BASE = process.env.POLYWEATHER_API_BASE_URL;
|
||||
|
||||
@@ -13,6 +14,20 @@ export async function POST(req: NextRequest) {
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
const requestHost =
|
||||
req.headers.get("x-forwarded-host") ||
|
||||
req.headers.get("host") ||
|
||||
req.nextUrl.hostname;
|
||||
if (!isPaymentHostAllowed(requestHost)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"Payments are disabled on this host. Please return to the main production site and retry.",
|
||||
host: requestHost,
|
||||
},
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
try {
|
||||
const body = await req.json();
|
||||
const auth = await buildBackendRequestHeaders(req);
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
applyAuthResponseCookies,
|
||||
buildBackendRequestHeaders,
|
||||
} from "@/lib/backend-auth";
|
||||
|
||||
const API_BASE = process.env.POLYWEATHER_API_BASE_URL;
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
if (!API_BASE) {
|
||||
return NextResponse.json(
|
||||
{ error: "POLYWEATHER_API_BASE_URL is not configured" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await buildBackendRequestHeaders(req);
|
||||
const res = await fetch(`${API_BASE}/api/payments/reconcile-latest`, {
|
||||
method: "POST",
|
||||
headers: auth.headers,
|
||||
cache: "no-store",
|
||||
});
|
||||
const raw = await res.text();
|
||||
const response = new NextResponse(raw, {
|
||||
status: res.status,
|
||||
headers: {
|
||||
"content-type":
|
||||
res.headers.get("content-type") || "application/json; charset=utf-8",
|
||||
},
|
||||
});
|
||||
return applyAuthResponseCookies(response, auth.response);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to reconcile latest payment", detail: String(error) },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
applyAuthResponseCookies,
|
||||
buildBackendRequestHeaders,
|
||||
} from "@/lib/backend-auth";
|
||||
|
||||
const API_BASE = process.env.POLYWEATHER_API_BASE_URL;
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
if (!API_BASE) {
|
||||
return NextResponse.json(
|
||||
{ error: "POLYWEATHER_API_BASE_URL is not configured" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await buildBackendRequestHeaders(req);
|
||||
const res = await fetch(`${API_BASE}/api/payments/runtime`, {
|
||||
headers: auth.headers,
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) {
|
||||
const raw = await res.text();
|
||||
const response = NextResponse.json(
|
||||
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 500) },
|
||||
{ status: res.status },
|
||||
);
|
||||
return applyAuthResponseCookies(response, auth.response);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const response = NextResponse.json(data, {
|
||||
headers: { "Cache-Control": "no-store" },
|
||||
});
|
||||
return applyAuthResponseCookies(response, auth.response);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch payment runtime", detail: String(error) },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import {
|
||||
applyAuthResponseCookies,
|
||||
buildBackendRequestHeaders,
|
||||
} from "@/lib/backend-auth";
|
||||
|
||||
const API_BASE = process.env.POLYWEATHER_API_BASE_URL;
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
if (!API_BASE) {
|
||||
return NextResponse.json(
|
||||
{ error: "POLYWEATHER_API_BASE_URL is not configured" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const auth = await buildBackendRequestHeaders(req);
|
||||
const res = await fetch(`${API_BASE}/api/system/status`, {
|
||||
headers: auth.headers,
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) {
|
||||
const raw = await res.text();
|
||||
const response = NextResponse.json(
|
||||
{ error: `Backend returned ${res.status}`, detail: raw.slice(0, 500) },
|
||||
{ status: res.status },
|
||||
);
|
||||
return applyAuthResponseCookies(response, auth.response);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
const response = NextResponse.json(data, {
|
||||
headers: { "Cache-Control": "no-store" },
|
||||
});
|
||||
return applyAuthResponseCookies(response, auth.response);
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch system status", detail: String(error) },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { DocsScreen } from "@/components/docs/DocsScreen";
|
||||
import { DOCS_PAGES, getDocsPage } from "@/content/docs/docs";
|
||||
|
||||
export function generateStaticParams() {
|
||||
return DOCS_PAGES.map((page) => ({ slug: [page.slug] }));
|
||||
}
|
||||
|
||||
export default async function DocsDetailPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ slug?: string[] }>;
|
||||
}) {
|
||||
const resolvedParams = await params;
|
||||
if ((resolvedParams.slug?.length || 0) > 1) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
const slug = resolvedParams.slug?.[0] || "intro";
|
||||
const page = getDocsPage(slug);
|
||||
|
||||
if (!page) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
return <DocsScreen page={page} />;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { I18nProvider } from "@/hooks/useI18n";
|
||||
|
||||
export default function DocsLayout({ children }: { children: React.ReactNode }) {
|
||||
return <I18nProvider>{children}</I18nProvider>;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
export default function DocsIndexPage() {
|
||||
redirect("/docs/intro");
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Analytics } from "@vercel/analytics/react";
|
||||
import { SpeedInsights } from "@vercel/speed-insights/next";
|
||||
import { WebVitalsReporter } from "@/components/observability/WebVitalsReporter";
|
||||
import "./globals.css";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
@@ -35,9 +33,7 @@ export default function RootLayout({
|
||||
</head>
|
||||
<body className="min-h-screen font-sans antialiased">
|
||||
{children}
|
||||
<WebVitalsReporter />
|
||||
<Analytics />
|
||||
<SpeedInsights />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Metadata } from "next";
|
||||
import { OpsDashboard } from "@/components/ops/OpsDashboard";
|
||||
import { requireOpsAdmin } from "@/lib/ops-admin";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "PolyWeather Ops",
|
||||
description: "PolyWeather lightweight operations dashboard.",
|
||||
};
|
||||
|
||||
export default async function OpsPage() {
|
||||
await requireOpsAdmin("/ops");
|
||||
return <OpsDashboard />;
|
||||
}
|
||||
@@ -390,6 +390,10 @@
|
||||
.cards {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.metaList dd {
|
||||
max-width: 56%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 560px) {
|
||||
@@ -414,5 +418,74 @@
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.ghostBtn,
|
||||
.primaryBtn {
|
||||
min-height: 40px;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.heroCard {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
border-radius: 16px;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.heroMain h2 {
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.updatedText {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.metaList > div {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.metaList dd {
|
||||
max-width: 100%;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.commandRow {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.command {
|
||||
flex: 1 1 auto;
|
||||
width: 100%;
|
||||
min-height: 48px;
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.copyBtn {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.noticeRow,
|
||||
.errorRow {
|
||||
width: 100%;
|
||||
align-items: flex-start;
|
||||
line-height: 1.5;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -165,6 +165,23 @@ export function CitySidebar() {
|
||||
const summary = store.citySummariesByName[city.name];
|
||||
const snapshot = detail || summary;
|
||||
const isActive = store.selectedCity === city.name;
|
||||
const tempSymbol = snapshot?.temp_symbol || "°C";
|
||||
const currentTempText =
|
||||
snapshot?.current?.temp != null
|
||||
? t("sidebar.currentTemp", {
|
||||
temp: `${snapshot.current.temp}${tempSymbol}`,
|
||||
})
|
||||
: t("common.na");
|
||||
const peakTempText =
|
||||
detail?.current?.max_so_far != null &&
|
||||
detail.current.max_temp_time
|
||||
? t("sidebar.peakTempAt", {
|
||||
temp: `${detail.current.max_so_far}${tempSymbol}`,
|
||||
time: detail.current.max_temp_time,
|
||||
})
|
||||
: detail?.current?.max_temp_time
|
||||
? t("sidebar.peakAt", { time: detail.current.max_temp_time })
|
||||
: "";
|
||||
|
||||
return (
|
||||
<button
|
||||
@@ -186,9 +203,7 @@ export function CitySidebar() {
|
||||
snapshot?.current?.temp != null && "loaded",
|
||||
)}
|
||||
>
|
||||
{snapshot?.current?.temp != null
|
||||
? `${snapshot.current.temp}${snapshot.temp_symbol || "°C"}`
|
||||
: t("common.na")}
|
||||
{currentTempText}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -196,11 +211,7 @@ export function CitySidebar() {
|
||||
<span className="city-local-time">
|
||||
{snapshot?.local_time ? `🕒 ${snapshot.local_time}` : ""}
|
||||
</span>
|
||||
<span className="city-max-info">
|
||||
{detail?.current?.max_temp_time
|
||||
? t("sidebar.peakAt", { time: detail.current.max_temp_time })
|
||||
: ""}
|
||||
</span>
|
||||
<span className="city-max-info">{peakTempText}</span>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,11 +2,13 @@
|
||||
|
||||
import type { ChartConfiguration } from "chart.js";
|
||||
import clsx from "clsx";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ForecastTable } from "@/components/dashboard/PanelSections";
|
||||
import { useChart } from "@/hooks/useChart";
|
||||
import { useDashboardStore } from "@/hooks/useDashboardStore";
|
||||
import { useI18n } from "@/hooks/useI18n";
|
||||
import { getOfficialSourceLinks } from "@/lib/dashboard-official-sources";
|
||||
import { getCityScenery } from "@/lib/dashboard-scenery";
|
||||
import { CityDetail } from "@/lib/dashboard-types";
|
||||
import {
|
||||
@@ -129,24 +131,42 @@ function DetailMiniTemperatureChart({ detail }: { detail: CityDetail }) {
|
||||
export function DetailPanel() {
|
||||
const store = useDashboardStore();
|
||||
const { locale, t } = useI18n();
|
||||
const router = useRouter();
|
||||
const detail = store.selectedDetail;
|
||||
const selectedCityItem = useMemo(
|
||||
() =>
|
||||
store.selectedCity
|
||||
? store.cities.find((city) => city.name === store.selectedCity) || null
|
||||
: null,
|
||||
[store.cities, store.selectedCity],
|
||||
);
|
||||
const isPro = store.proAccess.subscriptionActive;
|
||||
const isAuthenticated = store.proAccess.authenticated;
|
||||
const panelRef = useRef<HTMLElement | null>(null);
|
||||
const [heavyContentReady, setHeavyContentReady] = useState(false);
|
||||
const isOverlayOpen =
|
||||
Boolean(store.futureModalDate) ||
|
||||
store.historyState.isOpen ||
|
||||
store.isGuideOpen;
|
||||
store.historyState.isOpen;
|
||||
const isVisible =
|
||||
store.isPanelOpen &&
|
||||
Boolean(store.selectedCity) &&
|
||||
Boolean(detail) &&
|
||||
!store.loadingState.cityDetail &&
|
||||
!isOverlayOpen;
|
||||
const panelDisplayName =
|
||||
detail?.display_name ||
|
||||
selectedCityItem?.display_name ||
|
||||
store.selectedCity ||
|
||||
"...";
|
||||
const panelRiskLevel = detail?.risk?.level || selectedCityItem?.risk_level || "low";
|
||||
const profileStats = useMemo(
|
||||
() => (detail ? getCityProfileStats(detail, locale) : []),
|
||||
[detail, locale],
|
||||
);
|
||||
const officialLinks = useMemo(
|
||||
() => (detail ? getOfficialSourceLinks(detail) : []),
|
||||
[detail],
|
||||
);
|
||||
const scenery = getCityScenery(detail?.name);
|
||||
const blurActiveElement = () => {
|
||||
if (typeof document === "undefined") return;
|
||||
@@ -155,6 +175,29 @@ export function DetailPanel() {
|
||||
active.blur();
|
||||
}
|
||||
};
|
||||
const handleFeatureAccess = (feature: "today" | "history") => {
|
||||
blurActiveElement();
|
||||
|
||||
if (isPro) {
|
||||
if (feature === "today") {
|
||||
void store.openTodayModal();
|
||||
return;
|
||||
}
|
||||
void store.openHistory();
|
||||
return;
|
||||
}
|
||||
|
||||
if (isAuthenticated) {
|
||||
router.push("/account");
|
||||
return;
|
||||
}
|
||||
|
||||
if (feature === "today") {
|
||||
void store.openTodayModal();
|
||||
return;
|
||||
}
|
||||
void store.openHistory();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const panel = panelRef.current;
|
||||
@@ -231,10 +274,10 @@ export function DetailPanel() {
|
||||
×
|
||||
</button>
|
||||
<div className="panel-title-area">
|
||||
<h2>{detail?.display_name?.toUpperCase() || "..."}</h2>
|
||||
<h2>{panelDisplayName.toUpperCase()}</h2>
|
||||
<div className="panel-meta">
|
||||
<span className={clsx("risk-badge", detail?.risk?.level || "low")}>
|
||||
{getRiskBadgeLabel(detail?.risk?.level, locale)}
|
||||
<span className={clsx("risk-badge", panelRiskLevel)}>
|
||||
{getRiskBadgeLabel(panelRiskLevel, locale)}
|
||||
</span>
|
||||
<div className="relative group">
|
||||
<button
|
||||
@@ -245,11 +288,8 @@ export function DetailPanel() {
|
||||
? t("detail.todayAnalysis")
|
||||
: `${t("detail.todayAnalysis")} (Pro)`
|
||||
}
|
||||
onClick={() => {
|
||||
blurActiveElement();
|
||||
void store.openTodayModal();
|
||||
}}
|
||||
disabled={!detail}
|
||||
onClick={() => handleFeatureAccess("today")}
|
||||
disabled={!store.selectedCity}
|
||||
>
|
||||
{isPro
|
||||
? t("detail.todayAnalysis")
|
||||
@@ -261,11 +301,8 @@ export function DetailPanel() {
|
||||
title={
|
||||
isPro ? t("detail.history") : `${t("detail.history")} (Pro)`
|
||||
}
|
||||
onClick={() => {
|
||||
blurActiveElement();
|
||||
void store.openHistory();
|
||||
}}
|
||||
disabled={!detail}
|
||||
onClick={() => handleFeatureAccess("history")}
|
||||
disabled={!store.selectedCity}
|
||||
>
|
||||
{isPro ? t("detail.history") : `${t("detail.history")} · Pro`}
|
||||
</button>
|
||||
@@ -291,12 +328,12 @@ export function DetailPanel() {
|
||||
<img
|
||||
className="detail-scenery-image"
|
||||
src={scenery.imageUrl}
|
||||
alt={t("detail.sceneryAlt", { city: detail.display_name })}
|
||||
alt={t("detail.sceneryAlt", { city: detail?.display_name || "" })}
|
||||
/>
|
||||
<div className="detail-scenery-overlay">
|
||||
<div className="detail-scenery-copy">
|
||||
<span className="detail-scenery-kicker">
|
||||
{detail.display_name}
|
||||
{detail?.display_name}
|
||||
</span>
|
||||
</div>
|
||||
<a
|
||||
@@ -312,7 +349,7 @@ export function DetailPanel() {
|
||||
) : (
|
||||
<div className="detail-scenery-fallback">
|
||||
<span className="detail-scenery-kicker">
|
||||
{detail.display_name}
|
||||
{detail?.display_name}
|
||||
</span>
|
||||
<strong className="detail-scenery-title">
|
||||
{t("detail.sceneryTitle")}
|
||||
@@ -336,10 +373,37 @@ export function DetailPanel() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{officialLinks.length > 0 ? (
|
||||
<section className="detail-section">
|
||||
<h3>{locale === "en-US" ? "Official Sources" : "官方参考"}</h3>
|
||||
<p className="detail-source-note">
|
||||
{locale === "en-US"
|
||||
? "AGENCY = national meteorological service, METAR = airport observation, AIRPORT = airport official page."
|
||||
: "AGENCY = 国家气象机构,METAR = 机场实测报文,AIRPORT = 机场官网页面。"}
|
||||
</p>
|
||||
<div className="detail-source-list">
|
||||
{officialLinks.map((link) => (
|
||||
<a
|
||||
key={`${link.label}-${link.href}`}
|
||||
className="detail-source-link"
|
||||
href={link.href}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
<span className="detail-source-kind">
|
||||
{link.kind.toUpperCase()}
|
||||
</span>
|
||||
<span className="detail-source-label">{link.label}</span>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<section className="detail-section rounded-2xl">
|
||||
<h3>{t("detail.todayMiniTrend")}</h3>
|
||||
{heavyContentReady ? (
|
||||
<DetailMiniTemperatureChart detail={detail} />
|
||||
<DetailMiniTemperatureChart detail={detail!} />
|
||||
) : (
|
||||
<div className="detail-mini-meta">{t("detail.loading")}</div>
|
||||
)}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,105 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useDashboardStore } from "@/hooks/useDashboardStore";
|
||||
import { useI18n } from "@/hooks/useI18n";
|
||||
|
||||
const GUIDE_CARDS = {
|
||||
"zh-CN": [
|
||||
{
|
||||
body: "Dynamic Ensemble Blending 是系统的核心预测层。它不是对 ECMWF、GFS、ICON、GEM、JMA 等模型的简单平均,而是结合近期样本表现、当前实况与城市偏置后得到的动态加权结果。",
|
||||
title: "DEB 动态融合预测",
|
||||
},
|
||||
{
|
||||
body: "右侧的结算概率分布基于 DEB 预测值与多模型离散度动态计算。μ 代表当前分布中心,会随着模型、实况和时间变化而变化,不是固定结算值。",
|
||||
title: "结算概率引擎",
|
||||
},
|
||||
{
|
||||
body: "结算源按城市市场定义:米兰(LIMC)、华沙(EPWA)、马德里(LEMD)使用机场 METAR;香港市场使用香港天文台(HKO);台北市场使用交通部中央气象署(CWA)。系统仍会保留 METAR/MGM 作为临近结构参考,并区分观测时间与接收时间。",
|
||||
title: "结算点与主观测源",
|
||||
},
|
||||
{
|
||||
body: "Ankara 不走通用城市逻辑。结算主站以 LTAC / Esenboğa 为准,周边领先信号优先参考 Turkish MGM 站网,其中 Ankara (Bölge/Center) 是重点监控站,不用 Etimesgut 代替。",
|
||||
title: "Ankara 专属增强",
|
||||
},
|
||||
{
|
||||
body: "点击多日预报后的模态框,主要用于分析下一个交易日。6-48 小时趋势以 weather.gov 和 Open-Meteo 为主;0-2 小时临近判断优先看 METAR 与周边站。",
|
||||
title: "未来日期分析",
|
||||
},
|
||||
{
|
||||
body: "历史准确率对账只统计已结算样本。网页端采用近 15 天滚动视图,不把当天尚未结算的样本算入胜率和 MAE。",
|
||||
title: "历史对账规则",
|
||||
},
|
||||
],
|
||||
"en-US": [
|
||||
{
|
||||
body: "Dynamic Ensemble Blending (DEB) is the core prediction layer. It is not a simple average across ECMWF/GFS/ICON/GEM/JMA, but a dynamically weighted blend adjusted by recent model performance, current observations, and city bias.",
|
||||
title: "DEB Dynamic Fusion",
|
||||
},
|
||||
{
|
||||
body: "Settlement probability distribution is dynamically computed from DEB forecast and model spread. μ is the current distribution center and shifts with model updates, observations, and time.",
|
||||
title: "Settlement Probability Engine",
|
||||
},
|
||||
{
|
||||
body: "Settlement source follows market rule by city: Milan (LIMC), Warsaw (EPWA), and Madrid (LEMD) settle on airport METAR, Hong Kong settles on HKO, and Taipei settles on CWA. METAR/MGM are still kept for intraday structure tracking with observation time vs receipt time separated.",
|
||||
title: "Settlement Source Logic",
|
||||
},
|
||||
{
|
||||
body: "Ankara does not follow the generic city path. LTAC / Esenboğa is the settlement station, with Turkish MGM network for leading signals. Ankara (Bölge/Center) is a key station and is not replaced by Etimesgut.",
|
||||
title: "Ankara-specific Enhancement",
|
||||
},
|
||||
{
|
||||
body: "The multi-day modal focuses on next-session analysis. 6-48h trend mainly relies on weather.gov and Open-Meteo; 0-2h nowcast prioritizes METAR and nearby stations.",
|
||||
title: "Future-date Analysis",
|
||||
},
|
||||
{
|
||||
body: "History reconciliation only uses settled samples. The web dashboard uses a rolling 15-day window and excludes same-day unsettled samples from hit-rate and MAE.",
|
||||
title: "History Rules",
|
||||
},
|
||||
],
|
||||
} as const;
|
||||
|
||||
export function GuideModal() {
|
||||
const store = useDashboardStore();
|
||||
const { locale, t } = useI18n();
|
||||
|
||||
if (!store.isGuideOpen) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="modal-overlay"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="guide-modal-title"
|
||||
onClick={(event) => {
|
||||
if (event.target === event.currentTarget) {
|
||||
store.closeGuide();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="modal-content large">
|
||||
<div className="modal-header">
|
||||
<h2 id="guide-modal-title">{t("guide.title")}</h2>
|
||||
<button
|
||||
type="button"
|
||||
className="modal-close"
|
||||
aria-label={t("guide.closeAria")}
|
||||
onClick={store.closeGuide}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
<div className="guide-grid">
|
||||
{GUIDE_CARDS[locale].map((card) => (
|
||||
<div key={card.title} className="guide-card">
|
||||
<h3>{card.title}</h3>
|
||||
<p>{card.body}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="guide-footer">{t("guide.footer")}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import clsx from "clsx";
|
||||
import { LogIn, UserRound } from "lucide-react";
|
||||
import { useDashboardStore } from "@/hooks/useDashboardStore";
|
||||
@@ -14,8 +15,11 @@ import {
|
||||
export function HeaderBar() {
|
||||
const store = useDashboardStore();
|
||||
const { locale, setLocale, t } = useI18n();
|
||||
const pathname = usePathname();
|
||||
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
||||
const supabaseReady = hasSupabasePublicEnv();
|
||||
const docsHref = "/docs/intro";
|
||||
const docsActive = pathname?.startsWith("/docs");
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
@@ -78,6 +82,15 @@ export function HeaderBar() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<Link
|
||||
href={docsHref}
|
||||
className={clsx("info-btn", docsActive && "active")}
|
||||
title={t("header.docsAria")}
|
||||
aria-label={t("header.docsAria")}
|
||||
>
|
||||
{t("header.docs")}
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
href={accountHref}
|
||||
className="account-btn"
|
||||
@@ -88,16 +101,6 @@ export function HeaderBar() {
|
||||
<span>{accountLabel}</span>
|
||||
</Link>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="info-btn"
|
||||
title={t("header.infoAria")}
|
||||
aria-label={t("header.infoAria")}
|
||||
onClick={store.openGuide}
|
||||
>
|
||||
{t("header.info")}
|
||||
</button>
|
||||
|
||||
<div className="live-badge" id="liveBadge">
|
||||
<span className="pulse-dot" />
|
||||
<span>{t("header.live")}</span>
|
||||
@@ -115,4 +118,4 @@ export function HeaderBar() {
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,12 +12,23 @@ function HistoryChart() {
|
||||
const store = useDashboardStore();
|
||||
const { locale } = useI18n();
|
||||
const { data } = useHistoryData();
|
||||
const isNoaaSettlement =
|
||||
store.selectedDetail?.current?.settlement_source === "noaa" ||
|
||||
store.selectedDetail?.current?.settlement_source_label === "NOAA";
|
||||
const noaaStationCode = String(
|
||||
store.selectedDetail?.current?.station_code ||
|
||||
store.selectedDetail?.risk?.icao ||
|
||||
"NOAA",
|
||||
)
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
const summary = useMemo(
|
||||
() => getHistorySummary(data, store.selectedDetail?.local_date),
|
||||
[data, store.selectedDetail?.local_date],
|
||||
);
|
||||
const hasMgm =
|
||||
store.selectedCity === "ankara" &&
|
||||
summary.mgmSeriesComplete &&
|
||||
summary.mgms.some((value) => value != null);
|
||||
const hasBestBaseline =
|
||||
Boolean(summary.bestModelName) &&
|
||||
@@ -33,7 +44,13 @@ function HistoryChart() {
|
||||
borderColor: "#f87171",
|
||||
borderWidth: 2,
|
||||
data: summary.actuals,
|
||||
label: locale === "en-US" ? "Observed High" : "实测最高温",
|
||||
label: isNoaaSettlement
|
||||
? locale === "en-US"
|
||||
? `NOAA Settled High (${noaaStationCode})`
|
||||
: `NOAA 结算最高温 (${noaaStationCode})`
|
||||
: locale === "en-US"
|
||||
? "Observed High"
|
||||
: "实测最高温",
|
||||
pointBackgroundColor: "#f87171",
|
||||
pointBorderColor: "#fff",
|
||||
pointHoverRadius: 7,
|
||||
@@ -135,7 +152,7 @@ function HistoryChart() {
|
||||
},
|
||||
type: "line",
|
||||
} satisfies ChartConfiguration<"line">;
|
||||
}, [hasBestBaseline, hasMgm, summary, locale]);
|
||||
}, [hasBestBaseline, hasMgm, isNoaaSettlement, noaaStationCode, summary, locale]);
|
||||
|
||||
if (!summary.recentData.length) return null;
|
||||
|
||||
@@ -148,14 +165,40 @@ function HistoryChart() {
|
||||
|
||||
export function HistoryModal() {
|
||||
const store = useDashboardStore();
|
||||
const { t } = useI18n();
|
||||
const { t, locale } = useI18n();
|
||||
const { data, error, isLoading, isOpen } = useHistoryData();
|
||||
const isPro = store.proAccess.subscriptionActive;
|
||||
const isProLoading = store.proAccess.loading;
|
||||
const isNoaaSettlement =
|
||||
store.selectedDetail?.current?.settlement_source === "noaa" ||
|
||||
store.selectedDetail?.current?.settlement_source_label === "NOAA";
|
||||
const noaaStationCode = String(
|
||||
store.selectedDetail?.current?.station_code ||
|
||||
store.selectedDetail?.risk?.icao ||
|
||||
"NOAA",
|
||||
)
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
const noaaStationName =
|
||||
String(store.selectedDetail?.current?.station_name || "").trim() ||
|
||||
String(store.selectedDetail?.risk?.airport || "").trim() ||
|
||||
noaaStationCode;
|
||||
const summary = useMemo(
|
||||
() => getHistorySummary(data, store.selectedDetail?.local_date),
|
||||
[data, store.selectedDetail?.local_date],
|
||||
);
|
||||
const settledPeakRows = useMemo(
|
||||
() =>
|
||||
summary.recentData
|
||||
.filter(
|
||||
(row) =>
|
||||
row.actual != null &&
|
||||
row.actual_peak_time &&
|
||||
row.deb_at_peak_minus_12h != null,
|
||||
)
|
||||
.reverse(),
|
||||
[summary.recentData],
|
||||
);
|
||||
|
||||
if (!isOpen) return null;
|
||||
|
||||
@@ -200,20 +243,70 @@ export function HistoryModal() {
|
||||
</button>
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
<div className="history-stats">
|
||||
{isLoading ? (
|
||||
<span style={{ color: "var(--text-muted)" }}>
|
||||
{t("history.loading")}
|
||||
</span>
|
||||
) : error ? (
|
||||
{isNoaaSettlement && (
|
||||
<div
|
||||
style={{
|
||||
marginBottom: "16px",
|
||||
padding: "12px 14px",
|
||||
border: "1px solid rgba(56, 189, 248, 0.24)",
|
||||
borderRadius: "12px",
|
||||
background: "rgba(14, 165, 233, 0.08)",
|
||||
color: "var(--text-secondary)",
|
||||
fontSize: "13px",
|
||||
lineHeight: 1.6,
|
||||
}}
|
||||
>
|
||||
{t("lang") === "en-US"
|
||||
? `${store.selectedDetail?.display_name || store.selectedCity || "This city"} historical actuals are aligned to NOAA ${noaaStationCode} (${noaaStationName}) settlement rules: use the highest rounded whole-degree Celsius reading after the date is finalized.`
|
||||
: `${store.selectedDetail?.display_name || store.selectedCity || "该城市"}历史对账已按 NOAA ${noaaStationCode}(${noaaStationName})结算口径对齐:采用该日最终完成质控后的最高整度摄氏值。`}
|
||||
</div>
|
||||
)}
|
||||
{isLoading ? (
|
||||
<div className="history-modal-loading">
|
||||
<div className="history-fetch-loading">
|
||||
<div className="history-fetch-scan" aria-hidden="true">
|
||||
<span className="history-fetch-ring history-fetch-ring-1" />
|
||||
<span className="history-fetch-ring history-fetch-ring-2" />
|
||||
<span className="history-fetch-sweep" />
|
||||
<span className="history-fetch-core" />
|
||||
</div>
|
||||
<div className="history-fetch-bars" aria-hidden="true">
|
||||
<span className="history-fetch-bar history-fetch-bar-1" />
|
||||
<span className="history-fetch-bar history-fetch-bar-2" />
|
||||
<span className="history-fetch-bar history-fetch-bar-3" />
|
||||
<span className="history-fetch-bar history-fetch-bar-4" />
|
||||
</div>
|
||||
<div className="history-fetch-lines" aria-hidden="true">
|
||||
<span className="history-fetch-line history-fetch-line-1" />
|
||||
<span className="history-fetch-line history-fetch-line-2" />
|
||||
<span className="history-fetch-line history-fetch-line-3" />
|
||||
</div>
|
||||
<div className="history-fetch-copy">
|
||||
<strong>
|
||||
{locale === "en-US"
|
||||
? "Scanning archived settlement history"
|
||||
: "正在扫描历史结算档案"}
|
||||
</strong>
|
||||
<span>
|
||||
{locale === "en-US"
|
||||
? "Reconciling settled highs, DEB traces, and baseline forecasts..."
|
||||
: "正在对齐实测高温、DEB 轨迹与基线预报..."}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="history-stats">
|
||||
{error ? (
|
||||
<span style={{ color: "var(--accent-red)" }}>
|
||||
{t("history.error")}
|
||||
</span>
|
||||
) : !summary.recentData.length ? (
|
||||
) : !summary.recentData.length ? (
|
||||
<span style={{ color: "var(--text-muted)" }}>
|
||||
{t("history.empty")}
|
||||
</span>
|
||||
) : (
|
||||
) : (
|
||||
<>
|
||||
<div className="h-stat-card">
|
||||
<span className="label">{t("history.debHitRate")}</span>
|
||||
@@ -254,9 +347,69 @@ export function HistoryModal() {
|
||||
</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{!isLoading && !error && <HistoryChart />}
|
||||
)}
|
||||
</div>
|
||||
{!error && <HistoryChart />}
|
||||
{!error && settledPeakRows.length > 0 && (
|
||||
<div className="history-peak-reference">
|
||||
<div className="history-peak-reference-title">
|
||||
{locale === "en-US"
|
||||
? "Peak-12h DEB Reference (Approx.)"
|
||||
: "峰值前 12 小时 DEB 参考(近似)"}
|
||||
</div>
|
||||
<div className="history-peak-reference-scroll">
|
||||
{settledPeakRows.map((row) => (
|
||||
<div key={row.date} className="history-peak-reference-row">
|
||||
<div className="history-peak-reference-date">
|
||||
{row.date}
|
||||
</div>
|
||||
<div className="history-peak-reference-meta">
|
||||
<div>
|
||||
{locale === "en-US" ? "Peak ref" : "峰值参考"}:{" "}
|
||||
<span style={{ color: "var(--text-primary)" }}>
|
||||
{row.actual}
|
||||
{store.selectedDetail?.temp_symbol || "°C"} @{" "}
|
||||
{row.actual_peak_time}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
{locale === "en-US" ? "DEB@-12h" : "峰值前12小时 DEB"}:{" "}
|
||||
<span style={{ color: "var(--text-primary)" }}>
|
||||
{row.deb_at_peak_minus_12h}
|
||||
{store.selectedDetail?.temp_symbol || "°C"} @{" "}
|
||||
{row.deb_at_peak_minus_12h_time}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
{locale === "en-US" ? "Actual" : "最终实测"}:{" "}
|
||||
<span style={{ color: "var(--text-primary)" }}>
|
||||
{row.actual}
|
||||
{store.selectedDetail?.temp_symbol || "°C"}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
{locale === "en-US" ? "Error" : "误差"}:{" "}
|
||||
<span
|
||||
style={{
|
||||
color:
|
||||
(row.deb_at_peak_minus_12h_error ?? 0) > 0
|
||||
? "#f59e0b"
|
||||
: "#34d399",
|
||||
}}
|
||||
>
|
||||
{row.deb_at_peak_minus_12h_error != null
|
||||
? `${row.deb_at_peak_minus_12h_error > 0 ? "+" : ""}${row.deb_at_peak_minus_12h_error}${store.selectedDetail?.temp_symbol || "°C"}`
|
||||
: "--"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import * as THREE from "three";
|
||||
import { usePrefersReducedMotion } from "@/hooks/usePrefersReducedMotion";
|
||||
|
||||
export interface IntradaySignalMetric {
|
||||
key: string;
|
||||
label: string;
|
||||
value: string;
|
||||
hint: string;
|
||||
fill: number | null;
|
||||
tone: string;
|
||||
}
|
||||
|
||||
function clamp(value: number, min: number, max: number) {
|
||||
return Math.min(Math.max(value, min), max);
|
||||
}
|
||||
|
||||
function getToneColor(tone: string) {
|
||||
if (tone === "cyan") return "#22d3ee";
|
||||
if (tone === "blue") return "#60a5fa";
|
||||
if (tone === "amber") return "#f59e0b";
|
||||
return "#94a3b8";
|
||||
}
|
||||
|
||||
export function IntradaySignalScene({
|
||||
metrics,
|
||||
score,
|
||||
}: {
|
||||
metrics: IntradaySignalMetric[];
|
||||
score: number;
|
||||
}) {
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const prefersReducedMotion = usePrefersReducedMotion();
|
||||
|
||||
useEffect(() => {
|
||||
const host = containerRef.current;
|
||||
if (!host) return;
|
||||
|
||||
const renderer = new THREE.WebGLRenderer({
|
||||
alpha: true,
|
||||
antialias: true,
|
||||
powerPreference: "low-power",
|
||||
});
|
||||
renderer.setClearColor(0x000000, 0);
|
||||
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.5));
|
||||
|
||||
const scene = new THREE.Scene();
|
||||
const camera = new THREE.PerspectiveCamera(34, 1, 0.1, 100);
|
||||
camera.position.set(0, 2.8, 7.2);
|
||||
camera.lookAt(0, 1.2, 0);
|
||||
|
||||
const ambient = new THREE.AmbientLight(0xbfe8ff, 1.25);
|
||||
const keyLight = new THREE.PointLight(0x67e8f9, 22, 18, 2);
|
||||
keyLight.position.set(-3.8, 5.6, 4.8);
|
||||
const warmLight = new THREE.PointLight(0xf59e0b, 12, 16, 2);
|
||||
warmLight.position.set(4.2, 2.8, 4);
|
||||
scene.add(ambient, keyLight, warmLight);
|
||||
|
||||
const stage = new THREE.Group();
|
||||
scene.add(stage);
|
||||
|
||||
const floor = new THREE.Mesh(
|
||||
new THREE.CylinderGeometry(3.3, 3.8, 0.12, 48),
|
||||
new THREE.MeshStandardMaterial({
|
||||
color: new THREE.Color(score >= 0 ? "#10263b" : "#2c1d12"),
|
||||
emissive: new THREE.Color(score >= 0 ? "#0e7490" : "#b45309"),
|
||||
emissiveIntensity: 0.18 + clamp(Math.abs(score) / 8, 0, 0.24),
|
||||
metalness: 0.2,
|
||||
roughness: 0.78,
|
||||
}),
|
||||
);
|
||||
floor.position.y = -0.12;
|
||||
stage.add(floor);
|
||||
|
||||
const ring = new THREE.Mesh(
|
||||
new THREE.TorusGeometry(2.8, 0.03, 18, 100),
|
||||
new THREE.MeshBasicMaterial({
|
||||
color: new THREE.Color(score >= 0 ? "#22d3ee" : "#f59e0b"),
|
||||
transparent: true,
|
||||
opacity: 0.5,
|
||||
}),
|
||||
);
|
||||
ring.rotation.x = Math.PI / 2;
|
||||
ring.position.y = 0.03;
|
||||
stage.add(ring);
|
||||
|
||||
const barGeometry = new THREE.BoxGeometry(0.8, 1, 0.8);
|
||||
const capGeometry = new THREE.SphereGeometry(0.16, 16, 16);
|
||||
const bars: Array<{
|
||||
mesh: THREE.Mesh;
|
||||
cap: THREE.Mesh;
|
||||
glow: THREE.Mesh;
|
||||
baseY: number;
|
||||
targetHeight: number;
|
||||
}> = [];
|
||||
|
||||
const xPositions = [-1.8, -0.6, 0.6, 1.8];
|
||||
metrics.slice(0, 4).forEach((metric, index) => {
|
||||
const height = 0.5 + ((metric.fill ?? 20) / 100) * 2.8;
|
||||
const color = new THREE.Color(getToneColor(metric.tone));
|
||||
const material = new THREE.MeshStandardMaterial({
|
||||
color,
|
||||
emissive: color,
|
||||
emissiveIntensity: 0.22,
|
||||
metalness: 0.14,
|
||||
roughness: 0.38,
|
||||
});
|
||||
const mesh = new THREE.Mesh(barGeometry, material);
|
||||
mesh.position.set(xPositions[index] || 0, height / 2, 0);
|
||||
mesh.scale.y = height;
|
||||
stage.add(mesh);
|
||||
|
||||
const cap = new THREE.Mesh(
|
||||
capGeometry,
|
||||
new THREE.MeshBasicMaterial({
|
||||
color,
|
||||
transparent: true,
|
||||
opacity: 0.95,
|
||||
}),
|
||||
);
|
||||
cap.position.set(mesh.position.x, height + 0.2, 0);
|
||||
stage.add(cap);
|
||||
|
||||
const glow = new THREE.Mesh(
|
||||
new THREE.CylinderGeometry(0.46, 0.58, 0.08, 32),
|
||||
new THREE.MeshBasicMaterial({
|
||||
color,
|
||||
transparent: true,
|
||||
opacity: 0.22,
|
||||
}),
|
||||
);
|
||||
glow.position.set(mesh.position.x, 0.06, 0);
|
||||
stage.add(glow);
|
||||
|
||||
bars.push({ mesh, cap, glow, baseY: cap.position.y, targetHeight: height });
|
||||
});
|
||||
|
||||
const resize = () => {
|
||||
const width = Math.max(host.clientWidth, 1);
|
||||
const height = Math.max(host.clientHeight, 1);
|
||||
renderer.setSize(width, height, false);
|
||||
camera.aspect = width / height;
|
||||
camera.updateProjectionMatrix();
|
||||
};
|
||||
|
||||
resize();
|
||||
host.appendChild(renderer.domElement);
|
||||
|
||||
const clock = new THREE.Clock();
|
||||
let frameId = 0;
|
||||
|
||||
const renderFrame = () => {
|
||||
frameId = window.requestAnimationFrame(renderFrame);
|
||||
const elapsed = clock.getElapsedTime();
|
||||
stage.rotation.y = Math.sin(elapsed * 0.35) * 0.16;
|
||||
ring.material.opacity = 0.38 + Math.sin(elapsed * 0.8) * 0.08;
|
||||
|
||||
bars.forEach((bar, index) => {
|
||||
const pulse = prefersReducedMotion
|
||||
? 0
|
||||
: Math.sin(elapsed * 1.5 + index * 0.8) * 0.08;
|
||||
bar.cap.position.y = bar.baseY + pulse;
|
||||
bar.glow.scale.x = 1 + Math.sin(elapsed * 1.2 + index) * 0.06;
|
||||
bar.glow.scale.z = 1 + Math.sin(elapsed * 1.2 + index) * 0.06;
|
||||
});
|
||||
|
||||
renderer.render(scene, camera);
|
||||
};
|
||||
|
||||
const observer = new ResizeObserver(resize);
|
||||
observer.observe(host);
|
||||
frameId = window.requestAnimationFrame(renderFrame);
|
||||
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
window.cancelAnimationFrame(frameId);
|
||||
stage.traverse((child) => {
|
||||
if (child instanceof THREE.Mesh) {
|
||||
child.geometry.dispose();
|
||||
if (Array.isArray(child.material)) {
|
||||
child.material.forEach((material) => material.dispose());
|
||||
} else {
|
||||
child.material.dispose();
|
||||
}
|
||||
}
|
||||
});
|
||||
renderer.dispose();
|
||||
if (renderer.domElement.parentNode === host) {
|
||||
host.removeChild(renderer.domElement);
|
||||
}
|
||||
};
|
||||
}, [metrics, prefersReducedMotion, score]);
|
||||
|
||||
return (
|
||||
<div className="intraday-scene-shell">
|
||||
<div ref={containerRef} className="intraday-scene-frame" aria-hidden="true" />
|
||||
<div className="intraday-scene-legend">
|
||||
{metrics.slice(0, 4).map((metric) => (
|
||||
<div key={metric.key} className="intraday-scene-chip">
|
||||
<span
|
||||
className="intraday-scene-chip-dot"
|
||||
style={{ backgroundColor: getToneColor(metric.tone) }}
|
||||
/>
|
||||
<div className="intraday-scene-chip-copy">
|
||||
<strong>{metric.label}</strong>
|
||||
<span>
|
||||
{metric.value} · {metric.hint}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -21,8 +21,7 @@ export function MapCanvas() {
|
||||
selectedDetail: store.selectedDetail,
|
||||
suspendMotion:
|
||||
Boolean(store.futureModalDate) ||
|
||||
store.historyState.isOpen ||
|
||||
store.isGuideOpen,
|
||||
store.historyState.isOpen,
|
||||
isLoadingDetail: store.loadingState.cityDetail,
|
||||
});
|
||||
|
||||
|
||||
@@ -711,6 +711,10 @@ export function ForecastTable() {
|
||||
if (!data) return null;
|
||||
|
||||
const daily = data.forecast?.daily || [];
|
||||
const resolveForecastTemp = (date: string, fallback: number | null | undefined) => {
|
||||
const debPrediction = data.multi_model_daily?.[date]?.deb?.prediction;
|
||||
return debPrediction ?? fallback ?? null;
|
||||
};
|
||||
return (
|
||||
<section className="forecast-section">
|
||||
<h3>{t("forecast.title")}</h3>
|
||||
@@ -744,7 +748,7 @@ export function ForecastTable() {
|
||||
: day.date.substring(5).replace("-", "/")}
|
||||
</div>
|
||||
<div className="f-temp">
|
||||
{day.max_temp}
|
||||
{resolveForecastTemp(day.date, day.max_temp)}
|
||||
{data.temp_symbol}
|
||||
</div>
|
||||
</button>
|
||||
|
||||
@@ -21,9 +21,11 @@ const MapCanvas = dynamic(
|
||||
},
|
||||
);
|
||||
|
||||
const GuideModal = dynamic(
|
||||
const WeatherAuraLayer = dynamic(
|
||||
() =>
|
||||
import("@/components/dashboard/GuideModal").then((module) => module.GuideModal),
|
||||
import("@/components/dashboard/WeatherAuraLayer").then(
|
||||
(module) => module.WeatherAuraLayer,
|
||||
),
|
||||
{
|
||||
ssr: false,
|
||||
loading: () => null,
|
||||
@@ -56,6 +58,11 @@ function DashboardScreen() {
|
||||
const store = useDashboardStore();
|
||||
const { t } = useI18n();
|
||||
|
||||
useEffect(() => {
|
||||
void import("@/components/dashboard/HistoryModal");
|
||||
void import("@/components/dashboard/FutureForecastModal");
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== "Escape") return;
|
||||
@@ -67,10 +74,6 @@ function DashboardScreen() {
|
||||
store.closeHistory();
|
||||
return;
|
||||
}
|
||||
if (store.isGuideOpen) {
|
||||
store.closeGuide();
|
||||
return;
|
||||
}
|
||||
if (store.isPanelOpen) {
|
||||
store.closePanel();
|
||||
}
|
||||
@@ -91,16 +94,50 @@ function DashboardScreen() {
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<MapCanvas />
|
||||
<WeatherAuraLayer />
|
||||
<HeaderBar />
|
||||
<CitySidebar />
|
||||
<DetailPanel />
|
||||
{store.isGuideOpen && <GuideModal />}
|
||||
{store.historyState.isOpen && <HistoryModal />}
|
||||
{store.futureModalDate && <FutureForecastModal />}
|
||||
{showLoading && (
|
||||
<div className="loading-overlay">
|
||||
<div className="loading-spinner" />
|
||||
<span>{t("dashboard.loading")}</span>
|
||||
<div className="loading-card">
|
||||
<div className="loading-clouds" aria-hidden="true">
|
||||
<span className="loading-cloud loading-cloud-1" />
|
||||
<span className="loading-cloud loading-cloud-2" />
|
||||
</div>
|
||||
<div className="loading-windfield" aria-hidden="true">
|
||||
<span className="loading-windline loading-windline-1" />
|
||||
<span className="loading-windline loading-windline-2" />
|
||||
<span className="loading-windline loading-windline-3" />
|
||||
</div>
|
||||
<div className="loading-radar" aria-hidden="true">
|
||||
<div className="loading-radar-core" />
|
||||
<div className="loading-radar-ring loading-radar-ring-1" />
|
||||
<div className="loading-radar-ring loading-radar-ring-2" />
|
||||
<div className="loading-radar-sweep" />
|
||||
<div className="loading-radar-blip loading-radar-blip-1" />
|
||||
<div className="loading-radar-blip loading-radar-blip-2" />
|
||||
</div>
|
||||
<div className="loading-thermals" aria-hidden="true">
|
||||
<span className="loading-thermal loading-thermal-1" />
|
||||
<span className="loading-thermal loading-thermal-2" />
|
||||
<span className="loading-thermal loading-thermal-3" />
|
||||
<span className="loading-thermal loading-thermal-4" />
|
||||
</div>
|
||||
<div className="loading-drizzle" aria-hidden="true">
|
||||
<span className="loading-drizzle-drop loading-drizzle-drop-1" />
|
||||
<span className="loading-drizzle-drop loading-drizzle-drop-2" />
|
||||
<span className="loading-drizzle-drop loading-drizzle-drop-3" />
|
||||
<span className="loading-drizzle-drop loading-drizzle-drop-4" />
|
||||
<span className="loading-drizzle-drop loading-drizzle-drop-5" />
|
||||
</div>
|
||||
<div className="loading-copy">
|
||||
<strong>PolyWeather</strong>
|
||||
<span>{t("dashboard.loading")}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,500 @@
|
||||
"use client";
|
||||
|
||||
import { CSSProperties, useEffect, useRef, useState } from "react";
|
||||
import * as THREE from "three";
|
||||
import { useDashboardStore } from "@/hooks/useDashboardStore";
|
||||
import { usePrefersReducedMotion } from "@/hooks/usePrefersReducedMotion";
|
||||
import { getWeatherAuraProfile } from "@/lib/weather-aura";
|
||||
import styles from "./Dashboard.module.css";
|
||||
|
||||
function hexToRgba(hex: string, alpha: number) {
|
||||
const sanitized = hex.replace("#", "");
|
||||
const normalized =
|
||||
sanitized.length === 3
|
||||
? sanitized
|
||||
.split("")
|
||||
.map((char) => `${char}${char}`)
|
||||
.join("")
|
||||
: sanitized.padEnd(6, "0");
|
||||
const numeric = Number.parseInt(normalized, 16);
|
||||
const r = (numeric >> 16) & 255;
|
||||
const g = (numeric >> 8) & 255;
|
||||
const b = numeric & 255;
|
||||
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
|
||||
}
|
||||
|
||||
export function WeatherAuraLayer() {
|
||||
const store = useDashboardStore();
|
||||
const prefersReducedMotion = usePrefersReducedMotion();
|
||||
const [isDesktop, setIsDesktop] = useState(false);
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const aura = getWeatherAuraProfile(store.selectedDetail, store.cities);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined" || !window.matchMedia) {
|
||||
return;
|
||||
}
|
||||
|
||||
const mediaQuery = window.matchMedia("(min-width: 1024px)");
|
||||
const apply = () => {
|
||||
setIsDesktop(mediaQuery.matches);
|
||||
};
|
||||
|
||||
apply();
|
||||
mediaQuery.addEventListener("change", apply);
|
||||
return () => {
|
||||
mediaQuery.removeEventListener("change", apply);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const host = containerRef.current;
|
||||
if (!host || !isDesktop || prefersReducedMotion) {
|
||||
return;
|
||||
}
|
||||
|
||||
const renderer = new THREE.WebGLRenderer({
|
||||
alpha: true,
|
||||
antialias: true,
|
||||
powerPreference: "low-power",
|
||||
});
|
||||
renderer.setClearColor(0x000000, 0);
|
||||
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.5));
|
||||
|
||||
const scene = new THREE.Scene();
|
||||
const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 10);
|
||||
camera.position.z = 2;
|
||||
|
||||
const clock = new THREE.Clock();
|
||||
const cleanupMaterials = new Set<THREE.Material>();
|
||||
const particleGroups: Array<{
|
||||
kind: "flow" | "rain" | "snow" | "fog" | "cloud";
|
||||
geometry: THREE.BufferGeometry;
|
||||
positions: Float32Array;
|
||||
baseY: Float32Array;
|
||||
drift: Float32Array;
|
||||
phase: Float32Array;
|
||||
material: THREE.Material;
|
||||
mesh: THREE.Object3D;
|
||||
}> = [];
|
||||
const effectLights: THREE.Light[] = [];
|
||||
const flashOverlay = new THREE.Mesh(
|
||||
new THREE.PlaneGeometry(2.2, 2.2),
|
||||
new THREE.MeshBasicMaterial({
|
||||
color: new THREE.Color("#e0f2fe"),
|
||||
transparent: true,
|
||||
opacity: 0,
|
||||
blending: THREE.AdditiveBlending,
|
||||
}),
|
||||
);
|
||||
flashOverlay.position.z = -0.3;
|
||||
scene.add(flashOverlay);
|
||||
cleanupMaterials.add(flashOverlay.material as THREE.Material);
|
||||
|
||||
function createParticleField(
|
||||
count: number,
|
||||
pointSize: number,
|
||||
opacity: number,
|
||||
depthShift: number,
|
||||
) {
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
const positions = new Float32Array(count * 3);
|
||||
const colors = new Float32Array(count * 3);
|
||||
const baseY = new Float32Array(count);
|
||||
const drift = new Float32Array(count);
|
||||
const phase = new Float32Array(count);
|
||||
const primaryColor = new THREE.Color(aura.primary);
|
||||
const secondaryColor = new THREE.Color(aura.secondary);
|
||||
const tertiaryColor = new THREE.Color(aura.tertiary);
|
||||
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const offset = index * 3;
|
||||
const x = Math.random() * 2.6 - 1.3;
|
||||
const y = Math.random() * 1.8 - 0.9;
|
||||
const z = (Math.random() * 0.8 - 0.4) + depthShift;
|
||||
positions[offset] = x;
|
||||
positions[offset + 1] = y;
|
||||
positions[offset + 2] = z;
|
||||
baseY[index] = y;
|
||||
drift[index] = (0.00045 + Math.random() * 0.0012) * aura.drift;
|
||||
phase[index] = Math.random() * Math.PI * 2;
|
||||
|
||||
const mixedColor = primaryColor
|
||||
.clone()
|
||||
.lerp(secondaryColor, Math.random() * 0.65)
|
||||
.lerp(tertiaryColor, Math.random() * 0.4);
|
||||
colors[offset] = mixedColor.r;
|
||||
colors[offset + 1] = mixedColor.g;
|
||||
colors[offset + 2] = mixedColor.b;
|
||||
}
|
||||
|
||||
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
|
||||
geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
|
||||
|
||||
const material = new THREE.PointsMaterial({
|
||||
size: pointSize,
|
||||
transparent: true,
|
||||
opacity,
|
||||
vertexColors: true,
|
||||
depthWrite: false,
|
||||
blending: THREE.AdditiveBlending,
|
||||
sizeAttenuation: true,
|
||||
});
|
||||
|
||||
const points = new THREE.Points(geometry, material);
|
||||
scene.add(points);
|
||||
cleanupMaterials.add(material);
|
||||
particleGroups.push({
|
||||
geometry,
|
||||
positions,
|
||||
baseY,
|
||||
drift,
|
||||
phase,
|
||||
kind: "flow",
|
||||
material,
|
||||
mesh: points,
|
||||
});
|
||||
}
|
||||
|
||||
function createRainField(count: number) {
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
const positions = new Float32Array(count * 3);
|
||||
const baseY = new Float32Array(count);
|
||||
const drift = new Float32Array(count);
|
||||
const phase = new Float32Array(count);
|
||||
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const offset = index * 3;
|
||||
positions[offset] = Math.random() * 2.8 - 1.4;
|
||||
positions[offset + 1] = Math.random() * 2.2 - 1.1;
|
||||
positions[offset + 2] = Math.random() * 0.4 - 0.2;
|
||||
baseY[index] = positions[offset + 1];
|
||||
drift[index] = (0.018 + Math.random() * 0.016) * aura.effectIntensity;
|
||||
phase[index] = 0.004 + Math.random() * 0.004;
|
||||
}
|
||||
|
||||
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
|
||||
const material = new THREE.PointsMaterial({
|
||||
size: 0.018,
|
||||
color: new THREE.Color("#7dd3fc"),
|
||||
transparent: true,
|
||||
opacity: 0.72,
|
||||
depthWrite: false,
|
||||
blending: THREE.AdditiveBlending,
|
||||
});
|
||||
const points = new THREE.Points(geometry, material);
|
||||
scene.add(points);
|
||||
cleanupMaterials.add(material);
|
||||
particleGroups.push({
|
||||
geometry,
|
||||
positions,
|
||||
baseY,
|
||||
drift,
|
||||
phase,
|
||||
kind: "rain",
|
||||
material,
|
||||
mesh: points,
|
||||
});
|
||||
}
|
||||
|
||||
function createSnowField(count: number) {
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
const positions = new Float32Array(count * 3);
|
||||
const baseY = new Float32Array(count);
|
||||
const drift = new Float32Array(count);
|
||||
const phase = new Float32Array(count);
|
||||
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const offset = index * 3;
|
||||
positions[offset] = Math.random() * 2.8 - 1.4;
|
||||
positions[offset + 1] = Math.random() * 2.1 - 1.05;
|
||||
positions[offset + 2] = Math.random() * 0.35 - 0.18;
|
||||
baseY[index] = positions[offset + 1];
|
||||
drift[index] = (0.0045 + Math.random() * 0.0045) * aura.effectIntensity;
|
||||
phase[index] = Math.random() * Math.PI * 2;
|
||||
}
|
||||
|
||||
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
|
||||
const material = new THREE.PointsMaterial({
|
||||
size: 0.024,
|
||||
color: new THREE.Color("#f8fafc"),
|
||||
transparent: true,
|
||||
opacity: 0.85,
|
||||
depthWrite: false,
|
||||
blending: THREE.AdditiveBlending,
|
||||
});
|
||||
const points = new THREE.Points(geometry, material);
|
||||
scene.add(points);
|
||||
cleanupMaterials.add(material);
|
||||
particleGroups.push({
|
||||
geometry,
|
||||
positions,
|
||||
baseY,
|
||||
drift,
|
||||
phase,
|
||||
kind: "snow",
|
||||
material,
|
||||
mesh: points,
|
||||
});
|
||||
}
|
||||
|
||||
function createFogField(count: number) {
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
const positions = new Float32Array(count * 3);
|
||||
const baseY = new Float32Array(count);
|
||||
const drift = new Float32Array(count);
|
||||
const phase = new Float32Array(count);
|
||||
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const offset = index * 3;
|
||||
positions[offset] = Math.random() * 2.6 - 1.3;
|
||||
positions[offset + 1] = Math.random() * 0.9 - 0.45;
|
||||
positions[offset + 2] = Math.random() * 0.45 - 0.2;
|
||||
baseY[index] = positions[offset + 1];
|
||||
drift[index] = (0.0014 + Math.random() * 0.001) * aura.effectIntensity;
|
||||
phase[index] = Math.random() * Math.PI * 2;
|
||||
}
|
||||
|
||||
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
|
||||
const material = new THREE.PointsMaterial({
|
||||
size: 0.12,
|
||||
color: new THREE.Color("#cbd5e1"),
|
||||
transparent: true,
|
||||
opacity: 0.18,
|
||||
depthWrite: false,
|
||||
blending: THREE.AdditiveBlending,
|
||||
});
|
||||
const points = new THREE.Points(geometry, material);
|
||||
scene.add(points);
|
||||
cleanupMaterials.add(material);
|
||||
particleGroups.push({
|
||||
geometry,
|
||||
positions,
|
||||
baseY,
|
||||
drift,
|
||||
phase,
|
||||
kind: "fog",
|
||||
material,
|
||||
mesh: points,
|
||||
});
|
||||
}
|
||||
|
||||
function createCloudField(count: number) {
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
const positions = new Float32Array(count * 3);
|
||||
const baseY = new Float32Array(count);
|
||||
const drift = new Float32Array(count);
|
||||
const phase = new Float32Array(count);
|
||||
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const offset = index * 3;
|
||||
positions[offset] = Math.random() * 2.7 - 1.35;
|
||||
positions[offset + 1] = Math.random() * 0.75 + 0.1;
|
||||
positions[offset + 2] = Math.random() * 0.3 - 0.15;
|
||||
baseY[index] = positions[offset + 1];
|
||||
drift[index] = (0.0012 + Math.random() * 0.0009) * aura.effectIntensity;
|
||||
phase[index] = Math.random() * Math.PI * 2;
|
||||
}
|
||||
|
||||
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
|
||||
const material = new THREE.PointsMaterial({
|
||||
size: 0.1,
|
||||
color: new THREE.Color("#dbeafe"),
|
||||
transparent: true,
|
||||
opacity: 0.13,
|
||||
depthWrite: false,
|
||||
blending: THREE.AdditiveBlending,
|
||||
});
|
||||
const points = new THREE.Points(geometry, material);
|
||||
scene.add(points);
|
||||
cleanupMaterials.add(material);
|
||||
particleGroups.push({
|
||||
geometry,
|
||||
positions,
|
||||
baseY,
|
||||
drift,
|
||||
phase,
|
||||
kind: "cloud",
|
||||
material,
|
||||
mesh: points,
|
||||
});
|
||||
}
|
||||
|
||||
createParticleField(90, 0.018, aura.particleOpacity * 0.9, -0.1);
|
||||
createParticleField(60, 0.026, aura.particleOpacity * 0.65, 0.08);
|
||||
|
||||
if (aura.effect === "rain" || aura.effect === "storm") {
|
||||
createRainField(aura.effect === "storm" ? 240 : 170);
|
||||
} else if (aura.effect === "snow") {
|
||||
createSnowField(150);
|
||||
} else if (aura.effect === "fog") {
|
||||
createFogField(90);
|
||||
} else if (aura.effect === "cloud" || aura.effect === "wind") {
|
||||
createCloudField(aura.effect === "wind" ? 80 : 54);
|
||||
}
|
||||
|
||||
if (aura.effect === "storm") {
|
||||
const flashLight = new THREE.PointLight(0xdbeafe, 0, 6, 2);
|
||||
flashLight.position.set(0.2, 0.9, 1.1);
|
||||
scene.add(flashLight);
|
||||
effectLights.push(flashLight);
|
||||
}
|
||||
|
||||
const resize = () => {
|
||||
const width = host.clientWidth || window.innerWidth;
|
||||
const height = host.clientHeight || window.innerHeight;
|
||||
renderer.setSize(width, height, false);
|
||||
};
|
||||
|
||||
resize();
|
||||
host.appendChild(renderer.domElement);
|
||||
|
||||
let frameId = 0;
|
||||
let lastFrameAt = 0;
|
||||
|
||||
const renderFrame = (timestamp: number) => {
|
||||
frameId = window.requestAnimationFrame(renderFrame);
|
||||
if (timestamp - lastFrameAt < 40) {
|
||||
return;
|
||||
}
|
||||
lastFrameAt = timestamp;
|
||||
|
||||
const elapsed = clock.getElapsedTime();
|
||||
for (const field of particleGroups) {
|
||||
for (let index = 0; index < field.baseY.length; index += 1) {
|
||||
const offset = index * 3;
|
||||
if (field.kind === "flow") {
|
||||
let nextX = field.positions[offset] + field.drift[index];
|
||||
if (nextX > 1.35) {
|
||||
nextX = -1.35;
|
||||
field.baseY[index] = Math.random() * 1.8 - 0.9;
|
||||
}
|
||||
field.positions[offset] = nextX;
|
||||
field.positions[offset + 1] =
|
||||
field.baseY[index] +
|
||||
Math.sin(elapsed * 0.45 + field.phase[index] + nextX * 2.4) *
|
||||
0.06 *
|
||||
aura.intensity;
|
||||
} else if (field.kind === "rain") {
|
||||
let nextY = field.positions[offset + 1] - field.drift[index];
|
||||
let nextX = field.positions[offset] + field.phase[index] * aura.drift;
|
||||
if (nextY < -1.12 || nextX > 1.45) {
|
||||
nextY = 1.15 + Math.random() * 0.25;
|
||||
nextX = Math.random() * 2.9 - 1.45;
|
||||
}
|
||||
field.positions[offset] = nextX;
|
||||
field.positions[offset + 1] = nextY;
|
||||
} else if (field.kind === "snow") {
|
||||
let nextY = field.positions[offset + 1] - field.drift[index];
|
||||
let nextX =
|
||||
field.positions[offset] +
|
||||
Math.sin(elapsed * 0.9 + field.phase[index]) * 0.0024 * aura.effectIntensity;
|
||||
if (nextY < -1.1) {
|
||||
nextY = 1.12 + Math.random() * 0.2;
|
||||
nextX = Math.random() * 2.8 - 1.4;
|
||||
}
|
||||
field.positions[offset] = nextX;
|
||||
field.positions[offset + 1] = nextY;
|
||||
} else if (field.kind === "fog" || field.kind === "cloud") {
|
||||
let nextX = field.positions[offset] + field.drift[index];
|
||||
if (nextX > 1.38) {
|
||||
nextX = -1.38;
|
||||
field.baseY[index] =
|
||||
field.kind === "cloud"
|
||||
? Math.random() * 0.75 + 0.1
|
||||
: Math.random() * 0.9 - 0.45;
|
||||
}
|
||||
field.positions[offset] = nextX;
|
||||
field.positions[offset + 1] =
|
||||
field.baseY[index] +
|
||||
Math.sin(elapsed * 0.3 + field.phase[index]) *
|
||||
(field.kind === "cloud" ? 0.03 : 0.05);
|
||||
}
|
||||
}
|
||||
|
||||
field.geometry.attributes.position.needsUpdate = true;
|
||||
}
|
||||
|
||||
if (effectLights.length > 0) {
|
||||
const flashPulse = Math.max(0, Math.sin(elapsed * 2.1) - 0.78) * 20;
|
||||
for (const light of effectLights) {
|
||||
if (light instanceof THREE.PointLight) {
|
||||
light.intensity = flashPulse;
|
||||
}
|
||||
}
|
||||
(flashOverlay.material as THREE.MeshBasicMaterial).opacity = Math.min(
|
||||
0.18,
|
||||
flashPulse / 120,
|
||||
);
|
||||
} else {
|
||||
(flashOverlay.material as THREE.MeshBasicMaterial).opacity = 0;
|
||||
}
|
||||
|
||||
renderer.render(scene, camera);
|
||||
};
|
||||
|
||||
frameId = window.requestAnimationFrame(renderFrame);
|
||||
window.addEventListener("resize", resize);
|
||||
|
||||
return () => {
|
||||
window.cancelAnimationFrame(frameId);
|
||||
window.removeEventListener("resize", resize);
|
||||
for (const child of [...scene.children]) {
|
||||
scene.remove(child);
|
||||
}
|
||||
for (const field of particleGroups) {
|
||||
field.geometry.dispose();
|
||||
}
|
||||
cleanupMaterials.forEach((material) => material.dispose());
|
||||
renderer.dispose();
|
||||
if (renderer.domElement.parentNode === host) {
|
||||
host.removeChild(renderer.domElement);
|
||||
}
|
||||
};
|
||||
}, [
|
||||
aura.drift,
|
||||
aura.intensity,
|
||||
aura.particleOpacity,
|
||||
aura.primary,
|
||||
aura.secondary,
|
||||
aura.tertiary,
|
||||
aura.effect,
|
||||
aura.effectIntensity,
|
||||
isDesktop,
|
||||
prefersReducedMotion,
|
||||
]);
|
||||
|
||||
if (!isDesktop) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const overlayStyle = {
|
||||
backgroundImage: [
|
||||
`radial-gradient(circle at 18% 22%, ${hexToRgba(aura.primary, 0.18 * aura.intensity)}, transparent 32%)`,
|
||||
`radial-gradient(circle at 78% 20%, ${hexToRgba(aura.secondary, 0.14 * aura.intensity)}, transparent 34%)`,
|
||||
`radial-gradient(circle at 52% 78%, ${hexToRgba(aura.tertiary, 0.12 * aura.intensity)}, transparent 38%)`,
|
||||
aura.effect === "rain" || aura.effect === "storm"
|
||||
? `linear-gradient(180deg, ${hexToRgba("#67e8f9", 0.06 * aura.effectIntensity)}, transparent 45%)`
|
||||
: aura.effect === "snow"
|
||||
? `linear-gradient(180deg, ${hexToRgba("#e2e8f0", 0.06 * aura.effectIntensity)}, transparent 45%)`
|
||||
: aura.effect === "fog"
|
||||
? `radial-gradient(circle at 50% 56%, ${hexToRgba("#cbd5e1", 0.08 * aura.effectIntensity)}, transparent 60%)`
|
||||
: aura.effect === "cloud"
|
||||
? `linear-gradient(180deg, ${hexToRgba("#dbeafe", 0.04 * aura.effectIntensity)}, transparent 40%)`
|
||||
: "none",
|
||||
].join(", "),
|
||||
} as CSSProperties;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
aria-hidden="true"
|
||||
className={styles.weatherAura}
|
||||
data-reduced-motion={prefersReducedMotion ? "true" : "false"}
|
||||
style={overlayStyle}
|
||||
>
|
||||
<div className={styles.weatherAuraScrim} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
.docsShell {
|
||||
min-height: 100vh;
|
||||
color: rgba(226, 232, 240, 0.94);
|
||||
}
|
||||
|
||||
.docsHeader {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 40;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 18px 24px;
|
||||
background: rgba(2, 6, 23, 0.82);
|
||||
border-bottom: 1px solid rgba(148, 163, 184, 0.12);
|
||||
backdrop-filter: blur(16px);
|
||||
}
|
||||
|
||||
.brandWrap {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.brandLink {
|
||||
color: #67e8f9;
|
||||
font-size: 1.9rem;
|
||||
font-weight: 800;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.brandSubtitle {
|
||||
color: rgba(148, 163, 184, 0.88);
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.headerActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.headerButton,
|
||||
.headerGhost {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 38px;
|
||||
padding: 0 14px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(148, 163, 184, 0.18);
|
||||
background: rgba(15, 23, 42, 0.75);
|
||||
color: rgba(226, 232, 240, 0.95);
|
||||
text-decoration: none;
|
||||
font-size: 0.92rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.headerGhost {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.langSwitch {
|
||||
display: flex;
|
||||
border: 1px solid rgba(148, 163, 184, 0.18);
|
||||
border-radius: 999px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.langButton {
|
||||
min-width: 54px;
|
||||
min-height: 38px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: rgba(148, 163, 184, 0.92);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.langButtonActive {
|
||||
background: rgba(34, 211, 238, 0.16);
|
||||
color: #67e8f9;
|
||||
}
|
||||
|
||||
.docsFrame {
|
||||
display: grid;
|
||||
grid-template-columns: 280px minmax(0, 1fr) 220px;
|
||||
gap: 28px;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
position: sticky;
|
||||
top: 86px;
|
||||
align-self: start;
|
||||
max-height: calc(100vh - 110px);
|
||||
overflow: auto;
|
||||
padding: 20px;
|
||||
border: 1px solid rgba(148, 163, 184, 0.12);
|
||||
border-radius: 20px;
|
||||
background: rgba(15, 23, 42, 0.72);
|
||||
}
|
||||
|
||||
.sidebarGroup + .sidebarGroup {
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.sidebarTitle {
|
||||
margin: 0 0 10px;
|
||||
color: rgba(148, 163, 184, 0.92);
|
||||
font-size: 0.8rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.sidebarLink {
|
||||
display: block;
|
||||
margin-bottom: 6px;
|
||||
padding: 10px 12px;
|
||||
border-radius: 12px;
|
||||
color: rgba(226, 232, 240, 0.88);
|
||||
text-decoration: none;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.sidebarLinkActive {
|
||||
background: rgba(34, 211, 238, 0.12);
|
||||
color: #67e8f9;
|
||||
}
|
||||
|
||||
.content {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.contentInner {
|
||||
padding: 12px 0 48px;
|
||||
}
|
||||
|
||||
.pageTitle {
|
||||
margin: 0;
|
||||
font-size: clamp(2.1rem, 4vw, 3.2rem);
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.03em;
|
||||
}
|
||||
|
||||
.pageDescription {
|
||||
max-width: 820px;
|
||||
margin: 14px 0 0;
|
||||
color: rgba(191, 219, 254, 0.9);
|
||||
font-size: 1.03rem;
|
||||
line-height: 1.75;
|
||||
}
|
||||
|
||||
.section {
|
||||
margin-top: 40px;
|
||||
scroll-margin-top: 110px;
|
||||
}
|
||||
|
||||
.sectionTitle {
|
||||
margin: 0 0 16px;
|
||||
font-size: 1.65rem;
|
||||
font-weight: 750;
|
||||
}
|
||||
|
||||
.paragraph {
|
||||
margin: 0 0 16px;
|
||||
color: rgba(226, 232, 240, 0.94);
|
||||
line-height: 1.9;
|
||||
}
|
||||
|
||||
.callout {
|
||||
margin: 18px 0;
|
||||
padding: 18px 20px;
|
||||
border: 1px solid rgba(148, 163, 184, 0.16);
|
||||
border-radius: 18px;
|
||||
background: rgba(15, 23, 42, 0.72);
|
||||
}
|
||||
|
||||
.calloutInfo {
|
||||
border-color: rgba(34, 211, 238, 0.24);
|
||||
background: rgba(8, 47, 73, 0.26);
|
||||
}
|
||||
|
||||
.calloutWarning {
|
||||
border-color: rgba(251, 191, 36, 0.24);
|
||||
background: rgba(120, 53, 15, 0.2);
|
||||
}
|
||||
|
||||
.calloutSuccess {
|
||||
border-color: rgba(52, 211, 153, 0.24);
|
||||
background: rgba(6, 78, 59, 0.22);
|
||||
}
|
||||
|
||||
.calloutTitle {
|
||||
margin: 0 0 8px;
|
||||
font-size: 0.98rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.calloutText {
|
||||
margin: 0;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
.list {
|
||||
margin: 0;
|
||||
padding-left: 20px;
|
||||
color: rgba(226, 232, 240, 0.94);
|
||||
line-height: 1.85;
|
||||
}
|
||||
|
||||
.list li + li {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.linkCard {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 42px;
|
||||
padding: 0 16px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(34, 211, 238, 0.34);
|
||||
background: rgba(8, 47, 73, 0.3);
|
||||
color: #67e8f9;
|
||||
text-decoration: none;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.linkCard:hover {
|
||||
background: rgba(34, 211, 238, 0.12);
|
||||
}
|
||||
|
||||
.linkCaption {
|
||||
margin: 10px 0 0;
|
||||
color: rgba(148, 163, 184, 0.92);
|
||||
line-height: 1.75;
|
||||
}
|
||||
|
||||
.toc {
|
||||
position: sticky;
|
||||
top: 86px;
|
||||
align-self: start;
|
||||
padding: 20px;
|
||||
border: 1px solid rgba(148, 163, 184, 0.12);
|
||||
border-radius: 20px;
|
||||
background: rgba(15, 23, 42, 0.64);
|
||||
}
|
||||
|
||||
.tocTitle {
|
||||
margin: 0 0 12px;
|
||||
color: rgba(148, 163, 184, 0.92);
|
||||
font-size: 0.82rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.tocLink {
|
||||
display: block;
|
||||
color: rgba(226, 232, 240, 0.86);
|
||||
text-decoration: none;
|
||||
line-height: 1.7;
|
||||
font-size: 0.92rem;
|
||||
}
|
||||
|
||||
.mobileMenuButton {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.mobileSidebarBackdrop {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.docsFrame {
|
||||
grid-template-columns: 260px minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.toc {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.docsHeader {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.docsFrame {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.mobileMenuButton {
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 60;
|
||||
width: min(320px, 88vw);
|
||||
height: 100vh;
|
||||
max-height: none;
|
||||
border-radius: 0 20px 20px 0;
|
||||
transform: translateX(-100%);
|
||||
transition: transform 180ms ease-out;
|
||||
}
|
||||
|
||||
.sidebarOpen {
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
.mobileSidebarBackdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 50;
|
||||
background: rgba(2, 6, 23, 0.52);
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.docsHeader {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.docsFrame {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.brandWrap {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.pageDescription {
|
||||
font-size: 0.98rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useMemo, useState } from "react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import clsx from "clsx";
|
||||
import styles from "./DocsLayout.module.css";
|
||||
import {
|
||||
DocsLocale,
|
||||
DocsPage,
|
||||
DocsPageContent,
|
||||
} from "@/content/docs/docs";
|
||||
import { DOCS_GROUPS } from "@/content/docs/docs.config";
|
||||
import { DOCS_PAGES } from "@/content/docs/docs";
|
||||
import { useI18n } from "@/hooks/useI18n";
|
||||
|
||||
function DocsHeader() {
|
||||
const { locale, setLocale } = useI18n();
|
||||
|
||||
return (
|
||||
<header className={styles.docsHeader}>
|
||||
<div className={styles.brandWrap}>
|
||||
<Link href="/" className={styles.brandLink}>
|
||||
PolyWeather
|
||||
</Link>
|
||||
<span className={styles.brandSubtitle}>
|
||||
{locale === "zh-CN" ? "产品文档中心" : "Product Documentation"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className={styles.headerActions}>
|
||||
<Link href="/" className={styles.headerGhost}>
|
||||
{locale === "zh-CN" ? "返回主站" : "Back to App"}
|
||||
</Link>
|
||||
<div className={styles.langSwitch} role="group" aria-label="Language switch">
|
||||
<button
|
||||
type="button"
|
||||
className={clsx(styles.langButton, locale === "zh-CN" && styles.langButtonActive)}
|
||||
onClick={() => setLocale("zh-CN")}
|
||||
>
|
||||
中文
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={clsx(styles.langButton, locale === "en-US" && styles.langButtonActive)}
|
||||
onClick={() => setLocale("en-US")}
|
||||
>
|
||||
EN
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
function DocsSidebar({
|
||||
currentSlug,
|
||||
locale,
|
||||
open,
|
||||
onClose,
|
||||
}: {
|
||||
currentSlug: string;
|
||||
locale: DocsLocale;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
{open && <button type="button" className={styles.mobileSidebarBackdrop} onClick={onClose} aria-label="Close menu" />}
|
||||
<aside className={clsx(styles.sidebar, open && styles.sidebarOpen)}>
|
||||
{DOCS_GROUPS.map((group) => {
|
||||
const pages = DOCS_PAGES.filter((page) => page.group === group.id);
|
||||
return (
|
||||
<div key={group.id} className={styles.sidebarGroup}>
|
||||
<div className={styles.sidebarTitle}>{group.title[locale]}</div>
|
||||
{pages.map((page) => {
|
||||
const title = page.content[locale].title;
|
||||
const href = `/docs/${page.slug}`;
|
||||
return (
|
||||
<Link
|
||||
key={page.slug}
|
||||
href={href}
|
||||
className={clsx(styles.sidebarLink, currentSlug === page.slug && styles.sidebarLinkActive)}
|
||||
onClick={onClose}
|
||||
>
|
||||
{title}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DocsToc({ page, locale }: { page: DocsPageContent; locale: DocsLocale }) {
|
||||
return (
|
||||
<aside className={styles.toc}>
|
||||
<div className={styles.tocTitle}>{locale === "zh-CN" ? "本页目录" : "On this page"}</div>
|
||||
{page.sections.map((section) => (
|
||||
<a key={section.id} href={`#${section.id}`} className={styles.tocLink}>
|
||||
{section.title}
|
||||
</a>
|
||||
))}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
function BlockRenderer({ block }: { block: DocsPageContent["sections"][number]["blocks"][number] }) {
|
||||
switch (block.type) {
|
||||
case "paragraph":
|
||||
return <p className={styles.paragraph}>{block.text}</p>;
|
||||
case "callout":
|
||||
return (
|
||||
<div className={clsx(styles.callout, block.tone === "warning" && styles.calloutWarning, block.tone === "success" && styles.calloutSuccess, (!block.tone || block.tone === "info") && styles.calloutInfo)}>
|
||||
{block.title ? <div className={styles.calloutTitle}>{block.title}</div> : null}
|
||||
<p className={styles.calloutText}>{block.text}</p>
|
||||
</div>
|
||||
);
|
||||
case "bullets":
|
||||
case "steps":
|
||||
return (
|
||||
<ul className={styles.list}>
|
||||
{block.items.map((item) => (
|
||||
<li key={item}>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
case "link":
|
||||
return (
|
||||
<div>
|
||||
<a
|
||||
href={block.href}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className={styles.linkCard}
|
||||
>
|
||||
{block.label}
|
||||
</a>
|
||||
{block.caption ? <p className={styles.linkCaption}>{block.caption}</p> : null}
|
||||
</div>
|
||||
);
|
||||
case "image":
|
||||
return (
|
||||
<figure>
|
||||
<img src={block.src} alt={block.alt} />
|
||||
{block.caption ? <figcaption>{block.caption}</figcaption> : null}
|
||||
</figure>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function DocsScreen({ page }: { page: DocsPage }) {
|
||||
const pathname = usePathname();
|
||||
const { locale } = useI18n();
|
||||
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
|
||||
const localizedPage = useMemo(() => page.content[locale], [locale, page]);
|
||||
const currentSlug = pathname?.split("/").filter(Boolean).at(-1) || page.slug;
|
||||
|
||||
return (
|
||||
<div className={styles.docsShell}>
|
||||
<DocsHeader />
|
||||
<div className={styles.docsFrame}>
|
||||
<DocsSidebar
|
||||
currentSlug={currentSlug}
|
||||
locale={locale}
|
||||
open={mobileSidebarOpen}
|
||||
onClose={() => setMobileSidebarOpen(false)}
|
||||
/>
|
||||
|
||||
<main className={styles.content}>
|
||||
<div className={styles.contentInner}>
|
||||
<button type="button" className={clsx(styles.headerButton, styles.mobileMenuButton)} onClick={() => setMobileSidebarOpen(true)}>
|
||||
{locale === "zh-CN" ? "打开导航" : "Open navigation"}
|
||||
</button>
|
||||
<h1 className={styles.pageTitle}>{localizedPage.title}</h1>
|
||||
<p className={styles.pageDescription}>{localizedPage.description}</p>
|
||||
{localizedPage.sections.map((section) => (
|
||||
<section key={section.id} id={section.id} className={styles.section}>
|
||||
<h2 className={styles.sectionTitle}>{section.title}</h2>
|
||||
{section.blocks.map((block, index) => (
|
||||
<BlockRenderer key={`${section.id}-${index}`} block={block} />
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<DocsToc page={localizedPage} locale={locale} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,793 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { AlertTriangle, Database, RefreshCcw, ShieldCheck, Wallet } from "lucide-react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
type HealthPayload = {
|
||||
status?: string;
|
||||
db?: { ok?: boolean };
|
||||
};
|
||||
|
||||
type ProbabilityRollout = {
|
||||
decision?: string;
|
||||
ready_for_primary?: boolean;
|
||||
blocking_reasons?: string[];
|
||||
};
|
||||
|
||||
type SystemStatusPayload = {
|
||||
state_storage_mode?: string;
|
||||
db?: { ok?: boolean; db_path?: string };
|
||||
features?: Record<string, unknown>;
|
||||
metrics?: Record<string, unknown>;
|
||||
probability?: {
|
||||
engine_mode?: string;
|
||||
rollout?: {
|
||||
decision?: ProbabilityRollout;
|
||||
evaluation_report_exists?: boolean;
|
||||
shadow_report_exists?: boolean;
|
||||
};
|
||||
};
|
||||
integrations?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
type PaymentRuntimePayload = {
|
||||
checkout?: {
|
||||
enabled?: boolean;
|
||||
configured?: boolean;
|
||||
chain_id?: number;
|
||||
receiver_contract?: string;
|
||||
confirmations?: number;
|
||||
};
|
||||
rpc?: {
|
||||
configured_rpc_count?: number;
|
||||
active_rpc_url?: string;
|
||||
};
|
||||
event_loop_state?: {
|
||||
last_scanned_block?: number;
|
||||
updated_at?: string;
|
||||
};
|
||||
recent_audit_events?: Array<{
|
||||
id: number;
|
||||
event_type: string;
|
||||
created_at: string;
|
||||
payload?: {
|
||||
reason?: string;
|
||||
detail?: string;
|
||||
tx_hash?: string;
|
||||
receiver_actual?: string;
|
||||
receiver_expected?: string;
|
||||
};
|
||||
}>;
|
||||
};
|
||||
|
||||
type PaymentIncident = {
|
||||
id: number;
|
||||
event_type: string;
|
||||
created_at: string;
|
||||
payload?: {
|
||||
reason?: string;
|
||||
detail?: string;
|
||||
tx_hash?: string;
|
||||
receiver_actual?: string;
|
||||
receiver_expected?: string;
|
||||
plan_code?: string;
|
||||
resolved_at?: string;
|
||||
resolved_by?: string;
|
||||
};
|
||||
};
|
||||
|
||||
type AuthMePayload = {
|
||||
authenticated?: boolean;
|
||||
email?: string | null;
|
||||
entitlement_mode?: string;
|
||||
subscription_active?: boolean | null;
|
||||
weekly_rank?: number | null;
|
||||
points?: number;
|
||||
};
|
||||
|
||||
type OpsUser = {
|
||||
telegram_id: number;
|
||||
username?: string | null;
|
||||
points?: number;
|
||||
daily_points?: number;
|
||||
daily_points_date?: string | null;
|
||||
weekly_points?: number;
|
||||
weekly_points_week?: string | null;
|
||||
message_count?: number;
|
||||
supabase_email?: string | null;
|
||||
last_message_at?: string | null;
|
||||
};
|
||||
|
||||
type WeeklyLeaderboardEntry = {
|
||||
telegram_id: number;
|
||||
username?: string | null;
|
||||
points?: number;
|
||||
message_count?: number;
|
||||
weekly_points?: number;
|
||||
};
|
||||
|
||||
type MembershipEntry = {
|
||||
user_id: string;
|
||||
email?: string | null;
|
||||
telegram_id?: number | null;
|
||||
username?: string | null;
|
||||
registered_at?: string | null;
|
||||
plan_code?: string | null;
|
||||
starts_at?: string | null;
|
||||
expires_at?: string | null;
|
||||
};
|
||||
|
||||
function formatDateTime(value?: string | null) {
|
||||
if (!value) return "-";
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
return date.toLocaleString("zh-CN", { hour12: false });
|
||||
}
|
||||
|
||||
function maskUrl(value?: string | null) {
|
||||
if (!value) return "-";
|
||||
if (value.length <= 40) return value;
|
||||
return `${value.slice(0, 28)}...${value.slice(-8)}`;
|
||||
}
|
||||
|
||||
async function readJson<T>(url: string): Promise<T> {
|
||||
const response = await fetch(url, { cache: "no-store" });
|
||||
if (!response.ok) {
|
||||
const raw = await response.text();
|
||||
throw new Error(`${url} -> HTTP ${response.status} ${raw.slice(0, 180)}`);
|
||||
}
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
function MobileField({
|
||||
label,
|
||||
value,
|
||||
mono = false,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
mono?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className="rounded-xl border border-slate-800 bg-slate-950/60 px-3 py-2">
|
||||
<div className="text-[11px] font-bold uppercase tracking-[0.14em] text-slate-500">{label}</div>
|
||||
<div className={`mt-1 break-all text-sm text-slate-200 ${mono ? "font-mono text-xs" : ""}`}>{value}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function OpsDashboard() {
|
||||
const [health, setHealth] = useState<HealthPayload | null>(null);
|
||||
const [status, setStatus] = useState<SystemStatusPayload | null>(null);
|
||||
const [payments, setPayments] = useState<PaymentRuntimePayload | null>(null);
|
||||
const [auth, setAuth] = useState<AuthMePayload | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [refreshedAt, setRefreshedAt] = useState<string | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [users, setUsers] = useState<OpsUser[]>([]);
|
||||
const [memberships, setMemberships] = useState<MembershipEntry[]>([]);
|
||||
const [paymentIncidents, setPaymentIncidents] = useState<PaymentIncident[]>([]);
|
||||
const [incidentReasonFilter, setIncidentReasonFilter] = useState("all");
|
||||
const [usersLoading, setUsersLoading] = useState(false);
|
||||
const [usersError, setUsersError] = useState<string | null>(null);
|
||||
const [leaderboard, setLeaderboard] = useState<WeeklyLeaderboardEntry[]>([]);
|
||||
const [membershipsLoading, setMembershipsLoading] = useState(false);
|
||||
const [incidentsLoading, setIncidentsLoading] = useState(false);
|
||||
const [resolvingIncidentId, setResolvingIncidentId] = useState<number | null>(null);
|
||||
const [grantEmail, setGrantEmail] = useState("");
|
||||
const [grantPoints, setGrantPoints] = useState("300");
|
||||
const [grantStatus, setGrantStatus] = useState<string | null>(null);
|
||||
const [grantError, setGrantError] = useState<string | null>(null);
|
||||
const [grantLoading, setGrantLoading] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const [healthData, statusData, paymentData, authData] = await Promise.all([
|
||||
readJson<HealthPayload>("/api/healthz"),
|
||||
readJson<SystemStatusPayload>("/api/system/status"),
|
||||
readJson<PaymentRuntimePayload>("/api/payments/runtime"),
|
||||
readJson<AuthMePayload>("/api/auth/me"),
|
||||
]);
|
||||
|
||||
setHealth(healthData);
|
||||
setStatus(statusData);
|
||||
setPayments(paymentData);
|
||||
setAuth(authData);
|
||||
setRefreshedAt(new Date().toISOString());
|
||||
} catch (loadError) {
|
||||
setError(String(loadError));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
const loadUsers = useCallback(async (query: string) => {
|
||||
setUsersLoading(true);
|
||||
setUsersError(null);
|
||||
try {
|
||||
const url = new URL("/api/ops/users", window.location.origin);
|
||||
if (query.trim()) {
|
||||
url.searchParams.set("q", query.trim());
|
||||
}
|
||||
url.searchParams.set("limit", "20");
|
||||
const data = await readJson<{ users?: OpsUser[] }>(url.toString());
|
||||
setUsers(data.users || []);
|
||||
} catch (loadError) {
|
||||
setUsersError(String(loadError));
|
||||
} finally {
|
||||
setUsersLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadLeaderboard = useCallback(async () => {
|
||||
try {
|
||||
const data = await readJson<{ leaderboard?: WeeklyLeaderboardEntry[] }>(
|
||||
"/api/ops/leaderboard/weekly?limit=10",
|
||||
);
|
||||
setLeaderboard(data.leaderboard || []);
|
||||
} catch {
|
||||
setLeaderboard([]);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadMemberships = useCallback(async () => {
|
||||
setMembershipsLoading(true);
|
||||
try {
|
||||
const data = await readJson<{ memberships?: MembershipEntry[] }>(
|
||||
"/api/ops/memberships?limit=200",
|
||||
);
|
||||
setMemberships(data.memberships || []);
|
||||
} catch {
|
||||
setMemberships([]);
|
||||
} finally {
|
||||
setMembershipsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const loadPaymentIncidents = useCallback(async (reasonFilter?: string) => {
|
||||
setIncidentsLoading(true);
|
||||
try {
|
||||
const url = new URL("/api/ops/payments/incidents", window.location.origin);
|
||||
url.searchParams.set("limit", "20");
|
||||
const selectedReason = String(reasonFilter || incidentReasonFilter || "all");
|
||||
if (selectedReason && selectedReason !== "all") {
|
||||
url.searchParams.set("reason", selectedReason);
|
||||
}
|
||||
const data = await readJson<{ incidents?: PaymentIncident[] }>(url.toString());
|
||||
setPaymentIncidents(data.incidents || []);
|
||||
} catch {
|
||||
setPaymentIncidents([]);
|
||||
} finally {
|
||||
setIncidentsLoading(false);
|
||||
}
|
||||
}, [incidentReasonFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadUsers("");
|
||||
void loadLeaderboard();
|
||||
void loadMemberships();
|
||||
void loadPaymentIncidents(incidentReasonFilter);
|
||||
}, [loadLeaderboard, loadMemberships, loadPaymentIncidents, loadUsers]);
|
||||
|
||||
const resolveIncident = useCallback(async (eventId: number) => {
|
||||
setResolvingIncidentId(eventId);
|
||||
try {
|
||||
const response = await fetch(`/api/ops/payments/incidents/${eventId}/resolve`, {
|
||||
method: "POST",
|
||||
});
|
||||
if (!response.ok) {
|
||||
const raw = await response.text();
|
||||
throw new Error(raw || `HTTP ${response.status}`);
|
||||
}
|
||||
await loadPaymentIncidents(incidentReasonFilter);
|
||||
await load();
|
||||
} finally {
|
||||
setResolvingIncidentId(null);
|
||||
}
|
||||
}, [incidentReasonFilter, load, loadPaymentIncidents]);
|
||||
|
||||
const rolloutDecision = status?.probability?.rollout?.decision;
|
||||
|
||||
const rolloutVariant = useMemo(() => {
|
||||
const decision = rolloutDecision?.decision;
|
||||
if (decision === "promote") return "success" as const;
|
||||
if (decision === "observe") return "warning" as const;
|
||||
return "danger" as const;
|
||||
}, [rolloutDecision?.decision]);
|
||||
|
||||
const submitGrant = useCallback(async () => {
|
||||
setGrantLoading(true);
|
||||
setGrantError(null);
|
||||
setGrantStatus(null);
|
||||
try {
|
||||
const response = await fetch("/api/ops/users/grant-points", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
email: grantEmail.trim(),
|
||||
points: Number(grantPoints),
|
||||
}),
|
||||
});
|
||||
const payload = (await response.json()) as {
|
||||
ok?: boolean;
|
||||
detail?: { reason?: string };
|
||||
points_after?: number;
|
||||
points_added?: number;
|
||||
supabase_email?: string;
|
||||
};
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
payload?.detail?.reason || `HTTP ${response.status}`,
|
||||
);
|
||||
}
|
||||
setGrantStatus(
|
||||
`${payload.supabase_email || grantEmail.trim()} 已补 ${payload.points_added || grantPoints} 分,当前 ${payload.points_after ?? "-"}`,
|
||||
);
|
||||
await loadUsers(searchQuery);
|
||||
await loadLeaderboard();
|
||||
await loadMemberships();
|
||||
await loadPaymentIncidents(incidentReasonFilter);
|
||||
} catch (submitError) {
|
||||
setGrantError(String(submitError));
|
||||
} finally {
|
||||
setGrantLoading(false);
|
||||
}
|
||||
}, [grantEmail, grantPoints, incidentReasonFilter, loadLeaderboard, loadMemberships, loadPaymentIncidents, loadUsers, searchQuery]);
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-slate-950 px-3 py-6 text-slate-100 sm:px-6 sm:py-8 lg:px-8">
|
||||
<div className="mx-auto flex max-w-7xl flex-col gap-5 sm:gap-6">
|
||||
<section className="flex flex-col gap-4 rounded-2xl border border-slate-800 bg-slate-900/80 p-4 shadow-2xl backdrop-blur-xl sm:rounded-3xl sm:p-6 lg:flex-row lg:items-end lg:justify-between">
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Badge variant="secondary">Ops</Badge>
|
||||
<Badge variant={health?.status === "ok" ? "success" : "danger"}>
|
||||
Health {health?.status || "unknown"}
|
||||
</Badge>
|
||||
<Badge variant={status?.db?.ok ? "success" : "danger"}>
|
||||
SQLite {status?.db?.ok ? "ok" : "error"}
|
||||
</Badge>
|
||||
<Badge variant={rolloutVariant}>
|
||||
EMOS {rolloutDecision?.decision || "hold"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-black tracking-tight sm:text-3xl">PolyWeather Ops</h1>
|
||||
<p className="mt-2 max-w-3xl text-sm text-slate-400">
|
||||
直接挂在现有域名下的轻量运营页。先做只读运维视图,把系统状态、支付运行态和当前登录态聚合起来。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col items-stretch gap-3 text-xs text-slate-400 sm:flex-row sm:flex-wrap sm:items-center">
|
||||
<span className="break-all">刷新时间: {formatDateTime(refreshedAt)}</span>
|
||||
<Button onClick={() => void load()} disabled={loading} className="gap-2 sm:w-auto">
|
||||
<RefreshCcw className="h-4 w-4" />
|
||||
{loading ? "加载中" : "刷新"}
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{error ? (
|
||||
<Card className="border-rose-500/30 bg-rose-500/10">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-rose-300">加载失败</CardTitle>
|
||||
<CardDescription className="text-rose-200/80">{error}</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
<section className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<ShieldCheck className="h-4 w-4" /> 系统健康
|
||||
</CardTitle>
|
||||
<CardDescription>后端健康、鉴权策略、状态存储模式。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm text-slate-300">
|
||||
<div className="flex justify-between gap-3"><span>healthz</span><span>{health?.status || "-"}</span></div>
|
||||
<div className="flex justify-between gap-3"><span>鉴权模式</span><span>{auth?.entitlement_mode || "-"}</span></div>
|
||||
<div className="flex justify-between gap-3"><span>状态存储</span><span>{status?.state_storage_mode || "-"}</span></div>
|
||||
<div className="flex justify-between gap-3"><span>DB</span><span>{health?.db?.ok ? "ok" : "-"}</span></div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Database className="h-4 w-4" /> 运行态存储
|
||||
</CardTitle>
|
||||
<CardDescription>SQLite 是否正常,以及 rollout 当前状态。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm text-slate-300">
|
||||
<div className="flex justify-between gap-3"><span>SQLite</span><span>{status?.db?.ok ? "ok" : "error"}</span></div>
|
||||
<div className="flex justify-between gap-3"><span>EMOS 模式</span><span>{status?.probability?.engine_mode || "-"}</span></div>
|
||||
<div className="flex justify-between gap-3"><span>上线门禁</span><span>{rolloutDecision?.decision || "-"}</span></div>
|
||||
<div className="flex justify-between gap-3"><span>ready_for_primary</span><span>{rolloutDecision?.ready_for_primary ? "true" : "false"}</span></div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Wallet className="h-4 w-4" /> 支付运行态
|
||||
</CardTitle>
|
||||
<CardDescription>当前 RPC、事件循环区块、合约配置。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm text-slate-300">
|
||||
<div className="flex justify-between gap-3"><span>支付启用</span><span>{payments?.checkout?.enabled ? "true" : "false"}</span></div>
|
||||
<div className="flex justify-between gap-3"><span>RPC 数量</span><span>{payments?.rpc?.configured_rpc_count ?? 0}</span></div>
|
||||
<div className="flex justify-between gap-3"><span>链</span><span>{payments?.checkout?.chain_id ?? "-"}</span></div>
|
||||
<div className="flex justify-between gap-3"><span>最后区块</span><span>{payments?.event_loop_state?.last_scanned_block ?? "-"}</span></div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-4 w-4" /> 当前登录态
|
||||
</CardTitle>
|
||||
<CardDescription>先确认管理员自己当前有没有会话。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm text-slate-300">
|
||||
<div className="flex justify-between gap-3"><span>authenticated</span><span>{auth?.authenticated ? "true" : "false"}</span></div>
|
||||
<div className="flex justify-between gap-3"><span>email</span><span className="truncate text-right">{auth?.email || "-"}</span></div>
|
||||
<div className="flex justify-between gap-3"><span>points</span><span>{auth?.points ?? 0}</span></div>
|
||||
<div className="flex justify-between gap-3"><span>weekly_rank</span><span>{auth?.weekly_rank ?? "-"}</span></div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
|
||||
<section className="grid gap-4 xl:grid-cols-[1.4fr_1fr]">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>EMOS 上线门禁</CardTitle>
|
||||
<CardDescription>当前 shadow 到 primary 的发布判断。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 text-sm text-slate-300">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Badge variant={rolloutVariant}>{rolloutDecision?.decision || "hold"}</Badge>
|
||||
<Badge variant={rolloutDecision?.ready_for_primary ? "success" : "warning"}>
|
||||
ready={rolloutDecision?.ready_for_primary ? "true" : "false"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-2 text-xs font-bold uppercase tracking-[0.16em] text-slate-500">阻塞原因</div>
|
||||
<ul className="space-y-2">
|
||||
{(rolloutDecision?.blocking_reasons || []).length ? (
|
||||
(rolloutDecision?.blocking_reasons || []).map((reason) => (
|
||||
<li key={reason} className="rounded-2xl border border-slate-800 bg-slate-950/70 px-3 py-2">
|
||||
{reason}
|
||||
</li>
|
||||
))
|
||||
) : (
|
||||
<li className="rounded-2xl border border-slate-800 bg-slate-950/70 px-3 py-2">当前无阻塞项</li>
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>支付审计摘要</CardTitle>
|
||||
<CardDescription>先展示最新几条事件,日常巡检够用。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3 text-sm text-slate-300">
|
||||
<div className="rounded-2xl border border-slate-800 bg-slate-950/70 p-3">
|
||||
<div className="text-xs font-bold uppercase tracking-[0.16em] text-slate-500">RPC</div>
|
||||
<div className="mt-2 break-all text-xs text-slate-300">{maskUrl(payments?.rpc?.active_rpc_url)}</div>
|
||||
</div>
|
||||
<div className="rounded-2xl border border-slate-800 bg-slate-950/70 p-3">
|
||||
<div className="text-xs font-bold uppercase tracking-[0.16em] text-slate-500">Receiver Contract</div>
|
||||
<div className="mt-2 break-all text-xs text-slate-300">{payments?.checkout?.receiver_contract || "-"}</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{(payments?.recent_audit_events || []).slice(0, 6).map((item) => (
|
||||
<div key={item.id} className="rounded-2xl border border-slate-800 bg-slate-950/70 px-3 py-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="font-semibold text-slate-100">{item.event_type}</span>
|
||||
<span className="text-xs text-slate-500">#{item.id}</span>
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-slate-500">{formatDateTime(item.created_at)}</div>
|
||||
{item.payload?.reason ? (
|
||||
<div className="mt-2 space-y-1 text-xs text-amber-300">
|
||||
<div>原因: {item.payload.reason}</div>
|
||||
{item.payload.tx_hash ? <div>Tx: {maskUrl(item.payload.tx_hash)}</div> : null}
|
||||
{item.payload.receiver_actual ? (
|
||||
<div>实际收款: {maskUrl(item.payload.receiver_actual)}</div>
|
||||
) : null}
|
||||
{item.payload.receiver_expected ? (
|
||||
<div>期望收款: {maskUrl(item.payload.receiver_expected)}</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
{!payments?.recent_audit_events?.length ? (
|
||||
<div className="rounded-2xl border border-slate-800 bg-slate-950/70 px-3 py-2 text-slate-500">暂无审计事件</div>
|
||||
) : null}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<CardTitle>支付异常单</CardTitle>
|
||||
<CardDescription>只显示已明确标记失败的支付确认事故。</CardDescription>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<select
|
||||
className="w-full rounded-xl border border-slate-700 bg-slate-950 px-3 py-2 text-sm text-slate-200 sm:w-auto"
|
||||
value={incidentReasonFilter}
|
||||
onChange={(event) => {
|
||||
const next = event.target.value;
|
||||
setIncidentReasonFilter(next);
|
||||
void loadPaymentIncidents(next);
|
||||
}}
|
||||
>
|
||||
<option value="all">全部原因</option>
|
||||
<option value="receiver_mismatch">receiver_mismatch</option>
|
||||
<option value="sender_mismatch">sender_mismatch</option>
|
||||
<option value="event_mismatch">event_mismatch</option>
|
||||
<option value="tx_reverted">tx_reverted</option>
|
||||
</select>
|
||||
<Button variant="secondary" onClick={() => void loadPaymentIncidents(incidentReasonFilter)} disabled={incidentsLoading} className="w-full sm:w-auto">
|
||||
{incidentsLoading ? "加载中" : "刷新异常"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3 md:hidden">
|
||||
{paymentIncidents.map((item) => (
|
||||
<div key={item.id} className="rounded-2xl border border-slate-800 bg-slate-950/70 p-3">
|
||||
<div className="mb-3 flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div className="font-semibold text-slate-100">{item.payload?.reason || "-"}</div>
|
||||
<div className="mt-1 text-xs text-slate-500">{formatDateTime(item.created_at)}</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => void resolveIncident(item.id)}
|
||||
disabled={resolvingIncidentId === item.id}
|
||||
>
|
||||
{resolvingIncidentId === item.id ? "处理中" : "已处理"}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<MobileField label="套餐" value={item.payload?.plan_code || "-"} />
|
||||
<MobileField label="Tx" value={maskUrl(item.payload?.tx_hash)} mono />
|
||||
<MobileField label="实际收款" value={maskUrl(item.payload?.receiver_actual)} mono />
|
||||
<MobileField label="期望收款" value={maskUrl(item.payload?.receiver_expected)} mono />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{!paymentIncidents.length ? (
|
||||
<div className="rounded-2xl border border-slate-800 bg-slate-950/70 px-3 py-4 text-sm text-slate-500">
|
||||
暂无支付异常单
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="hidden overflow-x-auto rounded-2xl border border-slate-800 bg-slate-950/70 md:block">
|
||||
<table className="min-w-full divide-y divide-slate-800 text-left text-sm">
|
||||
<thead className="bg-slate-900/80 text-xs uppercase tracking-[0.14em] text-slate-500">
|
||||
<tr>
|
||||
<th className="px-4 py-3">时间</th>
|
||||
<th className="px-4 py-3">原因</th>
|
||||
<th className="px-4 py-3">套餐</th>
|
||||
<th className="px-4 py-3">Tx</th>
|
||||
<th className="px-4 py-3">实际收款</th>
|
||||
<th className="px-4 py-3">期望收款</th>
|
||||
<th className="px-4 py-3">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-800">
|
||||
{paymentIncidents.map((item) => (
|
||||
<tr key={item.id}>
|
||||
<td className="px-4 py-3">{formatDateTime(item.created_at)}</td>
|
||||
<td className="px-4 py-3">{item.payload?.reason || "-"}</td>
|
||||
<td className="px-4 py-3">{item.payload?.plan_code || "-"}</td>
|
||||
<td className="px-4 py-3">{maskUrl(item.payload?.tx_hash)}</td>
|
||||
<td className="px-4 py-3">{maskUrl(item.payload?.receiver_actual)}</td>
|
||||
<td className="px-4 py-3">{maskUrl(item.payload?.receiver_expected)}</td>
|
||||
<td className="px-4 py-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => void resolveIncident(item.id)}
|
||||
disabled={resolvingIncidentId === item.id}
|
||||
>
|
||||
{resolvingIncidentId === item.id ? "处理中" : "标记已处理"}
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{!paymentIncidents.length ? (
|
||||
<tr>
|
||||
<td className="px-4 py-4 text-slate-500" colSpan={7}>
|
||||
暂无支付异常单
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>当前会员</CardTitle>
|
||||
<CardDescription>当前有效订阅用户、注册时间和到期时间。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 text-sm text-slate-300">
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div className="text-xs text-slate-500">
|
||||
当前有效会员数:{memberships.length}
|
||||
</div>
|
||||
<Button variant="secondary" onClick={() => void loadMemberships()} disabled={membershipsLoading} className="w-full sm:w-auto">
|
||||
{membershipsLoading ? "加载中" : "刷新会员"}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-3 md:hidden">
|
||||
{memberships.map((item) => (
|
||||
<div key={`${item.user_id}-${item.expires_at || ""}`} className="rounded-2xl border border-slate-800 bg-slate-950/70 p-3">
|
||||
<div className="font-semibold text-slate-100">{item.email || "-"}</div>
|
||||
<div className="mt-1 text-xs text-slate-500">{item.username || "-"}</div>
|
||||
<div className="mt-3 grid gap-2">
|
||||
<MobileField label="注册时间" value={formatDateTime(item.registered_at)} />
|
||||
<MobileField label="到期时间" value={formatDateTime(item.expires_at)} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{!memberships.length ? (
|
||||
<div className="rounded-2xl border border-slate-800 bg-slate-950/70 px-3 py-4 text-sm text-slate-500">
|
||||
暂无有效会员
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="hidden overflow-x-auto rounded-2xl border border-slate-800 bg-slate-950/70 md:block">
|
||||
<table className="min-w-full divide-y divide-slate-800 text-left text-sm">
|
||||
<thead className="bg-slate-900/80 text-xs uppercase tracking-[0.14em] text-slate-500">
|
||||
<tr>
|
||||
<th className="px-4 py-3">邮箱</th>
|
||||
<th className="px-4 py-3">用户名</th>
|
||||
<th className="px-4 py-3">注册时间</th>
|
||||
<th className="px-4 py-3">到期时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-slate-800">
|
||||
{memberships.map((item) => (
|
||||
<tr key={`${item.user_id}-${item.expires_at || ""}`}>
|
||||
<td className="px-4 py-3">{item.email || "-"}</td>
|
||||
<td className="px-4 py-3">{item.username || "-"}</td>
|
||||
<td className="px-4 py-3">{formatDateTime(item.registered_at)}</td>
|
||||
<td className="px-4 py-3">{formatDateTime(item.expires_at)}</td>
|
||||
</tr>
|
||||
))}
|
||||
{!memberships.length ? (
|
||||
<tr>
|
||||
<td className="px-4 py-4 text-slate-500" colSpan={4}>
|
||||
暂无有效会员
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<section className="grid gap-4 xl:grid-cols-[1.1fr_0.9fr]">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>用户查询</CardTitle>
|
||||
<CardDescription>按 Telegram ID、用户名或 Supabase 邮箱搜用户。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 text-sm text-slate-300">
|
||||
<div className="flex flex-col gap-3 sm:flex-row">
|
||||
<input
|
||||
value={searchQuery}
|
||||
onChange={(event) => setSearchQuery(event.target.value)}
|
||||
placeholder="telegram id / username / email"
|
||||
className="h-10 flex-1 rounded-xl border border-slate-800 bg-slate-950 px-3 text-sm text-slate-100 outline-none ring-0"
|
||||
/>
|
||||
<Button variant="secondary" onClick={() => void loadUsers(searchQuery)} disabled={usersLoading} className="w-full sm:w-auto">
|
||||
{usersLoading ? "查询中" : "查询"}
|
||||
</Button>
|
||||
</div>
|
||||
{usersError ? <div className="text-rose-300">{usersError}</div> : null}
|
||||
<div className="space-y-3">
|
||||
{users.map((user) => (
|
||||
<div key={user.telegram_id} className="rounded-2xl border border-slate-800 bg-slate-950/70 p-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<div className="font-semibold text-slate-100">{user.username || "(未命名用户)"}</div>
|
||||
<div className="text-xs text-slate-500">
|
||||
TG {user.telegram_id} · {user.supabase_email || "未绑定邮箱"}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Badge variant="secondary">总分 {user.points ?? 0}</Badge>
|
||||
<Badge variant="warning">周分 {user.weekly_points ?? 0}</Badge>
|
||||
<Badge variant="default">发言 {user.message_count ?? 0}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 text-xs text-slate-500">
|
||||
今日积分 {user.daily_points ?? 0} · 最近发言 {formatDateTime(user.last_message_at)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{!users.length && !usersLoading ? (
|
||||
<div className="rounded-2xl border border-slate-800 bg-slate-950/70 px-3 py-2 text-slate-500">没有匹配用户</div>
|
||||
) : null}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>积分运营</CardTitle>
|
||||
<CardDescription>先做最小版:按 Supabase 邮箱手动补分。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 text-sm text-slate-300">
|
||||
<div className="space-y-3">
|
||||
<input
|
||||
value={grantEmail}
|
||||
onChange={(event) => setGrantEmail(event.target.value)}
|
||||
placeholder="user@example.com"
|
||||
className="h-10 w-full rounded-xl border border-slate-800 bg-slate-950 px-3 text-sm text-slate-100 outline-none ring-0"
|
||||
/>
|
||||
<input
|
||||
value={grantPoints}
|
||||
onChange={(event) => setGrantPoints(event.target.value)}
|
||||
placeholder="300"
|
||||
className="h-10 w-full rounded-xl border border-slate-800 bg-slate-950 px-3 text-sm text-slate-100 outline-none ring-0"
|
||||
/>
|
||||
<Button onClick={() => void submitGrant()} disabled={grantLoading || !grantEmail.trim()} className="w-full">
|
||||
{grantLoading ? "提交中" : "补分"}
|
||||
</Button>
|
||||
</div>
|
||||
{grantStatus ? <div className="rounded-2xl border border-emerald-500/30 bg-emerald-500/10 px-3 py-2 text-emerald-300">{grantStatus}</div> : null}
|
||||
{grantError ? <div className="rounded-2xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-rose-300">{grantError}</div> : null}
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-bold uppercase tracking-[0.16em] text-slate-500">本周榜前 10</div>
|
||||
{(leaderboard || []).map((item, index) => (
|
||||
<div key={item.telegram_id} className="flex items-center justify-between gap-3 rounded-2xl border border-slate-800 bg-slate-950/70 px-3 py-2">
|
||||
<div>
|
||||
<div className="font-semibold text-slate-100">#{index + 1} {item.username || "(未命名用户)"}</div>
|
||||
<div className="text-xs text-slate-500">TG {item.telegram_id}</div>
|
||||
</div>
|
||||
<div className="text-right text-xs">
|
||||
<div className="text-amber-300">周分 {item.weekly_points ?? 0}</div>
|
||||
<div className="text-slate-500">总分 {item.points ?? 0}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{!leaderboard.length ? (
|
||||
<div className="rounded-2xl border border-slate-800 bg-slate-950/70 px-3 py-2 text-slate-500">当前没有周榜数据</div>
|
||||
) : null}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { DocsLocale, DocsNavGroup } from "./docs";
|
||||
|
||||
export const DOCS_GROUPS: DocsNavGroup[] = [
|
||||
{
|
||||
id: "getting-started",
|
||||
title: { "zh-CN": "开始", "en-US": "Getting Started" },
|
||||
},
|
||||
{
|
||||
id: "analysis",
|
||||
title: { "zh-CN": "分析逻辑", "en-US": "Analysis Logic" },
|
||||
},
|
||||
{
|
||||
id: "settlement",
|
||||
title: { "zh-CN": "结算与数据", "en-US": "Settlement & Data" },
|
||||
},
|
||||
{
|
||||
id: "history",
|
||||
title: { "zh-CN": "历史对账", "en-US": "History & Reconciliation" },
|
||||
},
|
||||
];
|
||||
|
||||
export function getDocsGroupTitle(groupId: DocsNavGroup["id"], locale: DocsLocale) {
|
||||
return DOCS_GROUPS.find((group) => group.id === groupId)?.title[locale] || groupId;
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
export type DocsLocale = "zh-CN" | "en-US";
|
||||
|
||||
export type DocsBlock =
|
||||
| { type: "paragraph"; text: string }
|
||||
| { type: "callout"; tone?: "info" | "warning" | "success"; title?: string; text: string }
|
||||
| { type: "bullets"; items: string[] }
|
||||
| { type: "steps"; items: string[] }
|
||||
| { type: "link"; href: string; label: string; caption?: string }
|
||||
| { type: "image"; src: string; alt: string; caption?: string };
|
||||
|
||||
export interface DocsSection {
|
||||
id: string;
|
||||
title: string;
|
||||
blocks: DocsBlock[];
|
||||
}
|
||||
|
||||
export interface DocsPageContent {
|
||||
title: string;
|
||||
description: string;
|
||||
sections: DocsSection[];
|
||||
}
|
||||
|
||||
export interface DocsPageMeta {
|
||||
slug: string;
|
||||
group: "getting-started" | "analysis" | "settlement" | "history";
|
||||
}
|
||||
|
||||
export interface DocsPage extends DocsPageMeta {
|
||||
content: Record<DocsLocale, DocsPageContent>;
|
||||
}
|
||||
|
||||
export interface DocsNavGroup {
|
||||
id: DocsPageMeta["group"];
|
||||
title: Record<DocsLocale, string>;
|
||||
}
|
||||
|
||||
export const DOCS_PAGES: DocsPage[] = [
|
||||
{
|
||||
slug: "intro",
|
||||
group: "getting-started",
|
||||
content: {
|
||||
"zh-CN": {
|
||||
title: "简介",
|
||||
description: "PolyWeather 文档中心解释核心产品概念、结算口径和日内结构信号,帮助用户把天气分析转成可执行判断。",
|
||||
sections: [
|
||||
{
|
||||
id: "what-is-polyweather",
|
||||
title: "PolyWeather 是什么",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "PolyWeather 不是通用天气 App。它面向天气衍生品和温度市场,重点回答三个问题:今天最高温大概会落在哪个区间、机场或官方结算站会不会被压温、市场有没有明显错定价。" },
|
||||
{ type: "callout", tone: "info", title: "产品定位", text: "主站的核心价值不是报天气,而是把模型、实况、机场预报和结算规则整合成交易可用的信息。" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "core-modules",
|
||||
title: "你会在页面上看到什么",
|
||||
blocks: [
|
||||
{ type: "bullets", items: ["今日日内分析:围绕今日峰值窗口,解释近地面信号、高空结构和机场 TAF。", "多模型预报:展示 DEB 与多模型最高温预测,帮助判断市场当前最热桶是否合理。", "历史对账:查看近 15 天已结算样本、DEB MAE 与最佳单模型表现。", "机场报文解读:把 METAR / TAF 缩写翻成普通用户能理解的话。"] },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "how-to-read",
|
||||
title: "如何快速读懂主站",
|
||||
blocks: [
|
||||
{ type: "steps", items: ["先看今日气温预测图,确认当前实测、DEB 预测和峰值窗口。", "再看今日日内结构信号,判断现在是偏支持继续升温、偏压制,还是先观察。", "最后看市场对照与概率分布,判断市场是否已经把天气结构计入价格。"] },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
"en-US": {
|
||||
title: "Introduction",
|
||||
description: "The PolyWeather docs explain the product's core concepts, settlement logic, and intraday structural signals so users can turn weather context into actionable decisions.",
|
||||
sections: [
|
||||
{
|
||||
id: "what-is-polyweather",
|
||||
title: "What PolyWeather is",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "PolyWeather is not a generic weather app. It is built for weather derivatives and temperature markets, with one job: estimate the likely high-temperature bucket, explain whether the airport or official settlement site may get capped, and surface whether the market is mispricing that outcome." },
|
||||
{ type: "callout", tone: "info", title: "Product focus", text: "The core value is not raw weather reporting. It is the conversion of models, observations, airport forecasts, and settlement rules into usable trading context." },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "core-modules",
|
||||
title: "What you see on the site",
|
||||
blocks: [
|
||||
{ type: "bullets", items: ["Intraday analysis: peak-window focused reading of surface structure, upper-air structure, and airport TAF.", "Multi-model forecast: DEB versus major model highs, useful for checking whether the hottest market bucket is justified.", "History reconciliation: settled-sample MAE and hit-rate over the last 15 days.", "Airport narrative: plain-language translation of METAR / TAF shorthand."] },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "how-to-read",
|
||||
title: "How to read the dashboard quickly",
|
||||
blocks: [
|
||||
{ type: "steps", items: ["Start with the intraday temperature chart to anchor current observations, DEB, and the expected peak window.", "Read the structural signal next to see whether the setup still supports further warming, leans suppressive, or remains mixed.", "Then compare that weather structure against market buckets and settlement probabilities."] },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "intraday-signal",
|
||||
group: "analysis",
|
||||
content: {
|
||||
"zh-CN": {
|
||||
title: "今日日内结构信号",
|
||||
description: "这页解释顶部“今日日内结构信号”如何生成,以及近地面与机场 TAF 为什么会同时出现。",
|
||||
sections: [
|
||||
{
|
||||
id: "surface-vs-upper",
|
||||
title: "近地面信号和高空结构信号的区别",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "近地面信号主要来自小时级温度、露点、气压、风向、降水概率和云量变化。它回答的是:在当前到峰值窗口这几个小时里,地面结构更支持继续升温,还是更容易被压住。" },
|
||||
{ type: "paragraph", text: "高空结构信号主要来自高空派生字段、机场 TAF 与市场侧信息的综合判断。它回答的是:峰值窗口附近,高空和机场侧有没有新的扰动把最高温封顶。" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "peak-window",
|
||||
title: "为什么总在讲峰值窗口",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "PolyWeather 不按固定下午时段做判断,而是尽量围绕当天预计最高温兑现的窗口来分析。这样不同城市的峰值时间差异才不会被硬套成同一套模板。" },
|
||||
{ type: "callout", tone: "success", title: "窗口感知", text: "页面里的“今日 12:00-16:00(约 5 小时,围绕峰值窗口)”就是在提示当前结构判断真正关注的时段。" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "trade-language",
|
||||
title: "交易语言怎么读",
|
||||
blocks: [
|
||||
{ type: "bullets", items: ["偏支持:结构仍支持继续升温,别太早押高温见顶。", "偏压制:高温继续上冲的把握不大,别盲目追热。", "先观察:现在还看不出明确方向,先等下一步走势确认。"] },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
"en-US": {
|
||||
title: "Intraday Structural Signal",
|
||||
description: "This page explains how the intraday structural signal is built and why surface structure and airport TAF both appear in the same reading.",
|
||||
sections: [
|
||||
{
|
||||
id: "surface-vs-upper",
|
||||
title: "Surface versus upper-air structure",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "The surface layer comes from hourly temperature, dew point, pressure, wind, precipitation probability, and cloud-cover changes. It answers a near-term question: between now and the peak window, does the local surface setup still support more warming or does it look easier to cap?" },
|
||||
{ type: "paragraph", text: "The upper-air layer combines derived profile signals, airport TAF, and market-side context. It answers a different question: around the peak window, is there a new airport-side or upper-air disturbance that could lock the high in place?" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "peak-window",
|
||||
title: "Why everything is framed around the peak window",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "PolyWeather does not force every city into the same afternoon template. It centers the analysis on the expected high-temperature payoff window for that city on that day, so different cities are not interpreted through the wrong hours." },
|
||||
{ type: "callout", tone: "success", title: "Window-aware reading", text: "When you see a line such as “12:00-16:00 (~5h, around the peak window)”, that is the actual window driving the current structural read." },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "trade-language",
|
||||
title: "How to read the trading language",
|
||||
blocks: [
|
||||
{ type: "bullets", items: ["Supportive: the setup still supports more warming. Do not call the high too early.", "Suppressive: further upside looks less reliable. Do not chase the high blindly.", "Wait / confirm: the setup is still mixed. Let the next move decide first."] },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "taf-signal",
|
||||
group: "analysis",
|
||||
content: {
|
||||
"zh-CN": {
|
||||
title: "TAF 信号",
|
||||
description: "TAF 不是结算温度,但它能告诉你机场侧在峰值窗口前后会不会有云雨、雷暴或风向切换,把最高温压住。",
|
||||
sections: [
|
||||
{
|
||||
id: "what-taf-does",
|
||||
title: "TAF 在 PolyWeather 里负责什么",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "TAF 在项目里是机场侧确认层,而不是温度主预测曲线。它主要补三类信息:峰值窗口有没有云雨压温、午后扰动是不是正在增强、机场风向是否发生阶段性切换。" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "taf-periods",
|
||||
title: "图上的 TAF 时段是什么意思",
|
||||
blocks: [
|
||||
{ type: "bullets", items: ["基础时段(BASE):TAF 的默认主背景天气。", "明确切换(FM):从某个时刻开始,机场预报切换到一套新天气状态。", "临时波动(TEMPO):一段时间内可能临时出现扰动,但不代表主背景永久改变。", "逐步转变(BECMG):天气不是一下子切,而是在一段时间里渐变。", "30% / 40% 风险窗(PROB30/40):风险有概率出现,不代表一定发生。"] },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "airport-suppression",
|
||||
title: "什么叫机场端压温风险偏高",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "它的意思不是整座城市一定更冷,而是作为结算依据的机场站点,在峰值窗口里更可能因为云、阵雨或雷暴扰动,冲不到本来可能达到的更高温度。" },
|
||||
{ type: "callout", tone: "warning", title: "重点区别", text: "TAF 负责告诉你机场侧未来几个小时会不会出现压温扰动,不直接等于结算温度本身。结算仍然看 METAR、HKO、MGM、NOAA 指定站点、Wunderground 指定站点等实际结算源。" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
"en-US": {
|
||||
title: "TAF Signal",
|
||||
description: "TAF is not the settlement temperature itself, but it is useful for telling you whether the airport side may see clouds, showers, thunderstorms, or wind shifts that cap the high around the payoff window.",
|
||||
sections: [
|
||||
{
|
||||
id: "what-taf-does",
|
||||
title: "What TAF does inside PolyWeather",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "Within the product, TAF acts as an airport-side confirmation layer rather than the main temperature curve. Its job is to tell you whether clouds/rain may suppress the airport high, whether afternoon disruption is building, and whether the airport wind regime is about to shift in stages." },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "taf-periods",
|
||||
title: "What the TAF timing labels mean",
|
||||
blocks: [
|
||||
{ type: "bullets", items: ["Base regime: the default background forecast segment.", "Hard shift (FM): a new weather regime begins from an explicit time.", "Temporary swing (TEMPO): a temporary disturbance window that does not replace the background regime permanently.", "Gradual shift (BECMG): conditions transition across a window instead of flipping instantly.", "30% / 40% risk window (PROB30/40): a probabilistic risk window, not a certainty signal."] },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "airport-suppression",
|
||||
title: "What airport-side suppression risk means",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "It does not mean the entire city must run cooler. It means the airport station used for settlement is more likely to get capped by clouds, showers, or thunderstorm disruption during the peak window and fail to reach the next warmer bucket." },
|
||||
{ type: "callout", tone: "warning", title: "Important distinction", text: "TAF explains whether the airport side may face suppressive weather over the next few hours. Settlement still comes from the actual settlement source such as METAR, HKO, MGM, a designated NOAA station, or a designated Wunderground station." },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "settlement-sources",
|
||||
group: "settlement",
|
||||
content: {
|
||||
"zh-CN": {
|
||||
title: "结算来源说明",
|
||||
description: "不同城市的结算口径不同。理解结算源,比单纯看模型曲线更重要。",
|
||||
sections: [
|
||||
{
|
||||
id: "why-settlement-matters",
|
||||
title: "为什么先看结算源",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "同样是“城市最高温”,市场真正结算看的往往不是城区平均温度,而是规则指定的机场或官方站点。交易上最常见的错觉,是把城市体感温度当成结算温度。" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "city-rules",
|
||||
title: "当前主要口径",
|
||||
blocks: [
|
||||
{ type: "bullets", items: ["多数欧美机场市场:按机场 METAR 或机场主站实况结算。", "香港:按香港天文台 HKO 主口径,不接机场 TAF 作为主结算逻辑。", "台北、伊斯坦布尔、深圳等 NOAA 市场:按 weather.gov / NOAA 指定站点最终完成质控后的最高整度摄氏值结算,机场观测和市区体感不可混用。", "Ankara:结算主站以 LTAC / Esenboğa 为准,同时保留 Turkish MGM 作为领先结构参考。"] },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "common-mistakes",
|
||||
title: "最常见的误解",
|
||||
blocks: [
|
||||
{ type: "bullets", items: ["TAF 不是结算源,它只告诉你机场未来有没有压温扰动。", "市场按机场结算时,城区更热不代表市场就该结到更高温桶。", "NOAA 市场要优先看 weather.gov 指定站点的最终 Temp 列,不要拿其他站或第三方页面替代。", "香港和台北不能简单套用机场 TAF / METAR 主链逻辑。"] },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
"en-US": {
|
||||
title: "Settlement Sources",
|
||||
description: "Settlement rules differ by city. Understanding the settlement source matters more than staring only at model curves.",
|
||||
sections: [
|
||||
{
|
||||
id: "why-settlement-matters",
|
||||
title: "Why settlement source comes first",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "A market may say “city high”, but the true settlement often comes from a designated airport or official site rather than the broader urban feel. One of the most common mistakes is to trade the city feel instead of the actual settlement station." },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "city-rules",
|
||||
title: "Current primary rules",
|
||||
blocks: [
|
||||
{ type: "bullets", items: ["Most airport-linked Western markets: settle on airport METAR or the airport primary observing site.", "Hong Kong: settles on HKO, not on airport TAF as the main settlement logic.", "NOAA markets such as Taipei, Istanbul, and Shenzhen settle against the designated weather.gov / NOAA station using the finalized highest rounded whole-degree Celsius reading; airport observations and downtown feel should not be mixed.", "Ankara: settlement centers on LTAC / Esenboğa, with Turkish MGM retained as a leading-structure reference."] },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "common-mistakes",
|
||||
title: "Common mistakes",
|
||||
blocks: [
|
||||
{ type: "bullets", items: ["TAF is not a settlement source. It only tells you whether airport-side suppressive weather may appear.", "If the market settles on an airport site, a hotter downtown feel does not automatically justify a warmer settlement bucket.", "NOAA markets should anchor to the designated weather.gov Temp column once the date is finalized, not to a nearby third-party station page.", "Hong Kong and Taipei should not be forced into the generic airport TAF / METAR chain."] },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "history-reconciliation",
|
||||
group: "history",
|
||||
content: {
|
||||
"zh-CN": {
|
||||
title: "历史对账",
|
||||
description: "历史对账用于看已结算样本,不用于把当天未结算的行情硬算进胜率。",
|
||||
sections: [
|
||||
{
|
||||
id: "settled-only",
|
||||
title: "为什么只看已结算样本",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "网页上的历史对账只统计已结算样本。当天还在交易中的市场,不会被提前算进 DEB 命中率或 MAE。这样做的目的,是避免用还没兑现的结果污染历史准确率。" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "rolling-window",
|
||||
title: "近 15 天滚动视图",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "网页默认展示近 15 天滚动视图,方便比较最近这轮模型状态,而不是用过长的旧样本稀释当前表现。" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "peak-minus-12h",
|
||||
title: "峰值前 12 小时 DEB 参考",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "这项指标用来回答一个更具体的问题:在真正出现高温之前 12 小时,DEB 当时大概有多准。它不是额外结算规则,而是一个用来观察模型是否过慢修正的参考视角。" },
|
||||
{ type: "callout", tone: "info", title: "近似值说明", text: "当前峰值时间是根据历史快照链路反推的近似时间,不是逐分钟官方复盘。页面会明确标记为“参考 / 近似”。" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
"en-US": {
|
||||
title: "History Reconciliation",
|
||||
description: "History reconciliation is for settled samples only. It is not meant to leak same-day unsettled outcomes into historical hit-rate or MAE.",
|
||||
sections: [
|
||||
{
|
||||
id: "settled-only",
|
||||
title: "Why only settled samples count",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "The history panel only counts settled samples. Markets still trading on the same day are excluded from DEB hit-rate and MAE so unfinished outcomes do not contaminate the historical record." },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "rolling-window",
|
||||
title: "Rolling 15-day view",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "The web dashboard defaults to a rolling 15-day view so the panel reflects current model behavior rather than being overly diluted by older regimes." },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "peak-minus-12h",
|
||||
title: "DEB at peak minus 12 hours",
|
||||
blocks: [
|
||||
{ type: "paragraph", text: "This field answers a more specific question: how good was DEB roughly 12 hours before the eventual high actually printed? It is not a settlement rule, but a way to judge whether the model corrected too slowly." },
|
||||
{ type: "callout", tone: "info", title: "Approximation note", text: "The current peak time is inferred from the snapshot chain and should be treated as an approximate reference rather than a minute-perfect official replay." },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "extension",
|
||||
group: "getting-started",
|
||||
content: {
|
||||
"zh-CN": {
|
||||
title: "浏览器插件",
|
||||
description: "侧边栏插件是主站的轻量入口,负责监控、基础判断和导流,不承载完整分析链路。",
|
||||
sections: [
|
||||
{
|
||||
id: "extension-install",
|
||||
title: "安装地址",
|
||||
blocks: [
|
||||
{
|
||||
type: "link",
|
||||
href: "https://chromewebstore.google.com/detail/mhndjbgjljjfcfkojhmhpfcbconnikne?utm_source=item-share-cb",
|
||||
label: "打开 Chrome Web Store",
|
||||
caption: "安装插件后,可在侧边栏里快速跳回主站的今日日内分析与历史对账。",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "extension-role",
|
||||
title: "插件负责什么",
|
||||
blocks: [
|
||||
{
|
||||
type: "bullets",
|
||||
items: [
|
||||
"自动识别当前市场 URL,对应切换城市。",
|
||||
"展示风险徽章、城市档案、今日日内走势简版和多日预报。",
|
||||
"提供今日日内分析、历史对账和返回主站的快捷入口。",
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "extension-boundary",
|
||||
title: "插件不负责什么",
|
||||
blocks: [
|
||||
{
|
||||
type: "paragraph",
|
||||
text: "插件不承担完整分析体验,也不承载支付链路。复杂结构判断、历史对账和完整交易语境仍以主站为准。",
|
||||
},
|
||||
{
|
||||
type: "callout",
|
||||
tone: "info",
|
||||
title: "当前定位",
|
||||
text: "插件是“监控 + 基础判断 + 导流回站”的轻量产品,而不是主站的 1:1 复制品。",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "extension-forecast",
|
||||
title: "当前多日预报口径",
|
||||
blocks: [
|
||||
{
|
||||
type: "paragraph",
|
||||
text: "插件的多日预报已改为 DEB 优先显示。只有某一天没有 DEB 值时,才回退到原始的日最高温预报值。",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
"en-US": {
|
||||
title: "Browser Extension",
|
||||
description: "The side-panel extension is a lightweight lead-in to the main site. It focuses on monitoring, basic bias, and traffic flow back to the full dashboard.",
|
||||
sections: [
|
||||
{
|
||||
id: "extension-install",
|
||||
title: "Install link",
|
||||
blocks: [
|
||||
{
|
||||
type: "link",
|
||||
href: "https://chromewebstore.google.com/detail/mhndjbgjljjfcfkojhmhpfcbconnikne?utm_source=item-share-cb",
|
||||
label: "Open Chrome Web Store",
|
||||
caption: "Once installed, the side panel can route users back into the main intraday analysis and history views.",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "extension-role",
|
||||
title: "What the extension does",
|
||||
blocks: [
|
||||
{
|
||||
type: "bullets",
|
||||
items: [
|
||||
"Auto-detects the current market URL and switches the side panel to the matching city.",
|
||||
"Shows risk badges, city profile, a compact intraday chart, and multi-day forecast.",
|
||||
"Provides quick links into the main intraday analysis and history reconciliation views.",
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "extension-boundary",
|
||||
title: "What it does not do",
|
||||
blocks: [
|
||||
{
|
||||
type: "paragraph",
|
||||
text: "The extension does not attempt to replicate the full analysis stack and does not carry the payment flow. Deeper structural reasoning and full trade context still live on the main site.",
|
||||
},
|
||||
{
|
||||
type: "callout",
|
||||
tone: "info",
|
||||
title: "Current positioning",
|
||||
text: "Think of the extension as monitoring plus lightweight bias, not as a full dashboard replacement.",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "extension-forecast",
|
||||
title: "Current forecast logic",
|
||||
blocks: [
|
||||
{
|
||||
type: "paragraph",
|
||||
text: "The extension now prefers DEB for the multi-day forecast. It falls back to the original daily max only when a DEB value is missing for that date.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export function getDocsPage(slug: string) {
|
||||
return DOCS_PAGES.find((page) => page.slug === slug) || null;
|
||||
}
|
||||
@@ -27,15 +27,12 @@ import {
|
||||
|
||||
interface DashboardStoreValue extends DashboardState {
|
||||
closeFutureModal: () => void;
|
||||
closeGuide: () => void;
|
||||
closeHistory: () => void;
|
||||
closePanel: () => void;
|
||||
ensureCityDetail: (cityName: string, force?: boolean) => Promise<CityDetail>;
|
||||
futureModalDate: string | null;
|
||||
isGuideOpen: boolean;
|
||||
loadCities: () => Promise<void>;
|
||||
openFutureModal: (dateStr: string, forceRefresh?: boolean) => void;
|
||||
openGuide: () => void;
|
||||
openHistory: () => Promise<void>;
|
||||
openTodayModal: (forceRefresh?: boolean) => Promise<void>;
|
||||
registerMapStopMotion: (stopMotion: () => void) => void;
|
||||
@@ -216,10 +213,10 @@ export function DashboardStoreProvider({
|
||||
const [historyState, setHistoryState] = useState<HistoryState>(
|
||||
getInitialHistoryState,
|
||||
);
|
||||
const [isGuideOpen, setIsGuideOpen] = useState(false);
|
||||
const [proAccess, setProAccess] = useState<ProAccessState>(
|
||||
getInitialProAccessState,
|
||||
);
|
||||
const proAccessRef = useRef<ProAccessState>(getInitialProAccessState());
|
||||
|
||||
const mapStopMotionRef = useRef<() => void>(() => {});
|
||||
const hydratedSelectionRef = useRef(false);
|
||||
@@ -258,6 +255,10 @@ export function DashboardStoreProvider({
|
||||
citySummariesRef.current = citySummariesByName;
|
||||
}, [citySummariesByName]);
|
||||
|
||||
useEffect(() => {
|
||||
proAccessRef.current = proAccess;
|
||||
}, [proAccess]);
|
||||
|
||||
const scheduleBackgroundDetailRefresh = (
|
||||
cityName: string,
|
||||
cached: CityDetail,
|
||||
@@ -485,14 +486,24 @@ export function DashboardStoreProvider({
|
||||
setIsPanelOpen(true);
|
||||
setSelectedForecastDate(null);
|
||||
setFutureModalDate(null);
|
||||
|
||||
if (proAccessRef.current.loading) {
|
||||
await refreshProAccess();
|
||||
}
|
||||
const access = proAccessRef.current;
|
||||
setLoadingState((current) => ({ ...current, cityDetail: true }));
|
||||
try {
|
||||
const detail = await ensureCityDetail(cityName);
|
||||
setSelectedForecastDate(detail.local_date);
|
||||
// 预热市场数据,不做 await 阻塞,后台静默拉取
|
||||
void ensureCityMarketScan(cityName, false, null, detail.local_date).catch(
|
||||
() => {},
|
||||
);
|
||||
if (access.authenticated && access.subscriptionActive) {
|
||||
// 预热市场数据,不做 await 阻塞,后台静默拉取
|
||||
void ensureCityMarketScan(
|
||||
cityName,
|
||||
false,
|
||||
null,
|
||||
detail.local_date,
|
||||
).catch(() => {});
|
||||
}
|
||||
} finally {
|
||||
setLoadingState((current) => ({ ...current, cityDetail: false }));
|
||||
}
|
||||
@@ -615,7 +626,6 @@ export function DashboardStoreProvider({
|
||||
cityDetailsByName,
|
||||
citySummariesByName,
|
||||
closeFutureModal: () => setFutureModalDate(null),
|
||||
closeGuide: () => setIsGuideOpen(false),
|
||||
closeHistory: () =>
|
||||
setHistoryState((current) => ({ ...current, isOpen: false })),
|
||||
closePanel: () => {
|
||||
@@ -625,7 +635,6 @@ export function DashboardStoreProvider({
|
||||
futureModalDate,
|
||||
historyState,
|
||||
isPanelOpen,
|
||||
isGuideOpen,
|
||||
loadCities,
|
||||
loadingState,
|
||||
proAccess,
|
||||
@@ -646,10 +655,9 @@ export function DashboardStoreProvider({
|
||||
setLoadingState((current) => ({ ...current, marketScan: false }));
|
||||
});
|
||||
},
|
||||
openGuide: () => setIsGuideOpen(true),
|
||||
openHistory,
|
||||
openTodayModal: async (forceRefresh?: boolean) => {
|
||||
if (!selectedCity || loadingState.cityDetail) {
|
||||
if (!selectedCity) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -659,35 +667,24 @@ export function DashboardStoreProvider({
|
||||
setSelectedForecastDate(cachedDetail.local_date);
|
||||
setFutureModalDate(cachedDetail.local_date);
|
||||
}
|
||||
if (!proAccess.subscriptionActive) {
|
||||
return;
|
||||
}
|
||||
if (!proAccess.subscriptionActive) return;
|
||||
|
||||
// 乐观 UI: 有缓存则立刻秒开 modal,不阻塞显示
|
||||
if (cachedDetail?.local_date) {
|
||||
setSelectedForecastDate(cachedDetail.local_date);
|
||||
setFutureModalDate(cachedDetail.local_date);
|
||||
setLoadingState((current) => ({ ...current, marketScan: true }));
|
||||
} else {
|
||||
setLoadingState((current) => ({
|
||||
...current,
|
||||
refresh: true,
|
||||
marketScan: true,
|
||||
}));
|
||||
}
|
||||
setLoadingState((current) => ({
|
||||
...current,
|
||||
refresh: !cachedDetail?.local_date,
|
||||
marketScan: true,
|
||||
}));
|
||||
|
||||
// 异步静默拉取最新气象与市场数据
|
||||
try {
|
||||
const detail = await ensureCityDetail(selectedCity, true);
|
||||
const detail = await ensureCityDetail(
|
||||
selectedCity,
|
||||
Boolean(forceRefresh),
|
||||
);
|
||||
setSelectedForecastDate(detail.local_date);
|
||||
setFutureModalDate(detail.local_date);
|
||||
|
||||
const marketKey = getMarketScanCacheKey(selectedCity, detail.local_date);
|
||||
try {
|
||||
// 如果缓存里没有或者想要强制刷新,则拉取最新市场数据
|
||||
const marketKey = getMarketScanCacheKey(
|
||||
selectedCity,
|
||||
detail.local_date,
|
||||
);
|
||||
await ensureCityMarketScan(
|
||||
selectedCity,
|
||||
forceRefresh || !marketScanByCityName[marketKey],
|
||||
@@ -697,6 +694,7 @@ export function DashboardStoreProvider({
|
||||
} catch {}
|
||||
} catch {
|
||||
if (cachedDetail?.local_date) {
|
||||
setSelectedForecastDate(cachedDetail.local_date);
|
||||
setFutureModalDate(cachedDetail.local_date);
|
||||
}
|
||||
} finally {
|
||||
@@ -729,7 +727,6 @@ export function DashboardStoreProvider({
|
||||
futureModalDate,
|
||||
historyState,
|
||||
isPanelOpen,
|
||||
isGuideOpen,
|
||||
loadingState,
|
||||
proAccess,
|
||||
marketScanByCityName,
|
||||
|
||||
@@ -30,6 +30,23 @@ interface UseLeafletMapArgs {
|
||||
const AUTO_NEARBY_MIN_ZOOM = 8;
|
||||
const AUTO_NEARBY_MAX_DISTANCE_M = 120000;
|
||||
const MAP_MAX_ZOOM = 19;
|
||||
const CITY_MARKER_DISPLAY_OFFSETS: Record<
|
||||
string,
|
||||
{ x: number; y: number; zIndexOffset?: number }
|
||||
> = {
|
||||
// Shek Kong sits between the Hong Kong and Shenzhen cards and gets visually buried
|
||||
// by their wide marker bubbles. Shift only the rendered marker, not the true point.
|
||||
"shek kong": { x: 34, y: -26, zIndexOffset: 320 },
|
||||
"lau fau shan": { x: -40, y: 14, zIndexOffset: 300 },
|
||||
};
|
||||
|
||||
function getMarkerDisplayOffset(cityName: string) {
|
||||
return CITY_MARKER_DISPLAY_OFFSETS[String(cityName || "").toLowerCase()] || {
|
||||
x: 0,
|
||||
y: 0,
|
||||
zIndexOffset: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function createMarkerIcon(
|
||||
city: CityListItem,
|
||||
@@ -41,11 +58,16 @@ function createMarkerIcon(
|
||||
const shortName = label.length > 10 ? `${label.substring(0, 8)}...` : label;
|
||||
const tempText =
|
||||
snapshot?.current?.temp != null ? `${snapshot.current.temp}${unit}` : "--";
|
||||
const offset = getMarkerDisplayOffset(city.name);
|
||||
const styleAttr =
|
||||
offset.x || offset.y
|
||||
? ` style="transform: translate(${offset.x}px, ${offset.y}px);"`
|
||||
: "";
|
||||
|
||||
return L.divIcon({
|
||||
className: "",
|
||||
html: `
|
||||
<div class="city-marker" data-city="${city.name}">
|
||||
<div class="city-marker" data-city="${city.name}"${styleAttr}>
|
||||
<div class="marker-bubble ${riskClass}">${tempText}</div>
|
||||
<div class="marker-name">${shortName}</div>
|
||||
</div>
|
||||
@@ -252,6 +274,7 @@ export function useLeafletMap({
|
||||
// Create new marker
|
||||
const marker = L.marker([city.lat, city.lon], {
|
||||
icon: createMarkerIcon(city, snapshot),
|
||||
zIndexOffset: getMarkerDisplayOffset(city.name).zIndexOffset || 0,
|
||||
}).addTo(map);
|
||||
|
||||
marker.on("click", () => {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export function usePrefersReducedMotion() {
|
||||
const [prefersReducedMotion, setPrefersReducedMotion] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined" || !window.matchMedia) {
|
||||
return;
|
||||
}
|
||||
|
||||
const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
|
||||
const apply = () => {
|
||||
setPrefersReducedMotion(mediaQuery.matches);
|
||||
};
|
||||
|
||||
apply();
|
||||
mediaQuery.addEventListener("change", apply);
|
||||
return () => {
|
||||
mediaQuery.removeEventListener("change", apply);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return prefersReducedMotion;
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
import type { CityDetail } from "@/lib/dashboard-types";
|
||||
|
||||
export type OfficialSourceLink = {
|
||||
label: string;
|
||||
href: string;
|
||||
kind: "agency" | "airport" | "metar";
|
||||
};
|
||||
|
||||
const CITY_SPECIFIC_SOURCES: Record<string, OfficialSourceLink[]> = {
|
||||
singapore: [
|
||||
{
|
||||
label: "MSS 官方天气",
|
||||
href: "https://www.weather.gov.sg/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "樟宜机场",
|
||||
href: "https://www.changiairport.com/",
|
||||
kind: "airport",
|
||||
},
|
||||
{
|
||||
label: "WSSS METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=WSSS&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
wellington: [
|
||||
{
|
||||
label: "MetService",
|
||||
href: "https://www.metservice.com/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "Wellington Airport",
|
||||
href: "https://www.wellingtonairport.co.nz/",
|
||||
kind: "airport",
|
||||
},
|
||||
{
|
||||
label: "NZWN METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=NZWN&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
"hong kong": [
|
||||
{
|
||||
label: "香港天文台",
|
||||
href: "https://www.hko.gov.hk/en/index.html",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "香港国际机场",
|
||||
href: "https://www.hongkongairport.com/",
|
||||
kind: "airport",
|
||||
},
|
||||
{
|
||||
label: "VHHH METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=VHHH&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
"shek kong": [
|
||||
{
|
||||
label: "香港天文台",
|
||||
href: "https://www.hko.gov.hk/en/index.html",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "HKO 区域天气数据",
|
||||
href: "https://data.weather.gov.hk/weatherAPI/hko_data/regional-weather/latest_1min_temperature.csv",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "VHSK Timeseries",
|
||||
href: "https://www.weather.gov/wrh/timeseries?site=VHSK",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
"lau fau shan": [
|
||||
{
|
||||
label: "香港天文台",
|
||||
href: "https://www.hko.gov.hk/en/index.html",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "HKO 区域天气数据",
|
||||
href: "https://data.weather.gov.hk/weatherAPI/hko_data/regional-weather/latest_1min_temperature.csv",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "HKO 实时读数页",
|
||||
href: "https://www.hko.gov.hk/textonly/v2/forecast/text_readings_e.htm",
|
||||
kind: "agency",
|
||||
},
|
||||
],
|
||||
taipei: [
|
||||
{
|
||||
label: "NOAA RCTP Timeseries",
|
||||
href: "https://www.weather.gov/wrh/timeseries?site=RCTP",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "桃园机场",
|
||||
href: "https://www.taoyuan-airport.com/",
|
||||
kind: "airport",
|
||||
},
|
||||
{
|
||||
label: "RCTP METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=RCTP&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
istanbul: [
|
||||
{
|
||||
label: "NOAA LTFM Timeseries",
|
||||
href: "https://www.weather.gov/wrh/timeseries?site=LTFM",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "Istanbul Airport",
|
||||
href: "https://www.istairport.com/en",
|
||||
kind: "airport",
|
||||
},
|
||||
{
|
||||
label: "LTFM METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=LTFM&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
london: [
|
||||
{
|
||||
label: "Met Office",
|
||||
href: "https://www.metoffice.gov.uk/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "EGLC METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=EGLC&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
"new york": [
|
||||
{
|
||||
label: "NWS",
|
||||
href: "https://www.weather.gov/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "KLGA METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=KLGA&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
ankara: [
|
||||
{
|
||||
label: "MGM",
|
||||
href: "https://www.mgm.gov.tr/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "LTAC METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=LTAC&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
paris: [
|
||||
{
|
||||
label: "Météo-France",
|
||||
href: "https://meteofrance.com/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "LFPG METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=LFPG&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
seoul: [
|
||||
{
|
||||
label: "KMA",
|
||||
href: "https://www.weather.go.kr/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "RKSI METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=RKSI&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
shanghai: [
|
||||
{
|
||||
label: "中国天气网",
|
||||
href: "https://www.weather.com.cn/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "ZSPD METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=ZSPD&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
tokyo: [
|
||||
{
|
||||
label: "JMA",
|
||||
href: "https://www.jma.go.jp/jma/indexe.html",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "RJTT METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=RJTT&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
"tel aviv": [
|
||||
{
|
||||
label: "IMS",
|
||||
href: "https://ims.gov.il/en",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "LLBG METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=LLBG&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
toronto: [
|
||||
{
|
||||
label: "Environment Canada",
|
||||
href: "https://weather.gc.ca/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "CYYZ METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=CYYZ&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
"buenos aires": [
|
||||
{
|
||||
label: "SMN",
|
||||
href: "https://www.smn.gob.ar/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "SAEZ METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=SAEZ&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
chicago: [
|
||||
{
|
||||
label: "NWS Chicago",
|
||||
href: "https://www.weather.gov/lot/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "KORD METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=KORD&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
dallas: [
|
||||
{
|
||||
label: "NWS Fort Worth",
|
||||
href: "https://www.weather.gov/fwd/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "KDAL METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=KDAL&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
miami: [
|
||||
{
|
||||
label: "NWS Miami",
|
||||
href: "https://www.weather.gov/mfl/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "KMIA METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=KMIA&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
atlanta: [
|
||||
{
|
||||
label: "NWS Peachtree City",
|
||||
href: "https://www.weather.gov/ffc/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "KATL METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=KATL&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
seattle: [
|
||||
{
|
||||
label: "NWS Seattle",
|
||||
href: "https://www.weather.gov/sew/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "KSEA METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=KSEA&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
lucknow: [
|
||||
{
|
||||
label: "IMD",
|
||||
href: "https://mausam.imd.gov.in/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "VILK METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=VILK&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
"sao paulo": [
|
||||
{
|
||||
label: "INMET",
|
||||
href: "https://portal.inmet.gov.br/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "SBGR METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=SBGR&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
munich: [
|
||||
{
|
||||
label: "DWD",
|
||||
href: "https://www.dwd.de/EN/Home/home_node.html",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "EDDM METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=EDDM&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
milan: [
|
||||
{
|
||||
label: "MeteoAM",
|
||||
href: "https://www.meteoam.it/en/home",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "LIMC METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=LIMC&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
warsaw: [
|
||||
{
|
||||
label: "IMGW",
|
||||
href: "https://meteo.imgw.pl/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "EPWA METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=EPWA&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
madrid: [
|
||||
{
|
||||
label: "AEMET",
|
||||
href: "https://www.aemet.es/en/portada",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "LEMD METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=LEMD&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
chengdu: [
|
||||
{
|
||||
label: "中国天气网",
|
||||
href: "https://www.weather.com.cn/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "ZUUU METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=ZUUU&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
chongqing: [
|
||||
{
|
||||
label: "中国天气网",
|
||||
href: "https://www.weather.com.cn/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "ZUCK METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=ZUCK&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
shenzhen: [
|
||||
{
|
||||
label: "NOAA ZGSZ Timeseries",
|
||||
href: "https://www.weather.gov/wrh/timeseries?site=ZGSZ",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "深圳宝安国际机场",
|
||||
href: "https://www.szairport.com/",
|
||||
kind: "airport",
|
||||
},
|
||||
{
|
||||
label: "ZGSZ METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=ZGSZ&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
beijing: [
|
||||
{
|
||||
label: "中国天气网",
|
||||
href: "https://www.weather.com.cn/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "ZBAA METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=ZBAA&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
wuhan: [
|
||||
{
|
||||
label: "中国天气网",
|
||||
href: "https://www.weather.com.cn/",
|
||||
kind: "agency",
|
||||
},
|
||||
{
|
||||
label: "ZHHH METAR",
|
||||
href: "https://aviationweather.gov/data/metar/?id=ZHHH&decoded=1&taf=1",
|
||||
kind: "metar",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export function getOfficialSourceLinks(detail: CityDetail): OfficialSourceLink[] {
|
||||
const cityKey = String(detail.name || "").trim().toLowerCase();
|
||||
const links = [...(CITY_SPECIFIC_SOURCES[cityKey] || [])];
|
||||
const seen = new Set<string>();
|
||||
return links.filter((link) => {
|
||||
const key = `${link.label}|${link.href}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
@@ -50,6 +50,8 @@ export interface CurrentConditions {
|
||||
wu_settlement: number | null;
|
||||
settlement_source?: string | null;
|
||||
settlement_source_label?: string | null;
|
||||
station_code?: string | null;
|
||||
station_name?: string | null;
|
||||
obs_time: string | null;
|
||||
obs_age_min: number | null;
|
||||
wind_speed_kt: number | null;
|
||||
@@ -66,6 +68,25 @@ export interface CurrentConditions {
|
||||
dewpoint?: number | null;
|
||||
}
|
||||
|
||||
export interface AirportCurrentConditions {
|
||||
temp: number | null;
|
||||
obs_time: string | null;
|
||||
max_so_far?: number | null;
|
||||
max_temp_time?: string | null;
|
||||
obs_age_min?: number | null;
|
||||
report_time?: string | null;
|
||||
receipt_time?: string | null;
|
||||
obs_time_epoch?: number | null;
|
||||
wind_speed_kt?: number | null;
|
||||
wind_dir?: number | null;
|
||||
humidity?: number | null;
|
||||
cloud_desc?: string | null;
|
||||
visibility_mi?: number | null;
|
||||
wx_desc?: string | null;
|
||||
raw_metar?: string | null;
|
||||
source_label?: string | null;
|
||||
}
|
||||
|
||||
export interface NearbyStation {
|
||||
name?: string;
|
||||
icao?: string;
|
||||
@@ -135,6 +156,8 @@ export interface CitySummary {
|
||||
current?: {
|
||||
temp?: number | null;
|
||||
obs_time?: string | null;
|
||||
settlement_source?: string | null;
|
||||
settlement_source_label?: string | null;
|
||||
};
|
||||
deb?: {
|
||||
prediction?: number | null;
|
||||
@@ -153,9 +176,15 @@ export interface HourlySeries {
|
||||
pressure_msl?: Array<number | null>;
|
||||
wind_speed_10m?: Array<number | null>;
|
||||
wind_direction_10m?: Array<number | null>;
|
||||
wind_speed_180m?: Array<number | null>;
|
||||
wind_direction_180m?: Array<number | null>;
|
||||
precipitation_probability?: Array<number | null>;
|
||||
cloud_cover?: Array<number | null>;
|
||||
radiation?: Array<number | null>;
|
||||
cape?: Array<number | null>;
|
||||
convective_inhibition?: Array<number | null>;
|
||||
lifted_index?: Array<number | null>;
|
||||
boundary_layer_height?: Array<number | null>;
|
||||
}
|
||||
|
||||
export interface WeatherGovPeriod {
|
||||
@@ -265,8 +294,10 @@ export interface CityDetail {
|
||||
local_date: string;
|
||||
risk: DashboardRisk;
|
||||
current: CurrentConditions;
|
||||
airport_current?: AirportCurrentConditions;
|
||||
mgm?: MgmData;
|
||||
mgm_nearby?: NearbyStation[];
|
||||
nearby_source?: string;
|
||||
forecast?: ForecastData;
|
||||
multi_model?: Record<string, number | null>;
|
||||
deb?: DebForecast;
|
||||
@@ -293,6 +324,64 @@ export interface CityDetail {
|
||||
}>;
|
||||
trend?: TrendInfo;
|
||||
peak?: PeakInfo;
|
||||
dynamic_commentary?: {
|
||||
summary?: string | null;
|
||||
notes?: string[] | null;
|
||||
};
|
||||
taf?: {
|
||||
source?: string | null;
|
||||
icao?: string | null;
|
||||
issue_time?: string | null;
|
||||
valid_time_from?: string | null;
|
||||
valid_time_to?: string | null;
|
||||
raw_taf?: string | null;
|
||||
signal?: {
|
||||
available?: boolean;
|
||||
source?: string | null;
|
||||
peak_window?: string | null;
|
||||
segments?: Array<{
|
||||
type?: string | null;
|
||||
start_local?: string | null;
|
||||
end_local?: string | null;
|
||||
tokens?: string[] | null;
|
||||
}> | null;
|
||||
markers?: Array<{
|
||||
label_time?: string | null;
|
||||
marker_type?: string | null;
|
||||
start_local?: string | null;
|
||||
end_local?: string | null;
|
||||
suppression_level?: string | null;
|
||||
summary_zh?: string | null;
|
||||
summary_en?: string | null;
|
||||
}> | null;
|
||||
low_ceiling_ft?: number | null;
|
||||
ceiling_cover?: string | null;
|
||||
wind_regimes?: string[] | null;
|
||||
wind_shift?: boolean | null;
|
||||
suppression_level?: string | null;
|
||||
disruption_level?: string | null;
|
||||
summary_zh?: string | null;
|
||||
summary_en?: string | null;
|
||||
};
|
||||
};
|
||||
vertical_profile_signal?: {
|
||||
source?: string | null;
|
||||
window_start?: string | null;
|
||||
window_end?: string | null;
|
||||
cape_max?: number | null;
|
||||
cin_min?: number | null;
|
||||
lifted_index_min?: number | null;
|
||||
boundary_layer_height_max?: number | null;
|
||||
shear_10m_180m_max?: number | null;
|
||||
suppression_risk?: string | null;
|
||||
trigger_risk?: string | null;
|
||||
mixing_strength?: string | null;
|
||||
shear_risk?: string | null;
|
||||
heating_setup?: string | null;
|
||||
heating_score?: number | null;
|
||||
summary_zh?: string | null;
|
||||
summary_en?: string | null;
|
||||
};
|
||||
ai_analysis?: string | AiAnalysisStructured | null;
|
||||
updated_at?: string;
|
||||
multi_model_daily?: Record<string, DailyModelForecast>;
|
||||
@@ -307,6 +396,10 @@ export interface HistoryPoint {
|
||||
mu?: number | null;
|
||||
mgm?: number | null;
|
||||
forecasts?: Record<string, number | null>;
|
||||
actual_peak_time?: string | null;
|
||||
deb_at_peak_minus_12h?: number | null;
|
||||
deb_at_peak_minus_12h_time?: string | null;
|
||||
deb_at_peak_minus_12h_error?: number | null;
|
||||
}
|
||||
|
||||
export interface LoadingState {
|
||||
|
||||
+1293
-113
File diff suppressed because it is too large
Load Diff
+13
-4
@@ -8,6 +8,8 @@ export const LOCALE_STORAGE_KEY = "polyweather.locale";
|
||||
const MESSAGES: Record<Locale, Record<string, string>> = {
|
||||
"zh-CN": {
|
||||
"header.subtitle": "天气衍生品智能分析",
|
||||
"header.docs": "文档",
|
||||
"header.docsAria": "打开产品文档中心",
|
||||
"header.info": "技术说明",
|
||||
"header.infoAria": "查看系统技术说明",
|
||||
"header.account": "账户",
|
||||
@@ -21,13 +23,15 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
||||
"header.langEn": "EN",
|
||||
|
||||
"sidebar.title": "监控城市",
|
||||
"sidebar.currentTemp": "当前 {temp}",
|
||||
"sidebar.peakTempAt": "峰值 {temp} @ {time}",
|
||||
"sidebar.peakAt": "峰值 @ {time}",
|
||||
"sidebar.group.high": "高风险",
|
||||
"sidebar.group.medium": "中风险",
|
||||
"sidebar.group.low": "低风险",
|
||||
"sidebar.group.other": "其他",
|
||||
|
||||
"dashboard.loading": "正在获取气象数据,请稍候...",
|
||||
"dashboard.loading": "正在同步站点观测与结算源,请稍候...",
|
||||
|
||||
"detail.closeAria": "关闭城市详情面板",
|
||||
"detail.waitSelect": "等待选择城市",
|
||||
@@ -50,7 +54,7 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
||||
"guide.title": "📎 PolyWeather 系统技术说明",
|
||||
"guide.closeAria": "关闭技术说明",
|
||||
"guide.footer":
|
||||
"数据源以 METAR、香港天文台(HKO)、中央气象署(CWA)、Turkish MGM、Open-Meteo、weather.gov 为主。",
|
||||
"数据源以 METAR、香港天文台(HKO)、NOAA 指定站点、Turkish MGM、Open-Meteo、weather.gov 为主。",
|
||||
|
||||
"history.title": "📊 历史准确率对账 - {city}",
|
||||
"history.closeAria": "关闭历史对账",
|
||||
@@ -167,6 +171,8 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
||||
},
|
||||
"en-US": {
|
||||
"header.subtitle": "Weather Derivatives Intelligence",
|
||||
"header.docs": "Docs",
|
||||
"header.docsAria": "Open product documentation",
|
||||
"header.info": "Tech Notes",
|
||||
"header.infoAria": "Open system technical notes",
|
||||
"header.account": "Account",
|
||||
@@ -180,13 +186,16 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
||||
"header.langEn": "EN",
|
||||
|
||||
"sidebar.title": "Monitored Cities",
|
||||
"sidebar.currentTemp": "Current {temp}",
|
||||
"sidebar.peakTempAt": "Peak {temp} @ {time}",
|
||||
"sidebar.peakAt": "Peak @ {time}",
|
||||
"sidebar.group.high": "High Risk",
|
||||
"sidebar.group.medium": "Medium Risk",
|
||||
"sidebar.group.low": "Low Risk",
|
||||
"sidebar.group.other": "Others",
|
||||
|
||||
"dashboard.loading": "Loading weather data, please wait...",
|
||||
"dashboard.loading":
|
||||
"Synchronizing station observations and settlement feeds...",
|
||||
|
||||
"detail.closeAria": "Close city detail panel",
|
||||
"detail.waitSelect": "Waiting for city selection",
|
||||
@@ -210,7 +219,7 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
||||
"guide.title": "📎 PolyWeather Technical Overview",
|
||||
"guide.closeAria": "Close technical overview",
|
||||
"guide.footer":
|
||||
"Primary data sources are METAR, Hong Kong Observatory (HKO), CWA (Taiwan), Turkish MGM, Open-Meteo, and weather.gov.",
|
||||
"Primary data sources are METAR, Hong Kong Observatory (HKO), designated NOAA stations, Turkish MGM, Open-Meteo, and weather.gov.",
|
||||
|
||||
"history.title": "📊 Historical Reconciliation - {city}",
|
||||
"history.closeAria": "Close history reconciliation",
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
import { createSupabaseServerClient, hasSupabaseServerEnv } from "@/lib/supabase/server";
|
||||
|
||||
function parseAdminEmails() {
|
||||
return String(process.env.POLYWEATHER_OPS_ADMIN_EMAILS || "")
|
||||
.split(",")
|
||||
.map((item) => item.trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
export async function requireOpsAdmin(nextPath = "/ops") {
|
||||
const allowedEmails = parseAdminEmails();
|
||||
if (!allowedEmails.length || !hasSupabaseServerEnv()) {
|
||||
redirect("/");
|
||||
}
|
||||
|
||||
const cookieStore = await cookies();
|
||||
const supabase = createSupabaseServerClient({
|
||||
getAll() {
|
||||
return cookieStore.getAll().map((item) => ({
|
||||
name: item.name,
|
||||
value: item.value,
|
||||
}));
|
||||
},
|
||||
setAll() {
|
||||
// Server components cannot persist refreshed cookies. Route handlers keep
|
||||
// the session fresh; here we only need read access for page gating.
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
|
||||
const email = String(user?.email || "").trim().toLowerCase();
|
||||
if (!email) {
|
||||
redirect(`/auth/login?next=${encodeURIComponent(nextPath)}`);
|
||||
}
|
||||
if (!allowedEmails.includes(email)) {
|
||||
redirect("/");
|
||||
}
|
||||
|
||||
return { email };
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
const DEFAULT_ALLOWED_PAYMENT_HOSTS = [
|
||||
"polyweather-pro.vercel.app",
|
||||
"localhost",
|
||||
"127.0.0.1",
|
||||
];
|
||||
|
||||
function normalizeHost(raw: string | undefined | null): string {
|
||||
return String(raw || "")
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/^https?:\/\//, "")
|
||||
.replace(/\/.*$/, "")
|
||||
.replace(/:\d+$/, "");
|
||||
}
|
||||
|
||||
export function getAllowedPaymentHosts(): string[] {
|
||||
const configured = String(
|
||||
process.env.NEXT_PUBLIC_PAYMENT_ALLOWED_HOSTS ||
|
||||
process.env.POLYWEATHER_PAYMENT_ALLOWED_HOSTS ||
|
||||
"",
|
||||
)
|
||||
.split(",")
|
||||
.map((item) => normalizeHost(item))
|
||||
.filter(Boolean);
|
||||
|
||||
if (!configured.length) {
|
||||
return DEFAULT_ALLOWED_PAYMENT_HOSTS;
|
||||
}
|
||||
|
||||
return Array.from(new Set([...configured, "localhost", "127.0.0.1"]));
|
||||
}
|
||||
|
||||
export function isPaymentHostAllowed(hostname: string | undefined | null): boolean {
|
||||
const normalized = normalizeHost(hostname);
|
||||
if (!normalized) return false;
|
||||
return getAllowedPaymentHosts().includes(normalized);
|
||||
}
|
||||
|
||||
export function getCurrentPaymentHost(): string {
|
||||
if (typeof window === "undefined") return "";
|
||||
return normalizeHost(window.location.hostname || window.location.host);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { CityDetail, CityListItem } from "@/lib/dashboard-types";
|
||||
|
||||
export interface WeatherAuraProfile {
|
||||
primary: string;
|
||||
secondary: string;
|
||||
tertiary: string;
|
||||
intensity: number;
|
||||
drift: number;
|
||||
particleOpacity: number;
|
||||
effect: WeatherAuraEffect;
|
||||
effectIntensity: number;
|
||||
}
|
||||
|
||||
export type WeatherAuraEffect =
|
||||
| "rain"
|
||||
| "snow"
|
||||
| "fog"
|
||||
| "storm"
|
||||
| "wind"
|
||||
| "cloud"
|
||||
| "clear";
|
||||
|
||||
const RISK_AURA: Record<
|
||||
string,
|
||||
Omit<WeatherAuraProfile, "intensity" | "drift" | "effect" | "effectIntensity">
|
||||
> =
|
||||
{
|
||||
high: {
|
||||
primary: "#ff7c2a",
|
||||
secondary: "#ffcf66",
|
||||
tertiary: "#56c7ff",
|
||||
particleOpacity: 0.42,
|
||||
},
|
||||
medium: {
|
||||
primary: "#f6c453",
|
||||
secondary: "#5eead4",
|
||||
tertiary: "#7dd3fc",
|
||||
particleOpacity: 0.34,
|
||||
},
|
||||
low: {
|
||||
primary: "#38bdf8",
|
||||
secondary: "#22d3ee",
|
||||
tertiary: "#34d399",
|
||||
particleOpacity: 0.28,
|
||||
},
|
||||
default: {
|
||||
primary: "#6ee7ff",
|
||||
secondary: "#7c8dff",
|
||||
tertiary: "#60a5fa",
|
||||
particleOpacity: 0.3,
|
||||
},
|
||||
};
|
||||
|
||||
function clamp(value: number, min: number, max: number) {
|
||||
return Math.min(Math.max(value, min), max);
|
||||
}
|
||||
|
||||
export function getWeatherAuraProfile(
|
||||
detail: CityDetail | null,
|
||||
cities: CityListItem[],
|
||||
): WeatherAuraProfile {
|
||||
const dominantRisk =
|
||||
String(detail?.risk?.level || "").toLowerCase() ||
|
||||
String(cities.find((city) => city.risk_level)?.risk_level || "").toLowerCase() ||
|
||||
"default";
|
||||
|
||||
const base = RISK_AURA[dominantRisk] || RISK_AURA.default;
|
||||
const currentTemp = Number(detail?.current?.temp);
|
||||
const validTemp = Number.isFinite(currentTemp) ? currentTemp : 18;
|
||||
const intensity = clamp(0.7 + validTemp / 40, 0.72, 1.45);
|
||||
const drift = clamp(0.45 + validTemp / 30, 0.55, 1.35);
|
||||
const particleOpacity = clamp(base.particleOpacity + (intensity - 1) * 0.08, 0.22, 0.48);
|
||||
const wxText = `${String(detail?.current?.wx_desc || "")} ${String(
|
||||
detail?.current?.cloud_desc || "",
|
||||
)}`.toUpperCase();
|
||||
const windSpeed = Number(detail?.current?.wind_speed_kt);
|
||||
const humidity = Number(detail?.current?.humidity);
|
||||
|
||||
let effect: WeatherAuraEffect = "clear";
|
||||
if (
|
||||
/(TS|VCTS|THUNDER|雷暴|LIGHTNING)/.test(wxText)
|
||||
) {
|
||||
effect = "storm";
|
||||
} else if (/(SN|SG|GS|ICE|SLEET|雪|霰)/.test(wxText)) {
|
||||
effect = "snow";
|
||||
} else if (/(RA|DZ|SHRA|SHOWER|RAIN|DRIZZLE|雨)/.test(wxText)) {
|
||||
effect = "rain";
|
||||
} else if (/(FG|BR|HZ|FU|MIST|FOG|雾|霾)/.test(wxText)) {
|
||||
effect = "fog";
|
||||
} else if (
|
||||
/(BKN|OVC|SCT|FEW|CLOUD|云|阴)/.test(wxText)
|
||||
) {
|
||||
effect = "cloud";
|
||||
} else if (Number.isFinite(windSpeed) && windSpeed >= 18) {
|
||||
effect = "wind";
|
||||
}
|
||||
|
||||
const effectIntensity =
|
||||
effect === "storm"
|
||||
? clamp(
|
||||
0.9 +
|
||||
(Number.isFinite(windSpeed) ? windSpeed / 35 : 0) +
|
||||
(Number.isFinite(humidity) ? humidity / 220 : 0),
|
||||
0.9,
|
||||
1.9,
|
||||
)
|
||||
: effect === "rain"
|
||||
? clamp(
|
||||
0.75 +
|
||||
(Number.isFinite(humidity) ? humidity / 180 : 0) +
|
||||
(Number.isFinite(windSpeed) ? windSpeed / 45 : 0),
|
||||
0.72,
|
||||
1.7,
|
||||
)
|
||||
: effect === "snow"
|
||||
? clamp(0.8 + (Number.isFinite(windSpeed) ? windSpeed / 50 : 0), 0.78, 1.4)
|
||||
: effect === "fog"
|
||||
? clamp(0.78 + (Number.isFinite(humidity) ? humidity / 240 : 0), 0.75, 1.3)
|
||||
: effect === "wind"
|
||||
? clamp(0.72 + (Number.isFinite(windSpeed) ? windSpeed / 40 : 0), 0.72, 1.5)
|
||||
: effect === "cloud"
|
||||
? 0.82
|
||||
: 0.72;
|
||||
|
||||
return {
|
||||
...base,
|
||||
intensity,
|
||||
drift,
|
||||
particleOpacity,
|
||||
effect,
|
||||
effectIntensity,
|
||||
};
|
||||
}
|
||||
+35
-2
@@ -31,18 +31,42 @@ function isStaticAsset(pathname: string) {
|
||||
pathname.startsWith("/sitemap.xml") ||
|
||||
pathname.startsWith("/icons/") ||
|
||||
pathname.startsWith("/images/") ||
|
||||
pathname.startsWith("/scenery/") ||
|
||||
pathname.startsWith("/static/")
|
||||
);
|
||||
}
|
||||
|
||||
function isPublicPage(pathname: string) {
|
||||
return (
|
||||
pathname === "/" ||
|
||||
pathname.startsWith("/docs") ||
|
||||
pathname.startsWith("/subscription-help") ||
|
||||
pathname === "/entitlement-required" ||
|
||||
pathname.startsWith("/auth/login") ||
|
||||
pathname.startsWith("/auth/callback")
|
||||
);
|
||||
}
|
||||
|
||||
function isPublicApi(pathname: string) {
|
||||
return (
|
||||
pathname === "/api/auth/me" ||
|
||||
pathname === "/api/cities" ||
|
||||
pathname === "/api/vitals" ||
|
||||
/^\/api\/city\/[^/]+$/i.test(pathname) ||
|
||||
/^\/api\/city\/[^/]+\/summary$/i.test(pathname)
|
||||
);
|
||||
}
|
||||
|
||||
function shouldRefreshOptionalSupabaseSession(pathname: string) {
|
||||
return (
|
||||
pathname.startsWith("/account") ||
|
||||
pathname.startsWith("/ops") ||
|
||||
pathname.startsWith("/api/ops/") ||
|
||||
pathname.startsWith("/api/payments/") ||
|
||||
pathname === "/api/system/status"
|
||||
);
|
||||
}
|
||||
|
||||
function handleLegacyTokenGate(request: NextRequest) {
|
||||
const requiredToken = process.env.POLYWEATHER_DASHBOARD_ACCESS_TOKEN?.trim();
|
||||
if (!requiredToken) {
|
||||
@@ -50,7 +74,7 @@ function handleLegacyTokenGate(request: NextRequest) {
|
||||
}
|
||||
|
||||
const { pathname, searchParams } = request.nextUrl;
|
||||
if (isStaticAsset(pathname) || isPublicPage(pathname)) {
|
||||
if (isStaticAsset(pathname) || isPublicPage(pathname) || isPublicApi(pathname)) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
@@ -91,7 +115,7 @@ function handleLegacyTokenGate(request: NextRequest) {
|
||||
|
||||
async function handleSupabaseAuthGate(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl;
|
||||
if (isPublicPage(pathname)) {
|
||||
if (isPublicPage(pathname) || isPublicApi(pathname)) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
if (pathname.startsWith("/api/")) {
|
||||
@@ -130,6 +154,15 @@ async function handleSupabaseAuthGate(request: NextRequest) {
|
||||
}
|
||||
|
||||
async function handleSupabaseOptionalSession(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl;
|
||||
if (
|
||||
isPublicPage(pathname) ||
|
||||
isPublicApi(pathname) ||
|
||||
!shouldRefreshOptionalSupabaseSession(pathname)
|
||||
) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
const response = NextResponse.next({
|
||||
request: {
|
||||
headers: request.headers,
|
||||
|
||||
Generated
+129
-3
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "polyweather-frontend",
|
||||
"version": "0.1.0",
|
||||
"version": "1.5.1",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "polyweather-frontend",
|
||||
"version": "0.1.0",
|
||||
"version": "1.5.1",
|
||||
"dependencies": {
|
||||
"@radix-ui/react-slot": "^1.1.2",
|
||||
"@supabase/ssr": "^0.5.2",
|
||||
@@ -23,13 +23,15 @@
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-leaflet": "^5.0.0",
|
||||
"tailwind-merge": "^3.3.0"
|
||||
"tailwind-merge": "^3.3.0",
|
||||
"three": "^0.183.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/leaflet": "^1.9.20",
|
||||
"@types/node": "^22.15.21",
|
||||
"@types/react": "^19.0.10",
|
||||
"@types/react-dom": "^19.0.4",
|
||||
"@types/three": "^0.183.1",
|
||||
"@types/trusted-types": "^2.0.7",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"postcss": "^8.5.3",
|
||||
@@ -109,6 +111,12 @@
|
||||
"zod": "^3.24.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@dimforge/rapier3d-compat": {
|
||||
"version": "0.12.0",
|
||||
"resolved": "https://registry.npmmirror.com/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",
|
||||
"integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@emnapi/runtime": {
|
||||
"version": "1.8.1",
|
||||
"resolved": "https://registry.npmmirror.com/@emnapi/runtime/-/runtime-1.8.1.tgz",
|
||||
@@ -2857,6 +2865,12 @@
|
||||
"tslib": "^2.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@tweenjs/tween.js": {
|
||||
"version": "23.1.3",
|
||||
"resolved": "https://registry.npmmirror.com/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
|
||||
"integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@types/connect": {
|
||||
"version": "3.4.38",
|
||||
"resolved": "https://registry.npmmirror.com/@types/connect/-/connect-3.4.38.tgz",
|
||||
@@ -2917,6 +2931,27 @@
|
||||
"@types/react": "^19.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/stats.js": {
|
||||
"version": "0.17.4",
|
||||
"resolved": "https://registry.npmmirror.com/@types/stats.js/-/stats.js-0.17.4.tgz",
|
||||
"integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@types/three": {
|
||||
"version": "0.183.1",
|
||||
"resolved": "https://registry.npmmirror.com/@types/three/-/three-0.183.1.tgz",
|
||||
"integrity": "sha512-f2Pu5Hrepfgavttdye3PsH5RWyY/AvdZQwIVhrc4uNtvF7nOWJacQKcoVJn0S4f0yYbmAE6AR+ve7xDcuYtMGw==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"@dimforge/rapier3d-compat": "~0.12.0",
|
||||
"@tweenjs/tween.js": "~23.1.3",
|
||||
"@types/stats.js": "*",
|
||||
"@types/webxr": ">=0.5.17",
|
||||
"@webgpu/types": "*",
|
||||
"fflate": "~0.8.2",
|
||||
"meshoptimizer": "~1.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/trusted-types": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmmirror.com/@types/trusted-types/-/trusted-types-2.0.7.tgz",
|
||||
@@ -2928,6 +2963,12 @@
|
||||
"integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/@types/webxr": {
|
||||
"version": "0.5.24",
|
||||
"resolved": "https://registry.npmmirror.com/@types/webxr/-/webxr-0.5.24.tgz",
|
||||
"integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@types/ws": {
|
||||
"version": "8.18.1",
|
||||
"resolved": "https://registry.npmmirror.com/@types/ws/-/ws-8.18.1.tgz",
|
||||
@@ -3475,6 +3516,12 @@
|
||||
"resolved": "https://registry.npmmirror.com/tslib/-/tslib-1.14.1.tgz",
|
||||
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="
|
||||
},
|
||||
"node_modules/@webgpu/types": {
|
||||
"version": "0.1.69",
|
||||
"resolved": "https://registry.npmmirror.com/@webgpu/types/-/types-0.1.69.tgz",
|
||||
"integrity": "sha512-RPmm6kgRbI8e98zSD3RVACvnuktIja5+yLgDAkTmxLr90BEwdTXRQWNLF3ETTTyH/8mKhznZuN5AveXYFEsMGQ==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/abitype": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmmirror.com/abitype/-/abitype-1.0.6.tgz",
|
||||
@@ -4308,6 +4355,12 @@
|
||||
"reusify": "^1.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/fflate": {
|
||||
"version": "0.8.2",
|
||||
"resolved": "https://registry.npmmirror.com/fflate/-/fflate-0.8.2.tgz",
|
||||
"integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/fill-range": {
|
||||
"version": "7.1.1",
|
||||
"resolved": "https://registry.npmmirror.com/fill-range/-/fill-range-7.1.1.tgz",
|
||||
@@ -4901,6 +4954,12 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/meshoptimizer": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/meshoptimizer/-/meshoptimizer-1.0.1.tgz",
|
||||
"integrity": "sha512-Vix+QlA1YYT3FwmBBZ+49cE5y/b+pRrcXKqGpS5ouh33d3lSp2PoTpCw19E0cKDFWalembrHnIaZetf27a+W2g==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/micromatch": {
|
||||
"version": "4.0.8",
|
||||
"resolved": "https://registry.npmmirror.com/micromatch/-/micromatch-4.0.8.tgz",
|
||||
@@ -6016,6 +6075,11 @@
|
||||
"real-require": "^0.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/three": {
|
||||
"version": "0.183.2",
|
||||
"resolved": "https://registry.npmmirror.com/three/-/three-0.183.2.tgz",
|
||||
"integrity": "sha512-di3BsL2FEQ1PA7Hcvn4fyJOlxRRgFYBpMTcyOgkwJIaDOdJMebEFPA+t98EvjuljDx4hNulAGwF6KIjtwI5jgQ=="
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.15",
|
||||
"resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
||||
@@ -6642,6 +6706,12 @@
|
||||
"zod": "^3.24.4"
|
||||
}
|
||||
},
|
||||
"@dimforge/rapier3d-compat": {
|
||||
"version": "0.12.0",
|
||||
"resolved": "https://registry.npmmirror.com/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",
|
||||
"integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==",
|
||||
"dev": true
|
||||
},
|
||||
"@emnapi/runtime": {
|
||||
"version": "1.8.1",
|
||||
"resolved": "https://registry.npmmirror.com/@emnapi/runtime/-/runtime-1.8.1.tgz",
|
||||
@@ -8349,6 +8419,12 @@
|
||||
"tslib": "^2.8.0"
|
||||
}
|
||||
},
|
||||
"@tweenjs/tween.js": {
|
||||
"version": "23.1.3",
|
||||
"resolved": "https://registry.npmmirror.com/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
|
||||
"integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
|
||||
"dev": true
|
||||
},
|
||||
"@types/connect": {
|
||||
"version": "3.4.38",
|
||||
"resolved": "https://registry.npmmirror.com/@types/connect/-/connect-3.4.38.tgz",
|
||||
@@ -8407,6 +8483,27 @@
|
||||
"dev": true,
|
||||
"requires": {}
|
||||
},
|
||||
"@types/stats.js": {
|
||||
"version": "0.17.4",
|
||||
"resolved": "https://registry.npmmirror.com/@types/stats.js/-/stats.js-0.17.4.tgz",
|
||||
"integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
|
||||
"dev": true
|
||||
},
|
||||
"@types/three": {
|
||||
"version": "0.183.1",
|
||||
"resolved": "https://registry.npmmirror.com/@types/three/-/three-0.183.1.tgz",
|
||||
"integrity": "sha512-f2Pu5Hrepfgavttdye3PsH5RWyY/AvdZQwIVhrc4uNtvF7nOWJacQKcoVJn0S4f0yYbmAE6AR+ve7xDcuYtMGw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"@dimforge/rapier3d-compat": "~0.12.0",
|
||||
"@tweenjs/tween.js": "~23.1.3",
|
||||
"@types/stats.js": "*",
|
||||
"@types/webxr": ">=0.5.17",
|
||||
"@webgpu/types": "*",
|
||||
"fflate": "~0.8.2",
|
||||
"meshoptimizer": "~1.0.1"
|
||||
}
|
||||
},
|
||||
"@types/trusted-types": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmmirror.com/@types/trusted-types/-/trusted-types-2.0.7.tgz",
|
||||
@@ -8418,6 +8515,12 @@
|
||||
"integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==",
|
||||
"optional": true
|
||||
},
|
||||
"@types/webxr": {
|
||||
"version": "0.5.24",
|
||||
"resolved": "https://registry.npmmirror.com/@types/webxr/-/webxr-0.5.24.tgz",
|
||||
"integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
|
||||
"dev": true
|
||||
},
|
||||
"@types/ws": {
|
||||
"version": "8.18.1",
|
||||
"resolved": "https://registry.npmmirror.com/@types/ws/-/ws-8.18.1.tgz",
|
||||
@@ -8838,6 +8941,12 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"@webgpu/types": {
|
||||
"version": "0.1.69",
|
||||
"resolved": "https://registry.npmmirror.com/@webgpu/types/-/types-0.1.69.tgz",
|
||||
"integrity": "sha512-RPmm6kgRbI8e98zSD3RVACvnuktIja5+yLgDAkTmxLr90BEwdTXRQWNLF3ETTTyH/8mKhznZuN5AveXYFEsMGQ==",
|
||||
"dev": true
|
||||
},
|
||||
"abitype": {
|
||||
"version": "1.0.6",
|
||||
"resolved": "https://registry.npmmirror.com/abitype/-/abitype-1.0.6.tgz",
|
||||
@@ -9423,6 +9532,12 @@
|
||||
"reusify": "^1.0.4"
|
||||
}
|
||||
},
|
||||
"fflate": {
|
||||
"version": "0.8.2",
|
||||
"resolved": "https://registry.npmmirror.com/fflate/-/fflate-0.8.2.tgz",
|
||||
"integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==",
|
||||
"dev": true
|
||||
},
|
||||
"fill-range": {
|
||||
"version": "7.1.1",
|
||||
"resolved": "https://registry.npmmirror.com/fill-range/-/fill-range-7.1.1.tgz",
|
||||
@@ -9835,6 +9950,12 @@
|
||||
"integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==",
|
||||
"dev": true
|
||||
},
|
||||
"meshoptimizer": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmmirror.com/meshoptimizer/-/meshoptimizer-1.0.1.tgz",
|
||||
"integrity": "sha512-Vix+QlA1YYT3FwmBBZ+49cE5y/b+pRrcXKqGpS5ouh33d3lSp2PoTpCw19E0cKDFWalembrHnIaZetf27a+W2g==",
|
||||
"dev": true
|
||||
},
|
||||
"micromatch": {
|
||||
"version": "4.0.8",
|
||||
"resolved": "https://registry.npmmirror.com/micromatch/-/micromatch-4.0.8.tgz",
|
||||
@@ -10534,6 +10655,11 @@
|
||||
"real-require": "^0.2.0"
|
||||
}
|
||||
},
|
||||
"three": {
|
||||
"version": "0.183.2",
|
||||
"resolved": "https://registry.npmmirror.com/three/-/three-0.183.2.tgz",
|
||||
"integrity": "sha512-di3BsL2FEQ1PA7Hcvn4fyJOlxRRgFYBpMTcyOgkwJIaDOdJMebEFPA+t98EvjuljDx4hNulAGwF6KIjtwI5jgQ=="
|
||||
},
|
||||
"tinyglobby": {
|
||||
"version": "0.2.15",
|
||||
"resolved": "https://registry.npmmirror.com/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "polyweather-frontend",
|
||||
"version": "1.4.0",
|
||||
"version": "1.5.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
@@ -24,13 +24,15 @@
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-leaflet": "^5.0.0",
|
||||
"tailwind-merge": "^3.3.0"
|
||||
"tailwind-merge": "^3.3.0",
|
||||
"three": "^0.183.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/leaflet": "^1.9.20",
|
||||
"@types/node": "^22.15.21",
|
||||
"@types/react": "^19.0.10",
|
||||
"@types/react-dom": "^19.0.4",
|
||||
"@types/three": "^0.183.1",
|
||||
"@types/trusted-types": "^2.0.7",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"postcss": "^8.5.3",
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
[33mtag v1.5.1[m
|
||||
Tagger: 2569718930@qq.com <2569718930@qq.com>
|
||||
Date: Mon Mar 23 17:59:19 2026 +0800
|
||||
|
||||
Release v1.5.1
|
||||
|
||||
[33mcommit 06b1e1b9fe9b921d5f98db889a590ff6118c06b3[m[33m ([m[1;36mHEAD -> [m[1;32mmain[m[33m, [m[1;33mtag: v1.5.1[m[33m, [m[1;31morigin/main[m[33m)[m
|
||||
Author: 2569718930@qq.com <2569718930@qq.com>
|
||||
Date: Mon Mar 23 17:54:14 2026 +0800
|
||||
|
||||
Release v1.5.1 and improve mobile dashboard layouts
|
||||
|
||||
CHANGELOG.md | 20 [32m+[m[31m-[m
|
||||
FRONTEND_REDESIGN_REPORT.md | 2 [32m+[m[31m-[m
|
||||
README.md | 2 [32m+[m[31m-[m
|
||||
README_ZH.md | 2 [32m+[m[31m-[m
|
||||
VERSION | 2 [32m+[m[31m-[m
|
||||
docs/API_ZH.md | 2 [32m+[m[31m-[m
|
||||
docs/SUPABASE_SETUP_ZH.md | 2 [32m+[m[31m-[m
|
||||
docs/TECH_DEBT.md | 2 [32m+[m[31m-[m
|
||||
docs/TECH_DEBT_ZH.md | 2 [32m+[m[31m-[m
|
||||
docs/payments/POLYGONSCAN_VERIFY.md | 2 [32m+[m[31m-[m
|
||||
.../components/account/AccountCenter.module.css | 73 [32m++++++[m
|
||||
frontend/components/dashboard/Dashboard.module.css | 289 [32m++++++++++++++++++++[m[31m-[m
|
||||
frontend/components/ops/OpsDashboard.tsx | 149 [32m++++++++[m[31m---[m
|
||||
frontend/package.json | 2 [32m+[m[31m-[m
|
||||
14 files changed, 492 insertions(+), 59 deletions(-)
|
||||
@@ -0,0 +1,2 @@
|
||||
[pytest]
|
||||
testpaths = tests
|
||||
@@ -0,0 +1,3 @@
|
||||
pytest
|
||||
ruff
|
||||
httpx
|
||||
@@ -0,0 +1,144 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
from src.analysis.deb_algorithm import load_history, save_history # noqa: E402
|
||||
from src.analysis.probability_snapshot_archive import ( # noqa: E402
|
||||
load_snapshot_rows_for_day,
|
||||
)
|
||||
from src.database.runtime_state import STATE_STORAGE_FILE, get_state_storage_mode # noqa: E402
|
||||
|
||||
|
||||
def _load_daily_records(path: Path) -> Dict[str, Dict[str, Dict[str, Any]]]:
|
||||
data = load_history(str(path))
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _pick_model_value_from_snapshots(
|
||||
city: str,
|
||||
target_date: str,
|
||||
model_name: str,
|
||||
) -> float | None:
|
||||
rows = load_snapshot_rows_for_day(city, target_date)
|
||||
values = []
|
||||
for row in rows:
|
||||
mm = row.get("multi_model") or {}
|
||||
if not isinstance(mm, dict):
|
||||
continue
|
||||
value = mm.get(model_name)
|
||||
if value is None:
|
||||
continue
|
||||
try:
|
||||
values.append(float(value))
|
||||
except Exception:
|
||||
continue
|
||||
if not values:
|
||||
return None
|
||||
counts = Counter(values)
|
||||
return counts.most_common(1)[0][0]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Backfill missing model forecasts in daily_records from archived probability snapshots."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--history-file",
|
||||
default=str(Path("data") / "daily_records.json"),
|
||||
help="Path to daily_records.json",
|
||||
)
|
||||
parser.add_argument("--city", help="Optional city filter, e.g. ankara")
|
||||
parser.add_argument("--date", help="Optional YYYY-MM-DD filter")
|
||||
parser.add_argument(
|
||||
"--model",
|
||||
default="MGM",
|
||||
help="Model name to backfill from snapshot multi_model payloads",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--write",
|
||||
action="store_true",
|
||||
help="Write recovered values back to history file / runtime state",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
history_path = Path(args.history_file)
|
||||
data = _load_daily_records(history_path)
|
||||
model_name = str(args.model or "").strip()
|
||||
city_filter = str(args.city or "").strip().lower() or None
|
||||
date_filter = str(args.date or "").strip() or None
|
||||
|
||||
recovered = []
|
||||
missing = []
|
||||
changed = False
|
||||
|
||||
for city, city_rows in sorted(data.items()):
|
||||
if city_filter and city != city_filter:
|
||||
continue
|
||||
if not isinstance(city_rows, dict):
|
||||
continue
|
||||
for target_date, record in sorted(city_rows.items()):
|
||||
if date_filter and target_date != date_filter:
|
||||
continue
|
||||
if not isinstance(record, dict):
|
||||
continue
|
||||
forecasts = record.get("forecasts") or {}
|
||||
if not isinstance(forecasts, dict):
|
||||
forecasts = {}
|
||||
if forecasts.get(model_name) is not None:
|
||||
continue
|
||||
|
||||
recovered_value = _pick_model_value_from_snapshots(city, target_date, model_name)
|
||||
if recovered_value is None:
|
||||
missing.append((city, target_date))
|
||||
continue
|
||||
|
||||
recovered.append((city, target_date, recovered_value))
|
||||
if args.write:
|
||||
next_forecasts = dict(forecasts)
|
||||
next_forecasts[model_name] = recovered_value
|
||||
record["forecasts"] = next_forecasts
|
||||
changed = True
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"model": model_name,
|
||||
"recovered_count": len(recovered),
|
||||
"missing_count": len(missing),
|
||||
"recovered": [
|
||||
{"city": city, "date": date_str, "value": value}
|
||||
for city, date_str, value in recovered
|
||||
],
|
||||
"missing": [
|
||||
{"city": city, "date": date_str}
|
||||
for city, date_str in missing
|
||||
],
|
||||
"write_requested": bool(args.write),
|
||||
"storage_mode": get_state_storage_mode(),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
if changed:
|
||||
previous_mode = get_state_storage_mode()
|
||||
# Reuse existing save path semantics. In sqlite-only mode, save_history would skip file write.
|
||||
save_history(str(history_path), data)
|
||||
if previous_mode == STATE_STORAGE_FILE and not history_path.exists():
|
||||
raise FileNotFoundError(history_path)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,210 @@
|
||||
import argparse
|
||||
import csv
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from datetime import date, timedelta
|
||||
from typing import Dict, Iterable, Tuple
|
||||
|
||||
import requests
|
||||
|
||||
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, PROJECT_ROOT)
|
||||
|
||||
from src.data_collection.city_registry import CITY_REGISTRY # noqa: E402
|
||||
|
||||
|
||||
HOURLY_FIELDS = (
|
||||
"temperature_2m",
|
||||
"relative_humidity_2m",
|
||||
"wind_speed_10m",
|
||||
"wind_direction_10m",
|
||||
"cloud_cover",
|
||||
"shortwave_radiation",
|
||||
"precipitation",
|
||||
"surface_pressure",
|
||||
)
|
||||
|
||||
|
||||
def _city_output_path(output_dir: str, city_name: str) -> str:
|
||||
filename = f"{city_name.replace(' ', '_').lower()}_historical.csv"
|
||||
return os.path.join(output_dir, filename)
|
||||
|
||||
|
||||
def _fetch_city_history(
|
||||
city_name: str,
|
||||
city_info: Dict[str, object],
|
||||
output_dir: str,
|
||||
start_date: str,
|
||||
end_date: str,
|
||||
session: requests.Session,
|
||||
overwrite: bool = False,
|
||||
max_retries: int = 4,
|
||||
) -> Tuple[str, str]:
|
||||
output_path = _city_output_path(output_dir, city_name)
|
||||
if os.path.exists(output_path) and not overwrite:
|
||||
return city_name, "skipped_existing"
|
||||
|
||||
lat = city_info["lat"]
|
||||
lon = city_info["lon"]
|
||||
url = (
|
||||
"https://archive-api.open-meteo.com/v1/archive"
|
||||
f"?latitude={lat}&longitude={lon}"
|
||||
f"&start_date={start_date}&end_date={end_date}"
|
||||
f"&hourly={','.join(HOURLY_FIELDS)}"
|
||||
"&timezone=auto"
|
||||
)
|
||||
last_error = None
|
||||
payload = None
|
||||
for attempt in range(max_retries + 1):
|
||||
try:
|
||||
response = session.get(url, timeout=90)
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
break
|
||||
except requests.HTTPError as exc:
|
||||
last_error = exc
|
||||
response = getattr(exc, "response", None)
|
||||
status_code = response.status_code if response is not None else None
|
||||
if status_code == 429 and attempt < max_retries:
|
||||
retry_after = 0
|
||||
if response is not None:
|
||||
try:
|
||||
retry_after = int(response.headers.get("Retry-After") or "0")
|
||||
except Exception:
|
||||
retry_after = 0
|
||||
sleep_sec = retry_after if retry_after > 0 else min(90, 5 * (attempt + 1))
|
||||
time.sleep(sleep_sec)
|
||||
continue
|
||||
raise
|
||||
except requests.RequestException as exc:
|
||||
last_error = exc
|
||||
if attempt < max_retries:
|
||||
time.sleep(min(30, 3 * (attempt + 1)))
|
||||
continue
|
||||
raise
|
||||
|
||||
if payload is None:
|
||||
raise RuntimeError(f"failed to fetch {city_name}: {last_error}")
|
||||
|
||||
hourly = payload.get("hourly") or {}
|
||||
times = hourly.get("time") or []
|
||||
if not times:
|
||||
raise RuntimeError(f"missing hourly data for {city_name}")
|
||||
|
||||
fieldnames = ["time", *HOURLY_FIELDS]
|
||||
rows = []
|
||||
for idx, ts in enumerate(times):
|
||||
row = {"time": ts}
|
||||
for field in HOURLY_FIELDS:
|
||||
values = hourly.get(field) or []
|
||||
row[field] = values[idx] if idx < len(values) else None
|
||||
rows.append(row)
|
||||
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
with open(output_path, "w", encoding="utf-8", newline="") as fh:
|
||||
writer = csv.DictWriter(fh, fieldnames=fieldnames)
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
return city_name, f"downloaded:{len(rows)}"
|
||||
|
||||
|
||||
def _iter_target_cities(selected: Iterable[str]) -> Iterable[Tuple[str, Dict[str, object]]]:
|
||||
if not selected:
|
||||
for city_name, city_info in sorted(CITY_REGISTRY.items()):
|
||||
yield city_name, city_info
|
||||
return
|
||||
|
||||
normalized = {str(city).strip().lower() for city in selected if str(city).strip()}
|
||||
for city_name, city_info in sorted(CITY_REGISTRY.items()):
|
||||
if city_name in normalized:
|
||||
yield city_name, city_info
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Backfill historical Open-Meteo CSVs for PolyWeather cities.")
|
||||
parser.add_argument(
|
||||
"--output-dir",
|
||||
default=os.path.join(PROJECT_ROOT, "data", "historical"),
|
||||
help="Output directory for per-city historical CSV files.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--start-date",
|
||||
default="2023-01-01",
|
||||
help="Archive start date in YYYY-MM-DD.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--end-date",
|
||||
default=(date.today() - timedelta(days=1)).strftime("%Y-%m-%d"),
|
||||
help="Archive end date in YYYY-MM-DD.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--cities",
|
||||
nargs="*",
|
||||
default=[],
|
||||
help="Optional subset of city registry keys to backfill.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--overwrite",
|
||||
action="store_true",
|
||||
help="Re-download existing CSV files instead of skipping them.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--workers",
|
||||
type=int,
|
||||
default=4,
|
||||
help="Maximum concurrent download workers.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
cities = list(_iter_target_cities(args.cities))
|
||||
if not cities:
|
||||
raise SystemExit("no matching cities found")
|
||||
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": "PolyWeather Historical Backfill/1.0"})
|
||||
|
||||
results = []
|
||||
with ThreadPoolExecutor(max_workers=max(1, args.workers)) as executor:
|
||||
futures = {
|
||||
executor.submit(
|
||||
_fetch_city_history,
|
||||
city_name,
|
||||
city_info,
|
||||
args.output_dir,
|
||||
args.start_date,
|
||||
args.end_date,
|
||||
session,
|
||||
args.overwrite,
|
||||
): city_name
|
||||
for city_name, city_info in cities
|
||||
}
|
||||
for future in as_completed(futures):
|
||||
city_name = futures[future]
|
||||
try:
|
||||
_, status = future.result()
|
||||
print(f"{city_name}: {status}")
|
||||
results.append((city_name, status))
|
||||
except Exception as exc:
|
||||
print(f"{city_name}: error:{exc}")
|
||||
results.append((city_name, f"error:{exc}"))
|
||||
time.sleep(0.1)
|
||||
|
||||
downloaded = sum(1 for _, status in results if status.startswith("downloaded:"))
|
||||
skipped = sum(1 for _, status in results if status == "skipped_existing")
|
||||
failed = [city for city, status in results if status.startswith("error:")]
|
||||
print(
|
||||
"summary downloaded={downloaded} skipped={skipped} failed={failed}".format(
|
||||
downloaded=downloaded,
|
||||
skipped=skipped,
|
||||
failed=len(failed),
|
||||
)
|
||||
)
|
||||
if failed:
|
||||
print("failed_cities=" + ",".join(sorted(failed)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,152 @@
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, PROJECT_ROOT)
|
||||
|
||||
from src.analysis.deb_algorithm import load_history, save_history # noqa: E402
|
||||
from src.analysis.probability_calibration import ( # noqa: E402
|
||||
ENGINE_MODE_EMOS_SHADOW,
|
||||
apply_probability_calibration,
|
||||
build_probability_features,
|
||||
)
|
||||
|
||||
|
||||
def _sample_to_features(sample):
|
||||
peak_flag = sample.get("peak_flag")
|
||||
if peak_flag == 1.0:
|
||||
peak_status = "past"
|
||||
elif peak_flag == 0.5:
|
||||
peak_status = "in_window"
|
||||
else:
|
||||
peak_status = "before"
|
||||
return build_probability_features(
|
||||
city_name=sample.get("city") or "",
|
||||
raw_mu=sample.get("raw_mu"),
|
||||
raw_sigma=sample.get("raw_sigma"),
|
||||
deb_prediction=sample.get("deb_prediction"),
|
||||
ens_data={
|
||||
"median": sample.get("ens_median"),
|
||||
"p10": None,
|
||||
"p90": None,
|
||||
},
|
||||
current_forecasts={},
|
||||
max_so_far=None,
|
||||
peak_status=peak_status,
|
||||
local_hour_frac=None,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Backfill shadow probability snapshots into daily records.")
|
||||
parser.add_argument(
|
||||
"--history-file",
|
||||
default=os.path.join(PROJECT_ROOT, "data", "daily_records.json"),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--training-samples",
|
||||
default=os.path.join(
|
||||
PROJECT_ROOT,
|
||||
"artifacts",
|
||||
"probability_calibration",
|
||||
"training_samples.json",
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--calibration-file",
|
||||
default=os.path.join(
|
||||
PROJECT_ROOT,
|
||||
"artifacts",
|
||||
"probability_calibration",
|
||||
"default.json",
|
||||
),
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
history = load_history(args.history_file)
|
||||
with open(args.training_samples, "r", encoding="utf-8") as fh:
|
||||
training_payload = json.load(fh)
|
||||
|
||||
updated = 0
|
||||
touched = 0
|
||||
|
||||
for sample in training_payload.get("samples") or []:
|
||||
city = str(sample.get("city") or "").strip().lower()
|
||||
date_str = str(sample.get("date") or "").strip()
|
||||
if not city or not date_str:
|
||||
continue
|
||||
record = ((history.get(city) or {}).get(date_str) or {})
|
||||
if not isinstance(record, dict) or not record:
|
||||
continue
|
||||
|
||||
legacy_distribution = [
|
||||
{"value": row.get("v"), "probability": row.get("p")}
|
||||
for row in (record.get("prob_snapshot") or [])
|
||||
if isinstance(row, dict) and row.get("v") is not None
|
||||
]
|
||||
if not legacy_distribution:
|
||||
continue
|
||||
|
||||
calibration = apply_probability_calibration(
|
||||
city_name=city,
|
||||
temp_symbol="°F" if city in {"atlanta", "chicago", "dallas", "miami", "new york", "seattle"} else "°C",
|
||||
raw_mu=sample.get("raw_mu"),
|
||||
raw_sigma=sample.get("raw_sigma"),
|
||||
max_so_far=None,
|
||||
legacy_distribution=legacy_distribution,
|
||||
features=_sample_to_features(sample),
|
||||
calibration_path=args.calibration_file,
|
||||
mode=ENGINE_MODE_EMOS_SHADOW,
|
||||
)
|
||||
|
||||
shadow_distribution = calibration.get("shadow_distribution") or []
|
||||
compact_shadow = [
|
||||
{
|
||||
"v": int(row.get("value")),
|
||||
"p": round(float(row.get("probability") or 0.0), 3),
|
||||
}
|
||||
for row in shadow_distribution[:4]
|
||||
if row.get("value") is not None
|
||||
]
|
||||
compact_calibration = {
|
||||
"mode": calibration.get("mode"),
|
||||
"engine": calibration.get("engine"),
|
||||
"version": calibration.get("calibration_version"),
|
||||
"source": calibration.get("calibration_source"),
|
||||
"raw_mu": calibration.get("raw_mu"),
|
||||
"raw_sigma": calibration.get("raw_sigma"),
|
||||
"calibrated_mu": calibration.get("calibrated_mu"),
|
||||
"calibrated_sigma": calibration.get("calibrated_sigma"),
|
||||
}
|
||||
|
||||
touched += 1
|
||||
if (
|
||||
record.get("shadow_prob_snapshot") == compact_shadow
|
||||
and record.get("probability_calibration") == compact_calibration
|
||||
):
|
||||
continue
|
||||
|
||||
record["shadow_prob_snapshot"] = compact_shadow
|
||||
record["probability_calibration"] = compact_calibration
|
||||
history[city][date_str] = record
|
||||
updated += 1
|
||||
|
||||
save_history(args.history_file, history)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"samples_seen": len(training_payload.get("samples") or []),
|
||||
"records_considered": touched,
|
||||
"records_updated": updated,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,105 @@
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, PROJECT_ROOT)
|
||||
|
||||
from src.analysis.deb_algorithm import load_history, reconcile_recent_actual_highs, save_history # noqa: E402
|
||||
from src.data_collection.city_registry import CITY_REGISTRY # noqa: E402
|
||||
|
||||
|
||||
def _target_dates(city_info: dict, lookback_days: int) -> list[str]:
|
||||
tz_offset = int(city_info.get("tz_offset") or 0)
|
||||
local_now = datetime.utcnow() + timedelta(seconds=tz_offset)
|
||||
local_today = local_now.date()
|
||||
dates = []
|
||||
for offset in range(max(lookback_days, 1), 0, -1):
|
||||
day = local_today - timedelta(days=offset)
|
||||
dates.append(day.strftime("%Y-%m-%d"))
|
||||
return dates
|
||||
|
||||
|
||||
def _is_metar_city(city_info: dict) -> bool:
|
||||
source = str(city_info.get("settlement_source") or "metar").strip().lower()
|
||||
return source == "metar"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Seed recent daily_records rows and backfill actual_high from aviationweather METAR history."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--cities",
|
||||
nargs="*",
|
||||
default=[],
|
||||
help="Optional subset of city registry keys.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--lookback-days",
|
||||
type=int,
|
||||
default=14,
|
||||
help="How many recent local days to seed/backfill (excluding today).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--only-missing-cities",
|
||||
action="store_true",
|
||||
help="Only process cities that do not exist in daily_records yet.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
history_file = os.path.join(PROJECT_ROOT, "data", "daily_records.json")
|
||||
data = load_history(history_file)
|
||||
|
||||
selected = {str(item).strip().lower() for item in args.cities if str(item).strip()}
|
||||
candidates: list[str] = []
|
||||
for city_name, city_info in sorted(CITY_REGISTRY.items()):
|
||||
if selected and city_name not in selected:
|
||||
continue
|
||||
if not isinstance(city_info, dict) or not _is_metar_city(city_info):
|
||||
continue
|
||||
if not str(city_info.get("icao") or "").strip():
|
||||
continue
|
||||
if args.only_missing_cities and city_name in data:
|
||||
continue
|
||||
candidates.append(city_name)
|
||||
|
||||
seeded_rows = 0
|
||||
seeded_cities = 0
|
||||
for city_name in candidates:
|
||||
city_info = CITY_REGISTRY[city_name]
|
||||
city_rows = data.get(city_name)
|
||||
if not isinstance(city_rows, dict):
|
||||
city_rows = {}
|
||||
data[city_name] = city_rows
|
||||
|
||||
before = len(city_rows)
|
||||
for date_str in _target_dates(city_info, args.lookback_days):
|
||||
city_rows.setdefault(date_str, {})
|
||||
if len(city_rows) > before:
|
||||
seeded_cities += 1
|
||||
seeded_rows += len(city_rows) - before
|
||||
|
||||
if seeded_rows > 0:
|
||||
save_history(history_file, data)
|
||||
|
||||
results = []
|
||||
for city_name in candidates:
|
||||
result = reconcile_recent_actual_highs(city_name, lookback_days=args.lookback_days)
|
||||
results.append((city_name, result))
|
||||
|
||||
print(
|
||||
{
|
||||
"lookback_days": args.lookback_days,
|
||||
"candidate_count": len(candidates),
|
||||
"seeded_cities": seeded_cities,
|
||||
"seeded_rows": seeded_rows,
|
||||
"results": results,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,219 @@
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
|
||||
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, PROJECT_ROOT)
|
||||
|
||||
from src.analysis.deb_algorithm import load_history # noqa: E402
|
||||
from src.analysis.settlement_rounding import apply_city_settlement # noqa: E402
|
||||
|
||||
|
||||
def _sf(value):
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return float(value)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _mean(values):
|
||||
return round(sum(values) / len(values), 6) if values else None
|
||||
|
||||
|
||||
def _top_bucket(snapshot):
|
||||
if not isinstance(snapshot, list):
|
||||
return None
|
||||
best = None
|
||||
best_prob = -1.0
|
||||
for row in snapshot:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
try:
|
||||
prob = float(row.get("p") if "p" in row else row.get("probability"))
|
||||
except Exception:
|
||||
continue
|
||||
value = row.get("v") if "v" in row else row.get("value")
|
||||
if value is None:
|
||||
continue
|
||||
if prob > best_prob:
|
||||
best = value
|
||||
best_prob = prob
|
||||
return best
|
||||
|
||||
|
||||
def _bucket_probability(snapshot, target_bucket):
|
||||
if not isinstance(snapshot, list):
|
||||
return 0.0
|
||||
for row in snapshot:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
value = row.get("v") if "v" in row else row.get("value")
|
||||
if value != target_bucket:
|
||||
continue
|
||||
try:
|
||||
return float(row.get("p") if "p" in row else row.get("probability") or 0.0)
|
||||
except Exception:
|
||||
return 0.0
|
||||
return 0.0
|
||||
|
||||
|
||||
def _brier_from_snapshot(snapshot, target_bucket):
|
||||
hit_prob = _bucket_probability(snapshot, target_bucket)
|
||||
total = (1.0 - hit_prob) ** 2
|
||||
if isinstance(snapshot, list):
|
||||
for row in snapshot:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
value = row.get("v") if "v" in row else row.get("value")
|
||||
if value == target_bucket:
|
||||
continue
|
||||
try:
|
||||
prob = float(row.get("p") if "p" in row else row.get("probability") or 0.0)
|
||||
except Exception:
|
||||
prob = 0.0
|
||||
total += prob * prob
|
||||
return round(total, 6)
|
||||
|
||||
|
||||
def _blank_metrics():
|
||||
return {
|
||||
"samples": 0,
|
||||
"legacy_mae": [],
|
||||
"shadow_mae": [],
|
||||
"legacy_bucket_hit": [],
|
||||
"shadow_bucket_hit": [],
|
||||
"legacy_bucket_brier": [],
|
||||
"shadow_bucket_brier": [],
|
||||
}
|
||||
|
||||
|
||||
def _rollup(metrics):
|
||||
return {
|
||||
"samples": metrics["samples"],
|
||||
"legacy_mean_mae": _mean(metrics["legacy_mae"]),
|
||||
"shadow_mean_mae": _mean(metrics["shadow_mae"]),
|
||||
"legacy_bucket_hit_rate": _mean(metrics["legacy_bucket_hit"]),
|
||||
"shadow_bucket_hit_rate": _mean(metrics["shadow_bucket_hit"]),
|
||||
"legacy_bucket_brier": _mean(metrics["legacy_bucket_brier"]),
|
||||
"shadow_bucket_brier": _mean(metrics["shadow_bucket_brier"]),
|
||||
"delta_mae": round((_mean(metrics["shadow_mae"]) or 0.0) - (_mean(metrics["legacy_mae"]) or 0.0), 6),
|
||||
"delta_bucket_hit_rate": round((_mean(metrics["shadow_bucket_hit"]) or 0.0) - (_mean(metrics["legacy_bucket_hit"]) or 0.0), 6),
|
||||
"delta_bucket_brier": round((_mean(metrics["shadow_bucket_brier"]) or 0.0) - (_mean(metrics["legacy_bucket_brier"]) or 0.0), 6),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Build live shadow probability report from daily records.")
|
||||
parser.add_argument(
|
||||
"--history-file",
|
||||
default=os.path.join(PROJECT_ROOT, "data", "daily_records.json"),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
default=os.path.join(
|
||||
PROJECT_ROOT,
|
||||
"artifacts",
|
||||
"probability_calibration",
|
||||
"shadow_report.json",
|
||||
),
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
history = load_history(args.history_file)
|
||||
overall = _blank_metrics()
|
||||
by_city = defaultdict(_blank_metrics)
|
||||
by_date = defaultdict(_blank_metrics)
|
||||
latest_observations = []
|
||||
|
||||
for city, city_records in sorted(history.items()):
|
||||
if not isinstance(city_records, dict):
|
||||
continue
|
||||
for date_str, record in sorted(city_records.items()):
|
||||
if not isinstance(record, dict):
|
||||
continue
|
||||
actual_high = _sf(record.get("actual_high"))
|
||||
shadow_snapshot = record.get("shadow_prob_snapshot")
|
||||
calibration = record.get("probability_calibration") or {}
|
||||
if actual_high is None or not shadow_snapshot:
|
||||
continue
|
||||
|
||||
legacy_mu = _sf(calibration.get("raw_mu"))
|
||||
if legacy_mu is None:
|
||||
legacy_mu = _sf(record.get("mu"))
|
||||
shadow_mu = _sf(calibration.get("calibrated_mu"))
|
||||
if shadow_mu is None:
|
||||
continue
|
||||
|
||||
actual_bucket = apply_city_settlement(city, actual_high)
|
||||
legacy_snapshot = record.get("prob_snapshot") or []
|
||||
legacy_bucket = _top_bucket(legacy_snapshot)
|
||||
shadow_bucket = _top_bucket(shadow_snapshot)
|
||||
|
||||
for metrics in (overall, by_city[city], by_date[date_str]):
|
||||
metrics["samples"] += 1
|
||||
metrics["legacy_mae"].append(abs(legacy_mu - actual_high))
|
||||
metrics["shadow_mae"].append(abs(shadow_mu - actual_high))
|
||||
metrics["legacy_bucket_hit"].append(1.0 if legacy_bucket == actual_bucket else 0.0)
|
||||
metrics["shadow_bucket_hit"].append(1.0 if shadow_bucket == actual_bucket else 0.0)
|
||||
metrics["legacy_bucket_brier"].append(_brier_from_snapshot(legacy_snapshot, actual_bucket))
|
||||
metrics["shadow_bucket_brier"].append(_brier_from_snapshot(shadow_snapshot, actual_bucket))
|
||||
|
||||
latest_observations.append(
|
||||
{
|
||||
"city": city,
|
||||
"date": date_str,
|
||||
"actual_high": actual_high,
|
||||
"actual_bucket": actual_bucket,
|
||||
"legacy_mu": round(legacy_mu, 3),
|
||||
"shadow_mu": round(shadow_mu, 3),
|
||||
"legacy_top_bucket": legacy_bucket,
|
||||
"shadow_top_bucket": shadow_bucket,
|
||||
"calibration_version": calibration.get("version"),
|
||||
"calibration_mode": calibration.get("mode"),
|
||||
}
|
||||
)
|
||||
|
||||
by_city_report = {
|
||||
city: _rollup(metrics)
|
||||
for city, metrics in sorted(by_city.items())
|
||||
}
|
||||
by_date_report = {
|
||||
date_str: _rollup(metrics)
|
||||
for date_str, metrics in sorted(
|
||||
by_date.items(),
|
||||
key=lambda item: datetime.strptime(item[0], "%Y-%m-%d"),
|
||||
)
|
||||
}
|
||||
|
||||
latest_observations = sorted(
|
||||
latest_observations,
|
||||
key=lambda row: (row["date"], row["city"]),
|
||||
reverse=True,
|
||||
)[:100]
|
||||
|
||||
payload = {
|
||||
"generated_at": datetime.utcnow().isoformat() + "Z",
|
||||
"summary": _rollup(overall),
|
||||
"by_city": by_city_report,
|
||||
"by_date": by_date_report,
|
||||
"recent_observations": latest_observations,
|
||||
}
|
||||
|
||||
output_dir = os.path.dirname(os.path.abspath(args.output))
|
||||
if output_dir:
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
with open(args.output, "w", encoding="utf-8") as fh:
|
||||
json.dump(payload, fh, ensure_ascii=False, indent=2)
|
||||
|
||||
print(json.dumps(payload["summary"], ensure_ascii=False, indent=2))
|
||||
print(f"saved shadow report to {args.output}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,84 @@
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
|
||||
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, PROJECT_ROOT)
|
||||
|
||||
from src.analysis.settlement_rounding import apply_city_settlement # noqa: E402
|
||||
from src.data_collection.city_registry import CITY_REGISTRY # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Build daily settlement history from historical weather CSV files.")
|
||||
parser.add_argument(
|
||||
"--history-dir",
|
||||
default=os.path.join(PROJECT_ROOT, "data", "historical"),
|
||||
help="Directory containing per-city *_historical.csv files.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
default=os.path.join(
|
||||
PROJECT_ROOT,
|
||||
"artifacts",
|
||||
"probability_calibration",
|
||||
"settlement_history.json",
|
||||
),
|
||||
help="Output JSON path.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
result = {}
|
||||
for city in sorted(CITY_REGISTRY.keys()):
|
||||
path = os.path.join(
|
||||
args.history_dir,
|
||||
f"{city.replace(' ', '_').lower()}_historical.csv",
|
||||
)
|
||||
if not os.path.exists(path):
|
||||
continue
|
||||
|
||||
daily_max = defaultdict(lambda: None)
|
||||
with open(path, "r", encoding="utf-8") as fh:
|
||||
reader = csv.DictReader(fh)
|
||||
for row in reader:
|
||||
ts = str(row.get("time") or "")
|
||||
raw_temp = row.get("temperature_2m")
|
||||
if not ts or raw_temp in (None, ""):
|
||||
continue
|
||||
try:
|
||||
temp = float(raw_temp)
|
||||
except Exception:
|
||||
continue
|
||||
day = ts[:10]
|
||||
prev = daily_max[day]
|
||||
if prev is None or temp > prev:
|
||||
daily_max[day] = temp
|
||||
|
||||
result[city] = {
|
||||
day: {
|
||||
"max_temp": round(max_temp, 3),
|
||||
"settlement_value": apply_city_settlement(city, max_temp),
|
||||
}
|
||||
for day, max_temp in sorted(daily_max.items())
|
||||
if max_temp is not None
|
||||
}
|
||||
|
||||
output_dir = os.path.dirname(os.path.abspath(args.output))
|
||||
if output_dir:
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
with open(args.output, "w", encoding="utf-8") as fh:
|
||||
json.dump(result, fh, ensure_ascii=False, indent=2)
|
||||
print(
|
||||
"saved settlement history to {path} for {count} cities".format(
|
||||
path=args.output,
|
||||
count=len(result),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,41 @@
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, PROJECT_ROOT)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
from src.payments.contract_audit import analyze_checkout_contract
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Static security review for PolyWeather checkout contract."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--contract",
|
||||
default=os.path.join(PROJECT_ROOT, "contracts", "PolyWeatherCheckout.sol"),
|
||||
help="Path to Solidity contract source.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
default="",
|
||||
help="Optional JSON output path.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
report = analyze_checkout_contract(args.contract)
|
||||
text = json.dumps(report, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
output_path = os.path.abspath(args.output)
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
with open(output_path, "w", encoding="utf-8") as fh:
|
||||
fh.write(text)
|
||||
print(text)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
||||
from eth_abi import encode
|
||||
from web3 import Web3
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Encode PolyWeatherCheckoutV2 constructor args for PolygonScan verification.",
|
||||
)
|
||||
parser.add_argument("--owner", required=True, help="Owner or multisig address")
|
||||
parser.add_argument("--treasury", required=True, help="Treasury address")
|
||||
parser.add_argument(
|
||||
"--signer",
|
||||
required=True,
|
||||
help="EIP-712 signer address (backend signer or multisig-controlled signer)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
for name, value in {
|
||||
"owner": args.owner,
|
||||
"treasury": args.treasury,
|
||||
"signer": args.signer,
|
||||
}.items():
|
||||
if not Web3.is_address(value):
|
||||
print(f"invalid --{name} address", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
encoded = encode(
|
||||
["address", "address", "address"],
|
||||
[
|
||||
Web3.to_checksum_address(args.owner),
|
||||
Web3.to_checksum_address(args.treasury),
|
||||
Web3.to_checksum_address(args.signer),
|
||||
],
|
||||
).hex()
|
||||
print(encoded)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,206 @@
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
|
||||
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if PROJECT_ROOT not in sys.path:
|
||||
sys.path.insert(0, PROJECT_ROOT)
|
||||
|
||||
from src.analysis.probability_calibration import ( # noqa: E402
|
||||
ENGINE_MODE_EMOS_PRIMARY,
|
||||
_gaussian_crps,
|
||||
apply_probability_calibration,
|
||||
build_probability_features,
|
||||
)
|
||||
from src.analysis.settlement_rounding import apply_city_settlement # noqa: E402
|
||||
from scripts.fit_probability_calibration import ( # noqa: E402
|
||||
_extract_samples,
|
||||
_load_json_if_exists,
|
||||
)
|
||||
from src.analysis.deb_algorithm import load_history # noqa: E402
|
||||
|
||||
|
||||
def _mean(values):
|
||||
return (sum(values) / len(values)) if values else None
|
||||
|
||||
|
||||
def _sample_to_features(sample):
|
||||
return build_probability_features(
|
||||
city_name=sample.get("city") or "",
|
||||
raw_mu=sample.get("raw_mu"),
|
||||
raw_sigma=sample.get("raw_sigma"),
|
||||
deb_prediction=sample.get("deb_prediction"),
|
||||
ens_data={
|
||||
"median": sample.get("ens_median"),
|
||||
"p10": None,
|
||||
"p90": None,
|
||||
},
|
||||
current_forecasts={},
|
||||
max_so_far=None,
|
||||
peak_status="in_window" if sample.get("peak_flag") == 0.5 else "past" if sample.get("peak_flag") == 1.0 else "before",
|
||||
local_hour_frac=None,
|
||||
)
|
||||
|
||||
|
||||
def _top_bucket_value(distribution):
|
||||
if not distribution:
|
||||
return None
|
||||
top = max(
|
||||
(row for row in distribution if isinstance(row, dict)),
|
||||
key=lambda row: float(row.get("probability") or 0.0),
|
||||
default=None,
|
||||
)
|
||||
if not top:
|
||||
return None
|
||||
return top.get("value")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Evaluate legacy vs EMOS probability calibration.")
|
||||
parser.add_argument(
|
||||
"--history-file",
|
||||
default=os.path.join(PROJECT_ROOT, "data", "daily_records.json"),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--settlement-history",
|
||||
default=os.path.join(
|
||||
PROJECT_ROOT,
|
||||
"artifacts",
|
||||
"probability_calibration",
|
||||
"settlement_history.json",
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--calibration-file",
|
||||
default=os.path.join(
|
||||
PROJECT_ROOT,
|
||||
"artifacts",
|
||||
"probability_calibration",
|
||||
"default.json",
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
default=os.path.join(
|
||||
PROJECT_ROOT,
|
||||
"artifacts",
|
||||
"probability_calibration",
|
||||
"evaluation_report.json",
|
||||
),
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
history = load_history(args.history_file)
|
||||
settlement_history = _load_json_if_exists(args.settlement_history)
|
||||
samples, filled_actual_from_history = _extract_samples(
|
||||
history,
|
||||
settlement_history=settlement_history,
|
||||
)
|
||||
|
||||
legacy_crps = []
|
||||
emos_crps = []
|
||||
legacy_mae = []
|
||||
emos_mae = []
|
||||
legacy_bucket_hits = []
|
||||
emos_bucket_hits = []
|
||||
by_city = defaultdict(lambda: {
|
||||
"samples": 0,
|
||||
"legacy_crps": [],
|
||||
"emos_crps": [],
|
||||
"legacy_mae": [],
|
||||
"emos_mae": [],
|
||||
"legacy_bucket_hits": [],
|
||||
"emos_bucket_hits": [],
|
||||
})
|
||||
|
||||
for sample in samples:
|
||||
city = str(sample.get("city") or "").strip().lower()
|
||||
actual_high = float(sample["actual_high"])
|
||||
raw_mu = float(sample["raw_mu"])
|
||||
raw_sigma = max(0.1, float(sample["raw_sigma"]))
|
||||
legacy_crps.append(_gaussian_crps(actual_high, raw_mu, raw_sigma))
|
||||
legacy_mae.append(abs(raw_mu - actual_high))
|
||||
|
||||
legacy_bucket = apply_city_settlement(city, raw_mu)
|
||||
actual_bucket = apply_city_settlement(city, actual_high)
|
||||
legacy_bucket_hits.append(1.0 if legacy_bucket == actual_bucket else 0.0)
|
||||
|
||||
calibration = apply_probability_calibration(
|
||||
city_name=city,
|
||||
temp_symbol="°F" if city in {"atlanta", "chicago", "dallas", "miami", "new york", "seattle"} else "°C",
|
||||
raw_mu=raw_mu,
|
||||
raw_sigma=raw_sigma,
|
||||
max_so_far=None,
|
||||
legacy_distribution=[],
|
||||
features=_sample_to_features(sample),
|
||||
calibration_path=args.calibration_file,
|
||||
mode=ENGINE_MODE_EMOS_PRIMARY,
|
||||
)
|
||||
emos_mu = float(calibration.get("calibrated_mu") or raw_mu)
|
||||
emos_sigma = max(0.1, float(calibration.get("calibrated_sigma") or raw_sigma))
|
||||
emos_distribution = calibration.get("distribution") or []
|
||||
emos_crps.append(_gaussian_crps(actual_high, emos_mu, emos_sigma))
|
||||
emos_mae.append(abs(emos_mu - actual_high))
|
||||
emos_bucket = _top_bucket_value(emos_distribution)
|
||||
emos_bucket_hits.append(1.0 if emos_bucket == actual_bucket else 0.0)
|
||||
|
||||
row = by_city[city]
|
||||
row["samples"] += 1
|
||||
row["legacy_crps"].append(legacy_crps[-1])
|
||||
row["emos_crps"].append(emos_crps[-1])
|
||||
row["legacy_mae"].append(legacy_mae[-1])
|
||||
row["emos_mae"].append(emos_mae[-1])
|
||||
row["legacy_bucket_hits"].append(legacy_bucket_hits[-1])
|
||||
row["emos_bucket_hits"].append(emos_bucket_hits[-1])
|
||||
|
||||
summary = {
|
||||
"sample_count": len(samples),
|
||||
"filled_actual_from_history": filled_actual_from_history,
|
||||
"legacy": {
|
||||
"mean_crps": round(_mean(legacy_crps), 6) if legacy_crps else None,
|
||||
"mean_mae": round(_mean(legacy_mae), 6) if legacy_mae else None,
|
||||
"bucket_hit_rate": round(_mean(legacy_bucket_hits), 6) if legacy_bucket_hits else None,
|
||||
},
|
||||
"emos": {
|
||||
"mean_crps": round(_mean(emos_crps), 6) if emos_crps else None,
|
||||
"mean_mae": round(_mean(emos_mae), 6) if emos_mae else None,
|
||||
"bucket_hit_rate": round(_mean(emos_bucket_hits), 6) if emos_bucket_hits else None,
|
||||
},
|
||||
"delta": {
|
||||
"crps": round((_mean(emos_crps) or 0.0) - (_mean(legacy_crps) or 0.0), 6),
|
||||
"mae": round((_mean(emos_mae) or 0.0) - (_mean(legacy_mae) or 0.0), 6),
|
||||
"bucket_hit_rate": round((_mean(emos_bucket_hits) or 0.0) - (_mean(legacy_bucket_hits) or 0.0), 6),
|
||||
},
|
||||
}
|
||||
|
||||
city_report = {}
|
||||
for city, metrics in sorted(by_city.items()):
|
||||
city_report[city] = {
|
||||
"samples": metrics["samples"],
|
||||
"legacy_mean_crps": round(_mean(metrics["legacy_crps"]), 6),
|
||||
"emos_mean_crps": round(_mean(metrics["emos_crps"]), 6),
|
||||
"legacy_mean_mae": round(_mean(metrics["legacy_mae"]), 6),
|
||||
"emos_mean_mae": round(_mean(metrics["emos_mae"]), 6),
|
||||
"legacy_bucket_hit_rate": round(_mean(metrics["legacy_bucket_hits"]), 6),
|
||||
"emos_bucket_hit_rate": round(_mean(metrics["emos_bucket_hits"]), 6),
|
||||
}
|
||||
|
||||
payload = {
|
||||
"summary": summary,
|
||||
"by_city": city_report,
|
||||
}
|
||||
|
||||
output_dir = os.path.dirname(os.path.abspath(args.output))
|
||||
if output_dir:
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
with open(args.output, "w", encoding="utf-8") as fh:
|
||||
json.dump(payload, fh, ensure_ascii=False, indent=2)
|
||||
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
print(f"saved evaluation report to {args.output}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user