Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitignore +48 -0
- .gitignore_hf +26 -0
- Dockerfile +61 -0
- README.md +23 -5
- backend/.env.example +35 -0
- backend/Dockerfile +16 -0
- backend/fix_venv.sh +57 -0
- backend/requirements.txt +29 -0
- backend/run_server.py +18 -0
- backend/server.py +0 -0
- backend/v2/__init__.py +0 -0
- backend/v2/api.py +0 -0
- backend/v2/celery_app.py +31 -0
- backend/v2/config.py +15 -0
- backend/v2/config.py.bak4sqlite +18 -0
- backend/v2/db.py +466 -0
- backend/v2/migrate_sqlite_to_postgres.py +266 -0
- backend/v2/models.py +318 -0
- backend/v2/repository.py +0 -0
- backend/v2/tasks/__init__.py +4 -0
- backend/v2/tasks/backtest.py +104 -0
- backend/v2/tasks/download.py +612 -0
- backend/v2/tasks/export.py +85 -0
- backend/v2/tdx_day.py +188 -0
- backend/v2/time_sync.py +171 -0
- backend/v2/worker.py +7 -0
- frontend/index.html +13 -0
- frontend/install-deps.bat +16 -0
- frontend/install-file-deps.cmd +20 -0
- frontend/package-lock.json +0 -0
- frontend/package.json +51 -0
- frontend/postcss.config.js +6 -0
- frontend/public/favicon.svg +1 -0
- frontend/src/App.tsx +39 -0
- frontend/src/components/Layout.tsx +163 -0
- frontend/src/components/ui/badge.tsx +36 -0
- frontend/src/components/ui/button.tsx +55 -0
- frontend/src/components/ui/card.tsx +78 -0
- frontend/src/components/ui/date-picker.tsx +195 -0
- frontend/src/components/ui/dialog.tsx +120 -0
- frontend/src/components/ui/file-upload.tsx +298 -0
- frontend/src/components/ui/input.tsx +24 -0
- frontend/src/components/ui/label.tsx +24 -0
- frontend/src/components/ui/popover.tsx +2 -0
- frontend/src/components/ui/select.tsx +158 -0
- frontend/src/components/ui/switch.tsx +27 -0
- frontend/src/components/ui/tabs.tsx +53 -0
- frontend/src/components/ui/toast.tsx +127 -0
- frontend/src/components/ui/toaster.tsx +33 -0
- frontend/src/hooks/use-toast.ts +186 -0
.gitignore
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
*.so
|
| 6 |
+
.Python
|
| 7 |
+
build/
|
| 8 |
+
develop-eggs/
|
| 9 |
+
dist/
|
| 10 |
+
downloads/
|
| 11 |
+
eggs/
|
| 12 |
+
.eggs/
|
| 13 |
+
lib/
|
| 14 |
+
lib64/
|
| 15 |
+
parts/
|
| 16 |
+
sdist/
|
| 17 |
+
var/
|
| 18 |
+
wheels/
|
| 19 |
+
*.egg-info/
|
| 20 |
+
.installed.cfg
|
| 21 |
+
*.egg
|
| 22 |
+
|
| 23 |
+
# Virtual Environment
|
| 24 |
+
venv/
|
| 25 |
+
env/
|
| 26 |
+
ENV/
|
| 27 |
+
.venv
|
| 28 |
+
|
| 29 |
+
# IDE
|
| 30 |
+
.idea/
|
| 31 |
+
.vscode/
|
| 32 |
+
*.swp
|
| 33 |
+
*.swo
|
| 34 |
+
*~
|
| 35 |
+
|
| 36 |
+
# Environment variables
|
| 37 |
+
.env
|
| 38 |
+
|
| 39 |
+
# Cache files
|
| 40 |
+
backend/cache/
|
| 41 |
+
**/cache/
|
| 42 |
+
|
| 43 |
+
# Logs
|
| 44 |
+
*.log
|
| 45 |
+
|
| 46 |
+
# OS
|
| 47 |
+
.DS_Store
|
| 48 |
+
Thumbs.db
|
.gitignore_hf
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Dependencies
|
| 2 |
+
node_modules/
|
| 3 |
+
venv/
|
| 4 |
+
__pycache__/
|
| 5 |
+
*.py[cod]
|
| 6 |
+
|
| 7 |
+
# Build artifacts
|
| 8 |
+
frontend/dist/
|
| 9 |
+
|
| 10 |
+
# Environment
|
| 11 |
+
.env
|
| 12 |
+
*.log
|
| 13 |
+
|
| 14 |
+
# Data
|
| 15 |
+
backend/cache/
|
| 16 |
+
backend/uploads/
|
| 17 |
+
backend/wgjy.db
|
| 18 |
+
backend/data/
|
| 19 |
+
|
| 20 |
+
# OS
|
| 21 |
+
.DS_Store
|
| 22 |
+
Thumbs.db
|
| 23 |
+
|
| 24 |
+
# IDE
|
| 25 |
+
.idea/
|
| 26 |
+
.vscode/
|
Dockerfile
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
# 安装 Nginx
|
| 4 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 5 |
+
curl nginx \
|
| 6 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 7 |
+
|
| 8 |
+
# 安装 Node.js 18
|
| 9 |
+
RUN curl -fsSL https://deb.nodesource.com/setup_18.x | bash - \
|
| 10 |
+
&& apt-get install -y --no-install-recommends nodejs \
|
| 11 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 12 |
+
|
| 13 |
+
WORKDIR /app
|
| 14 |
+
|
| 15 |
+
# === 前端构建 ===
|
| 16 |
+
COPY frontend/package.json frontend/package-lock.json /app/frontend/
|
| 17 |
+
RUN cd /app/frontend && npm ci
|
| 18 |
+
|
| 19 |
+
COPY frontend/ /app/frontend/
|
| 20 |
+
RUN cd /app/frontend && \
|
| 21 |
+
cp tsconfig.json tsconfig.json.bak && \
|
| 22 |
+
python3 -c "
|
| 23 |
+
import json
|
| 24 |
+
with open('tsconfig.json') as f: c = json.load(f)
|
| 25 |
+
c['compilerOptions']['noUnusedLocals'] = False
|
| 26 |
+
c['compilerOptions']['noUnusedParameters'] = False
|
| 27 |
+
with open('tsconfig.json','w') as f: json.dump(c, f, indent=2)
|
| 28 |
+
" && \
|
| 29 |
+
npx vite build && \
|
| 30 |
+
cp tsconfig.json.bak tsconfig.json && rm tsconfig.json.bak
|
| 31 |
+
|
| 32 |
+
# === 后端依赖(精简版,移除 PostgreSQL 驱动) ===
|
| 33 |
+
COPY hf-space/requirements.txt /app/backend/requirements.txt
|
| 34 |
+
RUN pip install --no-cache-dir -r /app/backend/requirements.txt
|
| 35 |
+
|
| 36 |
+
# === 后端代码 ===
|
| 37 |
+
COPY backend/ /app/backend/
|
| 38 |
+
|
| 39 |
+
# === 补丁:Celery 优雅降级 + CORS 开放 ===
|
| 40 |
+
COPY hf-space/patch_celery.py /app/patch_celery.py
|
| 41 |
+
COPY hf-space/patch_cors.py /app/patch_cors.py
|
| 42 |
+
RUN python3 /app/patch_celery.py && python3 /app/patch_cors.py && rm /app/patch_*.py
|
| 43 |
+
|
| 44 |
+
# === Nginx 配置 ===
|
| 45 |
+
RUN rm -f /etc/nginx/sites-enabled/default
|
| 46 |
+
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
| 47 |
+
|
| 48 |
+
# === 启动脚本 ===
|
| 49 |
+
COPY hf-space/start.sh /app/start.sh
|
| 50 |
+
RUN chmod +x /app/start.sh
|
| 51 |
+
|
| 52 |
+
# 环境变量:强制使用 SQLite,禁用交互式修复
|
| 53 |
+
ENV WGJY_DATABASE_URL="" \
|
| 54 |
+
DATABASE_URL="" \
|
| 55 |
+
WGJY_REDIS_URL="" \
|
| 56 |
+
WGJY_DB_INTERACTIVE_FIX=0
|
| 57 |
+
|
| 58 |
+
# HF Spaces 固定端口 7860
|
| 59 |
+
EXPOSE 7860
|
| 60 |
+
|
| 61 |
+
CMD ["/app/start.sh"]
|
README.md
CHANGED
|
@@ -1,10 +1,28 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
|
|
|
| 7 |
pinned: false
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: 网格交易和定投交易回测工具
|
| 3 |
+
emoji: 📈
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: green
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# 网格交易和定投交易回测工具
|
| 12 |
+
|
| 13 |
+
专业的量化交易策略回测平台,支持网格交易和定投策略的历史回测分析。
|
| 14 |
+
|
| 15 |
+
## 功能
|
| 16 |
+
|
| 17 |
+
- 📊 网格交易回测(等差网格、等比网格)
|
| 18 |
+
- 💰 定投交易回测
|
| 19 |
+
- 📈 支持A股/港股/美股历史数据
|
| 20 |
+
- 📉 详细的交易记录和收益分析
|
| 21 |
+
- 📄 支持导入自定义数据(CSV/Excel)
|
| 22 |
+
|
| 23 |
+
## 技术栈
|
| 24 |
+
|
| 25 |
+
- 前端: React + TypeScript + Tailwind CSS + Recharts
|
| 26 |
+
- 后端: Python FastAPI
|
| 27 |
+
- 数据库: SQLite (内置,无需外部依赖)
|
| 28 |
+
- 部署: Docker + Nginx
|
backend/.env.example
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 应用配置
|
| 2 |
+
APP_NAME=网格交易和定投交易回测工具
|
| 3 |
+
VERSION=1.0.0
|
| 4 |
+
DEBUG=True
|
| 5 |
+
|
| 6 |
+
# 数据库配置
|
| 7 |
+
DATABASE_URL=postgresql+psycopg2://wgjy:wgjy_pass@localhost:5432/wgjy
|
| 8 |
+
|
| 9 |
+
# v2 任务系统(Postgres + Redis)
|
| 10 |
+
# - 若设置 WGJY_DATABASE_URL/WGJY_REDIS_URL,则 v2 会优先使用
|
| 11 |
+
# - SQLite 已禁用
|
| 12 |
+
WGJY_DATABASE_URL=postgresql+psycopg2://wgjy:wgjy_pass@localhost:5432/wgjy
|
| 13 |
+
WGJY_REDIS_URL=redis://localhost:6379/0
|
| 14 |
+
|
| 15 |
+
# API配置
|
| 16 |
+
API_V1_STR=/api/v1
|
| 17 |
+
|
| 18 |
+
# 跨域配置(多个地址用逗号分隔)
|
| 19 |
+
BACKEND_CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
|
| 20 |
+
|
| 21 |
+
# 文件上传配置
|
| 22 |
+
UPLOAD_DIR=./uploads
|
| 23 |
+
MAX_UPLOAD_SIZE=52428800
|
| 24 |
+
ALLOWED_EXTENSIONS=.csv,.xlsx,.xls
|
| 25 |
+
|
| 26 |
+
# 回测配置
|
| 27 |
+
MAX_BACKTEST_DAYS=3650
|
| 28 |
+
DEFAULT_INITIAL_CAPITAL=100000.0
|
| 29 |
+
DEFAULT_FEE_RATE=0.0001
|
| 30 |
+
DEFAULT_MIN_FEE=5.0
|
| 31 |
+
|
| 32 |
+
# 数据源配置
|
| 33 |
+
USE_CACHE=True
|
| 34 |
+
CACHE_DIR=./cache
|
| 35 |
+
DATA_SOURCE=baostock
|
backend/Dockerfile
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 6 |
+
PYTHONUNBUFFERED=1
|
| 7 |
+
|
| 8 |
+
COPY requirements.txt /app/requirements.txt
|
| 9 |
+
|
| 10 |
+
RUN pip install --no-cache-dir -r /app/requirements.txt
|
| 11 |
+
|
| 12 |
+
COPY . /app
|
| 13 |
+
|
| 14 |
+
EXPOSE 8000
|
| 15 |
+
|
| 16 |
+
CMD ["python", "-m", "uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]
|
backend/fix_venv.sh
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
# 虚拟环境修复脚本
|
| 4 |
+
echo "开始修复虚拟环境..."
|
| 5 |
+
|
| 6 |
+
# 检查是否在正确的目录
|
| 7 |
+
if [ ! -f "main.py" ]; then
|
| 8 |
+
echo "错误:请在backend目录下运行此脚本"
|
| 9 |
+
exit 1
|
| 10 |
+
fi
|
| 11 |
+
|
| 12 |
+
# 删除可能有问题的虚拟环境
|
| 13 |
+
if [ -d "venv" ]; then
|
| 14 |
+
echo "删除现有虚拟环境..."
|
| 15 |
+
rm -rf venv
|
| 16 |
+
fi
|
| 17 |
+
|
| 18 |
+
# 检查Python版本
|
| 19 |
+
echo "检查Python版本..."
|
| 20 |
+
if command -v python3 &> /dev/null; then
|
| 21 |
+
PYTHON_CMD="python3"
|
| 22 |
+
echo "找到python3"
|
| 23 |
+
elif command -v python &> /dev/null; then
|
| 24 |
+
PYTHON_CMD="python"
|
| 25 |
+
echo "找到python"
|
| 26 |
+
else
|
| 27 |
+
echo "错误:未找到Python,请先安装Python 3.9或3.10"
|
| 28 |
+
exit 1
|
| 29 |
+
fi
|
| 30 |
+
|
| 31 |
+
# 创建新的虚拟环境
|
| 32 |
+
echo "创建新的虚拟环境..."
|
| 33 |
+
$PYTHON_CMD -m venv venv
|
| 34 |
+
if [ $? -ne 0 ]; then
|
| 35 |
+
echo "错误:创建虚拟环境失败,请确保已安装python3-venv包"
|
| 36 |
+
echo "可以尝试安装:apt install python3-venv"
|
| 37 |
+
exit 1
|
| 38 |
+
fi
|
| 39 |
+
|
| 40 |
+
# 激活虚拟环境
|
| 41 |
+
echo "激活虚拟环境..."
|
| 42 |
+
source venv/bin/activate
|
| 43 |
+
|
| 44 |
+
# 升级pip
|
| 45 |
+
echo "升级pip..."
|
| 46 |
+
pip install --upgrade pip
|
| 47 |
+
|
| 48 |
+
# 检查虚拟环境是否激活成功
|
| 49 |
+
if [ -z "$VIRTUAL_ENV" ]; then
|
| 50 |
+
echo "警告:虚拟环境可能未成功激活"
|
| 51 |
+
else
|
| 52 |
+
echo "虚拟环境已成功激活:$VIRTUAL_ENV"
|
| 53 |
+
fi
|
| 54 |
+
|
| 55 |
+
echo "虚拟环境修复完成!请继续安装依赖。"
|
| 56 |
+
echo "提示:运行 'source venv/bin/activate' 重新激活虚拟环境"
|
| 57 |
+
echo "然后运行 'pip install -r requirements.txt' 安装依赖"
|
backend/requirements.txt
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi==0.104.1
|
| 2 |
+
uvicorn[standard]==0.24.0
|
| 3 |
+
sqlalchemy>=2.0.36,<2.1.0
|
| 4 |
+
pydantic>=2.7.0,<3.0.0
|
| 5 |
+
pydantic-settings>=2.2.0,<3.0.0
|
| 6 |
+
python-multipart==0.0.6
|
| 7 |
+
celery>=5.3.6,<6.0.0
|
| 8 |
+
redis>=5.0.1,<6.0.0
|
| 9 |
+
psycopg[binary]>=3.2.0,<4.0.0
|
| 10 |
+
psycopg2-binary>=2.9.9,<3.0.0
|
| 11 |
+
pandas>=2.2.0
|
| 12 |
+
numpy>=2.1.0
|
| 13 |
+
openpyxl>=3.1.2
|
| 14 |
+
xlrd>=2.0.1
|
| 15 |
+
aiofiles==23.2.1
|
| 16 |
+
requests>=2.31.0
|
| 17 |
+
ip-region>=1.0.6,<2.0.0
|
| 18 |
+
python-jose[cryptography]==3.3.0
|
| 19 |
+
passlib[bcrypt]==1.7.4
|
| 20 |
+
email-validator==2.1.0
|
| 21 |
+
httpx==0.25.2
|
| 22 |
+
akshare>=1.16.72,<1.17.0
|
| 23 |
+
baostock>=0.8.9
|
| 24 |
+
efinance>=0.5.0
|
| 25 |
+
pypinyin==0.50.0
|
| 26 |
+
pytest==7.4.3
|
| 27 |
+
pytest-asyncio==0.21.1
|
| 28 |
+
reportlab==4.0.4
|
| 29 |
+
python-docx>=1.1.0,<2.0.0
|
backend/run_server.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Alternative script to run the server directly
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import sys
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
# Add the current directory to Python path
|
| 9 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 10 |
+
|
| 11 |
+
if __name__ == "__main__":
|
| 12 |
+
import uvicorn
|
| 13 |
+
uvicorn.run(
|
| 14 |
+
"server:app",
|
| 15 |
+
host="0.0.0.0",
|
| 16 |
+
port=8000,
|
| 17 |
+
reload=True
|
| 18 |
+
)
|
backend/server.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
backend/v2/__init__.py
ADDED
|
File without changes
|
backend/v2/api.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
backend/v2/celery_app.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
from celery import Celery
|
| 6 |
+
|
| 7 |
+
from .config import get_redis_url
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def make_celery() -> Celery:
|
| 11 |
+
app = Celery(
|
| 12 |
+
'wgjy',
|
| 13 |
+
broker=get_redis_url(),
|
| 14 |
+
backend=get_redis_url(),
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
app.conf.update(
|
| 18 |
+
task_acks_late=True,
|
| 19 |
+
worker_prefetch_multiplier=1,
|
| 20 |
+
task_track_started=True,
|
| 21 |
+
task_time_limit=int(os.getenv('WGJY_TASK_TIME_LIMIT', '600')),
|
| 22 |
+
task_soft_time_limit=int(os.getenv('WGJY_TASK_SOFT_TIME_LIMIT', '540')),
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
return app
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
celery_app = make_celery()
|
| 29 |
+
|
| 30 |
+
# 注册所有任务(在 celery_app 创建后导入,避免循环依赖)
|
| 31 |
+
from .tasks import backtest, download, export # noqa: F401, E402
|
backend/v2/config.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
def _get_backend_dir() -> str:
|
| 4 |
+
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 5 |
+
|
| 6 |
+
def get_database_url() -> str:
|
| 7 |
+
url = os.getenv('WGJY_DATABASE_URL') or os.getenv('DATABASE_URL')
|
| 8 |
+
if url:
|
| 9 |
+
return url
|
| 10 |
+
# PostgreSQL 不可用时,自动降级为 SQLite
|
| 11 |
+
db_path = os.path.join(_get_backend_dir(), 'wgjy.db')
|
| 12 |
+
return f'sqlite:///{db_path}'
|
| 13 |
+
|
| 14 |
+
def get_redis_url() -> str:
|
| 15 |
+
return os.getenv('WGJY_REDIS_URL') or os.getenv('REDIS_URL') or 'redis://localhost:6379/0'
|
backend/v2/config.py.bak4sqlite
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def _get_backend_dir() -> str:
|
| 5 |
+
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def get_database_url() -> str:
|
| 9 |
+
url = os.getenv('WGJY_DATABASE_URL') or os.getenv('DATABASE_URL')
|
| 10 |
+
if not url:
|
| 11 |
+
raise RuntimeError('DATABASE_URL/WGJY_DATABASE_URL must be set to a PostgreSQL connection string')
|
| 12 |
+
if str(url).startswith('sqlite:'):
|
| 13 |
+
raise RuntimeError('SQLite has been disabled. Please use PostgreSQL for DATABASE_URL/WGJY_DATABASE_URL')
|
| 14 |
+
return url
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_redis_url() -> str:
|
| 18 |
+
return os.getenv('WGJY_REDIS_URL') or os.getenv('REDIS_URL') or 'redis://localhost:6379/0'
|
backend/v2/db.py
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from contextlib import contextmanager
|
| 4 |
+
import socket
|
| 5 |
+
import os
|
| 6 |
+
import time
|
| 7 |
+
import re
|
| 8 |
+
|
| 9 |
+
from sqlalchemy import create_engine
|
| 10 |
+
from sqlalchemy.engine.url import make_url
|
| 11 |
+
from sqlalchemy.orm import declarative_base, sessionmaker
|
| 12 |
+
|
| 13 |
+
from .config import get_database_url
|
| 14 |
+
|
| 15 |
+
Base = declarative_base()
|
| 16 |
+
|
| 17 |
+
_engine = None
|
| 18 |
+
_SessionLocal = None
|
| 19 |
+
_engine_url_override: str | None = None
|
| 20 |
+
_db_ready: bool = False
|
| 21 |
+
_db_last_check_ts: float = 0.0
|
| 22 |
+
_db_last_error: str | None = None
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class DatabaseUnavailableError(RuntimeError):
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _is_safe_ident(name: str) -> bool:
|
| 30 |
+
s = str(name or '').strip()
|
| 31 |
+
if not s:
|
| 32 |
+
return False
|
| 33 |
+
return re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', s) is not None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _should_bootstrap_from_error(e: Exception) -> bool:
|
| 37 |
+
msg = str(e or '')
|
| 38 |
+
low = msg.lower()
|
| 39 |
+
keys = [
|
| 40 |
+
'password authentication failed',
|
| 41 |
+
'role',
|
| 42 |
+
'does not exist',
|
| 43 |
+
'invalid password',
|
| 44 |
+
'authentication failed',
|
| 45 |
+
'password',
|
| 46 |
+
]
|
| 47 |
+
return any(k in low for k in keys)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _bootstrap_postgres_if_configured(target_url: str) -> bool:
|
| 51 |
+
admin_url = str(os.getenv('WGJY_PG_ADMIN_URL') or os.getenv('WGJY_POSTGRES_ADMIN_URL') or '').strip()
|
| 52 |
+
if not admin_url:
|
| 53 |
+
return False
|
| 54 |
+
|
| 55 |
+
u = make_url(target_url)
|
| 56 |
+
if not str(u.drivername or '').startswith('postgresql'):
|
| 57 |
+
return False
|
| 58 |
+
|
| 59 |
+
target_user = str(u.username or '').strip()
|
| 60 |
+
target_password = u.password
|
| 61 |
+
target_db = str(u.database or '').strip() or 'wgjy'
|
| 62 |
+
|
| 63 |
+
if not _is_safe_ident(target_user) or not _is_safe_ident(target_db):
|
| 64 |
+
raise DatabaseUnavailableError('v2 数据库初始化失败:数据库名/用户名不符合安全规则(仅允许字母数字下划线,且不能以数字开头)')
|
| 65 |
+
|
| 66 |
+
reset_pw = str(os.getenv('WGJY_PG_BOOTSTRAP_RESET_PASSWORD', '1')).strip() == '1'
|
| 67 |
+
drop_db = str(os.getenv('WGJY_PG_BOOTSTRAP_DROP_DB', '0')).strip() in ('1', 'true', 'yes')
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
import psycopg # type: ignore
|
| 71 |
+
except Exception as e:
|
| 72 |
+
raise DatabaseUnavailableError('v2 数据库初始化失败:未安装 psycopg(psycopg3),无法执行自动初始化') from e
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
conn = psycopg.connect(admin_url, autocommit=True)
|
| 76 |
+
except Exception as e:
|
| 77 |
+
raise DatabaseUnavailableError('v2 数据库初始化失败:无法使用 WGJY_PG_ADMIN_URL 连接到 PostgreSQL(请确认该账号具备建库/建用户权限)') from e
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
with conn.cursor() as cur:
|
| 81 |
+
cur.execute('SELECT 1 FROM pg_roles WHERE rolname=%s', (target_user,))
|
| 82 |
+
role_exists = cur.fetchone() is not None
|
| 83 |
+
|
| 84 |
+
if not role_exists:
|
| 85 |
+
if target_password is None:
|
| 86 |
+
raise DatabaseUnavailableError('v2 数据库初始化失败:目标连接串缺少密码,无法自动创建用户')
|
| 87 |
+
cur.execute(f'CREATE ROLE {target_user} LOGIN PASSWORD %s', (str(target_password),))
|
| 88 |
+
else:
|
| 89 |
+
if reset_pw:
|
| 90 |
+
if target_password is None:
|
| 91 |
+
raise DatabaseUnavailableError('v2 数据库初始化失败:目标连接串缺少密码,无法自动重置用户密码')
|
| 92 |
+
cur.execute(f'ALTER ROLE {target_user} WITH LOGIN PASSWORD %s', (str(target_password),))
|
| 93 |
+
|
| 94 |
+
cur.execute('SELECT 1 FROM pg_database WHERE datname=%s', (target_db,))
|
| 95 |
+
db_exists = cur.fetchone() is not None
|
| 96 |
+
|
| 97 |
+
# 如果配置了 WGJY_PG_BOOTSTRAP_DROP_DB,则优先删除同名数据库后再重建
|
| 98 |
+
if db_exists and drop_db:
|
| 99 |
+
# 终止现有连接,避免 DROP DATABASE 失败
|
| 100 |
+
cur.execute(
|
| 101 |
+
'SELECT pg_terminate_backend(pid) '
|
| 102 |
+
'FROM pg_stat_activity '
|
| 103 |
+
'WHERE datname = %s AND pid <> pg_backend_pid()',
|
| 104 |
+
(target_db,),
|
| 105 |
+
)
|
| 106 |
+
cur.execute(f'DROP DATABASE {target_db}')
|
| 107 |
+
db_exists = False
|
| 108 |
+
|
| 109 |
+
if not db_exists:
|
| 110 |
+
cur.execute(f'CREATE DATABASE {target_db} OWNER {target_user}')
|
| 111 |
+
|
| 112 |
+
cur.execute(f'GRANT ALL PRIVILEGES ON DATABASE {target_db} TO {target_user}')
|
| 113 |
+
return True
|
| 114 |
+
finally:
|
| 115 |
+
try:
|
| 116 |
+
conn.close()
|
| 117 |
+
except Exception:
|
| 118 |
+
pass
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _reset_engine() -> None:
|
| 122 |
+
global _engine, _SessionLocal
|
| 123 |
+
try:
|
| 124 |
+
if _engine is not None:
|
| 125 |
+
_engine.dispose()
|
| 126 |
+
except Exception:
|
| 127 |
+
pass
|
| 128 |
+
_engine = None
|
| 129 |
+
_SessionLocal = None
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _get_effective_database_url() -> str:
|
| 133 |
+
return str(_engine_url_override or get_database_url())
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _set_engine_url_override(url: str | None) -> None:
|
| 137 |
+
global _engine_url_override
|
| 138 |
+
_engine_url_override = str(url) if url else None
|
| 139 |
+
_reset_engine()
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _to_psycopg_url(url: str) -> str | None:
|
| 143 |
+
s = str(url or '').strip()
|
| 144 |
+
if not s:
|
| 145 |
+
return None
|
| 146 |
+
if 'postgresql+psycopg2' in s:
|
| 147 |
+
return s.replace('postgresql+psycopg2', 'postgresql+psycopg', 1)
|
| 148 |
+
if s.startswith('postgresql://'):
|
| 149 |
+
return 'postgresql+psycopg://' + s[len('postgresql://'):]
|
| 150 |
+
return None
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _precheck_postgres_socket(url: str) -> None:
|
| 154 |
+
u = make_url(url)
|
| 155 |
+
driver = str(u.drivername or '')
|
| 156 |
+
if not driver.startswith('postgresql'):
|
| 157 |
+
return
|
| 158 |
+
host = u.host or 'localhost'
|
| 159 |
+
port = int(u.port or 5432)
|
| 160 |
+
timeout = float(os.getenv('WGJY_DB_SOCKET_TIMEOUT_SECONDS', '2.0') or '2.0')
|
| 161 |
+
try:
|
| 162 |
+
conn = socket.create_connection((host, port), timeout=timeout)
|
| 163 |
+
try:
|
| 164 |
+
conn.close()
|
| 165 |
+
except Exception:
|
| 166 |
+
pass
|
| 167 |
+
except OSError as e:
|
| 168 |
+
raise DatabaseUnavailableError(
|
| 169 |
+
f"v2 数据库不可用:无法连接 PostgreSQL {host}:{port}({type(e).__name__}: {e})。"
|
| 170 |
+
"请确认 PostgreSQL 已启动且端口可达,并检查 WGJY_DATABASE_URL/DATABASE_URL。"
|
| 171 |
+
) from e
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def test_postgres_socket(url: str | None = None) -> None:
|
| 175 |
+
"""
|
| 176 |
+
用于交互式诊断:检查 PostgreSQL 端口连通性。
|
| 177 |
+
|
| 178 |
+
:param url: 可选的数据库连接串;为空时使用当前有效配置。
|
| 179 |
+
:raises DatabaseUnavailableError: 当端口不可达或配置错误时。
|
| 180 |
+
"""
|
| 181 |
+
effective = str(url or _get_effective_database_url())
|
| 182 |
+
_precheck_postgres_socket(effective)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def manual_bootstrap_database() -> str:
|
| 186 |
+
"""
|
| 187 |
+
交互式/脚本调用的数据库自动初始化入口。
|
| 188 |
+
|
| 189 |
+
尝试基于当前数据库连接串(WGJY_DATABASE_URL/DATABASE_URL)和
|
| 190 |
+
管理员连接串(WGJY_PG_ADMIN_URL/WGJY_POSTGRES_ADMIN_URL)创建/修复
|
| 191 |
+
目标数据库和用户。
|
| 192 |
+
|
| 193 |
+
:return: 中文说明字符串,描述本次尝试的结果。
|
| 194 |
+
"""
|
| 195 |
+
target_url = _get_effective_database_url()
|
| 196 |
+
admin_url = str(os.getenv('WGJY_PG_ADMIN_URL') or os.getenv('WGJY_POSTGRES_ADMIN_URL') or '').strip()
|
| 197 |
+
if not admin_url:
|
| 198 |
+
return '未检测到 WGJY_PG_ADMIN_URL/WGJY_POSTGRES_ADMIN_URL 环境变量,未执行自动初始化。'
|
| 199 |
+
|
| 200 |
+
try:
|
| 201 |
+
if not _bootstrap_postgres_if_configured(target_url):
|
| 202 |
+
return '自动初始化未执行:连接串不是 PostgreSQL,或配置不符合自动初始化要求。'
|
| 203 |
+
except Exception as e:
|
| 204 |
+
return f'自动初始化失败:{type(e).__name__}: {e}'
|
| 205 |
+
else:
|
| 206 |
+
_reset_engine()
|
| 207 |
+
# 不在此处强制建表,由上层在下次 init_db() 时完成
|
| 208 |
+
return '已使用管理员连接串尝试创建/修复 PostgreSQL 数据库和用户,请稍后重试启动或等待自动重连。'
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def get_engine():
|
| 212 |
+
global _engine
|
| 213 |
+
if _engine is None:
|
| 214 |
+
url = _get_effective_database_url()
|
| 215 |
+
_engine = create_engine(url, future=True, pool_pre_ping=True)
|
| 216 |
+
return _engine
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def get_session_factory():
|
| 220 |
+
global _SessionLocal
|
| 221 |
+
if _SessionLocal is None:
|
| 222 |
+
_SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=get_engine(), future=True, expire_on_commit=False)
|
| 223 |
+
return _SessionLocal
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@contextmanager
|
| 227 |
+
def session_scope():
|
| 228 |
+
SessionLocal = get_session_factory()
|
| 229 |
+
session = SessionLocal()
|
| 230 |
+
try:
|
| 231 |
+
yield session
|
| 232 |
+
session.commit()
|
| 233 |
+
except Exception:
|
| 234 |
+
session.rollback()
|
| 235 |
+
raise
|
| 236 |
+
finally:
|
| 237 |
+
session.close()
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def init_db() -> None:
|
| 241 |
+
from . import models
|
| 242 |
+
|
| 243 |
+
global _db_ready, _db_last_check_ts, _db_last_error
|
| 244 |
+
|
| 245 |
+
if _db_ready:
|
| 246 |
+
return
|
| 247 |
+
|
| 248 |
+
cooldown = float(os.getenv('WGJY_DB_RETRY_COOLDOWN_SECONDS', '3') or '3')
|
| 249 |
+
now_ts = time.monotonic()
|
| 250 |
+
if _db_last_error and (now_ts - float(_db_last_check_ts or 0.0)) < cooldown:
|
| 251 |
+
raise DatabaseUnavailableError(_db_last_error)
|
| 252 |
+
|
| 253 |
+
url0 = _get_effective_database_url()
|
| 254 |
+
try:
|
| 255 |
+
_precheck_postgres_socket(url0)
|
| 256 |
+
except DatabaseUnavailableError as e:
|
| 257 |
+
_db_last_check_ts = now_ts
|
| 258 |
+
_db_last_error = str(e)
|
| 259 |
+
raise
|
| 260 |
+
|
| 261 |
+
try:
|
| 262 |
+
Base.metadata.create_all(bind=get_engine())
|
| 263 |
+
_db_ready = True
|
| 264 |
+
_db_last_check_ts = now_ts
|
| 265 |
+
_db_last_error = None
|
| 266 |
+
except UnicodeDecodeError as e:
|
| 267 |
+
url1 = _to_psycopg_url(url0)
|
| 268 |
+
if not url1 or url1 == url0:
|
| 269 |
+
err = DatabaseUnavailableError(
|
| 270 |
+
'v2 数据库初始化失败:发生编码解码错误(UnicodeDecodeError)。'
|
| 271 |
+
'这通常是 PostgreSQL 连接失败时,psycopg2 在本机编码环境下无法解码错误信息导致。'
|
| 272 |
+
'请检查 PostgreSQL 是否可连接,或将连接串改为 postgresql+psycopg://...。'
|
| 273 |
+
)
|
| 274 |
+
_db_last_check_ts = now_ts
|
| 275 |
+
_db_last_error = str(err)
|
| 276 |
+
raise err from e
|
| 277 |
+
|
| 278 |
+
try:
|
| 279 |
+
__import__('psycopg')
|
| 280 |
+
except Exception as e2:
|
| 281 |
+
raise DatabaseUnavailableError(
|
| 282 |
+
'v2 数据库初始化失败:检测到 psycopg2 编码问题,尝试切换 psycopg3 但未安装。'
|
| 283 |
+
'请安装 psycopg[binary],或将 requirements 更新后重装依赖。'
|
| 284 |
+
) from e2
|
| 285 |
+
|
| 286 |
+
_set_engine_url_override(url1)
|
| 287 |
+
_precheck_postgres_socket(url1)
|
| 288 |
+
try:
|
| 289 |
+
Base.metadata.create_all(bind=get_engine())
|
| 290 |
+
_db_ready = True
|
| 291 |
+
_db_last_check_ts = now_ts
|
| 292 |
+
_db_last_error = None
|
| 293 |
+
except Exception as e3:
|
| 294 |
+
# 若错误与账号/密码/数据库缺失相关,尝试在 psycopg3 模式下执行自动初始化
|
| 295 |
+
if _should_bootstrap_from_error(e3):
|
| 296 |
+
try:
|
| 297 |
+
if _bootstrap_postgres_if_configured(url1):
|
| 298 |
+
_reset_engine()
|
| 299 |
+
_db_ready = False
|
| 300 |
+
_db_last_error = None
|
| 301 |
+
Base.metadata.create_all(bind=get_engine())
|
| 302 |
+
_db_ready = True
|
| 303 |
+
_db_last_check_ts = now_ts
|
| 304 |
+
return
|
| 305 |
+
except Exception as e2:
|
| 306 |
+
err = DatabaseUnavailableError(str(e2) or 'v2 数据库初始化失败:自动初始化失败')
|
| 307 |
+
_db_last_check_ts = now_ts
|
| 308 |
+
_db_last_error = str(err)
|
| 309 |
+
raise err from e2
|
| 310 |
+
|
| 311 |
+
err = DatabaseUnavailableError(
|
| 312 |
+
f"v2 数据库初始化失败:已切换 psycopg3 仍无法连接({type(e3).__name__}: {e3})。"
|
| 313 |
+
'请检查 WGJY_DATABASE_URL/DATABASE_URL 与 PostgreSQL 状态。'
|
| 314 |
+
)
|
| 315 |
+
_db_last_check_ts = now_ts
|
| 316 |
+
_db_last_error = str(err)
|
| 317 |
+
raise err from e3
|
| 318 |
+
except DatabaseUnavailableError as e:
|
| 319 |
+
_db_last_check_ts = now_ts
|
| 320 |
+
raise
|
| 321 |
+
except Exception as e:
|
| 322 |
+
if _should_bootstrap_from_error(e):
|
| 323 |
+
try:
|
| 324 |
+
if _bootstrap_postgres_if_configured(url0):
|
| 325 |
+
_reset_engine()
|
| 326 |
+
_db_ready = False
|
| 327 |
+
_db_last_error = None
|
| 328 |
+
Base.metadata.create_all(bind=get_engine())
|
| 329 |
+
_db_ready = True
|
| 330 |
+
_db_last_check_ts = now_ts
|
| 331 |
+
return
|
| 332 |
+
except Exception as e2:
|
| 333 |
+
err = DatabaseUnavailableError(str(e2) or 'v2 数据库初始化失败:自动初始化失败')
|
| 334 |
+
_db_last_check_ts = now_ts
|
| 335 |
+
_db_last_error = str(err)
|
| 336 |
+
raise err from e2
|
| 337 |
+
|
| 338 |
+
err = DatabaseUnavailableError(
|
| 339 |
+
f"v2 数据库初始化失败:{type(e).__name__}: {e}。"
|
| 340 |
+
'请检查环境变量 WGJY_DATABASE_URL 或 DATABASE_URL 是否正确,并确认 PostgreSQL 已启动且可连接。'
|
| 341 |
+
)
|
| 342 |
+
_db_last_check_ts = now_ts
|
| 343 |
+
_db_last_error = str(err)
|
| 344 |
+
raise err from e
|
| 345 |
+
|
| 346 |
+
engine = get_engine()
|
| 347 |
+
url = str(engine.url)
|
| 348 |
+
try:
|
| 349 |
+
if url.startswith('postgresql'):
|
| 350 |
+
with engine.begin() as conn:
|
| 351 |
+
conn.exec_driver_sql('ALTER TABLE tasks ADD COLUMN IF NOT EXISTS message TEXT')
|
| 352 |
+
conn.exec_driver_sql('ALTER TABLE users ADD COLUMN IF NOT EXISTS display_id VARCHAR(16)')
|
| 353 |
+
conn.exec_driver_sql('CREATE UNIQUE INDEX IF NOT EXISTS ix_users_display_id ON users (display_id)')
|
| 354 |
+
|
| 355 |
+
conn.exec_driver_sql('ALTER TABLE users ADD COLUMN IF NOT EXISTS network_type VARCHAR(32)')
|
| 356 |
+
|
| 357 |
+
conn.exec_driver_sql('ALTER TABLE users ADD COLUMN IF NOT EXISTS is_banned BOOLEAN NOT NULL DEFAULT FALSE')
|
| 358 |
+
conn.exec_driver_sql('ALTER TABLE users ADD COLUMN IF NOT EXISTS banned_at TIMESTAMPTZ')
|
| 359 |
+
conn.exec_driver_sql('ALTER TABLE users ADD COLUMN IF NOT EXISTS banned_reason TEXT')
|
| 360 |
+
conn.exec_driver_sql('ALTER TABLE users ADD COLUMN IF NOT EXISTS admin_fail_count INTEGER NOT NULL DEFAULT 0')
|
| 361 |
+
|
| 362 |
+
conn.exec_driver_sql('ALTER TABLE users ADD COLUMN IF NOT EXISTS last_seen_at TIMESTAMPTZ')
|
| 363 |
+
|
| 364 |
+
conn.exec_driver_sql(
|
| 365 |
+
'CREATE TABLE IF NOT EXISTS admin_secrets ('
|
| 366 |
+
'id INTEGER PRIMARY KEY, '
|
| 367 |
+
'token_hash VARCHAR(128) NOT NULL, '
|
| 368 |
+
'token_salt VARCHAR(64) NOT NULL, '
|
| 369 |
+
'password_hash VARCHAR(128) NOT NULL, '
|
| 370 |
+
'password_salt VARCHAR(64) NOT NULL, '
|
| 371 |
+
'updated_at TIMESTAMPTZ, '
|
| 372 |
+
'last_seen_at TIMESTAMPTZ'
|
| 373 |
+
')'
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
conn.exec_driver_sql(
|
| 377 |
+
'CREATE TABLE IF NOT EXISTS quota_defaults ('
|
| 378 |
+
'id INTEGER PRIMARY KEY, '
|
| 379 |
+
'download_quota_mode VARCHAR(16) NOT NULL DEFAULT \'daily\', '
|
| 380 |
+
'download_quota_limit INTEGER NOT NULL DEFAULT 0, '
|
| 381 |
+
'backtest_quota_mode VARCHAR(16) NOT NULL DEFAULT \'daily\', '
|
| 382 |
+
'backtest_quota_limit INTEGER NOT NULL DEFAULT 0, '
|
| 383 |
+
'updated_at TIMESTAMPTZ'
|
| 384 |
+
')'
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
conn.exec_driver_sql('CREATE INDEX IF NOT EXISTS ix_trade_records_user_symbol_ts ON trade_records (user_id, symbol_code, trade_ts)')
|
| 388 |
+
conn.exec_driver_sql('CREATE INDEX IF NOT EXISTS ix_trade_records_user_date ON trade_records (user_id, trade_date)')
|
| 389 |
+
conn.exec_driver_sql('CREATE INDEX IF NOT EXISTS ix_trade_uploads_user_uploaded_at ON trade_uploads (user_id, uploaded_at)')
|
| 390 |
+
|
| 391 |
+
conn.exec_driver_sql('ALTER TABLE trade_records ADD COLUMN IF NOT EXISTS deal_id VARCHAR(128)')
|
| 392 |
+
conn.exec_driver_sql('CREATE INDEX IF NOT EXISTS ix_trade_records_deal_id ON trade_records (deal_id)')
|
| 393 |
+
|
| 394 |
+
# 交割单完整字段迁移
|
| 395 |
+
conn.exec_driver_sql('ALTER TABLE trade_records ADD COLUMN IF NOT EXISTS settle_date VARCHAR(16)')
|
| 396 |
+
conn.exec_driver_sql('ALTER TABLE trade_records ADD COLUMN IF NOT EXISTS total_fee NUMERIC(20, 6)')
|
| 397 |
+
conn.exec_driver_sql('ALTER TABLE trade_records ADD COLUMN IF NOT EXISTS settle_amount NUMERIC(24, 6)')
|
| 398 |
+
conn.exec_driver_sql('ALTER TABLE trade_records ADD COLUMN IF NOT EXISTS balance NUMERIC(24, 6)')
|
| 399 |
+
conn.exec_driver_sql('ALTER TABLE trade_records ADD COLUMN IF NOT EXISTS net_commission NUMERIC(20, 6)')
|
| 400 |
+
conn.exec_driver_sql('ALTER TABLE trade_records ADD COLUMN IF NOT EXISTS stamp_duty NUMERIC(20, 6)')
|
| 401 |
+
conn.exec_driver_sql('ALTER TABLE trade_records ADD COLUMN IF NOT EXISTS transfer_fee NUMERIC(20, 6)')
|
| 402 |
+
conn.exec_driver_sql('ALTER TABLE trade_records ADD COLUMN IF NOT EXISTS clearing_fee NUMERIC(20, 6)')
|
| 403 |
+
conn.exec_driver_sql('ALTER TABLE trade_records ADD COLUMN IF NOT EXISTS trade_regulation_fee NUMERIC(20, 6)')
|
| 404 |
+
conn.exec_driver_sql('ALTER TABLE trade_records ADD COLUMN IF NOT EXISTS handling_fee NUMERIC(20, 6)')
|
| 405 |
+
conn.exec_driver_sql('ALTER TABLE trade_records ADD COLUMN IF NOT EXISTS securities_regulation_fee NUMERIC(20, 6)')
|
| 406 |
+
conn.exec_driver_sql('ALTER TABLE trade_records ADD COLUMN IF NOT EXISTS financial_levy NUMERIC(20, 6)')
|
| 407 |
+
conn.exec_driver_sql('ALTER TABLE trade_records ADD COLUMN IF NOT EXISTS other_fee NUMERIC(20, 6)')
|
| 408 |
+
conn.exec_driver_sql('ALTER TABLE trade_records ADD COLUMN IF NOT EXISTS currency VARCHAR(16)')
|
| 409 |
+
|
| 410 |
+
conn.exec_driver_sql(
|
| 411 |
+
'CREATE TABLE IF NOT EXISTS symbol_meta ('
|
| 412 |
+
'code6 VARCHAR(16) PRIMARY KEY, '
|
| 413 |
+
'code VARCHAR(32), '
|
| 414 |
+
'name TEXT, '
|
| 415 |
+
'market VARCHAR(8), '
|
| 416 |
+
'sec_type VARCHAR(16), '
|
| 417 |
+
'category VARCHAR(16), '
|
| 418 |
+
'updated_at TIMESTAMPTZ'
|
| 419 |
+
')'
|
| 420 |
+
)
|
| 421 |
+
conn.exec_driver_sql('CREATE INDEX IF NOT EXISTS ix_symbol_meta_market ON symbol_meta (market)')
|
| 422 |
+
conn.exec_driver_sql('CREATE INDEX IF NOT EXISTS ix_symbol_meta_sec_type ON symbol_meta (sec_type)')
|
| 423 |
+
conn.exec_driver_sql('CREATE INDEX IF NOT EXISTS ix_symbol_meta_category ON symbol_meta (category)')
|
| 424 |
+
|
| 425 |
+
conn.exec_driver_sql('ALTER TABLE symbol_meta ADD COLUMN IF NOT EXISTS latest_price NUMERIC(20, 6)')
|
| 426 |
+
conn.exec_driver_sql('ALTER TABLE symbol_meta ADD COLUMN IF NOT EXISTS pct_change NUMERIC(20, 6)')
|
| 427 |
+
conn.exec_driver_sql('ALTER TABLE symbol_meta ADD COLUMN IF NOT EXISTS open NUMERIC(20, 6)')
|
| 428 |
+
|
| 429 |
+
conn.exec_driver_sql(
|
| 430 |
+
'CREATE TABLE IF NOT EXISTS daily_close_prices ('
|
| 431 |
+
'code6 VARCHAR(16) NOT NULL, '
|
| 432 |
+
'trade_date VARCHAR(16) NOT NULL, '
|
| 433 |
+
'close NUMERIC(20, 6), '
|
| 434 |
+
'updated_at TIMESTAMPTZ, '
|
| 435 |
+
'PRIMARY KEY (code6, trade_date)'
|
| 436 |
+
')'
|
| 437 |
+
)
|
| 438 |
+
conn.exec_driver_sql('CREATE INDEX IF NOT EXISTS ix_daily_close_prices_trade_date ON daily_close_prices (trade_date)')
|
| 439 |
+
conn.exec_driver_sql('ALTER TABLE daily_close_prices ADD COLUMN IF NOT EXISTS open NUMERIC(20, 6)')
|
| 440 |
+
conn.exec_driver_sql('ALTER TABLE daily_close_prices ADD COLUMN IF NOT EXISTS high NUMERIC(20, 6)')
|
| 441 |
+
conn.exec_driver_sql('ALTER TABLE daily_close_prices ADD COLUMN IF NOT EXISTS low NUMERIC(20, 6)')
|
| 442 |
+
conn.exec_driver_sql('ALTER TABLE daily_close_prices ADD COLUMN IF NOT EXISTS volume NUMERIC(24, 6)')
|
| 443 |
+
conn.exec_driver_sql('ALTER TABLE daily_close_prices ADD COLUMN IF NOT EXISTS amount NUMERIC(24, 6)')
|
| 444 |
+
|
| 445 |
+
# 交易日度统计:用于“日期空间”快速查询
|
| 446 |
+
conn.exec_driver_sql(
|
| 447 |
+
'CREATE TABLE IF NOT EXISTS trade_daily_stats ('
|
| 448 |
+
'user_id VARCHAR(64) NOT NULL, '
|
| 449 |
+
'trade_date VARCHAR(16) NOT NULL, '
|
| 450 |
+
'transfer_net NUMERIC(24, 6), '
|
| 451 |
+
'total_asset NUMERIC(24, 6), '
|
| 452 |
+
'holding_market_value NUMERIC(24, 6), '
|
| 453 |
+
'holding_symbols INTEGER, '
|
| 454 |
+
'trades_total INTEGER, '
|
| 455 |
+
'buy_trades INTEGER, '
|
| 456 |
+
'sell_trades INTEGER, '
|
| 457 |
+
'fee_total NUMERIC(20, 6), '
|
| 458 |
+
'pnl NUMERIC(24, 6), '
|
| 459 |
+
'grid_paired_profit NUMERIC(24, 6), '
|
| 460 |
+
'updated_at TIMESTAMPTZ, '
|
| 461 |
+
'PRIMARY KEY (user_id, trade_date)'
|
| 462 |
+
')'
|
| 463 |
+
)
|
| 464 |
+
conn.exec_driver_sql('CREATE INDEX IF NOT EXISTS ix_trade_daily_stats_user_date ON trade_daily_stats (user_id, trade_date)')
|
| 465 |
+
except Exception:
|
| 466 |
+
pass
|
backend/v2/migrate_sqlite_to_postgres.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import sqlite3
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from .db import init_db, session_scope
|
| 11 |
+
from .models import BacktestRecord, Task
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _parse_dt(value: Any) -> datetime | None:
|
| 15 |
+
if value is None:
|
| 16 |
+
return None
|
| 17 |
+
if isinstance(value, datetime):
|
| 18 |
+
return value
|
| 19 |
+
if isinstance(value, (int, float)):
|
| 20 |
+
try:
|
| 21 |
+
return datetime.utcfromtimestamp(float(value))
|
| 22 |
+
except Exception:
|
| 23 |
+
return None
|
| 24 |
+
s = str(value).strip()
|
| 25 |
+
if not s:
|
| 26 |
+
return None
|
| 27 |
+
s = s.replace('Z', '+00:00')
|
| 28 |
+
try:
|
| 29 |
+
return datetime.fromisoformat(s)
|
| 30 |
+
except Exception:
|
| 31 |
+
return None
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _parse_json(value: Any) -> Any:
|
| 35 |
+
if value is None:
|
| 36 |
+
return None
|
| 37 |
+
if isinstance(value, (dict, list)):
|
| 38 |
+
return value
|
| 39 |
+
if isinstance(value, (bytes, bytearray)):
|
| 40 |
+
try:
|
| 41 |
+
value = value.decode('utf-8', errors='replace')
|
| 42 |
+
except Exception:
|
| 43 |
+
return None
|
| 44 |
+
if isinstance(value, str):
|
| 45 |
+
s = value.strip()
|
| 46 |
+
if not s:
|
| 47 |
+
return None
|
| 48 |
+
try:
|
| 49 |
+
return json.loads(s)
|
| 50 |
+
except Exception:
|
| 51 |
+
return None
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _sqlite_table_exists(conn: sqlite3.Connection, name: str) -> bool:
|
| 56 |
+
cur = conn.execute(
|
| 57 |
+
"SELECT 1 FROM sqlite_master WHERE type='table' AND name=? LIMIT 1",
|
| 58 |
+
(name,),
|
| 59 |
+
)
|
| 60 |
+
return cur.fetchone() is not None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _sqlite_fetch_all(conn: sqlite3.Connection, table: str) -> list[dict[str, Any]]:
|
| 64 |
+
conn.row_factory = sqlite3.Row
|
| 65 |
+
cur = conn.execute(f'SELECT * FROM {table}')
|
| 66 |
+
return [dict(r) for r in cur.fetchall()]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def migrate_v2_sqlite(sqlite_path: str, *, overwrite: bool) -> dict[str, int]:
|
| 70 |
+
stats = {
|
| 71 |
+
'tasks_total': 0,
|
| 72 |
+
'tasks_migrated': 0,
|
| 73 |
+
'tasks_skipped': 0,
|
| 74 |
+
'records_total': 0,
|
| 75 |
+
'records_migrated': 0,
|
| 76 |
+
'records_skipped': 0,
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
if not os.path.exists(sqlite_path):
|
| 80 |
+
return stats
|
| 81 |
+
|
| 82 |
+
conn = sqlite3.connect(sqlite_path)
|
| 83 |
+
try:
|
| 84 |
+
if _sqlite_table_exists(conn, 'tasks'):
|
| 85 |
+
rows = _sqlite_fetch_all(conn, 'tasks')
|
| 86 |
+
stats['tasks_total'] = len(rows)
|
| 87 |
+
for r in rows:
|
| 88 |
+
task_id = str(r.get('id') or '').strip()
|
| 89 |
+
if not task_id:
|
| 90 |
+
continue
|
| 91 |
+
|
| 92 |
+
payload = {
|
| 93 |
+
'id': task_id,
|
| 94 |
+
'user_id': (str(r.get('user_id')) if r.get('user_id') is not None else None),
|
| 95 |
+
'type': str(r.get('type') or ''),
|
| 96 |
+
'status': str(r.get('status') or ''),
|
| 97 |
+
'progress': int(r.get('progress') or 0),
|
| 98 |
+
'stage': (str(r.get('stage')) if r.get('stage') is not None else None),
|
| 99 |
+
'message': (str(r.get('message')) if r.get('message') is not None else None),
|
| 100 |
+
'params_json': _parse_json(r.get('params_json')),
|
| 101 |
+
'result_json': _parse_json(r.get('result_json')),
|
| 102 |
+
'file_path': (str(r.get('file_path')) if r.get('file_path') is not None else None),
|
| 103 |
+
'error': (str(r.get('error')) if r.get('error') is not None else None),
|
| 104 |
+
'created_at': _parse_dt(r.get('created_at')) or datetime.utcnow(),
|
| 105 |
+
'started_at': _parse_dt(r.get('started_at')),
|
| 106 |
+
'finished_at': _parse_dt(r.get('finished_at')),
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
with session_scope() as s:
|
| 110 |
+
existing = s.get(Task, task_id)
|
| 111 |
+
if existing is not None and not overwrite:
|
| 112 |
+
stats['tasks_skipped'] += 1
|
| 113 |
+
continue
|
| 114 |
+
if existing is None:
|
| 115 |
+
s.add(Task(**payload))
|
| 116 |
+
else:
|
| 117 |
+
for k, v in payload.items():
|
| 118 |
+
if k == 'id':
|
| 119 |
+
continue
|
| 120 |
+
setattr(existing, k, v)
|
| 121 |
+
stats['tasks_migrated'] += 1
|
| 122 |
+
|
| 123 |
+
if _sqlite_table_exists(conn, 'backtest_records_v2'):
|
| 124 |
+
rows = _sqlite_fetch_all(conn, 'backtest_records_v2')
|
| 125 |
+
stats['records_total'] = len(rows)
|
| 126 |
+
for r in rows:
|
| 127 |
+
rid = str(r.get('id') or '').strip()
|
| 128 |
+
if not rid:
|
| 129 |
+
continue
|
| 130 |
+
|
| 131 |
+
parameters = _parse_json(r.get('parameters')) or {}
|
| 132 |
+
results = _parse_json(r.get('results'))
|
| 133 |
+
|
| 134 |
+
payload = {
|
| 135 |
+
'id': rid,
|
| 136 |
+
'user_id': (str(r.get('user_id')) if r.get('user_id') is not None else None),
|
| 137 |
+
'strategy_type': str(r.get('strategy_type') or ''),
|
| 138 |
+
'symbol': str(r.get('symbol') or ''),
|
| 139 |
+
'start_date': (str(r.get('start_date')) if r.get('start_date') is not None else None),
|
| 140 |
+
'end_date': (str(r.get('end_date')) if r.get('end_date') is not None else None),
|
| 141 |
+
'parameters': parameters,
|
| 142 |
+
'results': results,
|
| 143 |
+
'created_at': _parse_dt(r.get('created_at')) or datetime.utcnow(),
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
with session_scope() as s:
|
| 147 |
+
existing = s.get(BacktestRecord, rid)
|
| 148 |
+
if existing is not None and not overwrite:
|
| 149 |
+
stats['records_skipped'] += 1
|
| 150 |
+
continue
|
| 151 |
+
if existing is None:
|
| 152 |
+
s.add(BacktestRecord(**payload))
|
| 153 |
+
else:
|
| 154 |
+
for k, v in payload.items():
|
| 155 |
+
if k == 'id':
|
| 156 |
+
continue
|
| 157 |
+
setattr(existing, k, v)
|
| 158 |
+
stats['records_migrated'] += 1
|
| 159 |
+
|
| 160 |
+
return stats
|
| 161 |
+
finally:
|
| 162 |
+
conn.close()
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def migrate_legacy_sqlite(sqlite_path: str, *, overwrite: bool) -> dict[str, int]:
|
| 166 |
+
stats = {
|
| 167 |
+
'legacy_total': 0,
|
| 168 |
+
'legacy_migrated': 0,
|
| 169 |
+
'legacy_skipped': 0,
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
if not os.path.exists(sqlite_path):
|
| 173 |
+
return stats
|
| 174 |
+
|
| 175 |
+
conn = sqlite3.connect(sqlite_path)
|
| 176 |
+
try:
|
| 177 |
+
if not _sqlite_table_exists(conn, 'backtest_records'):
|
| 178 |
+
return stats
|
| 179 |
+
|
| 180 |
+
rows = _sqlite_fetch_all(conn, 'backtest_records')
|
| 181 |
+
stats['legacy_total'] = len(rows)
|
| 182 |
+
|
| 183 |
+
for r in rows:
|
| 184 |
+
rid = str(r.get('id') or '').strip()
|
| 185 |
+
if not rid:
|
| 186 |
+
continue
|
| 187 |
+
|
| 188 |
+
strategy_type = str(r.get('strategy_type') or '').strip()
|
| 189 |
+
symbol = str(r.get('symbol') or '').strip()
|
| 190 |
+
|
| 191 |
+
parameters = _parse_json(r.get('parameters')) or {}
|
| 192 |
+
results = _parse_json(r.get('results'))
|
| 193 |
+
|
| 194 |
+
initial_capital = r.get('initial_capital')
|
| 195 |
+
if initial_capital is not None and 'initial_capital' not in parameters:
|
| 196 |
+
try:
|
| 197 |
+
parameters['initial_capital'] = float(initial_capital)
|
| 198 |
+
except Exception:
|
| 199 |
+
pass
|
| 200 |
+
|
| 201 |
+
payload = {
|
| 202 |
+
'id': rid,
|
| 203 |
+
'user_id': None,
|
| 204 |
+
'strategy_type': strategy_type,
|
| 205 |
+
'symbol': symbol,
|
| 206 |
+
'start_date': (str(r.get('start_date')) if r.get('start_date') is not None else None),
|
| 207 |
+
'end_date': (str(r.get('end_date')) if r.get('end_date') is not None else None),
|
| 208 |
+
'parameters': parameters,
|
| 209 |
+
'results': results,
|
| 210 |
+
'created_at': _parse_dt(r.get('created_at')) or datetime.utcnow(),
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
with session_scope() as s:
|
| 214 |
+
existing = s.get(BacktestRecord, rid)
|
| 215 |
+
if existing is not None and not overwrite:
|
| 216 |
+
stats['legacy_skipped'] += 1
|
| 217 |
+
continue
|
| 218 |
+
if existing is None:
|
| 219 |
+
s.add(BacktestRecord(**payload))
|
| 220 |
+
else:
|
| 221 |
+
for k, v in payload.items():
|
| 222 |
+
if k == 'id':
|
| 223 |
+
continue
|
| 224 |
+
setattr(existing, k, v)
|
| 225 |
+
stats['legacy_migrated'] += 1
|
| 226 |
+
|
| 227 |
+
return stats
|
| 228 |
+
finally:
|
| 229 |
+
conn.close()
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def _default_backend_data_file(name: str) -> str:
|
| 233 |
+
backend_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 234 |
+
return os.path.join(backend_dir, 'data', name)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def main() -> int:
|
| 238 |
+
parser = argparse.ArgumentParser(description='Migrate WGJY SQLite databases to PostgreSQL (Postgres-only).')
|
| 239 |
+
parser.add_argument('--v2-sqlite', default=_default_backend_data_file('wgjy_v2.db'))
|
| 240 |
+
parser.add_argument('--legacy-sqlite', default=_default_backend_data_file('backtest.db'))
|
| 241 |
+
parser.add_argument('--overwrite', action='store_true', help='Overwrite existing rows in PostgreSQL')
|
| 242 |
+
|
| 243 |
+
args = parser.parse_args()
|
| 244 |
+
|
| 245 |
+
init_db()
|
| 246 |
+
|
| 247 |
+
v2_stats = migrate_v2_sqlite(args.v2_sqlite, overwrite=args.overwrite)
|
| 248 |
+
legacy_stats = migrate_legacy_sqlite(args.legacy_sqlite, overwrite=args.overwrite)
|
| 249 |
+
|
| 250 |
+
print('=== Migration summary ===')
|
| 251 |
+
print(f"v2 sqlite: {args.v2_sqlite}")
|
| 252 |
+
print(f" tasks: {v2_stats['tasks_migrated']}/{v2_stats['tasks_total']} migrated, {v2_stats['tasks_skipped']} skipped")
|
| 253 |
+
print(
|
| 254 |
+
f" backtest_records_v2: {v2_stats['records_migrated']}/{v2_stats['records_total']} migrated, {v2_stats['records_skipped']} skipped"
|
| 255 |
+
)
|
| 256 |
+
print(f"legacy sqlite: {args.legacy_sqlite}")
|
| 257 |
+
print(
|
| 258 |
+
f" backtest_records: {legacy_stats['legacy_migrated']}/{legacy_stats['legacy_total']} migrated, {legacy_stats['legacy_skipped']} skipped"
|
| 259 |
+
)
|
| 260 |
+
print('=========================')
|
| 261 |
+
|
| 262 |
+
return 0
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
if __name__ == '__main__':
|
| 266 |
+
raise SystemExit(main())
|
backend/v2/models.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
|
| 5 |
+
from sqlalchemy import JSON, Boolean, DateTime, Integer, String, Text, Numeric, PrimaryKeyConstraint, Index
|
| 6 |
+
from sqlalchemy.orm import Mapped, mapped_column
|
| 7 |
+
|
| 8 |
+
from .db import Base
|
| 9 |
+
from .time_sync import now_utc
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class User(Base):
|
| 13 |
+
__tablename__ = 'users'
|
| 14 |
+
|
| 15 |
+
id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
| 16 |
+
|
| 17 |
+
display_id: Mapped[str | None] = mapped_column(String(16), nullable=True, unique=True, index=True)
|
| 18 |
+
|
| 19 |
+
device_os: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
| 20 |
+
user_agent: Mapped[str | None] = mapped_column(Text, nullable=True)
|
| 21 |
+
ip: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
| 22 |
+
province: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
| 23 |
+
mac_address: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
| 24 |
+
|
| 25 |
+
network_type: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
| 26 |
+
|
| 27 |
+
is_banned: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
| 28 |
+
banned_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
| 29 |
+
banned_reason: Mapped[str | None] = mapped_column(Text, nullable=True)
|
| 30 |
+
|
| 31 |
+
admin_fail_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
| 32 |
+
|
| 33 |
+
download_quota_mode: Mapped[str] = mapped_column(String(16), nullable=False, default='daily')
|
| 34 |
+
download_quota_limit: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
| 35 |
+
|
| 36 |
+
backtest_quota_mode: Mapped[str] = mapped_column(String(16), nullable=False, default='daily')
|
| 37 |
+
backtest_quota_limit: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
| 38 |
+
|
| 39 |
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc)
|
| 40 |
+
last_seen_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class AdminSecret(Base):
|
| 44 |
+
__tablename__ = 'admin_secrets'
|
| 45 |
+
|
| 46 |
+
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
| 47 |
+
|
| 48 |
+
token_hash: Mapped[str] = mapped_column(String(128), nullable=False)
|
| 49 |
+
token_salt: Mapped[str] = mapped_column(String(64), nullable=False)
|
| 50 |
+
|
| 51 |
+
password_hash: Mapped[str] = mapped_column(String(128), nullable=False)
|
| 52 |
+
password_salt: Mapped[str] = mapped_column(String(64), nullable=False)
|
| 53 |
+
|
| 54 |
+
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc)
|
| 55 |
+
last_seen_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class Task(Base):
|
| 59 |
+
__tablename__ = 'tasks'
|
| 60 |
+
|
| 61 |
+
id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
| 62 |
+
user_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
|
| 63 |
+
|
| 64 |
+
type: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
| 65 |
+
status: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
|
| 66 |
+
|
| 67 |
+
progress: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
| 68 |
+
stage: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
| 69 |
+
|
| 70 |
+
message: Mapped[str | None] = mapped_column(Text, nullable=True)
|
| 71 |
+
|
| 72 |
+
params_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
| 73 |
+
result_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
| 74 |
+
|
| 75 |
+
file_path: Mapped[str | None] = mapped_column(Text, nullable=True)
|
| 76 |
+
error: Mapped[str | None] = mapped_column(Text, nullable=True)
|
| 77 |
+
|
| 78 |
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc)
|
| 79 |
+
started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
| 80 |
+
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class BacktestRecord(Base):
|
| 84 |
+
__tablename__ = 'backtest_records_v2'
|
| 85 |
+
|
| 86 |
+
id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
| 87 |
+
user_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
|
| 88 |
+
|
| 89 |
+
strategy_type: Mapped[str] = mapped_column(String(32), nullable=False, index=True)
|
| 90 |
+
symbol: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
| 91 |
+
|
| 92 |
+
start_date: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
| 93 |
+
end_date: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
| 94 |
+
|
| 95 |
+
parameters: Mapped[dict] = mapped_column(JSON, nullable=False)
|
| 96 |
+
results: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
| 97 |
+
|
| 98 |
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class QuotaDefaults(Base):
|
| 102 |
+
__tablename__ = 'quota_defaults'
|
| 103 |
+
|
| 104 |
+
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
| 105 |
+
|
| 106 |
+
download_quota_mode: Mapped[str] = mapped_column(String(16), nullable=False, default='daily')
|
| 107 |
+
download_quota_limit: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
| 108 |
+
|
| 109 |
+
backtest_quota_mode: Mapped[str] = mapped_column(String(16), nullable=False, default='daily')
|
| 110 |
+
backtest_quota_limit: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
| 111 |
+
|
| 112 |
+
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class TradeUpload(Base):
|
| 116 |
+
__tablename__ = 'trade_uploads'
|
| 117 |
+
|
| 118 |
+
id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
| 119 |
+
user_id: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
| 120 |
+
|
| 121 |
+
filename: Mapped[str] = mapped_column(Text, nullable=False)
|
| 122 |
+
file_type: Mapped[str] = mapped_column(String(16), nullable=False)
|
| 123 |
+
|
| 124 |
+
rows_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
| 125 |
+
columns_json: Mapped[list[str] | None] = mapped_column(JSON, nullable=True)
|
| 126 |
+
|
| 127 |
+
uploaded_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc, index=True)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class TradeRecord(Base):
|
| 131 |
+
__tablename__ = 'trade_records'
|
| 132 |
+
|
| 133 |
+
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
| 134 |
+
|
| 135 |
+
user_id: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
| 136 |
+
upload_id: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
| 137 |
+
|
| 138 |
+
# 日期时间
|
| 139 |
+
trade_date: Mapped[str] = mapped_column(String(16), nullable=False, index=True)
|
| 140 |
+
trade_time: Mapped[str] = mapped_column(String(16), nullable=False)
|
| 141 |
+
trade_ts: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True, index=True)
|
| 142 |
+
settle_date: Mapped[str | None] = mapped_column(String(16), nullable=True) # 交收日期
|
| 143 |
+
|
| 144 |
+
# 标的信息
|
| 145 |
+
symbol_code: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
| 146 |
+
symbol_name: Mapped[str] = mapped_column(Text, nullable=False)
|
| 147 |
+
side: Mapped[str] = mapped_column(String(16), nullable=False, index=True) # 业务名称/买卖标志
|
| 148 |
+
|
| 149 |
+
# 委托信息
|
| 150 |
+
order_price: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True)
|
| 151 |
+
order_qty: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
| 152 |
+
order_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
|
| 153 |
+
|
| 154 |
+
# 成交信息
|
| 155 |
+
deal_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True) # 成交编号
|
| 156 |
+
trade_price: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True) # 成交价格
|
| 157 |
+
trade_qty: Mapped[int | None] = mapped_column(Integer, nullable=True) # 成交数量
|
| 158 |
+
trade_amount: Mapped[float | None] = mapped_column(Numeric(24, 6), nullable=True) # 成交金额
|
| 159 |
+
remaining_qty: Mapped[int | None] = mapped_column(Integer, nullable=True) # 剩余数量
|
| 160 |
+
|
| 161 |
+
# 费用字段(从交割单读取)
|
| 162 |
+
total_fee: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True) # 总费用
|
| 163 |
+
settle_amount: Mapped[float | None] = mapped_column(Numeric(24, 6), nullable=True) # 清算金额
|
| 164 |
+
balance: Mapped[float | None] = mapped_column(Numeric(24, 6), nullable=True) # 资金本次余额
|
| 165 |
+
net_commission: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True) # 净佣金
|
| 166 |
+
stamp_duty: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True) # 印花税
|
| 167 |
+
transfer_fee: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True) # 过户费
|
| 168 |
+
clearing_fee: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True) # 清算费
|
| 169 |
+
trade_regulation_fee: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True) # 交易规费
|
| 170 |
+
handling_fee: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True) # 经手费
|
| 171 |
+
securities_regulation_fee: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True) # 证管费
|
| 172 |
+
financial_levy: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True) # 财汇局征费
|
| 173 |
+
other_fee: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True) # 其他费
|
| 174 |
+
currency: Mapped[str | None] = mapped_column(String(16), nullable=True) # 币种
|
| 175 |
+
|
| 176 |
+
extra_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
| 177 |
+
|
| 178 |
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class SymbolMeta(Base):
|
| 182 |
+
__tablename__ = 'symbol_meta'
|
| 183 |
+
|
| 184 |
+
code6: Mapped[str] = mapped_column(String(16), primary_key=True)
|
| 185 |
+
|
| 186 |
+
code: Mapped[str | None] = mapped_column(String(32), nullable=True, index=True)
|
| 187 |
+
name: Mapped[str | None] = mapped_column(Text, nullable=True)
|
| 188 |
+
|
| 189 |
+
market: Mapped[str | None] = mapped_column(String(8), nullable=True, index=True)
|
| 190 |
+
sec_type: Mapped[str | None] = mapped_column(String(16), nullable=True, index=True)
|
| 191 |
+
category: Mapped[str | None] = mapped_column(String(16), nullable=True, index=True)
|
| 192 |
+
|
| 193 |
+
latest_price: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True)
|
| 194 |
+
pct_change: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True)
|
| 195 |
+
open: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True)
|
| 196 |
+
|
| 197 |
+
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc, index=True)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class DailyClosePrice(Base):
|
| 201 |
+
__tablename__ = 'daily_close_prices'
|
| 202 |
+
|
| 203 |
+
code6: Mapped[str] = mapped_column(String(16), primary_key=True)
|
| 204 |
+
trade_date: Mapped[str] = mapped_column(String(16), primary_key=True, index=True)
|
| 205 |
+
|
| 206 |
+
close: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True)
|
| 207 |
+
open: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True)
|
| 208 |
+
high: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True)
|
| 209 |
+
low: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True)
|
| 210 |
+
volume: Mapped[float | None] = mapped_column(Numeric(24, 6), nullable=True)
|
| 211 |
+
amount: Mapped[float | None] = mapped_column(Numeric(24, 6), nullable=True)
|
| 212 |
+
|
| 213 |
+
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc, index=True)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class TradeDailyStat(Base):
|
| 217 |
+
"""
|
| 218 |
+
交易日度统计(按用户、按交易日):
|
| 219 |
+
用于"日期空间"按日/月/年快速展示统计概览,避免前端每次重算。
|
| 220 |
+
"""
|
| 221 |
+
|
| 222 |
+
__tablename__ = 'trade_daily_stats'
|
| 223 |
+
|
| 224 |
+
user_id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
| 225 |
+
trade_date: Mapped[str] = mapped_column(String(16), primary_key=True, index=True) # YYYY-MM-DD
|
| 226 |
+
|
| 227 |
+
# 外部现金流(银证转账净额):转入为正,转出为负
|
| 228 |
+
transfer_net: Mapped[float | None] = mapped_column(Numeric(24, 6), nullable=True)
|
| 229 |
+
|
| 230 |
+
# 账户总资产/持仓市值(收盘估值)
|
| 231 |
+
total_asset: Mapped[float | None] = mapped_column(Numeric(24, 6), nullable=True)
|
| 232 |
+
holding_market_value: Mapped[float | None] = mapped_column(Numeric(24, 6), nullable=True)
|
| 233 |
+
holding_symbols: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
| 234 |
+
|
| 235 |
+
# 当日交易统计(仅买入/卖出)
|
| 236 |
+
trades_total: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
| 237 |
+
buy_trades: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
| 238 |
+
sell_trades: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
| 239 |
+
fee_total: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True)
|
| 240 |
+
|
| 241 |
+
# 当日盈亏(剔除当日银证转账净额后的收益金额)
|
| 242 |
+
pnl: Mapped[float | None] = mapped_column(Numeric(24, 6), nullable=True)
|
| 243 |
+
|
| 244 |
+
# 当日网格配对总收益(简化配对口径,详见计算函数注释)
|
| 245 |
+
grid_paired_profit: Mapped[float | None] = mapped_column(Numeric(24, 6), nullable=True)
|
| 246 |
+
|
| 247 |
+
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc, index=True)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
class GridStrategy(Base):
|
| 251 |
+
"""网格策略配置"""
|
| 252 |
+
__tablename__ = 'grid_strategies'
|
| 253 |
+
|
| 254 |
+
id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
| 255 |
+
user_id: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
| 256 |
+
|
| 257 |
+
# 标的信息
|
| 258 |
+
symbol_name: Mapped[str] = mapped_column(Text, nullable=False) # 网格标的名称
|
| 259 |
+
symbol_code: Mapped[str] = mapped_column(String(32), nullable=False, index=True) # 网格标的代码
|
| 260 |
+
|
| 261 |
+
# 网格参数
|
| 262 |
+
start_date: Mapped[str | None] = mapped_column(String(16), nullable=True) # 网格起始时间
|
| 263 |
+
base_price: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True) # 网格基准价
|
| 264 |
+
initial_position: Mapped[int | None] = mapped_column(Integer, nullable=True) # 网格初始持仓(股)
|
| 265 |
+
|
| 266 |
+
# 上涨幅度(支持固定价格或百分比)
|
| 267 |
+
up_type: Mapped[str] = mapped_column(String(16), nullable=False, default='percent') # 'percent' 或 'price'
|
| 268 |
+
up_value: Mapped[float] = mapped_column(Numeric(20, 6), nullable=False, default=0) # 百分比或价格值
|
| 269 |
+
|
| 270 |
+
# 下跌幅度(支持固定价格或百分比)
|
| 271 |
+
down_type: Mapped[str] = mapped_column(String(16), nullable=False, default='percent') # 'percent' 或 'price'
|
| 272 |
+
down_value: Mapped[float] = mapped_column(Numeric(20, 6), nullable=False, default=0) # 百分比或价格值
|
| 273 |
+
|
| 274 |
+
# 每次买卖股数
|
| 275 |
+
trade_qty: Mapped[int] = mapped_column(Integer, nullable=False, default=100)
|
| 276 |
+
|
| 277 |
+
# 状态
|
| 278 |
+
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
| 279 |
+
note: Mapped[str | None] = mapped_column(Text, nullable=True) # 备注
|
| 280 |
+
|
| 281 |
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc)
|
| 282 |
+
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc, onupdate=now_utc)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class HoldingSnapshot(Base):
|
| 286 |
+
"""
|
| 287 |
+
持仓快照(来自「持仓数据」sheet 的盘后导出数据)。
|
| 288 |
+
每上传一次文件产生一行,记录当日收盘后的持仓状态。
|
| 289 |
+
"""
|
| 290 |
+
__tablename__ = 'holding_snapshots'
|
| 291 |
+
|
| 292 |
+
user_id: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
| 293 |
+
snapshot_date: Mapped[str] = mapped_column(String(16), nullable=False) # YYYY-MM-DD
|
| 294 |
+
symbol_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
| 295 |
+
symbol_name: Mapped[str] = mapped_column(Text, nullable=False)
|
| 296 |
+
market: Mapped[str | None] = mapped_column(String(8), nullable=True) # 上交所/深交所
|
| 297 |
+
|
| 298 |
+
# 持仓数量(市盈率/均价相关)
|
| 299 |
+
net_qty: Mapped[int | None] = mapped_column(Integer, nullable=True) # 持股数
|
| 300 |
+
avg_cost: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True) # 成本均价
|
| 301 |
+
|
| 302 |
+
# 来自文件的值(盘后快照,最准确)
|
| 303 |
+
holding_market_value: Mapped[float | None] = mapped_column(Numeric(24, 6), nullable=True) # 持有金额 = 持仓市值
|
| 304 |
+
total_pnl: Mapped[float | None] = mapped_column(Numeric(24, 6), nullable=True) # 持有盈亏 = 总盈亏
|
| 305 |
+
unrealized_pnl: Mapped[float | None] = mapped_column(Numeric(24, 6), nullable=True) # 浮动盈亏
|
| 306 |
+
realized_pnl: Mapped[float | None] = mapped_column(Numeric(24, 6), nullable=True) # 已实现盈亏
|
| 307 |
+
|
| 308 |
+
# 原始字段(存疑:有些版本是百分比,有些是固定价格)
|
| 309 |
+
pct_change: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True) # 当日涨跌幅
|
| 310 |
+
|
| 311 |
+
extra_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
| 312 |
+
upload_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
| 313 |
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=now_utc)
|
| 314 |
+
|
| 315 |
+
__table_args__ = (
|
| 316 |
+
PrimaryKeyConstraint('user_id', 'snapshot_date', 'symbol_code'),
|
| 317 |
+
Index('ix_holding_snapshots_date', 'user_id', 'snapshot_date'),
|
| 318 |
+
)
|
backend/v2/repository.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
backend/v2/tasks/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 注册所有 Celery 任务
|
| 2 |
+
from . import backtest # noqa: F401
|
| 3 |
+
from . import download # noqa: F401
|
| 4 |
+
from . import export # noqa: F401
|
backend/v2/tasks/backtest.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
from ..time_sync import now_utc
|
| 6 |
+
|
| 7 |
+
from ..celery_app import celery_app
|
| 8 |
+
from ..db import init_db
|
| 9 |
+
from ..repository import create_backtest_record, update_task
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _read_file_bytes(path: str) -> bytes:
|
| 13 |
+
with open(path, 'rb') as f:
|
| 14 |
+
return f.read()
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@celery_app.task(name='wgjy.grid_backtest_file')
|
| 18 |
+
def grid_backtest_file(task_id: str, user_id: str | None, file_path: str, params: dict) -> dict:
|
| 19 |
+
os.environ.setdefault('WGJY_CELERY_WORKER', '1')
|
| 20 |
+
init_db()
|
| 21 |
+
|
| 22 |
+
update_task(task_id=task_id, status='running', stage='parsing', progress=5, started_at=now_utc())
|
| 23 |
+
|
| 24 |
+
t0 = time.perf_counter()
|
| 25 |
+
filename = os.path.basename(file_path)
|
| 26 |
+
content = _read_file_bytes(file_path)
|
| 27 |
+
|
| 28 |
+
import server as legacy
|
| 29 |
+
|
| 30 |
+
market_data = legacy.parse_uploaded_file(content, filename, keep_intraday=True)
|
| 31 |
+
|
| 32 |
+
update_task(task_id=task_id, stage='backtesting', progress=45)
|
| 33 |
+
results = legacy._grid_backtest_job(params, market_data)
|
| 34 |
+
|
| 35 |
+
update_task(task_id=task_id, stage='saving', progress=85)
|
| 36 |
+
|
| 37 |
+
start_date = market_data[0]['date'] if market_data else None
|
| 38 |
+
end_date = market_data[-1]['date'] if market_data else None
|
| 39 |
+
|
| 40 |
+
record_id = task_id
|
| 41 |
+
create_backtest_record(
|
| 42 |
+
record_id=record_id,
|
| 43 |
+
user_id=user_id,
|
| 44 |
+
strategy_type='grid',
|
| 45 |
+
symbol=str(params.get('symbol') or ''),
|
| 46 |
+
start_date=start_date,
|
| 47 |
+
end_date=end_date,
|
| 48 |
+
parameters=params,
|
| 49 |
+
results=results,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
payload = {
|
| 53 |
+
'id': record_id,
|
| 54 |
+
'results': results,
|
| 55 |
+
'elapsed_ms': int((time.perf_counter() - t0) * 1000),
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
update_task(task_id=task_id, status='completed', stage='completed', progress=100, finished_at=now_utc(), result_json=payload)
|
| 59 |
+
return payload
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@celery_app.task(name='wgjy.dca_backtest_file')
|
| 63 |
+
def dca_backtest_file(task_id: str, user_id: str | None, file_path: str, params: dict) -> dict:
|
| 64 |
+
os.environ.setdefault('WGJY_CELERY_WORKER', '1')
|
| 65 |
+
init_db()
|
| 66 |
+
|
| 67 |
+
update_task(task_id=task_id, status='running', stage='parsing', progress=5, started_at=now_utc())
|
| 68 |
+
|
| 69 |
+
t0 = time.perf_counter()
|
| 70 |
+
filename = os.path.basename(file_path)
|
| 71 |
+
content = _read_file_bytes(file_path)
|
| 72 |
+
|
| 73 |
+
import server as legacy
|
| 74 |
+
|
| 75 |
+
market_data = legacy.parse_uploaded_file(content, filename, keep_intraday=False)
|
| 76 |
+
|
| 77 |
+
update_task(task_id=task_id, stage='backtesting', progress=45)
|
| 78 |
+
results = legacy._dca_backtest_job(params, market_data)
|
| 79 |
+
|
| 80 |
+
update_task(task_id=task_id, stage='saving', progress=85)
|
| 81 |
+
|
| 82 |
+
start_date = market_data[0]['date'] if market_data else None
|
| 83 |
+
end_date = market_data[-1]['date'] if market_data else None
|
| 84 |
+
|
| 85 |
+
record_id = task_id
|
| 86 |
+
create_backtest_record(
|
| 87 |
+
record_id=record_id,
|
| 88 |
+
user_id=user_id,
|
| 89 |
+
strategy_type='dca',
|
| 90 |
+
symbol=str(params.get('symbol') or ''),
|
| 91 |
+
start_date=start_date,
|
| 92 |
+
end_date=end_date,
|
| 93 |
+
parameters=params,
|
| 94 |
+
results=results,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
payload = {
|
| 98 |
+
'id': record_id,
|
| 99 |
+
'results': results,
|
| 100 |
+
'elapsed_ms': int((time.perf_counter() - t0) * 1000),
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
update_task(task_id=task_id, status='completed', stage='completed', progress=100, finished_at=now_utc(), result_json=payload)
|
| 104 |
+
return payload
|
backend/v2/tasks/download.py
ADDED
|
@@ -0,0 +1,612 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import random
|
| 6 |
+
import time
|
| 7 |
+
import traceback
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from concurrent.futures import as_completed
|
| 10 |
+
from ..time_sync import now_utc
|
| 11 |
+
from typing import Callable, TypeVar
|
| 12 |
+
|
| 13 |
+
from ..celery_app import celery_app
|
| 14 |
+
from ..db import init_db
|
| 15 |
+
from ..repository import update_task
|
| 16 |
+
|
| 17 |
+
T = TypeVar('T')
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _is_transient_network_error(e: Exception) -> bool:
|
| 21 |
+
try:
|
| 22 |
+
import http.client
|
| 23 |
+
|
| 24 |
+
if isinstance(e, http.client.RemoteDisconnected):
|
| 25 |
+
return True
|
| 26 |
+
except Exception:
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
if isinstance(e, (TimeoutError, ConnectionError, OSError)):
|
| 30 |
+
return True
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
import requests
|
| 34 |
+
|
| 35 |
+
if isinstance(e, requests.exceptions.RequestException):
|
| 36 |
+
return True
|
| 37 |
+
except Exception:
|
| 38 |
+
pass
|
| 39 |
+
|
| 40 |
+
return False
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _call_with_retries(
|
| 44 |
+
fn: Callable[[], T],
|
| 45 |
+
*,
|
| 46 |
+
task_id: str,
|
| 47 |
+
stage: str,
|
| 48 |
+
progress: int,
|
| 49 |
+
tries: int,
|
| 50 |
+
base_delay_seconds: float,
|
| 51 |
+
max_delay_seconds: float,
|
| 52 |
+
message_prefix: str,
|
| 53 |
+
) -> T:
|
| 54 |
+
last_exc: Exception | None = None
|
| 55 |
+
for attempt in range(1, max(1, int(tries)) + 1):
|
| 56 |
+
try:
|
| 57 |
+
return fn()
|
| 58 |
+
except Exception as e:
|
| 59 |
+
last_exc = e
|
| 60 |
+
if not _is_transient_network_error(e) or attempt >= int(tries):
|
| 61 |
+
raise
|
| 62 |
+
|
| 63 |
+
delay = min(float(max_delay_seconds), float(base_delay_seconds) * (2 ** (attempt - 1)))
|
| 64 |
+
delay = max(0.0, delay + random.random() * 0.25)
|
| 65 |
+
update_task(
|
| 66 |
+
task_id=task_id,
|
| 67 |
+
stage=stage,
|
| 68 |
+
progress=progress,
|
| 69 |
+
message=(
|
| 70 |
+
f"{message_prefix}网络请求失败,准备重试 {attempt}/{tries}:"
|
| 71 |
+
f"{type(e).__name__}: {e}"
|
| 72 |
+
)[:500],
|
| 73 |
+
)
|
| 74 |
+
time.sleep(delay)
|
| 75 |
+
|
| 76 |
+
assert last_exc is not None
|
| 77 |
+
raise last_exc
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _safe_filename(text: str) -> str:
|
| 81 |
+
invalid = '<>:/\\|?*\"'
|
| 82 |
+
out = ''.join('_' if ch in invalid else ch for ch in (text or ""))
|
| 83 |
+
return out.strip() or 'data'
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _split_symbols(symbol_text: str) -> list[str]:
|
| 87 |
+
raw = str(symbol_text or '')
|
| 88 |
+
parts = [p.strip() for p in raw.replace('\n', ',').replace('\t', ',').split(',')]
|
| 89 |
+
out: list[str] = []
|
| 90 |
+
seen: set[str] = set()
|
| 91 |
+
for p in parts:
|
| 92 |
+
if not p:
|
| 93 |
+
continue
|
| 94 |
+
if p in seen:
|
| 95 |
+
continue
|
| 96 |
+
seen.add(p)
|
| 97 |
+
out.append(p)
|
| 98 |
+
return out
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _standardize_download_df(df, stock_name: str | None):
|
| 102 |
+
import pandas as pd
|
| 103 |
+
|
| 104 |
+
if df is None or not isinstance(df, pd.DataFrame) or df.empty:
|
| 105 |
+
return df
|
| 106 |
+
|
| 107 |
+
df = df.copy()
|
| 108 |
+
df.columns = [str(c).strip() for c in df.columns]
|
| 109 |
+
|
| 110 |
+
column_map = {
|
| 111 |
+
'date': '日期',
|
| 112 |
+
'time': '时间',
|
| 113 |
+
'code': '股票代码',
|
| 114 |
+
'symbol': '股票代码',
|
| 115 |
+
'ts_code': '股票代码',
|
| 116 |
+
'代码': '股票代码',
|
| 117 |
+
'open': '开盘价',
|
| 118 |
+
'high': '最高价',
|
| 119 |
+
'low': '最低价',
|
| 120 |
+
'close': '收盘价',
|
| 121 |
+
'volume': '成交量',
|
| 122 |
+
'amount': '成交额',
|
| 123 |
+
'preclose': '昨收价',
|
| 124 |
+
'pre_close': '昨收价',
|
| 125 |
+
'adjustflag': '复权状态',
|
| 126 |
+
'turn': '换手率',
|
| 127 |
+
'tradestatus': '交易状态',
|
| 128 |
+
'pctChg': '涨跌幅',
|
| 129 |
+
'peTTM': '市盈率TTM',
|
| 130 |
+
'pbMRQ': '市净率',
|
| 131 |
+
'psTTM': '市销率TTM',
|
| 132 |
+
'pcfNcfTTM': '市现率TTM',
|
| 133 |
+
'isST': '是否ST',
|
| 134 |
+
'code_name': '股票名称',
|
| 135 |
+
'name': '股票名称',
|
| 136 |
+
'名称': '股票名称',
|
| 137 |
+
'股票名称': '股票名称',
|
| 138 |
+
'ipoDate': '上市日期',
|
| 139 |
+
'outDate': '退市日期',
|
| 140 |
+
'type': '股票类型',
|
| 141 |
+
'status': '上市状态',
|
| 142 |
+
'item': '项目',
|
| 143 |
+
'value': '值',
|
| 144 |
+
}
|
| 145 |
+
df.rename(columns={k: v for k, v in column_map.items() if k in df.columns}, inplace=True)
|
| 146 |
+
|
| 147 |
+
def _ensure_stock_name_col() -> None:
|
| 148 |
+
if '股票名称' in df.columns:
|
| 149 |
+
return
|
| 150 |
+
try:
|
| 151 |
+
if '股票代码' in df.columns:
|
| 152 |
+
idx = int(df.columns.get_loc('股票代码'))
|
| 153 |
+
df.insert(idx + 1, '股票名称', '')
|
| 154 |
+
else:
|
| 155 |
+
df.insert(0, '股票名称', '')
|
| 156 |
+
except Exception:
|
| 157 |
+
if '股票名称' not in df.columns:
|
| 158 |
+
df['股票名称'] = ''
|
| 159 |
+
|
| 160 |
+
_ensure_stock_name_col()
|
| 161 |
+
|
| 162 |
+
try:
|
| 163 |
+
s = df['股票名称']
|
| 164 |
+
empty_mask = s.isna() | (s.astype(str).str.strip() == '')
|
| 165 |
+
if bool(empty_mask.any()):
|
| 166 |
+
fill_val = str(stock_name or '').strip()
|
| 167 |
+
if not fill_val:
|
| 168 |
+
if '股票代码' in df.columns:
|
| 169 |
+
fill_val = None
|
| 170 |
+
else:
|
| 171 |
+
fill_val = ''
|
| 172 |
+
|
| 173 |
+
if fill_val is not None and fill_val != '':
|
| 174 |
+
df.loc[empty_mask, '股票名称'] = fill_val
|
| 175 |
+
else:
|
| 176 |
+
if '股票代码' in df.columns:
|
| 177 |
+
code_s = df['股票代码'].astype(str)
|
| 178 |
+
df.loc[empty_mask, '股票名称'] = code_s.loc[empty_mask].astype(str)
|
| 179 |
+
except Exception:
|
| 180 |
+
pass
|
| 181 |
+
|
| 182 |
+
if '复权状态' in df.columns:
|
| 183 |
+
adjust_map = {
|
| 184 |
+
'1': '前复权',
|
| 185 |
+
'2': '后复权',
|
| 186 |
+
'3': '不复权',
|
| 187 |
+
}
|
| 188 |
+
try:
|
| 189 |
+
df['复权状态'] = df['复权状态'].astype(str).map(adjust_map).fillna(df['复权状态'])
|
| 190 |
+
except Exception:
|
| 191 |
+
pass
|
| 192 |
+
|
| 193 |
+
if '日期' in df.columns:
|
| 194 |
+
if '时间' not in df.columns:
|
| 195 |
+
try:
|
| 196 |
+
s = df['日期'].astype(str)
|
| 197 |
+
if bool(s.str.contains(r'\d{1,2}:\d{2}', regex=True, na=False).any()):
|
| 198 |
+
dt = pd.to_datetime(s, errors='coerce')
|
| 199 |
+
if bool(dt.notna().any()):
|
| 200 |
+
df['日期'] = dt.dt.strftime('%Y-%m-%d')
|
| 201 |
+
df.insert(int(df.columns.get_loc('日期')) + 1, '时间', dt.dt.strftime('%H:%M:%S'))
|
| 202 |
+
except Exception:
|
| 203 |
+
pass
|
| 204 |
+
else:
|
| 205 |
+
try:
|
| 206 |
+
dt = pd.to_datetime(df['日期'].astype(str), errors='coerce')
|
| 207 |
+
if bool(dt.notna().any()):
|
| 208 |
+
df['日期'] = dt.dt.strftime('%Y-%m-%d')
|
| 209 |
+
except Exception:
|
| 210 |
+
pass
|
| 211 |
+
|
| 212 |
+
base = ['股票代码', '股票名称', '日期', '时间', '开盘价', '最高价', '最低价', '收盘价', '成交量', '成交额', '复权状态']
|
| 213 |
+
if '时间' not in df.columns:
|
| 214 |
+
base = [c for c in base if c != '时间']
|
| 215 |
+
ordered = [c for c in base if c in df.columns]
|
| 216 |
+
extras = [c for c in df.columns if c not in ordered]
|
| 217 |
+
return df[ordered + extras]
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _infer_data_range(df) -> tuple[str | None, str | None]:
|
| 221 |
+
import pandas as pd
|
| 222 |
+
|
| 223 |
+
if df is None or not isinstance(df, pd.DataFrame) or df.empty:
|
| 224 |
+
return None, None
|
| 225 |
+
|
| 226 |
+
date_col = None
|
| 227 |
+
for c in ('日期', 'date', 'Date', 'datetime', '时间'):
|
| 228 |
+
if c in df.columns:
|
| 229 |
+
date_col = c
|
| 230 |
+
break
|
| 231 |
+
if date_col is None:
|
| 232 |
+
return None, None
|
| 233 |
+
|
| 234 |
+
time_col = None
|
| 235 |
+
for c in ('时间', 'time'):
|
| 236 |
+
if c in df.columns:
|
| 237 |
+
time_col = c
|
| 238 |
+
break
|
| 239 |
+
|
| 240 |
+
def _normalize_time_str(val: str) -> str:
|
| 241 |
+
t = (val or '').strip()
|
| 242 |
+
if not t:
|
| 243 |
+
return t
|
| 244 |
+
if t.isdigit():
|
| 245 |
+
if len(t) == 6:
|
| 246 |
+
return f"{t[0:2]}:{t[2:4]}:{t[4:6]}"
|
| 247 |
+
if len(t) == 4:
|
| 248 |
+
return f"{t[0:2]}:{t[2:4]}:00"
|
| 249 |
+
if len(t) == 2:
|
| 250 |
+
return f"{t}:00:00"
|
| 251 |
+
return t
|
| 252 |
+
|
| 253 |
+
try:
|
| 254 |
+
if time_col and date_col != time_col:
|
| 255 |
+
time_series = df[time_col].astype(str).map(_normalize_time_str)
|
| 256 |
+
series = pd.to_datetime(
|
| 257 |
+
df[date_col].astype(str).str.strip() + ' ' + time_series.astype(str).str.strip(),
|
| 258 |
+
errors='coerce'
|
| 259 |
+
)
|
| 260 |
+
else:
|
| 261 |
+
series = pd.to_datetime(df[date_col].astype(str).str.strip(), errors='coerce')
|
| 262 |
+
except Exception:
|
| 263 |
+
return None, None
|
| 264 |
+
|
| 265 |
+
series = series.dropna()
|
| 266 |
+
if series.empty:
|
| 267 |
+
try:
|
| 268 |
+
series = pd.to_datetime(df[date_col].astype(str).str.strip(), errors='coerce').dropna()
|
| 269 |
+
except Exception:
|
| 270 |
+
return None, None
|
| 271 |
+
if series.empty:
|
| 272 |
+
return None, None
|
| 273 |
+
|
| 274 |
+
dt_min = series.min()
|
| 275 |
+
dt_max = series.max()
|
| 276 |
+
if time_col and date_col != time_col:
|
| 277 |
+
return dt_min.strftime('%Y-%m-%d %H:%M:%S'), dt_max.strftime('%Y-%m-%d %H:%M:%S')
|
| 278 |
+
return dt_min.strftime('%Y-%m-%d'), dt_max.strftime('%Y-%m-%d')
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def _baostock_days_per_segment(data_type: str) -> int:
|
| 282 |
+
dt = str(data_type or '').lower().strip()
|
| 283 |
+
if dt == 'daily':
|
| 284 |
+
return 730
|
| 285 |
+
if dt == '60min':
|
| 286 |
+
return 180
|
| 287 |
+
if dt == '30min':
|
| 288 |
+
return 120
|
| 289 |
+
return 60
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def _merge_baostock_segment_rows(all_rows: list[list[str]], columns: list[str]):
|
| 293 |
+
import pandas as pd
|
| 294 |
+
|
| 295 |
+
rows: list[list[str]] = []
|
| 296 |
+
for part in all_rows:
|
| 297 |
+
if part:
|
| 298 |
+
rows.extend(part)
|
| 299 |
+
if not rows:
|
| 300 |
+
return pd.DataFrame(columns=columns)
|
| 301 |
+
|
| 302 |
+
df = pd.DataFrame(rows, columns=columns)
|
| 303 |
+
try:
|
| 304 |
+
if 'date' in df.columns and 'time' in df.columns and 'code' in df.columns:
|
| 305 |
+
df = df.sort_values(['code', 'date', 'time'])
|
| 306 |
+
elif 'date' in df.columns and 'time' in df.columns:
|
| 307 |
+
df = df.sort_values(['date', 'time'])
|
| 308 |
+
elif 'date' in df.columns and 'code' in df.columns:
|
| 309 |
+
df = df.sort_values(['code', 'date'])
|
| 310 |
+
elif 'date' in df.columns:
|
| 311 |
+
df = df.sort_values(['date'])
|
| 312 |
+
except Exception:
|
| 313 |
+
pass
|
| 314 |
+
return df
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def _persist_df(
|
| 318 |
+
task_id: str,
|
| 319 |
+
save_format: str,
|
| 320 |
+
df,
|
| 321 |
+
file_label: str | None,
|
| 322 |
+
data_type: str | None,
|
| 323 |
+
df_stock_name: str | None = None,
|
| 324 |
+
) -> str:
|
| 325 |
+
import pandas as pd
|
| 326 |
+
|
| 327 |
+
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
|
| 328 |
+
uploads_dir = os.path.abspath(os.path.join(base_dir, 'uploads', 'v2', 'downloads', task_id))
|
| 329 |
+
os.makedirs(uploads_dir, exist_ok=True)
|
| 330 |
+
|
| 331 |
+
df = _standardize_download_df(df, df_stock_name)
|
| 332 |
+
|
| 333 |
+
name = _safe_filename(file_label or 'data')
|
| 334 |
+
dtype = _safe_filename(data_type or 'data')
|
| 335 |
+
|
| 336 |
+
fmt = (save_format or 'excel').lower().strip()
|
| 337 |
+
if fmt == 'excel':
|
| 338 |
+
path = os.path.join(uploads_dir, f"{name}_{dtype}.xlsx")
|
| 339 |
+
with pd.ExcelWriter(path, engine='openpyxl') as writer:
|
| 340 |
+
df.to_excel(writer, index=False, sheet_name='data')
|
| 341 |
+
return path
|
| 342 |
+
|
| 343 |
+
if fmt == 'csv':
|
| 344 |
+
path = os.path.join(uploads_dir, f"{name}_{dtype}.csv")
|
| 345 |
+
df.to_csv(path, index=False, encoding='utf-8-sig')
|
| 346 |
+
return path
|
| 347 |
+
|
| 348 |
+
if fmt == 'json':
|
| 349 |
+
path = os.path.join(uploads_dir, f"{name}_{dtype}.json")
|
| 350 |
+
rows = df.to_dict(orient='records')
|
| 351 |
+
with open(path, 'w', encoding='utf-8') as f:
|
| 352 |
+
json.dump(rows, f, ensure_ascii=False, indent=2, default=str)
|
| 353 |
+
return path
|
| 354 |
+
|
| 355 |
+
path = os.path.join(uploads_dir, f"{name}_{dtype}.xlsx")
|
| 356 |
+
with pd.ExcelWriter(path, engine='openpyxl') as writer:
|
| 357 |
+
df.to_excel(writer, index=False, sheet_name='data')
|
| 358 |
+
return path
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
@celery_app.task(name='wgjy.download_task')
|
| 362 |
+
def download_task(task_id: str, user_id: str | None, params: dict) -> dict:
|
| 363 |
+
os.environ.setdefault('WGJY_CELERY_WORKER', '1')
|
| 364 |
+
init_db()
|
| 365 |
+
|
| 366 |
+
t0 = time.perf_counter()
|
| 367 |
+
update_task(task_id=task_id, status='running', stage='initializing', progress=5, started_at=now_utc(), message='初始化下载任务')
|
| 368 |
+
|
| 369 |
+
import sys; sys.path.insert(0, "/Users/shaun/Documents/学习/网格交易和定投交易回测工具/backend"); import server as legacy
|
| 370 |
+
import pandas as pd
|
| 371 |
+
|
| 372 |
+
provider = str((params or {}).get('data_provider') or 'baostock').strip().lower()
|
| 373 |
+
data_type = str((params or {}).get('data_type') or 'daily').strip().lower()
|
| 374 |
+
|
| 375 |
+
task = dict(params or {})
|
| 376 |
+
task['data_provider'] = provider
|
| 377 |
+
task['data_type'] = data_type
|
| 378 |
+
|
| 379 |
+
try:
|
| 380 |
+
yesterday = (datetime.now() - legacy.timedelta(days=1)).strftime('%Y-%m-%d')
|
| 381 |
+
except Exception:
|
| 382 |
+
yesterday = (datetime.now()).strftime('%Y-%m-%d')
|
| 383 |
+
|
| 384 |
+
start_date = task.get('start_date')
|
| 385 |
+
end_date = task.get('end_date')
|
| 386 |
+
|
| 387 |
+
try:
|
| 388 |
+
effective_start, _ = legacy._clamp_date_str(str(start_date or ''), min_date='1990-01-01')
|
| 389 |
+
effective_end, _ = legacy._clamp_date_str(str(end_date or ''), max_date=yesterday)
|
| 390 |
+
task['effective_start_date'] = effective_start
|
| 391 |
+
task['effective_end_date'] = effective_end
|
| 392 |
+
except Exception:
|
| 393 |
+
task['effective_start_date'] = start_date
|
| 394 |
+
task['effective_end_date'] = end_date
|
| 395 |
+
|
| 396 |
+
update_task(task_id=task_id, stage='query', progress=20, message=f"准备获取数据源: {provider} {data_type}")
|
| 397 |
+
|
| 398 |
+
df = None
|
| 399 |
+
|
| 400 |
+
try:
|
| 401 |
+
update_task(task_id=task_id, stage='query', progress=35, message=f"正在获取数据: {provider} {data_type}")
|
| 402 |
+
|
| 403 |
+
retries = int(os.getenv('WGJY_DOWNLOAD_RETRIES') or '3')
|
| 404 |
+
base_delay_seconds = float(os.getenv('WGJY_DOWNLOAD_RETRY_BASE_DELAY_SECONDS') or '1')
|
| 405 |
+
max_delay_seconds = float(os.getenv('WGJY_DOWNLOAD_RETRY_MAX_DELAY_SECONDS') or '10')
|
| 406 |
+
|
| 407 |
+
if provider == 'canghai':
|
| 408 |
+
if data_type == 'daily':
|
| 409 |
+
df = _call_with_retries(
|
| 410 |
+
lambda: legacy._canghai_daily_bars(task),
|
| 411 |
+
task_id=task_id,
|
| 412 |
+
stage='query',
|
| 413 |
+
progress=35,
|
| 414 |
+
tries=retries,
|
| 415 |
+
base_delay_seconds=base_delay_seconds,
|
| 416 |
+
max_delay_seconds=max_delay_seconds,
|
| 417 |
+
message_prefix='沧海数据源:',
|
| 418 |
+
)
|
| 419 |
+
else:
|
| 420 |
+
df = _call_with_retries(
|
| 421 |
+
lambda: legacy._canghai_minute_bars(task),
|
| 422 |
+
task_id=task_id,
|
| 423 |
+
stage='query',
|
| 424 |
+
progress=35,
|
| 425 |
+
tries=retries,
|
| 426 |
+
base_delay_seconds=base_delay_seconds,
|
| 427 |
+
max_delay_seconds=max_delay_seconds,
|
| 428 |
+
message_prefix='沧海数据源:',
|
| 429 |
+
)
|
| 430 |
+
elif provider == 'efinance':
|
| 431 |
+
df = _call_with_retries(
|
| 432 |
+
lambda: legacy._efinance_kline(task),
|
| 433 |
+
task_id=task_id,
|
| 434 |
+
stage='query',
|
| 435 |
+
progress=35,
|
| 436 |
+
tries=retries,
|
| 437 |
+
base_delay_seconds=base_delay_seconds,
|
| 438 |
+
max_delay_seconds=max_delay_seconds,
|
| 439 |
+
message_prefix='efinance 数据源:',
|
| 440 |
+
)
|
| 441 |
+
else:
|
| 442 |
+
sec_type = legacy._infer_security_type(task.get('symbol', ''), task.get('security_type'))
|
| 443 |
+
task['security_type'] = sec_type
|
| 444 |
+
|
| 445 |
+
if provider != 'akshare' and data_type in ('daily', '60min', '30min', '5min'):
|
| 446 |
+
raw_symbols = _split_symbols(str(task.get('symbol', '')))
|
| 447 |
+
symbol_list = [legacy._normalize_symbol_for_baostock(s) for s in raw_symbols]
|
| 448 |
+
symbol_list = [s for s in symbol_list if str(s or '').strip()]
|
| 449 |
+
if not symbol_list:
|
| 450 |
+
symbol_list = [legacy._normalize_symbol_for_baostock(task.get('symbol', ''))]
|
| 451 |
+
|
| 452 |
+
if data_type == 'daily':
|
| 453 |
+
frequency = 'd'
|
| 454 |
+
fields = 'date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,isST'
|
| 455 |
+
elif data_type == '60min':
|
| 456 |
+
frequency = '60'
|
| 457 |
+
fields = 'date,time,code,open,high,low,close,volume,amount,adjustflag'
|
| 458 |
+
elif data_type == '30min':
|
| 459 |
+
frequency = '30'
|
| 460 |
+
fields = 'date,time,code,open,high,low,close,volume,amount,adjustflag'
|
| 461 |
+
else:
|
| 462 |
+
frequency = '5'
|
| 463 |
+
fields = 'date,time,code,open,high,low,close,volume,amount,adjustflag'
|
| 464 |
+
|
| 465 |
+
start_date_str = task.get('effective_start_date') or task.get('start_date')
|
| 466 |
+
end_date_str = task.get('effective_end_date') or task.get('end_date')
|
| 467 |
+
|
| 468 |
+
adjust_flag = str(task.get('adjust_flag', '3'))
|
| 469 |
+
days_per_segment = _baostock_days_per_segment(data_type)
|
| 470 |
+
ranges = list(legacy._iter_date_ranges(str(start_date_str), str(end_date_str), days_per_segment))
|
| 471 |
+
payloads: list[tuple[str, str, str, str, str, str]] = []
|
| 472 |
+
for sym in symbol_list:
|
| 473 |
+
for seg_start, seg_end in ranges:
|
| 474 |
+
payloads.append(
|
| 475 |
+
(
|
| 476 |
+
str(sym),
|
| 477 |
+
str(fields),
|
| 478 |
+
str(seg_start),
|
| 479 |
+
str(seg_end),
|
| 480 |
+
str(frequency),
|
| 481 |
+
str(adjust_flag),
|
| 482 |
+
)
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
try:
|
| 486 |
+
if len(payloads) <= 1:
|
| 487 |
+
rows, flds = legacy._baostock_segment_worker(payloads[0])
|
| 488 |
+
if rows:
|
| 489 |
+
df = pd.DataFrame(rows, columns=(flds or fields.split(',')))
|
| 490 |
+
else:
|
| 491 |
+
total = len(payloads)
|
| 492 |
+
completed = 0
|
| 493 |
+
parts: list[list[str]] = []
|
| 494 |
+
cols: list[str] = fields.split(',')
|
| 495 |
+
seg_cnt = max(1, len(ranges))
|
| 496 |
+
sym_cnt = max(1, len(symbol_list))
|
| 497 |
+
update_task(
|
| 498 |
+
task_id=task_id,
|
| 499 |
+
stage='query',
|
| 500 |
+
progress=38,
|
| 501 |
+
message=f"Baostock 并行下载:{sym_cnt} 只股票 × {seg_cnt} 段 = {total} 任务",
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
executor = getattr(legacy, 'BAOSTOCK_SEGMENT_EXECUTOR', None)
|
| 505 |
+
if executor is None:
|
| 506 |
+
raise RuntimeError('BAOSTOCK_SEGMENT_EXECUTOR 不存在')
|
| 507 |
+
|
| 508 |
+
futures = [executor.submit(legacy._baostock_segment_worker, p) for p in payloads]
|
| 509 |
+
for fut in as_completed(futures):
|
| 510 |
+
try:
|
| 511 |
+
seg_rows, seg_cols = fut.result()
|
| 512 |
+
if seg_cols:
|
| 513 |
+
cols = list(seg_cols)
|
| 514 |
+
if seg_rows:
|
| 515 |
+
parts.append(seg_rows)
|
| 516 |
+
except Exception:
|
| 517 |
+
parts.append([])
|
| 518 |
+
completed += 1
|
| 519 |
+
progress = 38 + int(22 * completed / max(1, total))
|
| 520 |
+
update_task(task_id=task_id, stage='query', progress=progress, message=f"Baostock 下载进度:{completed}/{total}")
|
| 521 |
+
|
| 522 |
+
df = _merge_baostock_segment_rows(parts, cols)
|
| 523 |
+
except Exception:
|
| 524 |
+
df = None
|
| 525 |
+
|
| 526 |
+
if df is None:
|
| 527 |
+
if data_type == 'daily':
|
| 528 |
+
df = _call_with_retries(
|
| 529 |
+
lambda: legacy._akshare_kline_daily(task),
|
| 530 |
+
task_id=task_id,
|
| 531 |
+
stage='query',
|
| 532 |
+
progress=55,
|
| 533 |
+
tries=retries,
|
| 534 |
+
base_delay_seconds=base_delay_seconds,
|
| 535 |
+
max_delay_seconds=max_delay_seconds,
|
| 536 |
+
message_prefix='AkShare:',
|
| 537 |
+
)
|
| 538 |
+
elif data_type in ('60min', '30min', '5min'):
|
| 539 |
+
df = _call_with_retries(
|
| 540 |
+
lambda: legacy._akshare_kline_min(task),
|
| 541 |
+
task_id=task_id,
|
| 542 |
+
stage='query',
|
| 543 |
+
progress=55,
|
| 544 |
+
tries=retries,
|
| 545 |
+
base_delay_seconds=base_delay_seconds,
|
| 546 |
+
max_delay_seconds=max_delay_seconds,
|
| 547 |
+
message_prefix='AkShare:',
|
| 548 |
+
)
|
| 549 |
+
else:
|
| 550 |
+
raise RuntimeError('不支持的数据类型')
|
| 551 |
+
|
| 552 |
+
if df is None or not isinstance(df, pd.DataFrame) or df.empty:
|
| 553 |
+
raise RuntimeError('未获取到数据')
|
| 554 |
+
|
| 555 |
+
update_task(task_id=task_id, stage='processing', progress=65, message='正在处理数据')
|
| 556 |
+
|
| 557 |
+
save_format = task.get('save_format') or 'excel'
|
| 558 |
+
symbol = str(task.get('symbol') or '')
|
| 559 |
+
symbols_for_name = _split_symbols(symbol)
|
| 560 |
+
is_multi_symbol = len(symbols_for_name) > 1
|
| 561 |
+
file_label = task.get('stock_name') or (symbol if not is_multi_symbol else '批量下载')
|
| 562 |
+
df_stock_name = (task.get('stock_name') or symbol) if not is_multi_symbol else ''
|
| 563 |
+
|
| 564 |
+
df_out = _standardize_download_df(df, df_stock_name)
|
| 565 |
+
data_range_start, data_range_end = _infer_data_range(df_out)
|
| 566 |
+
|
| 567 |
+
update_task(task_id=task_id, stage='saving', progress=85, message='正在保存文件')
|
| 568 |
+
file_path = _persist_df(task_id, str(save_format), df_out, file_label, data_type, df_stock_name=df_stock_name)
|
| 569 |
+
|
| 570 |
+
payload = {
|
| 571 |
+
'task_id': task_id,
|
| 572 |
+
'file_path': file_path,
|
| 573 |
+
'data_count': int(len(df_out)),
|
| 574 |
+
'columns': list(df_out.columns),
|
| 575 |
+
'elapsed_ms': int((time.perf_counter() - t0) * 1000),
|
| 576 |
+
'data_provider': provider,
|
| 577 |
+
'data_type': data_type,
|
| 578 |
+
'symbol': task.get('symbol'),
|
| 579 |
+
'stock_name': file_label,
|
| 580 |
+
'save_format': save_format,
|
| 581 |
+
'effective_start_date': task.get('effective_start_date'),
|
| 582 |
+
'effective_end_date': task.get('effective_end_date'),
|
| 583 |
+
'data_range_start': data_range_start,
|
| 584 |
+
'data_range_end': data_range_end,
|
| 585 |
+
}
|
| 586 |
+
|
| 587 |
+
update_task(
|
| 588 |
+
task_id=task_id,
|
| 589 |
+
status='completed',
|
| 590 |
+
stage='completed',
|
| 591 |
+
progress=100,
|
| 592 |
+
finished_at=now_utc(),
|
| 593 |
+
result_json=payload,
|
| 594 |
+
file_path=file_path,
|
| 595 |
+
message='下载完成',
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
return payload
|
| 599 |
+
|
| 600 |
+
except Exception as e:
|
| 601 |
+
err = f"{type(e).__name__}: {e}"
|
| 602 |
+
tb = traceback.format_exc()
|
| 603 |
+
update_task(
|
| 604 |
+
task_id=task_id,
|
| 605 |
+
status='failed',
|
| 606 |
+
stage='failed',
|
| 607 |
+
progress=100,
|
| 608 |
+
finished_at=now_utc(),
|
| 609 |
+
error=err,
|
| 610 |
+
message=(f"下载失败:{err}"[:500]),
|
| 611 |
+
)
|
| 612 |
+
raise
|
backend/v2/tasks/export.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
from ..time_sync import now_utc
|
| 6 |
+
|
| 7 |
+
from ..celery_app import celery_app
|
| 8 |
+
from ..db import init_db
|
| 9 |
+
from ..repository import get_backtest_record, update_task
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@celery_app.task(name='wgjy.export_backtest_excel')
|
| 13 |
+
def export_backtest_excel(task_id: str, user_id: str | None, record_id: str) -> dict:
|
| 14 |
+
os.environ.setdefault('WGJY_CELERY_WORKER', '1')
|
| 15 |
+
init_db()
|
| 16 |
+
|
| 17 |
+
t0 = time.perf_counter()
|
| 18 |
+
update_task(task_id=task_id, status='running', stage='loading', progress=5, started_at=now_utc(), message='开始导出')
|
| 19 |
+
|
| 20 |
+
rec = get_backtest_record(record_id=record_id, user_id=user_id)
|
| 21 |
+
if rec is None:
|
| 22 |
+
update_task(task_id=task_id, status='failed', stage='failed', progress=100, finished_at=now_utc(), error='记录不存在', message='导出失败')
|
| 23 |
+
raise RuntimeError('记录不存在')
|
| 24 |
+
|
| 25 |
+
results = rec.get('results') or {}
|
| 26 |
+
trade_records = results.get('trade_records') or []
|
| 27 |
+
if not trade_records:
|
| 28 |
+
update_task(task_id=task_id, status='failed', stage='failed', progress=100, finished_at=now_utc(), error='无交易记录可导出', message='导出失败')
|
| 29 |
+
raise RuntimeError('无交易记录可导出')
|
| 30 |
+
|
| 31 |
+
update_task(task_id=task_id, stage='building', progress=40, message='生成Excel文件')
|
| 32 |
+
|
| 33 |
+
import io
|
| 34 |
+
import pandas as pd
|
| 35 |
+
|
| 36 |
+
df = pd.DataFrame(trade_records)
|
| 37 |
+
bio = io.BytesIO()
|
| 38 |
+
with pd.ExcelWriter(bio, engine='openpyxl') as writer:
|
| 39 |
+
df.to_excel(writer, index=False, sheet_name='trade_records')
|
| 40 |
+
|
| 41 |
+
summary_rows = []
|
| 42 |
+
summary_rows.append(['record_id', rec.get('id')])
|
| 43 |
+
summary_rows.append(['strategy_type', rec.get('strategy_type')])
|
| 44 |
+
summary_rows.append(['symbol', rec.get('symbol')])
|
| 45 |
+
summary_rows.append(['start_date', rec.get('start_date')])
|
| 46 |
+
summary_rows.append(['end_date', rec.get('end_date')])
|
| 47 |
+
for k, v in (results or {}).items():
|
| 48 |
+
if k in ('trade_records', 'equity_curve'):
|
| 49 |
+
continue
|
| 50 |
+
if isinstance(v, (dict, list)):
|
| 51 |
+
continue
|
| 52 |
+
summary_rows.append([k, v])
|
| 53 |
+
pd.DataFrame(summary_rows, columns=['key', 'value']).to_excel(writer, index=False, sheet_name='summary')
|
| 54 |
+
|
| 55 |
+
bio.seek(0)
|
| 56 |
+
|
| 57 |
+
update_task(task_id=task_id, stage='saving', progress=85, message='保存文件')
|
| 58 |
+
|
| 59 |
+
base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
|
| 60 |
+
out_dir = os.path.abspath(os.path.join(base_dir, 'uploads', 'v2', 'exports', task_id))
|
| 61 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 62 |
+
|
| 63 |
+
file_path = os.path.join(out_dir, f"backtest_{record_id}.xlsx")
|
| 64 |
+
with open(file_path, 'wb') as f:
|
| 65 |
+
f.write(bio.getvalue())
|
| 66 |
+
|
| 67 |
+
payload = {
|
| 68 |
+
'task_id': task_id,
|
| 69 |
+
'record_id': record_id,
|
| 70 |
+
'file_path': file_path,
|
| 71 |
+
'elapsed_ms': int((time.perf_counter() - t0) * 1000),
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
update_task(
|
| 75 |
+
task_id=task_id,
|
| 76 |
+
status='completed',
|
| 77 |
+
stage='completed',
|
| 78 |
+
progress=100,
|
| 79 |
+
finished_at=now_utc(),
|
| 80 |
+
result_json=payload,
|
| 81 |
+
file_path=file_path,
|
| 82 |
+
message='导出完成',
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
return payload
|
backend/v2/tdx_day.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import csv
|
| 4 |
+
import os
|
| 5 |
+
import struct
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
RECORD_SIZE = 32
|
| 10 |
+
STRUCT_FMT = 'IIIIIfII'
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _project_root() -> str:
|
| 14 |
+
# backend/v2/tdx_day.py -> backend/v2 -> backend -> project root
|
| 15 |
+
return os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def default_code_info_csv_path() -> str:
|
| 19 |
+
return os.path.join(_project_root(), 'resources', '数据.csv')
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load_code_info(*, csv_path: str | None = None) -> dict[str, dict]:
|
| 23 |
+
"""Load code basic info from `数据.csv`.
|
| 24 |
+
|
| 25 |
+
Returns mapping: code6 -> {name, industry, area, list_date, kind, fund_company}
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
path = str(csv_path or default_code_info_csv_path()).strip()
|
| 29 |
+
if not path or not os.path.exists(path):
|
| 30 |
+
return {}
|
| 31 |
+
|
| 32 |
+
rows = None
|
| 33 |
+
for encoding in ('utf-8-sig', 'gbk'):
|
| 34 |
+
try:
|
| 35 |
+
with open(path, 'r', encoding=encoding, newline='') as f:
|
| 36 |
+
reader = csv.reader(f)
|
| 37 |
+
rows = list(reader)
|
| 38 |
+
break
|
| 39 |
+
except Exception:
|
| 40 |
+
rows = None
|
| 41 |
+
|
| 42 |
+
if not rows:
|
| 43 |
+
return {}
|
| 44 |
+
|
| 45 |
+
header = rows[0]
|
| 46 |
+
idx = {str(name).strip(): i for i, name in enumerate(header)}
|
| 47 |
+
|
| 48 |
+
def get(row, col_name, default=''):
|
| 49 |
+
j = idx.get(col_name)
|
| 50 |
+
if j is None or j >= len(row):
|
| 51 |
+
return default
|
| 52 |
+
return str(row[j]).strip()
|
| 53 |
+
|
| 54 |
+
out: dict[str, dict] = {}
|
| 55 |
+
for row in rows[1:]:
|
| 56 |
+
if not row:
|
| 57 |
+
continue
|
| 58 |
+
code = get(row, '代码')
|
| 59 |
+
name = get(row, '名称')
|
| 60 |
+
if not code:
|
| 61 |
+
continue
|
| 62 |
+
code6 = str(code)[-6:]
|
| 63 |
+
industry = get(row, '细分行业')
|
| 64 |
+
area = get(row, '地区')
|
| 65 |
+
list_date = get(row, '上市日期')
|
| 66 |
+
|
| 67 |
+
up_name = (name or '').upper()
|
| 68 |
+
if 'ETF' in up_name:
|
| 69 |
+
kind = 'ETF'
|
| 70 |
+
elif 'LOF' in up_name:
|
| 71 |
+
kind = 'LOF'
|
| 72 |
+
else:
|
| 73 |
+
kind = '股票'
|
| 74 |
+
|
| 75 |
+
fund_company = area if kind in ('ETF', 'LOF') else ''
|
| 76 |
+
|
| 77 |
+
out[code6] = {
|
| 78 |
+
'name': name,
|
| 79 |
+
'industry': industry,
|
| 80 |
+
'area': area,
|
| 81 |
+
'list_date': list_date,
|
| 82 |
+
'kind': kind,
|
| 83 |
+
'fund_company': fund_company,
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
return out
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def detect_price_scale(*, buf: bytes, sample_size: int = 80) -> int:
|
| 90 |
+
"""Detect price scale (10/100/1000/10000) for TDX .day file."""
|
| 91 |
+
|
| 92 |
+
if not isinstance(buf, (bytes, bytearray)):
|
| 93 |
+
return 100
|
| 94 |
+
|
| 95 |
+
n = int(len(buf) // RECORD_SIZE)
|
| 96 |
+
if n <= 0:
|
| 97 |
+
return 100
|
| 98 |
+
|
| 99 |
+
n_sample = min(max(0, int(sample_size)), n)
|
| 100 |
+
st = struct.Struct(STRUCT_FMT)
|
| 101 |
+
candidate_scales = (10, 100, 1000, 10000)
|
| 102 |
+
scores = {s: 0 for s in candidate_scales}
|
| 103 |
+
|
| 104 |
+
for i in range(n_sample):
|
| 105 |
+
b = i * RECORD_SIZE
|
| 106 |
+
a = st.unpack_from(buf, b)
|
| 107 |
+
close_raw = float(a[4] or 0)
|
| 108 |
+
amount = float(a[5] or 0)
|
| 109 |
+
vol_raw = float(a[6] or 0) # shares
|
| 110 |
+
if close_raw <= 0 or amount <= 0 or vol_raw <= 0:
|
| 111 |
+
continue
|
| 112 |
+
|
| 113 |
+
price_imp = amount / vol_raw
|
| 114 |
+
for scale in candidate_scales:
|
| 115 |
+
close = close_raw / float(scale)
|
| 116 |
+
if close <= 0:
|
| 117 |
+
continue
|
| 118 |
+
diff_ratio = abs(price_imp - close) / close
|
| 119 |
+
if diff_ratio <= 0.5:
|
| 120 |
+
scores[scale] += 1
|
| 121 |
+
|
| 122 |
+
if all(v == 0 for v in scores.values()):
|
| 123 |
+
return 100
|
| 124 |
+
|
| 125 |
+
pref_order = [100, 10, 1000, 10000]
|
| 126 |
+
return max(candidate_scales, key=lambda s: (scores[s], -pref_order.index(s)))
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def parse_tdx_day_bytes(*, buf: bytes, code6: str) -> list[dict]:
|
| 130 |
+
"""Parse TDX `.day` bytes to daily kline rows for DB.
|
| 131 |
+
|
| 132 |
+
Volume unit: shares.
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
if not isinstance(buf, (bytes, bytearray)):
|
| 136 |
+
return []
|
| 137 |
+
|
| 138 |
+
n = int(len(buf) // RECORD_SIZE)
|
| 139 |
+
if n <= 0:
|
| 140 |
+
return []
|
| 141 |
+
buf = buf[: n * RECORD_SIZE]
|
| 142 |
+
|
| 143 |
+
scale = detect_price_scale(buf=buf)
|
| 144 |
+
st = struct.Struct(STRUCT_FMT)
|
| 145 |
+
|
| 146 |
+
out: list[dict] = []
|
| 147 |
+
for i in range(n):
|
| 148 |
+
b = i * RECORD_SIZE
|
| 149 |
+
a = st.unpack_from(buf, b)
|
| 150 |
+
|
| 151 |
+
date_int = int(a[0] or 0)
|
| 152 |
+
if date_int <= 0:
|
| 153 |
+
continue
|
| 154 |
+
try:
|
| 155 |
+
trade_date = datetime.strptime(str(date_int), '%Y%m%d').strftime('%Y-%m-%d')
|
| 156 |
+
except Exception:
|
| 157 |
+
continue
|
| 158 |
+
|
| 159 |
+
open_v = round(float(a[1] or 0) / float(scale), 4)
|
| 160 |
+
high_v = round(float(a[2] or 0) / float(scale), 4)
|
| 161 |
+
low_v = round(float(a[3] or 0) / float(scale), 4)
|
| 162 |
+
close_v = round(float(a[4] or 0) / float(scale), 4)
|
| 163 |
+
amount_v = float(a[5] or 0)
|
| 164 |
+
volume_v = float(a[6] or 0) # shares
|
| 165 |
+
|
| 166 |
+
if close_v <= 0:
|
| 167 |
+
continue
|
| 168 |
+
|
| 169 |
+
out.append(
|
| 170 |
+
{
|
| 171 |
+
'code6': str(code6),
|
| 172 |
+
'trade_date': trade_date,
|
| 173 |
+
'close': float(close_v),
|
| 174 |
+
'open': float(open_v),
|
| 175 |
+
'high': float(high_v),
|
| 176 |
+
'low': float(low_v),
|
| 177 |
+
'volume': float(volume_v),
|
| 178 |
+
'amount': float(amount_v),
|
| 179 |
+
}
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
return out
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def parse_tdx_day_file(*, file_path: str, code6: str) -> list[dict]:
|
| 186 |
+
with open(file_path, 'rb') as f:
|
| 187 |
+
buf = f.read()
|
| 188 |
+
return parse_tdx_day_bytes(buf=buf, code6=code6)
|
backend/v2/time_sync.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import threading
|
| 4 |
+
import os
|
| 5 |
+
from datetime import datetime, timedelta, timezone
|
| 6 |
+
from email.utils import parsedate_to_datetime
|
| 7 |
+
import json
|
| 8 |
+
|
| 9 |
+
import httpx
|
| 10 |
+
|
| 11 |
+
_LOCK = threading.Lock()
|
| 12 |
+
|
| 13 |
+
_cached_offset: timedelta | None = None
|
| 14 |
+
_cached_at_utc: datetime | None = None
|
| 15 |
+
_cached_source: str | None = None
|
| 16 |
+
|
| 17 |
+
_DEFAULT_URLS = [
|
| 18 |
+
# Prefer HTTP to avoid TLS issues when local clock is skewed
|
| 19 |
+
'http://www.baidu.com',
|
| 20 |
+
'http://www.qq.com',
|
| 21 |
+
'http://www.aliyun.com',
|
| 22 |
+
# China-friendly time APIs
|
| 23 |
+
'http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp',
|
| 24 |
+
'http://quan.suning.com/getSysTime.do',
|
| 25 |
+
# Time API fallback
|
| 26 |
+
'http://worldtimeapi.org/api/timezone/Asia/Shanghai',
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def get_time_sync_status() -> dict:
|
| 31 |
+
local_utc = datetime.now(timezone.utc)
|
| 32 |
+
with _LOCK:
|
| 33 |
+
enabled = str(os.environ.get('WGJY_DISABLE_TIME_SYNC', '')).strip() != '1'
|
| 34 |
+
offset = _cached_offset
|
| 35 |
+
last_refresh = _cached_at_utc
|
| 36 |
+
source = _cached_source
|
| 37 |
+
|
| 38 |
+
synced_utc = local_utc if (not enabled or offset is None) else (local_utc + offset)
|
| 39 |
+
return {
|
| 40 |
+
'enabled': enabled,
|
| 41 |
+
'local_utc': local_utc.isoformat(),
|
| 42 |
+
'synced_utc': synced_utc.isoformat(),
|
| 43 |
+
'offset_seconds': (synced_utc - local_utc).total_seconds(),
|
| 44 |
+
'last_refresh_utc': last_refresh.isoformat() if last_refresh else None,
|
| 45 |
+
'source': source,
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _parse_worldtimeapi_utc(text: str) -> datetime | None:
|
| 50 |
+
try:
|
| 51 |
+
obj = json.loads(text)
|
| 52 |
+
dt_text = obj.get('utc_datetime') or obj.get('datetime')
|
| 53 |
+
if isinstance(dt_text, str) and dt_text:
|
| 54 |
+
dt = datetime.fromisoformat(dt_text.replace('Z', '+00:00'))
|
| 55 |
+
if dt.tzinfo is None:
|
| 56 |
+
dt = dt.replace(tzinfo=timezone.utc)
|
| 57 |
+
return dt.astimezone(timezone.utc)
|
| 58 |
+
unixtime = obj.get('unixtime')
|
| 59 |
+
if isinstance(unixtime, (int, float)):
|
| 60 |
+
return datetime.fromtimestamp(float(unixtime), tz=timezone.utc)
|
| 61 |
+
except Exception:
|
| 62 |
+
return None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _parse_taobao_utc(text: str) -> datetime | None:
|
| 66 |
+
try:
|
| 67 |
+
obj = json.loads(text)
|
| 68 |
+
t = (obj.get('data') or {}).get('t')
|
| 69 |
+
if isinstance(t, str) and t.isdigit():
|
| 70 |
+
ms = int(t)
|
| 71 |
+
return datetime.fromtimestamp(ms / 1000.0, tz=timezone.utc)
|
| 72 |
+
if isinstance(t, (int, float)):
|
| 73 |
+
return datetime.fromtimestamp(float(t) / 1000.0, tz=timezone.utc)
|
| 74 |
+
except Exception:
|
| 75 |
+
return None
|
| 76 |
+
return None
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _parse_suning_utc(text: str) -> datetime | None:
|
| 80 |
+
try:
|
| 81 |
+
obj = json.loads(text)
|
| 82 |
+
# example: {"sysTime2":"2026-01-23 12:34:56"}
|
| 83 |
+
s = obj.get('sysTime2') or obj.get('sysTime1')
|
| 84 |
+
if isinstance(s, str) and s:
|
| 85 |
+
bj_tz = timezone(timedelta(hours=8))
|
| 86 |
+
dt = datetime.strptime(s.strip(), '%Y-%m-%d %H:%M:%S').replace(tzinfo=bj_tz)
|
| 87 |
+
return dt.astimezone(timezone.utc)
|
| 88 |
+
except Exception:
|
| 89 |
+
return None
|
| 90 |
+
return None
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _try_fetch_utc_from_url(url: str) -> datetime | None:
|
| 94 |
+
try:
|
| 95 |
+
with httpx.Client(timeout=2.0, follow_redirects=True) as client:
|
| 96 |
+
use_get = any(k in url for k in ('worldtimeapi.org', 'api.m.taobao.com', 'suning.com'))
|
| 97 |
+
if use_get:
|
| 98 |
+
r = client.get(url)
|
| 99 |
+
else:
|
| 100 |
+
try:
|
| 101 |
+
r = client.head(url)
|
| 102 |
+
except Exception:
|
| 103 |
+
r = client.get(url)
|
| 104 |
+
|
| 105 |
+
try:
|
| 106 |
+
ct = (r.headers.get('content-type') or '').lower()
|
| 107 |
+
if 'application/json' in ct or r.text.strip().startswith('{'):
|
| 108 |
+
if 'worldtimeapi.org' in url:
|
| 109 |
+
dt = _parse_worldtimeapi_utc(r.text)
|
| 110 |
+
if dt is not None:
|
| 111 |
+
return dt
|
| 112 |
+
if 'api.m.taobao.com' in url:
|
| 113 |
+
dt = _parse_taobao_utc(r.text)
|
| 114 |
+
if dt is not None:
|
| 115 |
+
return dt
|
| 116 |
+
if 'suning.com' in url:
|
| 117 |
+
dt = _parse_suning_utc(r.text)
|
| 118 |
+
if dt is not None:
|
| 119 |
+
return dt
|
| 120 |
+
except Exception:
|
| 121 |
+
pass
|
| 122 |
+
|
| 123 |
+
date_str = r.headers.get('date')
|
| 124 |
+
if not date_str:
|
| 125 |
+
return None
|
| 126 |
+
dt = parsedate_to_datetime(date_str)
|
| 127 |
+
if dt.tzinfo is None:
|
| 128 |
+
dt = dt.replace(tzinfo=timezone.utc)
|
| 129 |
+
return dt.astimezone(timezone.utc)
|
| 130 |
+
except Exception:
|
| 131 |
+
return None
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _refresh_offset_if_needed() -> None:
|
| 135 |
+
global _cached_offset, _cached_at_utc, _cached_source
|
| 136 |
+
|
| 137 |
+
now = datetime.now(timezone.utc)
|
| 138 |
+
if _cached_offset is not None and _cached_at_utc is not None:
|
| 139 |
+
if (now - _cached_at_utc).total_seconds() < 300:
|
| 140 |
+
return
|
| 141 |
+
|
| 142 |
+
urls = _DEFAULT_URLS
|
| 143 |
+
try:
|
| 144 |
+
env_urls = str(os.environ.get('WGJY_TIME_SYNC_URLS', '')).strip()
|
| 145 |
+
if env_urls:
|
| 146 |
+
urls = [u.strip() for u in env_urls.split(',') if u.strip()]
|
| 147 |
+
except Exception:
|
| 148 |
+
pass
|
| 149 |
+
|
| 150 |
+
for url in urls:
|
| 151 |
+
net_utc = _try_fetch_utc_from_url(url)
|
| 152 |
+
if net_utc is None:
|
| 153 |
+
continue
|
| 154 |
+
local_utc = datetime.now(timezone.utc)
|
| 155 |
+
_cached_offset = net_utc - local_utc
|
| 156 |
+
_cached_at_utc = now
|
| 157 |
+
_cached_source = url
|
| 158 |
+
return
|
| 159 |
+
|
| 160 |
+
_cached_at_utc = now
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def now_utc() -> datetime:
|
| 164 |
+
if str(os.environ.get('WGJY_DISABLE_TIME_SYNC', '')).strip() == '1':
|
| 165 |
+
return datetime.now(timezone.utc)
|
| 166 |
+
|
| 167 |
+
with _LOCK:
|
| 168 |
+
_refresh_offset_if_needed()
|
| 169 |
+
if _cached_offset is None:
|
| 170 |
+
return datetime.now(timezone.utc)
|
| 171 |
+
return datetime.now(timezone.utc) + _cached_offset
|
backend/v2/worker.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from .celery_app import celery_app
|
| 4 |
+
|
| 5 |
+
from .tasks import backtest
|
| 6 |
+
from .tasks import download
|
| 7 |
+
from .tasks import export
|
frontend/index.html
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="zh-CN">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8" />
|
| 5 |
+
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
| 6 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
| 7 |
+
<title>网格交易和定投交易回测工具</title>
|
| 8 |
+
</head>
|
| 9 |
+
<body>
|
| 10 |
+
<div id="root"></div>
|
| 11 |
+
<script type="module" src="/src/main.tsx"></script>
|
| 12 |
+
</body>
|
| 13 |
+
</html>
|
frontend/install-deps.bat
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@echo off
|
| 2 |
+
echo Installing file parsing dependencies...
|
| 3 |
+
|
| 4 |
+
cd /d "%~dp0"
|
| 5 |
+
|
| 6 |
+
echo Installing xlsx for Excel support...
|
| 7 |
+
npm install xlsx
|
| 8 |
+
|
| 9 |
+
echo Installing parquetjs for Parquet support...
|
| 10 |
+
npm install parquetjs-lite
|
| 11 |
+
|
| 12 |
+
echo Installing additional type definitions...
|
| 13 |
+
npm install --save-dev @types/node
|
| 14 |
+
|
| 15 |
+
echo Dependencies installed successfully!
|
| 16 |
+
pause
|
frontend/install-file-deps.cmd
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@echo off
|
| 2 |
+
echo Installing file parsing dependencies...
|
| 3 |
+
|
| 4 |
+
echo.
|
| 5 |
+
echo Changing to frontend directory...
|
| 6 |
+
cd /d "%~dp0"
|
| 7 |
+
|
| 8 |
+
echo.
|
| 9 |
+
echo Installing xlsx for Excel support...
|
| 10 |
+
call npm install xlsx
|
| 11 |
+
|
| 12 |
+
echo.
|
| 13 |
+
echo Installing parquetjs-lite for Parquet support...
|
| 14 |
+
call npm install parquetjs-lite
|
| 15 |
+
|
| 16 |
+
echo.
|
| 17 |
+
echo Dependencies installed successfully!
|
| 18 |
+
echo You can now upload Excel and Parquet files.
|
| 19 |
+
|
| 20 |
+
pause
|
frontend/package-lock.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
frontend/package.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "backtest-frontend",
|
| 3 |
+
"version": "1.0.0",
|
| 4 |
+
"private": true,
|
| 5 |
+
"scripts": {
|
| 6 |
+
"dev": "vite",
|
| 7 |
+
"build": "tsc && vite build",
|
| 8 |
+
"preview": "vite preview"
|
| 9 |
+
},
|
| 10 |
+
"dependencies": {
|
| 11 |
+
"@radix-ui/react-alert-dialog": "^1.0.5",
|
| 12 |
+
"@radix-ui/react-checkbox": "^1.0.4",
|
| 13 |
+
"@radix-ui/react-dialog": "^1.1.15",
|
| 14 |
+
"@radix-ui/react-dropdown-menu": "^2.0.6",
|
| 15 |
+
"@radix-ui/react-label": "^2.0.2",
|
| 16 |
+
"@radix-ui/react-radio-group": "^1.1.3",
|
| 17 |
+
"@radix-ui/react-select": "^2.0.0",
|
| 18 |
+
"@radix-ui/react-separator": "^1.0.3",
|
| 19 |
+
"@radix-ui/react-switch": "^1.0.3",
|
| 20 |
+
"@radix-ui/react-tabs": "^1.0.4",
|
| 21 |
+
"@radix-ui/react-toast": "^1.1.5",
|
| 22 |
+
"@rollup/rollup-darwin-arm64": "^4.60.3",
|
| 23 |
+
"axios": "^1.6.2",
|
| 24 |
+
"class-variance-authority": "^0.7.1",
|
| 25 |
+
"clsx": "^2.0.0",
|
| 26 |
+
"date-fns": "^2.30.0",
|
| 27 |
+
"html2canvas": "^1.4.1",
|
| 28 |
+
"jspdf": "^2.5.2",
|
| 29 |
+
"lucide-react": "^0.294.0",
|
| 30 |
+
"react": "^18.2.0",
|
| 31 |
+
"react-dom": "^18.2.0",
|
| 32 |
+
"react-hook-form": "^7.48.2",
|
| 33 |
+
"react-router-dom": "^6.20.1",
|
| 34 |
+
"recharts": "^2.10.3",
|
| 35 |
+
"tailwind-merge": "^2.1.0",
|
| 36 |
+
"tailwindcss-animate": "^1.0.7",
|
| 37 |
+
"xlsx": "^0.18.5",
|
| 38 |
+
"zustand": "^4.4.7"
|
| 39 |
+
},
|
| 40 |
+
"devDependencies": {
|
| 41 |
+
"@types/node": "^20.10.4",
|
| 42 |
+
"@types/react": "^18.2.45",
|
| 43 |
+
"@types/react-dom": "^18.2.17",
|
| 44 |
+
"@vitejs/plugin-react": "^4.2.0",
|
| 45 |
+
"autoprefixer": "^10.4.16",
|
| 46 |
+
"postcss": "^8.4.32",
|
| 47 |
+
"tailwindcss": "^3.3.6",
|
| 48 |
+
"typescript": "^5.3.3",
|
| 49 |
+
"vite": "^5.0.8"
|
| 50 |
+
}
|
| 51 |
+
}
|
frontend/postcss.config.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export default {
|
| 2 |
+
plugins: {
|
| 3 |
+
tailwindcss: {},
|
| 4 |
+
autoprefixer: {},
|
| 5 |
+
},
|
| 6 |
+
}
|
frontend/public/favicon.svg
ADDED
|
|
frontend/src/App.tsx
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Routes, Route } from 'react-router-dom'
|
| 2 |
+
import Layout from './components/Layout'
|
| 3 |
+
import Home from './pages/Home'
|
| 4 |
+
import GridStrategies from './pages/GridStrategies'
|
| 5 |
+
import GridBacktest from './pages/GridBacktest'
|
| 6 |
+
import DCABacktest from './pages/DCABacktest'
|
| 7 |
+
import DataDownload from './pages/DataDownload'
|
| 8 |
+
import TechnicalIndicators from './pages/TechnicalIndicators'
|
| 9 |
+
import History from './pages/History'
|
| 10 |
+
import FileTest from './pages/FileTest'
|
| 11 |
+
import MarketLists from './pages/MarketLists'
|
| 12 |
+
import Admin from './pages/Admin'
|
| 13 |
+
import Trades from './pages/Trades'
|
| 14 |
+
import { Toaster } from './components/ui/toaster'
|
| 15 |
+
|
| 16 |
+
function App() {
|
| 17 |
+
return (
|
| 18 |
+
<>
|
| 19 |
+
<Layout>
|
| 20 |
+
<Routes>
|
| 21 |
+
<Route path="/" element={<Home />} />
|
| 22 |
+
<Route path="/grid-strategies" element={<GridStrategies />} />
|
| 23 |
+
<Route path="/grid" element={<GridBacktest />} />
|
| 24 |
+
<Route path="/dca" element={<DCABacktest />} />
|
| 25 |
+
<Route path="/data" element={<DataDownload />} />
|
| 26 |
+
<Route path="/indicators" element={<TechnicalIndicators />} />
|
| 27 |
+
<Route path="/history" element={<History />} />
|
| 28 |
+
<Route path="/market-lists" element={<MarketLists />} />
|
| 29 |
+
<Route path="/trades" element={<Trades />} />
|
| 30 |
+
<Route path="/test" element={<FileTest />} />
|
| 31 |
+
<Route path="/admin" element={<Admin />} />
|
| 32 |
+
</Routes>
|
| 33 |
+
</Layout>
|
| 34 |
+
<Toaster />
|
| 35 |
+
</>
|
| 36 |
+
)
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
export default App
|
frontend/src/components/Layout.tsx
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Link, useLocation } from 'react-router-dom'
|
| 2 |
+
import { cn } from '../lib/utils'
|
| 3 |
+
import {
|
| 4 |
+
Database,
|
| 5 |
+
TrendingUp,
|
| 6 |
+
History,
|
| 7 |
+
Home,
|
| 8 |
+
ClipboardList,
|
| 9 |
+
BarChart3,
|
| 10 |
+
PieChart,
|
| 11 |
+
} from 'lucide-react'
|
| 12 |
+
import { useEffect, useState } from 'react'
|
| 13 |
+
|
| 14 |
+
// 导航配置 - 精简版
|
| 15 |
+
const navItems = [
|
| 16 |
+
{ name: '仪表盘', href: '/', icon: Home },
|
| 17 |
+
{ name: '网格回测', href: '/grid', icon: BarChart3 },
|
| 18 |
+
{ name: '技术指标', href: '/indicators', icon: TrendingUp },
|
| 19 |
+
{ name: '交易记录', href: '/trades', icon: ClipboardList },
|
| 20 |
+
{ name: '回测历史', href: '/history', icon: History },
|
| 21 |
+
{ name: '数据中心', href: '/data', icon: Database },
|
| 22 |
+
{ name: '行情列表', href: '/market-lists', icon: PieChart },
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
// 世界时钟
|
| 26 |
+
const worldClocks = [
|
| 27 |
+
{ city: '东京', timezone: 'Asia/Tokyo', flag: '🇯🇵' },
|
| 28 |
+
{ city: '伦敦', timezone: 'Europe/London', flag: '🇬🇧' },
|
| 29 |
+
{ city: '纽约', timezone: 'America/New_York', flag: '🇺🇸' },
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
export default function Layout({ children }: { children: React.ReactNode }) {
|
| 33 |
+
const location = useLocation()
|
| 34 |
+
const [currentTime, setCurrentTime] = useState(new Date())
|
| 35 |
+
const [greeting, setGreeting] = useState('')
|
| 36 |
+
|
| 37 |
+
useEffect(() => {
|
| 38 |
+
const timer = setInterval(() => {
|
| 39 |
+
setCurrentTime(new Date())
|
| 40 |
+
}, 1000)
|
| 41 |
+
return () => clearInterval(timer)
|
| 42 |
+
}, [])
|
| 43 |
+
|
| 44 |
+
useEffect(() => {
|
| 45 |
+
const hour = currentTime.getHours()
|
| 46 |
+
if (hour < 12) setGreeting('上午好')
|
| 47 |
+
else if (hour < 18) setGreeting('下午好')
|
| 48 |
+
else setGreeting('晚上好')
|
| 49 |
+
}, [currentTime])
|
| 50 |
+
|
| 51 |
+
const formatTime = (timezone: string) => {
|
| 52 |
+
return new Intl.DateTimeFormat('zh-CN', {
|
| 53 |
+
hour: '2-digit',
|
| 54 |
+
minute: '2-digit',
|
| 55 |
+
timeZone: timezone,
|
| 56 |
+
hour12: false,
|
| 57 |
+
}).format(currentTime)
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
const isMarketOpen = (timezone: string) => {
|
| 61 |
+
const hour = parseInt(formatTime(timezone).split(':')[0])
|
| 62 |
+
return hour >= 9 && hour < 15
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
const isActive = (href: string) => {
|
| 66 |
+
if (href === '/') return location.pathname === '/'
|
| 67 |
+
return location.pathname.startsWith(href)
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
return (
|
| 71 |
+
<div className="min-h-screen flex flex-col bg-slate-50">
|
| 72 |
+
{/* 顶部导航栏 */}
|
| 73 |
+
<header className="sticky top-0 z-50 bg-white border-b border-slate-200">
|
| 74 |
+
<div className="flex items-center justify-between h-14 px-6">
|
| 75 |
+
{/* Logo */}
|
| 76 |
+
<Link to="/" className="flex items-center gap-2 hover:opacity-80 transition-opacity">
|
| 77 |
+
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-violet-500 to-purple-600 flex items-center justify-center text-white font-bold text-sm">
|
| 78 |
+
WG
|
| 79 |
+
</div>
|
| 80 |
+
<span className="text-lg font-bold text-slate-900">网格交易</span>
|
| 81 |
+
</Link>
|
| 82 |
+
|
| 83 |
+
{/* 导航链接 */}
|
| 84 |
+
<nav className="flex items-center gap-1">
|
| 85 |
+
{navItems.map((item) => {
|
| 86 |
+
const Icon = item.icon
|
| 87 |
+
const active = isActive(item.href)
|
| 88 |
+
return (
|
| 89 |
+
<Link
|
| 90 |
+
key={item.href}
|
| 91 |
+
to={item.href}
|
| 92 |
+
className={cn(
|
| 93 |
+
"flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-all",
|
| 94 |
+
active
|
| 95 |
+
? "bg-violet-100 text-violet-700"
|
| 96 |
+
: "text-slate-600 hover:bg-slate-100 hover:text-slate-900"
|
| 97 |
+
)}
|
| 98 |
+
>
|
| 99 |
+
<Icon className="h-4 w-4" />
|
| 100 |
+
<span>{item.name}</span>
|
| 101 |
+
</Link>
|
| 102 |
+
)
|
| 103 |
+
})}
|
| 104 |
+
</nav>
|
| 105 |
+
|
| 106 |
+
{/* 右侧时间 */}
|
| 107 |
+
<div className="text-sm text-slate-500">
|
| 108 |
+
{currentTime.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}
|
| 109 |
+
</div>
|
| 110 |
+
</div>
|
| 111 |
+
</header>
|
| 112 |
+
|
| 113 |
+
{/* 欢迎区(仅首页) */}
|
| 114 |
+
{location.pathname === '/' && (
|
| 115 |
+
<div className="bg-white border-b border-slate-200">
|
| 116 |
+
<div className="px-6 py-5">
|
| 117 |
+
<div className="flex items-start justify-between">
|
| 118 |
+
<div>
|
| 119 |
+
<h1 className="text-xl font-bold text-slate-900">
|
| 120 |
+
{greeting},交易员!
|
| 121 |
+
</h1>
|
| 122 |
+
<p className="text-slate-500 text-sm mt-1">
|
| 123 |
+
{currentTime.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' })}
|
| 124 |
+
</p>
|
| 125 |
+
</div>
|
| 126 |
+
|
| 127 |
+
{/* 世界时钟 */}
|
| 128 |
+
<div className="flex items-center gap-3">
|
| 129 |
+
{worldClocks.map((clock) => (
|
| 130 |
+
<div
|
| 131 |
+
key={clock.city}
|
| 132 |
+
className="flex items-center gap-2 px-3 py-1.5 bg-slate-50 rounded-lg"
|
| 133 |
+
>
|
| 134 |
+
<span className="text-lg">{clock.flag}</span>
|
| 135 |
+
<div>
|
| 136 |
+
<div className="text-xs text-slate-400">{clock.city}</div>
|
| 137 |
+
<div className="text-sm font-semibold text-slate-900">
|
| 138 |
+
{formatTime(clock.timezone)}
|
| 139 |
+
</div>
|
| 140 |
+
</div>
|
| 141 |
+
</div>
|
| 142 |
+
))}
|
| 143 |
+
</div>
|
| 144 |
+
</div>
|
| 145 |
+
</div>
|
| 146 |
+
</div>
|
| 147 |
+
)}
|
| 148 |
+
|
| 149 |
+
{/* 主内容 */}
|
| 150 |
+
<main className="flex-1 p-6 overflow-x-auto">
|
| 151 |
+
{children}
|
| 152 |
+
</main>
|
| 153 |
+
|
| 154 |
+
{/* 页脚 */}
|
| 155 |
+
<footer className="bg-white border-t border-slate-200 py-3 px-6">
|
| 156 |
+
<div className="flex items-center justify-between text-xs text-slate-400">
|
| 157 |
+
<p>© {new Date().getFullYear()} 网格交易和定投交易回测工具</p>
|
| 158 |
+
<p>投资有风险,入市需谨慎</p>
|
| 159 |
+
</div>
|
| 160 |
+
</footer>
|
| 161 |
+
</div>
|
| 162 |
+
)
|
| 163 |
+
}
|
frontend/src/components/ui/badge.tsx
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import * as React from "react"
|
| 2 |
+
import { cva, type VariantProps } from "class-variance-authority"
|
| 3 |
+
|
| 4 |
+
import { cn } from "../../lib/utils"
|
| 5 |
+
|
| 6 |
+
const badgeVariants = cva(
|
| 7 |
+
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
| 8 |
+
{
|
| 9 |
+
variants: {
|
| 10 |
+
variant: {
|
| 11 |
+
default:
|
| 12 |
+
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
|
| 13 |
+
secondary:
|
| 14 |
+
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
| 15 |
+
destructive:
|
| 16 |
+
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
|
| 17 |
+
outline: "text-foreground",
|
| 18 |
+
},
|
| 19 |
+
},
|
| 20 |
+
defaultVariants: {
|
| 21 |
+
variant: "default",
|
| 22 |
+
},
|
| 23 |
+
}
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
export interface BadgeProps
|
| 27 |
+
extends React.HTMLAttributes<HTMLDivElement>,
|
| 28 |
+
VariantProps<typeof badgeVariants> {}
|
| 29 |
+
|
| 30 |
+
function Badge({ className, variant, ...props }: BadgeProps) {
|
| 31 |
+
return (
|
| 32 |
+
<div className={cn(badgeVariants({ variant }), className)} {...props} />
|
| 33 |
+
)
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
export { Badge, badgeVariants }
|
frontend/src/components/ui/button.tsx
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import * as React from "react"
|
| 2 |
+
import { Slot } from "@radix-ui/react-slot"
|
| 3 |
+
import { cva, type VariantProps } from "class-variance-authority"
|
| 4 |
+
import { cn } from "../../lib/utils"
|
| 5 |
+
|
| 6 |
+
const buttonVariants = cva(
|
| 7 |
+
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
|
| 8 |
+
{
|
| 9 |
+
variants: {
|
| 10 |
+
variant: {
|
| 11 |
+
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
| 12 |
+
destructive:
|
| 13 |
+
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
| 14 |
+
outline:
|
| 15 |
+
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
| 16 |
+
secondary:
|
| 17 |
+
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
| 18 |
+
ghost: "hover:bg-accent hover:text-accent-foreground",
|
| 19 |
+
link: "text-primary underline-offset-4 hover:underline",
|
| 20 |
+
},
|
| 21 |
+
size: {
|
| 22 |
+
default: "h-10 px-4 py-2",
|
| 23 |
+
sm: "h-9 rounded-md px-3",
|
| 24 |
+
lg: "h-11 rounded-md px-8",
|
| 25 |
+
icon: "h-10 w-10",
|
| 26 |
+
},
|
| 27 |
+
},
|
| 28 |
+
defaultVariants: {
|
| 29 |
+
variant: "default",
|
| 30 |
+
size: "default",
|
| 31 |
+
},
|
| 32 |
+
}
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
export interface ButtonProps
|
| 36 |
+
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
| 37 |
+
VariantProps<typeof buttonVariants> {
|
| 38 |
+
asChild?: boolean
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
| 42 |
+
({ className, variant, size, asChild = false, ...props }, ref) => {
|
| 43 |
+
const Comp = asChild ? Slot : "button"
|
| 44 |
+
return (
|
| 45 |
+
<Comp
|
| 46 |
+
className={cn(buttonVariants({ variant, size, className }))}
|
| 47 |
+
ref={ref}
|
| 48 |
+
{...props}
|
| 49 |
+
/>
|
| 50 |
+
)
|
| 51 |
+
}
|
| 52 |
+
)
|
| 53 |
+
Button.displayName = "Button"
|
| 54 |
+
|
| 55 |
+
export { Button, buttonVariants }
|
frontend/src/components/ui/card.tsx
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import * as React from "react"
|
| 2 |
+
import { cn } from "../../lib/utils"
|
| 3 |
+
|
| 4 |
+
const Card = React.forwardRef<
|
| 5 |
+
HTMLDivElement,
|
| 6 |
+
React.HTMLAttributes<HTMLDivElement>
|
| 7 |
+
>(({ className, ...props }, ref) => (
|
| 8 |
+
<div
|
| 9 |
+
ref={ref}
|
| 10 |
+
className={cn(
|
| 11 |
+
"rounded-lg border bg-card text-card-foreground shadow-sm",
|
| 12 |
+
className
|
| 13 |
+
)}
|
| 14 |
+
{...props}
|
| 15 |
+
/>
|
| 16 |
+
))
|
| 17 |
+
Card.displayName = "Card"
|
| 18 |
+
|
| 19 |
+
const CardHeader = React.forwardRef<
|
| 20 |
+
HTMLDivElement,
|
| 21 |
+
React.HTMLAttributes<HTMLDivElement>
|
| 22 |
+
>(({ className, ...props }, ref) => (
|
| 23 |
+
<div
|
| 24 |
+
ref={ref}
|
| 25 |
+
className={cn("flex flex-col space-y-1.5 p-6", className)}
|
| 26 |
+
{...props}
|
| 27 |
+
/>
|
| 28 |
+
))
|
| 29 |
+
CardHeader.displayName = "CardHeader"
|
| 30 |
+
|
| 31 |
+
const CardTitle = React.forwardRef<
|
| 32 |
+
HTMLParagraphElement,
|
| 33 |
+
React.HTMLAttributes<HTMLHeadingElement>
|
| 34 |
+
>(({ className, ...props }, ref) => (
|
| 35 |
+
<h3
|
| 36 |
+
ref={ref}
|
| 37 |
+
className={cn(
|
| 38 |
+
"text-2xl font-semibold leading-none tracking-tight",
|
| 39 |
+
className
|
| 40 |
+
)}
|
| 41 |
+
{...props}
|
| 42 |
+
/>
|
| 43 |
+
))
|
| 44 |
+
CardTitle.displayName = "CardTitle"
|
| 45 |
+
|
| 46 |
+
const CardDescription = React.forwardRef<
|
| 47 |
+
HTMLParagraphElement,
|
| 48 |
+
React.HTMLAttributes<HTMLParagraphElement>
|
| 49 |
+
>(({ className, ...props }, ref) => (
|
| 50 |
+
<p
|
| 51 |
+
ref={ref}
|
| 52 |
+
className={cn("text-sm text-muted-foreground", className)}
|
| 53 |
+
{...props}
|
| 54 |
+
/>
|
| 55 |
+
))
|
| 56 |
+
CardDescription.displayName = "CardDescription"
|
| 57 |
+
|
| 58 |
+
const CardContent = React.forwardRef<
|
| 59 |
+
HTMLDivElement,
|
| 60 |
+
React.HTMLAttributes<HTMLDivElement>
|
| 61 |
+
>(({ className, ...props }, ref) => (
|
| 62 |
+
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
|
| 63 |
+
))
|
| 64 |
+
CardContent.displayName = "CardContent"
|
| 65 |
+
|
| 66 |
+
const CardFooter = React.forwardRef<
|
| 67 |
+
HTMLDivElement,
|
| 68 |
+
React.HTMLAttributes<HTMLDivElement>
|
| 69 |
+
>(({ className, ...props }, ref) => (
|
| 70 |
+
<div
|
| 71 |
+
ref={ref}
|
| 72 |
+
className={cn("flex items-center p-6 pt-0", className)}
|
| 73 |
+
{...props}
|
| 74 |
+
/>
|
| 75 |
+
))
|
| 76 |
+
CardFooter.displayName = "CardFooter"
|
| 77 |
+
|
| 78 |
+
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
|
frontend/src/components/ui/date-picker.tsx
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import * as React from "react"
|
| 2 |
+
import { Calendar as CalendarIcon } from "lucide-react"
|
| 3 |
+
import { cn } from "../../lib/utils"
|
| 4 |
+
import { Button } from "./button"
|
| 5 |
+
|
| 6 |
+
interface DatePickerProps {
|
| 7 |
+
date?: Date
|
| 8 |
+
onDateChange: (date: Date) => void
|
| 9 |
+
placeholder?: string
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
export function DatePicker({ date, onDateChange, placeholder = "选择日期" }: DatePickerProps) {
|
| 13 |
+
const [isOpen, setIsOpen] = React.useState(false)
|
| 14 |
+
const [month, setMonth] = React.useState<Date>(date || new Date())
|
| 15 |
+
const [year, setYear] = React.useState<number>(date?.getFullYear() || new Date().getFullYear())
|
| 16 |
+
const containerRef = React.useRef<HTMLDivElement>(null)
|
| 17 |
+
|
| 18 |
+
const handleDayClick = (day: number) => {
|
| 19 |
+
const newDate = new Date(year, month.getMonth(), day)
|
| 20 |
+
onDateChange(newDate)
|
| 21 |
+
setIsOpen(false)
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
const handleYearChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
| 25 |
+
const newYear = parseInt(e.target.value)
|
| 26 |
+
setYear(newYear)
|
| 27 |
+
const newMonth = new Date(month)
|
| 28 |
+
newMonth.setFullYear(newYear)
|
| 29 |
+
setMonth(newMonth)
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
const getDaysInMonth = (date: Date) => {
|
| 33 |
+
return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate()
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
const getFirstDayOfMonth = (date: Date) => {
|
| 37 |
+
return new Date(date.getFullYear(), date.getMonth(), 1).getDay()
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
const daysInMonth = getDaysInMonth(month)
|
| 41 |
+
const firstDay = getFirstDayOfMonth(month)
|
| 42 |
+
const days = Array.from({ length: daysInMonth }, (_, i) => i + 1)
|
| 43 |
+
const emptyDays = Array.from({ length: firstDay }, (_, i) => i)
|
| 44 |
+
const years = Array.from({ length: 100 }, (_, i) => new Date().getFullYear() - 50 + i)
|
| 45 |
+
|
| 46 |
+
const formatDate = (d: Date | undefined) => {
|
| 47 |
+
if (!d) return placeholder
|
| 48 |
+
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
// 点击外部关闭
|
| 52 |
+
React.useEffect(() => {
|
| 53 |
+
const handleClickOutside = (event: MouseEvent) => {
|
| 54 |
+
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
|
| 55 |
+
setIsOpen(false)
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
if (isOpen) {
|
| 60 |
+
document.addEventListener('mousedown', handleClickOutside)
|
| 61 |
+
return () => document.removeEventListener('mousedown', handleClickOutside)
|
| 62 |
+
}
|
| 63 |
+
}, [isOpen])
|
| 64 |
+
|
| 65 |
+
return (
|
| 66 |
+
<div ref={containerRef} className="relative w-full">
|
| 67 |
+
<Button
|
| 68 |
+
type="button"
|
| 69 |
+
variant="outline"
|
| 70 |
+
className={cn(
|
| 71 |
+
"w-full justify-start text-left font-normal",
|
| 72 |
+
!date && "text-muted-foreground"
|
| 73 |
+
)}
|
| 74 |
+
onClick={() => setIsOpen(!isOpen)}
|
| 75 |
+
>
|
| 76 |
+
<CalendarIcon className="mr-2 h-4 w-4" />
|
| 77 |
+
{formatDate(date)}
|
| 78 |
+
</Button>
|
| 79 |
+
|
| 80 |
+
{isOpen && (
|
| 81 |
+
<div className="absolute top-full left-0 mt-2 z-50 bg-background border rounded-lg shadow-lg p-4 w-80">
|
| 82 |
+
<div className="space-y-4">
|
| 83 |
+
{/* 年月选择 */}
|
| 84 |
+
<div className="flex items-center justify-between gap-2">
|
| 85 |
+
<select
|
| 86 |
+
value={year}
|
| 87 |
+
onChange={handleYearChange}
|
| 88 |
+
className="flex-1 px-2 py-1 border rounded text-sm"
|
| 89 |
+
>
|
| 90 |
+
{years.map((y) => (
|
| 91 |
+
<option key={y} value={y}>
|
| 92 |
+
{y}年
|
| 93 |
+
</option>
|
| 94 |
+
))}
|
| 95 |
+
</select>
|
| 96 |
+
<select
|
| 97 |
+
value={month.getMonth()}
|
| 98 |
+
onChange={(e) => {
|
| 99 |
+
const newMonth = new Date(month)
|
| 100 |
+
newMonth.setMonth(parseInt(e.target.value))
|
| 101 |
+
setMonth(newMonth)
|
| 102 |
+
}}
|
| 103 |
+
className="flex-1 px-2 py-1 border rounded text-sm"
|
| 104 |
+
>
|
| 105 |
+
{Array.from({ length: 12 }, (_, i) => (
|
| 106 |
+
<option key={i} value={i}>
|
| 107 |
+
{i + 1}月
|
| 108 |
+
</option>
|
| 109 |
+
))}
|
| 110 |
+
</select>
|
| 111 |
+
</div>
|
| 112 |
+
|
| 113 |
+
{/* 日期网格 */}
|
| 114 |
+
<div className="space-y-2">
|
| 115 |
+
{/* 星期标题 */}
|
| 116 |
+
<div className="grid grid-cols-7 gap-1 text-center text-xs font-semibold text-muted-foreground">
|
| 117 |
+
<div>日</div>
|
| 118 |
+
<div>一</div>
|
| 119 |
+
<div>二</div>
|
| 120 |
+
<div>三</div>
|
| 121 |
+
<div>四</div>
|
| 122 |
+
<div>五</div>
|
| 123 |
+
<div>六</div>
|
| 124 |
+
</div>
|
| 125 |
+
|
| 126 |
+
{/* 日期网格 */}
|
| 127 |
+
<div className="grid grid-cols-7 gap-1">
|
| 128 |
+
{/* 空白天数 */}
|
| 129 |
+
{emptyDays.map((_, i) => (
|
| 130 |
+
<div key={`empty-${i}`} className="h-8" />
|
| 131 |
+
))}
|
| 132 |
+
|
| 133 |
+
{/* 日期 */}
|
| 134 |
+
{days.map((day) => {
|
| 135 |
+
const isSelected =
|
| 136 |
+
date &&
|
| 137 |
+
date.getDate() === day &&
|
| 138 |
+
date.getMonth() === month.getMonth() &&
|
| 139 |
+
date.getFullYear() === year
|
| 140 |
+
|
| 141 |
+
return (
|
| 142 |
+
<button
|
| 143 |
+
key={day}
|
| 144 |
+
type="button"
|
| 145 |
+
onClick={() => handleDayClick(day)}
|
| 146 |
+
className={cn(
|
| 147 |
+
"h-8 w-8 rounded text-sm font-medium transition-colors hover:bg-muted",
|
| 148 |
+
isSelected && "bg-primary text-primary-foreground"
|
| 149 |
+
)}
|
| 150 |
+
>
|
| 151 |
+
{day}
|
| 152 |
+
</button>
|
| 153 |
+
)
|
| 154 |
+
})}
|
| 155 |
+
</div>
|
| 156 |
+
</div>
|
| 157 |
+
|
| 158 |
+
{/* 快速选择 */}
|
| 159 |
+
<div className="flex gap-2 pt-2 border-t">
|
| 160 |
+
<Button
|
| 161 |
+
type="button"
|
| 162 |
+
size="sm"
|
| 163 |
+
variant="outline"
|
| 164 |
+
onClick={() => {
|
| 165 |
+
const today = new Date()
|
| 166 |
+
onDateChange(today)
|
| 167 |
+
setMonth(today)
|
| 168 |
+
setYear(today.getFullYear())
|
| 169 |
+
setIsOpen(false)
|
| 170 |
+
}}
|
| 171 |
+
>
|
| 172 |
+
今天
|
| 173 |
+
</Button>
|
| 174 |
+
<Button
|
| 175 |
+
type="button"
|
| 176 |
+
size="sm"
|
| 177 |
+
variant="outline"
|
| 178 |
+
onClick={() => {
|
| 179 |
+
const yesterday = new Date()
|
| 180 |
+
yesterday.setDate(yesterday.getDate() - 1)
|
| 181 |
+
onDateChange(yesterday)
|
| 182 |
+
setMonth(yesterday)
|
| 183 |
+
setYear(yesterday.getFullYear())
|
| 184 |
+
setIsOpen(false)
|
| 185 |
+
}}
|
| 186 |
+
>
|
| 187 |
+
昨天
|
| 188 |
+
</Button>
|
| 189 |
+
</div>
|
| 190 |
+
</div>
|
| 191 |
+
</div>
|
| 192 |
+
)}
|
| 193 |
+
</div>
|
| 194 |
+
)
|
| 195 |
+
}
|
frontend/src/components/ui/dialog.tsx
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import * as React from "react"
|
| 2 |
+
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
| 3 |
+
import { X } from "lucide-react"
|
| 4 |
+
|
| 5 |
+
import { cn } from "../../lib/utils"
|
| 6 |
+
|
| 7 |
+
const Dialog = DialogPrimitive.Root
|
| 8 |
+
|
| 9 |
+
const DialogTrigger = DialogPrimitive.Trigger
|
| 10 |
+
|
| 11 |
+
const DialogPortal = DialogPrimitive.Portal
|
| 12 |
+
|
| 13 |
+
const DialogClose = DialogPrimitive.Close
|
| 14 |
+
|
| 15 |
+
const DialogOverlay = React.forwardRef<
|
| 16 |
+
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
| 17 |
+
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
| 18 |
+
>(({ className, ...props }, ref) => (
|
| 19 |
+
<DialogPrimitive.Overlay
|
| 20 |
+
ref={ref}
|
| 21 |
+
className={cn(
|
| 22 |
+
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
| 23 |
+
className
|
| 24 |
+
)}
|
| 25 |
+
{...props}
|
| 26 |
+
/>
|
| 27 |
+
))
|
| 28 |
+
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
|
| 29 |
+
|
| 30 |
+
const DialogContent = React.forwardRef<
|
| 31 |
+
React.ElementRef<typeof DialogPrimitive.Content>,
|
| 32 |
+
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
|
| 33 |
+
>(({ className, children, ...props }, ref) => (
|
| 34 |
+
<DialogPortal>
|
| 35 |
+
<DialogOverlay />
|
| 36 |
+
<DialogPrimitive.Content
|
| 37 |
+
ref={ref}
|
| 38 |
+
className={cn(
|
| 39 |
+
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
|
| 40 |
+
className
|
| 41 |
+
)}
|
| 42 |
+
{...props}
|
| 43 |
+
>
|
| 44 |
+
{children}
|
| 45 |
+
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
|
| 46 |
+
<X className="h-4 w-4" />
|
| 47 |
+
<span className="sr-only">Close</span>
|
| 48 |
+
</DialogPrimitive.Close>
|
| 49 |
+
</DialogPrimitive.Content>
|
| 50 |
+
</DialogPortal>
|
| 51 |
+
))
|
| 52 |
+
DialogContent.displayName = DialogPrimitive.Content.displayName
|
| 53 |
+
|
| 54 |
+
const DialogHeader = ({
|
| 55 |
+
className,
|
| 56 |
+
...props
|
| 57 |
+
}: React.HTMLAttributes<HTMLDivElement>) => (
|
| 58 |
+
<div
|
| 59 |
+
className={cn(
|
| 60 |
+
"flex flex-col space-y-1.5 text-center sm:text-left",
|
| 61 |
+
className
|
| 62 |
+
)}
|
| 63 |
+
{...props}
|
| 64 |
+
/>
|
| 65 |
+
)
|
| 66 |
+
DialogHeader.displayName = "DialogHeader"
|
| 67 |
+
|
| 68 |
+
const DialogFooter = ({
|
| 69 |
+
className,
|
| 70 |
+
...props
|
| 71 |
+
}: React.HTMLAttributes<HTMLDivElement>) => (
|
| 72 |
+
<div
|
| 73 |
+
className={cn(
|
| 74 |
+
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
|
| 75 |
+
className
|
| 76 |
+
)}
|
| 77 |
+
{...props}
|
| 78 |
+
/>
|
| 79 |
+
)
|
| 80 |
+
DialogFooter.displayName = "DialogFooter"
|
| 81 |
+
|
| 82 |
+
const DialogTitle = React.forwardRef<
|
| 83 |
+
React.ElementRef<typeof DialogPrimitive.Title>,
|
| 84 |
+
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
| 85 |
+
>(({ className, ...props }, ref) => (
|
| 86 |
+
<DialogPrimitive.Title
|
| 87 |
+
ref={ref}
|
| 88 |
+
className={cn(
|
| 89 |
+
"text-lg font-semibold leading-none tracking-tight",
|
| 90 |
+
className
|
| 91 |
+
)}
|
| 92 |
+
{...props}
|
| 93 |
+
/>
|
| 94 |
+
))
|
| 95 |
+
DialogTitle.displayName = DialogPrimitive.Title.displayName
|
| 96 |
+
|
| 97 |
+
const DialogDescription = React.forwardRef<
|
| 98 |
+
React.ElementRef<typeof DialogPrimitive.Description>,
|
| 99 |
+
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
| 100 |
+
>(({ className, ...props }, ref) => (
|
| 101 |
+
<DialogPrimitive.Description
|
| 102 |
+
ref={ref}
|
| 103 |
+
className={cn("text-sm text-muted-foreground", className)}
|
| 104 |
+
{...props}
|
| 105 |
+
/>
|
| 106 |
+
))
|
| 107 |
+
DialogDescription.displayName = DialogPrimitive.Description.displayName
|
| 108 |
+
|
| 109 |
+
export {
|
| 110 |
+
Dialog,
|
| 111 |
+
DialogPortal,
|
| 112 |
+
DialogOverlay,
|
| 113 |
+
DialogClose,
|
| 114 |
+
DialogTrigger,
|
| 115 |
+
DialogContent,
|
| 116 |
+
DialogHeader,
|
| 117 |
+
DialogFooter,
|
| 118 |
+
DialogTitle,
|
| 119 |
+
DialogDescription,
|
| 120 |
+
}
|
frontend/src/components/ui/file-upload.tsx
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import React, { useRef, useState } from 'react'
|
| 2 |
+
import { Button } from './button'
|
| 3 |
+
import { Card, CardContent } from './card'
|
| 4 |
+
import { Upload, File, X, CheckCircle, AlertCircle } from 'lucide-react'
|
| 5 |
+
import { cn } from '../../lib/utils'
|
| 6 |
+
|
| 7 |
+
interface FileUploadProps {
|
| 8 |
+
onFileSelect?: (file: File) => void
|
| 9 |
+
onFilesSelect?: (files: File[]) => void
|
| 10 |
+
onFileRemove?: () => void
|
| 11 |
+
onFilesRemove?: () => void
|
| 12 |
+
acceptedTypes?: string[]
|
| 13 |
+
maxSize?: number // MB
|
| 14 |
+
selectedFile?: File | null
|
| 15 |
+
selectedFiles?: File[]
|
| 16 |
+
multiple?: boolean
|
| 17 |
+
className?: string
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
export function FileUpload({
|
| 21 |
+
onFileSelect,
|
| 22 |
+
onFilesSelect,
|
| 23 |
+
onFileRemove,
|
| 24 |
+
onFilesRemove,
|
| 25 |
+
acceptedTypes = ['.xlsx', '.xls', '.csv', '.json'],
|
| 26 |
+
maxSize = 50,
|
| 27 |
+
selectedFile,
|
| 28 |
+
selectedFiles,
|
| 29 |
+
multiple = false,
|
| 30 |
+
className
|
| 31 |
+
}: FileUploadProps) {
|
| 32 |
+
const fileInputRef = useRef<HTMLInputElement>(null)
|
| 33 |
+
const [dragActive, setDragActive] = useState(false)
|
| 34 |
+
const [error, setError] = useState<string>('')
|
| 35 |
+
|
| 36 |
+
const supportedExtensions = acceptedTypes
|
| 37 |
+
.map((t) => String(t || '').trim().toLowerCase())
|
| 38 |
+
.filter(Boolean)
|
| 39 |
+
.map((t) => (t.startsWith('.') ? t : `.${t}`))
|
| 40 |
+
|
| 41 |
+
const handleDrag = (e: React.DragEvent) => {
|
| 42 |
+
e.preventDefault()
|
| 43 |
+
e.stopPropagation()
|
| 44 |
+
if (e.type === 'dragenter' || e.type === 'dragover') {
|
| 45 |
+
setDragActive(true)
|
| 46 |
+
} else if (e.type === 'dragleave') {
|
| 47 |
+
setDragActive(false)
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
const validateFile = (file: File): string | null => {
|
| 52 |
+
// 检查文件类型
|
| 53 |
+
const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase()
|
| 54 |
+
|
| 55 |
+
if (!supportedExtensions.includes(fileExtension)) {
|
| 56 |
+
return `不支持的文件格式。支持格式:${supportedExtensions.join(', ')}`
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
// 检查文件大小
|
| 60 |
+
if (file.size > maxSize * 1024 * 1024) {
|
| 61 |
+
return `文件大小超过限制(最大 ${maxSize}MB)`
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
return null
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
const handleFiles = (files: FileList) => {
|
| 68 |
+
if (multiple) {
|
| 69 |
+
// 多文件模式
|
| 70 |
+
const validFiles: File[] = []
|
| 71 |
+
const errors: string[] = []
|
| 72 |
+
for (let i = 0; i < files.length; i++) {
|
| 73 |
+
const file = files[i]
|
| 74 |
+
const validationError = validateFile(file)
|
| 75 |
+
if (validationError) {
|
| 76 |
+
errors.push(`${file.name}: ${validationError}`)
|
| 77 |
+
} else {
|
| 78 |
+
validFiles.push(file)
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
if (errors.length > 0) {
|
| 82 |
+
setError(errors.join('\n'))
|
| 83 |
+
} else {
|
| 84 |
+
setError('')
|
| 85 |
+
}
|
| 86 |
+
if (validFiles.length > 0 && onFilesSelect) {
|
| 87 |
+
onFilesSelect(validFiles)
|
| 88 |
+
}
|
| 89 |
+
} else {
|
| 90 |
+
// 单文件模式
|
| 91 |
+
const file = files[0]
|
| 92 |
+
if (!file) return
|
| 93 |
+
|
| 94 |
+
const validationError = validateFile(file)
|
| 95 |
+
if (validationError) {
|
| 96 |
+
setError(validationError)
|
| 97 |
+
return
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
setError('')
|
| 101 |
+
if (onFileSelect) onFileSelect(file)
|
| 102 |
+
}
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
const handleDrop = (e: React.DragEvent) => {
|
| 106 |
+
e.preventDefault()
|
| 107 |
+
e.stopPropagation()
|
| 108 |
+
setDragActive(false)
|
| 109 |
+
|
| 110 |
+
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
|
| 111 |
+
handleFiles(e.dataTransfer.files)
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
| 116 |
+
e.preventDefault()
|
| 117 |
+
if (e.target.files && e.target.files.length > 0) {
|
| 118 |
+
handleFiles(e.target.files)
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
const handleButtonClick = () => {
|
| 123 |
+
fileInputRef.current?.click()
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
const handleRemove = (e?: React.MouseEvent) => {
|
| 127 |
+
if (e) {
|
| 128 |
+
e.stopPropagation()
|
| 129 |
+
}
|
| 130 |
+
setError('')
|
| 131 |
+
if (multiple && onFilesRemove) {
|
| 132 |
+
onFilesRemove()
|
| 133 |
+
} else if (onFileRemove) {
|
| 134 |
+
onFileRemove()
|
| 135 |
+
}
|
| 136 |
+
if (fileInputRef.current) {
|
| 137 |
+
fileInputRef.current.value = ''
|
| 138 |
+
}
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
const handleRemoveSingleFile = (e: React.MouseEvent, index: number) => {
|
| 142 |
+
e.stopPropagation()
|
| 143 |
+
if (multiple && selectedFiles && onFilesSelect) {
|
| 144 |
+
const newFiles = selectedFiles.filter((_, i) => i !== index)
|
| 145 |
+
if (newFiles.length === 0) {
|
| 146 |
+
handleRemove()
|
| 147 |
+
} else {
|
| 148 |
+
onFilesSelect(newFiles)
|
| 149 |
+
}
|
| 150 |
+
}
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
const formatFileSize = (bytes: number) => {
|
| 154 |
+
if (bytes === 0) return '0 Bytes'
|
| 155 |
+
const k = 1024
|
| 156 |
+
const sizes = ['Bytes', 'KB', 'MB', 'GB']
|
| 157 |
+
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
| 158 |
+
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
const hasFiles = multiple ? (selectedFiles && selectedFiles.length > 0) : !!selectedFile
|
| 162 |
+
|
| 163 |
+
return (
|
| 164 |
+
<div className={cn('w-full', className)}>
|
| 165 |
+
<input
|
| 166 |
+
ref={fileInputRef}
|
| 167 |
+
type="file"
|
| 168 |
+
multiple={multiple}
|
| 169 |
+
accept={[
|
| 170 |
+
...acceptedTypes,
|
| 171 |
+
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
| 172 |
+
'application/vnd.ms-excel',
|
| 173 |
+
'text/csv',
|
| 174 |
+
'application/json',
|
| 175 |
+
'application/octet-stream'
|
| 176 |
+
].join(',')}
|
| 177 |
+
onChange={handleChange}
|
| 178 |
+
className="hidden"
|
| 179 |
+
/>
|
| 180 |
+
|
| 181 |
+
{!hasFiles ? (
|
| 182 |
+
<Card
|
| 183 |
+
className={cn(
|
| 184 |
+
'border-2 border-dashed transition-colors cursor-pointer hover:border-primary/50',
|
| 185 |
+
dragActive ? 'border-primary bg-primary/5' : 'border-muted-foreground/25',
|
| 186 |
+
error ? 'border-destructive' : ''
|
| 187 |
+
)}
|
| 188 |
+
onDragEnter={handleDrag}
|
| 189 |
+
onDragLeave={handleDrag}
|
| 190 |
+
onDragOver={handleDrag}
|
| 191 |
+
onDrop={handleDrop}
|
| 192 |
+
onClick={handleButtonClick}
|
| 193 |
+
>
|
| 194 |
+
<CardContent className="py-3 px-4">
|
| 195 |
+
<div className="flex items-center gap-3">
|
| 196 |
+
<Upload className={cn(
|
| 197 |
+
'h-6 w-6',
|
| 198 |
+
dragActive ? 'text-primary' : 'text-muted-foreground',
|
| 199 |
+
error ? 'text-destructive' : ''
|
| 200 |
+
)} />
|
| 201 |
+
<div className="text-left">
|
| 202 |
+
<p className="text-sm font-medium mb-1">
|
| 203 |
+
点击上传或拖拽文件到此处{multiple ? '(可多选)' : ''}
|
| 204 |
+
</p>
|
| 205 |
+
<p className="text-xs text-muted-foreground">
|
| 206 |
+
支持 {acceptedTypes.join(', ')} 格式
|
| 207 |
+
</p>
|
| 208 |
+
<p className="text-xs text-muted-foreground">
|
| 209 |
+
最大文件大小:{maxSize}MB
|
| 210 |
+
</p>
|
| 211 |
+
</div>
|
| 212 |
+
</div>
|
| 213 |
+
{error && (
|
| 214 |
+
<div className="flex items-center gap-2 mt-2 text-destructive">
|
| 215 |
+
<AlertCircle className="h-4 w-4" />
|
| 216 |
+
<p className="text-xs whitespace-pre-line">{error}</p>
|
| 217 |
+
</div>
|
| 218 |
+
)}
|
| 219 |
+
</CardContent>
|
| 220 |
+
</Card>
|
| 221 |
+
) : multiple && selectedFiles ? (
|
| 222 |
+
<Card className="border-primary/50 bg-primary/5">
|
| 223 |
+
<CardContent className="py-3 px-4">
|
| 224 |
+
<div className="flex items-center justify-between mb-2">
|
| 225 |
+
<p className="text-sm font-medium">已选择 {selectedFiles.length} 个文件</p>
|
| 226 |
+
<div className="flex items-center gap-2">
|
| 227 |
+
<Button
|
| 228 |
+
variant="outline"
|
| 229 |
+
size="sm"
|
| 230 |
+
onClick={handleButtonClick}
|
| 231 |
+
>
|
| 232 |
+
添加更多
|
| 233 |
+
</Button>
|
| 234 |
+
<Button
|
| 235 |
+
variant="ghost"
|
| 236 |
+
size="sm"
|
| 237 |
+
onClick={(e) => handleRemove(e)}
|
| 238 |
+
className="text-destructive hover:text-destructive"
|
| 239 |
+
>
|
| 240 |
+
清空全部
|
| 241 |
+
</Button>
|
| 242 |
+
</div>
|
| 243 |
+
</div>
|
| 244 |
+
<div className="space-y-2 max-h-[200px] overflow-y-auto">
|
| 245 |
+
{selectedFiles.map((file, index) => (
|
| 246 |
+
<div key={`${file.name}-${index}`} className="flex items-center justify-between p-2 bg-background rounded border">
|
| 247 |
+
<div className="flex items-center gap-2">
|
| 248 |
+
<File className="h-4 w-4 text-primary" />
|
| 249 |
+
<span className="text-sm truncate max-w-[200px]">{file.name}</span>
|
| 250 |
+
<span className="text-xs text-muted-foreground">({formatFileSize(file.size)})</span>
|
| 251 |
+
</div>
|
| 252 |
+
<Button
|
| 253 |
+
variant="ghost"
|
| 254 |
+
size="sm"
|
| 255 |
+
onClick={(e) => handleRemoveSingleFile(e, index)}
|
| 256 |
+
className="h-6 w-6 p-0"
|
| 257 |
+
>
|
| 258 |
+
<X className="h-3 w-3" />
|
| 259 |
+
</Button>
|
| 260 |
+
</div>
|
| 261 |
+
))}
|
| 262 |
+
</div>
|
| 263 |
+
</CardContent>
|
| 264 |
+
</Card>
|
| 265 |
+
) : selectedFile ? (
|
| 266 |
+
<Card
|
| 267 |
+
className="border-primary/50 bg-primary/5 cursor-pointer hover:border-primary/70 transition-colors"
|
| 268 |
+
onClick={handleButtonClick}
|
| 269 |
+
>
|
| 270 |
+
<CardContent className="flex items-center justify-between py-3 px-4">
|
| 271 |
+
<div className="flex items-center gap-3">
|
| 272 |
+
<div className="p-2 bg-primary/10 rounded-lg">
|
| 273 |
+
<File className="h-5 w-5 text-primary" />
|
| 274 |
+
</div>
|
| 275 |
+
<div>
|
| 276 |
+
<p className="text-sm font-medium">{selectedFile.name}</p>
|
| 277 |
+
<p className="text-xs text-muted-foreground">
|
| 278 |
+
{formatFileSize(selectedFile.size)}
|
| 279 |
+
</p>
|
| 280 |
+
</div>
|
| 281 |
+
</div>
|
| 282 |
+
<div className="flex items-center gap-2">
|
| 283 |
+
<CheckCircle className="h-5 w-5 text-green-500" />
|
| 284 |
+
<Button
|
| 285 |
+
variant="ghost"
|
| 286 |
+
size="sm"
|
| 287 |
+
onClick={(e) => handleRemove(e)}
|
| 288 |
+
className="h-8 w-8 p-0"
|
| 289 |
+
>
|
| 290 |
+
<X className="h-4 w-4" />
|
| 291 |
+
</Button>
|
| 292 |
+
</div>
|
| 293 |
+
</CardContent>
|
| 294 |
+
</Card>
|
| 295 |
+
) : null}
|
| 296 |
+
</div>
|
| 297 |
+
)
|
| 298 |
+
}
|
frontend/src/components/ui/input.tsx
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import * as React from "react"
|
| 2 |
+
import { cn } from "../../lib/utils"
|
| 3 |
+
|
| 4 |
+
export interface InputProps
|
| 5 |
+
extends React.InputHTMLAttributes<HTMLInputElement> {}
|
| 6 |
+
|
| 7 |
+
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
| 8 |
+
({ className, type, ...props }, ref) => {
|
| 9 |
+
return (
|
| 10 |
+
<input
|
| 11 |
+
type={type}
|
| 12 |
+
className={cn(
|
| 13 |
+
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
|
| 14 |
+
className
|
| 15 |
+
)}
|
| 16 |
+
ref={ref}
|
| 17 |
+
{...props}
|
| 18 |
+
/>
|
| 19 |
+
)
|
| 20 |
+
}
|
| 21 |
+
)
|
| 22 |
+
Input.displayName = "Input"
|
| 23 |
+
|
| 24 |
+
export { Input }
|
frontend/src/components/ui/label.tsx
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import * as React from "react"
|
| 2 |
+
import * as LabelPrimitive from "@radix-ui/react-label"
|
| 3 |
+
import { cva, type VariantProps } from "class-variance-authority"
|
| 4 |
+
|
| 5 |
+
import { cn } from "../../lib/utils"
|
| 6 |
+
|
| 7 |
+
const labelVariants = cva(
|
| 8 |
+
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
const Label = React.forwardRef<
|
| 12 |
+
React.ElementRef<typeof LabelPrimitive.Root>,
|
| 13 |
+
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
|
| 14 |
+
VariantProps<typeof labelVariants>
|
| 15 |
+
>(({ className, ...props }, ref) => (
|
| 16 |
+
<LabelPrimitive.Root
|
| 17 |
+
ref={ref}
|
| 18 |
+
className={cn(labelVariants(), className)}
|
| 19 |
+
{...props}
|
| 20 |
+
/>
|
| 21 |
+
))
|
| 22 |
+
Label.displayName = LabelPrimitive.Root.displayName
|
| 23 |
+
|
| 24 |
+
export { Label }
|
frontend/src/components/ui/popover.tsx
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// 此文件已弃用 - 日期选择器现在使用自定义实现
|
| 2 |
+
// 保留此文件以避免导入错误
|
frontend/src/components/ui/select.tsx
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import * as React from "react"
|
| 2 |
+
import * as SelectPrimitive from "@radix-ui/react-select"
|
| 3 |
+
import { Check, ChevronDown, ChevronUp } from "lucide-react"
|
| 4 |
+
|
| 5 |
+
import { cn } from "../../lib/utils"
|
| 6 |
+
|
| 7 |
+
const Select = SelectPrimitive.Root
|
| 8 |
+
|
| 9 |
+
const SelectGroup = SelectPrimitive.Group
|
| 10 |
+
|
| 11 |
+
const SelectValue = SelectPrimitive.Value
|
| 12 |
+
|
| 13 |
+
const SelectTrigger = React.forwardRef<
|
| 14 |
+
React.ElementRef<typeof SelectPrimitive.Trigger>,
|
| 15 |
+
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
|
| 16 |
+
>(({ className, children, ...props }, ref) => (
|
| 17 |
+
<SelectPrimitive.Trigger
|
| 18 |
+
ref={ref}
|
| 19 |
+
className={cn(
|
| 20 |
+
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
|
| 21 |
+
className
|
| 22 |
+
)}
|
| 23 |
+
{...props}
|
| 24 |
+
>
|
| 25 |
+
{children}
|
| 26 |
+
<SelectPrimitive.Icon asChild>
|
| 27 |
+
<ChevronDown className="h-4 w-4 opacity-50" />
|
| 28 |
+
</SelectPrimitive.Icon>
|
| 29 |
+
</SelectPrimitive.Trigger>
|
| 30 |
+
))
|
| 31 |
+
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
|
| 32 |
+
|
| 33 |
+
const SelectScrollUpButton = React.forwardRef<
|
| 34 |
+
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
|
| 35 |
+
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
|
| 36 |
+
>(({ className, ...props }, ref) => (
|
| 37 |
+
<SelectPrimitive.ScrollUpButton
|
| 38 |
+
ref={ref}
|
| 39 |
+
className={cn(
|
| 40 |
+
"flex cursor-default items-center justify-center py-1",
|
| 41 |
+
className
|
| 42 |
+
)}
|
| 43 |
+
{...props}
|
| 44 |
+
>
|
| 45 |
+
<ChevronUp className="h-4 w-4" />
|
| 46 |
+
</SelectPrimitive.ScrollUpButton>
|
| 47 |
+
))
|
| 48 |
+
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
|
| 49 |
+
|
| 50 |
+
const SelectScrollDownButton = React.forwardRef<
|
| 51 |
+
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
|
| 52 |
+
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
|
| 53 |
+
>(({ className, ...props }, ref) => (
|
| 54 |
+
<SelectPrimitive.ScrollDownButton
|
| 55 |
+
ref={ref}
|
| 56 |
+
className={cn(
|
| 57 |
+
"flex cursor-default items-center justify-center py-1",
|
| 58 |
+
className
|
| 59 |
+
)}
|
| 60 |
+
{...props}
|
| 61 |
+
>
|
| 62 |
+
<ChevronDown className="h-4 w-4" />
|
| 63 |
+
</SelectPrimitive.ScrollDownButton>
|
| 64 |
+
))
|
| 65 |
+
SelectScrollDownButton.displayName =
|
| 66 |
+
SelectPrimitive.ScrollDownButton.displayName
|
| 67 |
+
|
| 68 |
+
const SelectContent = React.forwardRef<
|
| 69 |
+
React.ElementRef<typeof SelectPrimitive.Content>,
|
| 70 |
+
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
|
| 71 |
+
>(({ className, children, position = "popper", ...props }, ref) => (
|
| 72 |
+
<SelectPrimitive.Portal>
|
| 73 |
+
<SelectPrimitive.Content
|
| 74 |
+
ref={ref}
|
| 75 |
+
className={cn(
|
| 76 |
+
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
| 77 |
+
position === "popper" &&
|
| 78 |
+
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
| 79 |
+
className
|
| 80 |
+
)}
|
| 81 |
+
position={position}
|
| 82 |
+
{...props}
|
| 83 |
+
>
|
| 84 |
+
<SelectScrollUpButton />
|
| 85 |
+
<SelectPrimitive.Viewport
|
| 86 |
+
className={cn(
|
| 87 |
+
"p-1",
|
| 88 |
+
position === "popper" &&
|
| 89 |
+
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
|
| 90 |
+
)}
|
| 91 |
+
>
|
| 92 |
+
{children}
|
| 93 |
+
</SelectPrimitive.Viewport>
|
| 94 |
+
<SelectScrollDownButton />
|
| 95 |
+
</SelectPrimitive.Content>
|
| 96 |
+
</SelectPrimitive.Portal>
|
| 97 |
+
))
|
| 98 |
+
SelectContent.displayName = SelectPrimitive.Content.displayName
|
| 99 |
+
|
| 100 |
+
const SelectLabel = React.forwardRef<
|
| 101 |
+
React.ElementRef<typeof SelectPrimitive.Label>,
|
| 102 |
+
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
|
| 103 |
+
>(({ className, ...props }, ref) => (
|
| 104 |
+
<SelectPrimitive.Label
|
| 105 |
+
ref={ref}
|
| 106 |
+
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
|
| 107 |
+
{...props}
|
| 108 |
+
/>
|
| 109 |
+
))
|
| 110 |
+
SelectLabel.displayName = SelectPrimitive.Label.displayName
|
| 111 |
+
|
| 112 |
+
const SelectItem = React.forwardRef<
|
| 113 |
+
React.ElementRef<typeof SelectPrimitive.Item>,
|
| 114 |
+
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
|
| 115 |
+
>(({ className, children, ...props }, ref) => (
|
| 116 |
+
<SelectPrimitive.Item
|
| 117 |
+
ref={ref}
|
| 118 |
+
className={cn(
|
| 119 |
+
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
| 120 |
+
className
|
| 121 |
+
)}
|
| 122 |
+
{...props}
|
| 123 |
+
>
|
| 124 |
+
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
|
| 125 |
+
<SelectPrimitive.ItemIndicator>
|
| 126 |
+
<Check className="h-4 w-4" />
|
| 127 |
+
</SelectPrimitive.ItemIndicator>
|
| 128 |
+
</span>
|
| 129 |
+
|
| 130 |
+
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
| 131 |
+
</SelectPrimitive.Item>
|
| 132 |
+
))
|
| 133 |
+
SelectItem.displayName = SelectPrimitive.Item.displayName
|
| 134 |
+
|
| 135 |
+
const SelectSeparator = React.forwardRef<
|
| 136 |
+
React.ElementRef<typeof SelectPrimitive.Separator>,
|
| 137 |
+
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
|
| 138 |
+
>(({ className, ...props }, ref) => (
|
| 139 |
+
<SelectPrimitive.Separator
|
| 140 |
+
ref={ref}
|
| 141 |
+
className={cn("-mx-1 my-1 h-px bg-muted", className)}
|
| 142 |
+
{...props}
|
| 143 |
+
/>
|
| 144 |
+
))
|
| 145 |
+
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
|
| 146 |
+
|
| 147 |
+
export {
|
| 148 |
+
Select,
|
| 149 |
+
SelectGroup,
|
| 150 |
+
SelectValue,
|
| 151 |
+
SelectTrigger,
|
| 152 |
+
SelectContent,
|
| 153 |
+
SelectLabel,
|
| 154 |
+
SelectItem,
|
| 155 |
+
SelectSeparator,
|
| 156 |
+
SelectScrollUpButton,
|
| 157 |
+
SelectScrollDownButton,
|
| 158 |
+
}
|
frontend/src/components/ui/switch.tsx
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import * as React from "react"
|
| 2 |
+
import * as SwitchPrimitives from "@radix-ui/react-switch"
|
| 3 |
+
|
| 4 |
+
import { cn } from "../../lib/utils"
|
| 5 |
+
|
| 6 |
+
const Switch = React.forwardRef<
|
| 7 |
+
React.ElementRef<typeof SwitchPrimitives.Root>,
|
| 8 |
+
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
|
| 9 |
+
>(({ className, ...props }, ref) => (
|
| 10 |
+
<SwitchPrimitives.Root
|
| 11 |
+
className={cn(
|
| 12 |
+
"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
|
| 13 |
+
className
|
| 14 |
+
)}
|
| 15 |
+
{...props}
|
| 16 |
+
ref={ref}
|
| 17 |
+
>
|
| 18 |
+
<SwitchPrimitives.Thumb
|
| 19 |
+
className={cn(
|
| 20 |
+
"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0"
|
| 21 |
+
)}
|
| 22 |
+
/>
|
| 23 |
+
</SwitchPrimitives.Root>
|
| 24 |
+
))
|
| 25 |
+
Switch.displayName = SwitchPrimitives.Root.displayName
|
| 26 |
+
|
| 27 |
+
export { Switch }
|
frontend/src/components/ui/tabs.tsx
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import * as React from "react"
|
| 2 |
+
import * as TabsPrimitive from "@radix-ui/react-tabs"
|
| 3 |
+
|
| 4 |
+
import { cn } from "../../lib/utils"
|
| 5 |
+
|
| 6 |
+
const Tabs = TabsPrimitive.Root
|
| 7 |
+
|
| 8 |
+
const TabsList = React.forwardRef<
|
| 9 |
+
React.ElementRef<typeof TabsPrimitive.List>,
|
| 10 |
+
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
|
| 11 |
+
>(({ className, ...props }, ref) => (
|
| 12 |
+
<TabsPrimitive.List
|
| 13 |
+
ref={ref}
|
| 14 |
+
className={cn(
|
| 15 |
+
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
|
| 16 |
+
className
|
| 17 |
+
)}
|
| 18 |
+
{...props}
|
| 19 |
+
/>
|
| 20 |
+
))
|
| 21 |
+
TabsList.displayName = TabsPrimitive.List.displayName
|
| 22 |
+
|
| 23 |
+
const TabsTrigger = React.forwardRef<
|
| 24 |
+
React.ElementRef<typeof TabsPrimitive.Trigger>,
|
| 25 |
+
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
|
| 26 |
+
>(({ className, ...props }, ref) => (
|
| 27 |
+
<TabsPrimitive.Trigger
|
| 28 |
+
ref={ref}
|
| 29 |
+
className={cn(
|
| 30 |
+
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
|
| 31 |
+
className
|
| 32 |
+
)}
|
| 33 |
+
{...props}
|
| 34 |
+
/>
|
| 35 |
+
))
|
| 36 |
+
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
|
| 37 |
+
|
| 38 |
+
const TabsContent = React.forwardRef<
|
| 39 |
+
React.ElementRef<typeof TabsPrimitive.Content>,
|
| 40 |
+
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
|
| 41 |
+
>(({ className, ...props }, ref) => (
|
| 42 |
+
<TabsPrimitive.Content
|
| 43 |
+
ref={ref}
|
| 44 |
+
className={cn(
|
| 45 |
+
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
| 46 |
+
className
|
| 47 |
+
)}
|
| 48 |
+
{...props}
|
| 49 |
+
/>
|
| 50 |
+
))
|
| 51 |
+
TabsContent.displayName = TabsPrimitive.Content.displayName
|
| 52 |
+
|
| 53 |
+
export { Tabs, TabsList, TabsTrigger, TabsContent }
|
frontend/src/components/ui/toast.tsx
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import * as React from "react"
|
| 2 |
+
import * as ToastPrimitives from "@radix-ui/react-toast"
|
| 3 |
+
import { cva, type VariantProps } from "class-variance-authority"
|
| 4 |
+
import { X } from "lucide-react"
|
| 5 |
+
|
| 6 |
+
import { cn } from "../../lib/utils"
|
| 7 |
+
|
| 8 |
+
const ToastProvider = ToastPrimitives.Provider
|
| 9 |
+
|
| 10 |
+
const ToastViewport = React.forwardRef<
|
| 11 |
+
React.ElementRef<typeof ToastPrimitives.Viewport>,
|
| 12 |
+
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
|
| 13 |
+
>(({ className, ...props }, ref) => (
|
| 14 |
+
<ToastPrimitives.Viewport
|
| 15 |
+
ref={ref}
|
| 16 |
+
className={cn(
|
| 17 |
+
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
|
| 18 |
+
className
|
| 19 |
+
)}
|
| 20 |
+
{...props}
|
| 21 |
+
/>
|
| 22 |
+
))
|
| 23 |
+
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
|
| 24 |
+
|
| 25 |
+
const toastVariants = cva(
|
| 26 |
+
"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
|
| 27 |
+
{
|
| 28 |
+
variants: {
|
| 29 |
+
variant: {
|
| 30 |
+
default: "border bg-background text-foreground",
|
| 31 |
+
destructive:
|
| 32 |
+
"destructive group border-destructive bg-destructive text-destructive-foreground",
|
| 33 |
+
},
|
| 34 |
+
},
|
| 35 |
+
defaultVariants: {
|
| 36 |
+
variant: "default",
|
| 37 |
+
},
|
| 38 |
+
}
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
const Toast = React.forwardRef<
|
| 42 |
+
React.ElementRef<typeof ToastPrimitives.Root>,
|
| 43 |
+
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
|
| 44 |
+
VariantProps<typeof toastVariants>
|
| 45 |
+
>(({ className, variant, ...props }, ref) => {
|
| 46 |
+
return (
|
| 47 |
+
<ToastPrimitives.Root
|
| 48 |
+
ref={ref}
|
| 49 |
+
className={cn(toastVariants({ variant }), className)}
|
| 50 |
+
{...props}
|
| 51 |
+
/>
|
| 52 |
+
)
|
| 53 |
+
})
|
| 54 |
+
Toast.displayName = ToastPrimitives.Root.displayName
|
| 55 |
+
|
| 56 |
+
const ToastAction = React.forwardRef<
|
| 57 |
+
React.ElementRef<typeof ToastPrimitives.Action>,
|
| 58 |
+
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
|
| 59 |
+
>(({ className, ...props }, ref) => (
|
| 60 |
+
<ToastPrimitives.Action
|
| 61 |
+
ref={ref}
|
| 62 |
+
className={cn(
|
| 63 |
+
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
|
| 64 |
+
className
|
| 65 |
+
)}
|
| 66 |
+
{...props}
|
| 67 |
+
/>
|
| 68 |
+
))
|
| 69 |
+
ToastAction.displayName = ToastPrimitives.Action.displayName
|
| 70 |
+
|
| 71 |
+
const ToastClose = React.forwardRef<
|
| 72 |
+
React.ElementRef<typeof ToastPrimitives.Close>,
|
| 73 |
+
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
|
| 74 |
+
>(({ className, ...props }, ref) => (
|
| 75 |
+
<ToastPrimitives.Close
|
| 76 |
+
ref={ref}
|
| 77 |
+
className={cn(
|
| 78 |
+
"absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
|
| 79 |
+
className
|
| 80 |
+
)}
|
| 81 |
+
toast-close=""
|
| 82 |
+
{...props}
|
| 83 |
+
>
|
| 84 |
+
<X className="h-4 w-4" />
|
| 85 |
+
</ToastPrimitives.Close>
|
| 86 |
+
))
|
| 87 |
+
ToastClose.displayName = ToastPrimitives.Close.displayName
|
| 88 |
+
|
| 89 |
+
const ToastTitle = React.forwardRef<
|
| 90 |
+
React.ElementRef<typeof ToastPrimitives.Title>,
|
| 91 |
+
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
|
| 92 |
+
>(({ className, ...props }, ref) => (
|
| 93 |
+
<ToastPrimitives.Title
|
| 94 |
+
ref={ref}
|
| 95 |
+
className={cn("text-sm font-semibold", className)}
|
| 96 |
+
{...props}
|
| 97 |
+
/>
|
| 98 |
+
))
|
| 99 |
+
ToastTitle.displayName = ToastPrimitives.Title.displayName
|
| 100 |
+
|
| 101 |
+
const ToastDescription = React.forwardRef<
|
| 102 |
+
React.ElementRef<typeof ToastPrimitives.Description>,
|
| 103 |
+
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
|
| 104 |
+
>(({ className, ...props }, ref) => (
|
| 105 |
+
<ToastPrimitives.Description
|
| 106 |
+
ref={ref}
|
| 107 |
+
className={cn("text-sm opacity-90", className)}
|
| 108 |
+
{...props}
|
| 109 |
+
/>
|
| 110 |
+
))
|
| 111 |
+
ToastDescription.displayName = ToastPrimitives.Description.displayName
|
| 112 |
+
|
| 113 |
+
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
|
| 114 |
+
|
| 115 |
+
type ToastActionElement = React.ReactElement<typeof ToastAction>
|
| 116 |
+
|
| 117 |
+
export {
|
| 118 |
+
type ToastProps,
|
| 119 |
+
type ToastActionElement,
|
| 120 |
+
ToastProvider,
|
| 121 |
+
ToastViewport,
|
| 122 |
+
Toast,
|
| 123 |
+
ToastTitle,
|
| 124 |
+
ToastDescription,
|
| 125 |
+
ToastClose,
|
| 126 |
+
ToastAction,
|
| 127 |
+
}
|
frontend/src/components/ui/toaster.tsx
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useToast } from "../../hooks/use-toast"
|
| 2 |
+
import {
|
| 3 |
+
Toast,
|
| 4 |
+
ToastClose,
|
| 5 |
+
ToastDescription,
|
| 6 |
+
ToastProvider,
|
| 7 |
+
ToastTitle,
|
| 8 |
+
ToastViewport,
|
| 9 |
+
} from "./toast"
|
| 10 |
+
|
| 11 |
+
export function Toaster() {
|
| 12 |
+
const { toasts } = useToast()
|
| 13 |
+
|
| 14 |
+
return (
|
| 15 |
+
<ToastProvider>
|
| 16 |
+
{toasts.map(function ({ id, title, description, action, ...props }) {
|
| 17 |
+
return (
|
| 18 |
+
<Toast key={id} {...props}>
|
| 19 |
+
<div className="grid gap-1">
|
| 20 |
+
{title && <ToastTitle>{title}</ToastTitle>}
|
| 21 |
+
{description && (
|
| 22 |
+
<ToastDescription>{description}</ToastDescription>
|
| 23 |
+
)}
|
| 24 |
+
</div>
|
| 25 |
+
{action}
|
| 26 |
+
<ToastClose />
|
| 27 |
+
</Toast>
|
| 28 |
+
)
|
| 29 |
+
})}
|
| 30 |
+
<ToastViewport />
|
| 31 |
+
</ToastProvider>
|
| 32 |
+
)
|
| 33 |
+
}
|
frontend/src/hooks/use-toast.ts
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import * as React from "react"
|
| 2 |
+
|
| 3 |
+
import type { ToastActionElement, ToastProps } from "../components/ui/toast"
|
| 4 |
+
|
| 5 |
+
const TOAST_LIMIT = 1
|
| 6 |
+
const TOAST_REMOVE_DELAY = 1000000
|
| 7 |
+
|
| 8 |
+
type ToasterToast = ToastProps & {
|
| 9 |
+
id: string
|
| 10 |
+
title?: React.ReactNode
|
| 11 |
+
description?: React.ReactNode
|
| 12 |
+
action?: ToastActionElement
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
const actionTypes = {
|
| 16 |
+
ADD_TOAST: "ADD_TOAST",
|
| 17 |
+
UPDATE_TOAST: "UPDATE_TOAST",
|
| 18 |
+
DISMISS_TOAST: "DISMISS_TOAST",
|
| 19 |
+
REMOVE_TOAST: "REMOVE_TOAST",
|
| 20 |
+
} as const
|
| 21 |
+
|
| 22 |
+
let count = 0
|
| 23 |
+
|
| 24 |
+
function genId() {
|
| 25 |
+
count = (count + 1) % Number.MAX_SAFE_INTEGER
|
| 26 |
+
return count.toString()
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
type ActionType = typeof actionTypes
|
| 30 |
+
|
| 31 |
+
type Action =
|
| 32 |
+
| {
|
| 33 |
+
type: ActionType["ADD_TOAST"]
|
| 34 |
+
toast: ToasterToast
|
| 35 |
+
}
|
| 36 |
+
| {
|
| 37 |
+
type: ActionType["UPDATE_TOAST"]
|
| 38 |
+
toast: Partial<ToasterToast>
|
| 39 |
+
}
|
| 40 |
+
| {
|
| 41 |
+
type: ActionType["DISMISS_TOAST"]
|
| 42 |
+
toastId?: ToasterToast["id"]
|
| 43 |
+
}
|
| 44 |
+
| {
|
| 45 |
+
type: ActionType["REMOVE_TOAST"]
|
| 46 |
+
toastId?: ToasterToast["id"]
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
interface State {
|
| 50 |
+
toasts: ToasterToast[]
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
|
| 54 |
+
|
| 55 |
+
const addToRemoveQueue = (toastId: string) => {
|
| 56 |
+
if (toastTimeouts.has(toastId)) {
|
| 57 |
+
return
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
const timeout = setTimeout(() => {
|
| 61 |
+
toastTimeouts.delete(toastId)
|
| 62 |
+
dispatch({
|
| 63 |
+
type: "REMOVE_TOAST",
|
| 64 |
+
toastId: toastId,
|
| 65 |
+
})
|
| 66 |
+
}, TOAST_REMOVE_DELAY)
|
| 67 |
+
|
| 68 |
+
toastTimeouts.set(toastId, timeout)
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
export const reducer = (state: State, action: Action): State => {
|
| 72 |
+
switch (action.type) {
|
| 73 |
+
case "ADD_TOAST":
|
| 74 |
+
return {
|
| 75 |
+
...state,
|
| 76 |
+
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
case "UPDATE_TOAST":
|
| 80 |
+
return {
|
| 81 |
+
...state,
|
| 82 |
+
toasts: state.toasts.map((t) =>
|
| 83 |
+
t.id === action.toast.id ? { ...t, ...action.toast } : t
|
| 84 |
+
),
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
case "DISMISS_TOAST": {
|
| 88 |
+
const { toastId } = action
|
| 89 |
+
|
| 90 |
+
if (toastId) {
|
| 91 |
+
addToRemoveQueue(toastId)
|
| 92 |
+
} else {
|
| 93 |
+
state.toasts.forEach((toast) => {
|
| 94 |
+
addToRemoveQueue(toast.id)
|
| 95 |
+
})
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
return {
|
| 99 |
+
...state,
|
| 100 |
+
toasts: state.toasts.map((t) =>
|
| 101 |
+
t.id === toastId || toastId === undefined
|
| 102 |
+
? {
|
| 103 |
+
...t,
|
| 104 |
+
open: false,
|
| 105 |
+
}
|
| 106 |
+
: t
|
| 107 |
+
),
|
| 108 |
+
}
|
| 109 |
+
}
|
| 110 |
+
case "REMOVE_TOAST":
|
| 111 |
+
if (action.toastId === undefined) {
|
| 112 |
+
return {
|
| 113 |
+
...state,
|
| 114 |
+
toasts: [],
|
| 115 |
+
}
|
| 116 |
+
}
|
| 117 |
+
return {
|
| 118 |
+
...state,
|
| 119 |
+
toasts: state.toasts.filter((t) => t.id !== action.toastId),
|
| 120 |
+
}
|
| 121 |
+
}
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
const listeners: Array<(state: State) => void> = []
|
| 125 |
+
|
| 126 |
+
let memoryState: State = { toasts: [] }
|
| 127 |
+
|
| 128 |
+
function dispatch(action: Action) {
|
| 129 |
+
memoryState = reducer(memoryState, action)
|
| 130 |
+
listeners.forEach((listener) => {
|
| 131 |
+
listener(memoryState)
|
| 132 |
+
})
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
type Toast = Omit<ToasterToast, "id">
|
| 136 |
+
|
| 137 |
+
function toast({ ...props }: Toast) {
|
| 138 |
+
const id = genId()
|
| 139 |
+
|
| 140 |
+
const update = (props: ToasterToast) =>
|
| 141 |
+
dispatch({
|
| 142 |
+
type: "UPDATE_TOAST",
|
| 143 |
+
toast: { ...props, id },
|
| 144 |
+
})
|
| 145 |
+
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
|
| 146 |
+
|
| 147 |
+
dispatch({
|
| 148 |
+
type: "ADD_TOAST",
|
| 149 |
+
toast: {
|
| 150 |
+
...props,
|
| 151 |
+
id,
|
| 152 |
+
open: true,
|
| 153 |
+
onOpenChange: (open) => {
|
| 154 |
+
if (!open) dismiss()
|
| 155 |
+
},
|
| 156 |
+
},
|
| 157 |
+
})
|
| 158 |
+
|
| 159 |
+
return {
|
| 160 |
+
id: id,
|
| 161 |
+
dismiss,
|
| 162 |
+
update,
|
| 163 |
+
}
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
function useToast() {
|
| 167 |
+
const [state, setState] = React.useState<State>(memoryState)
|
| 168 |
+
|
| 169 |
+
React.useEffect(() => {
|
| 170 |
+
listeners.push(setState)
|
| 171 |
+
return () => {
|
| 172 |
+
const index = listeners.indexOf(setState)
|
| 173 |
+
if (index > -1) {
|
| 174 |
+
listeners.splice(index, 1)
|
| 175 |
+
}
|
| 176 |
+
}
|
| 177 |
+
}, [state])
|
| 178 |
+
|
| 179 |
+
return {
|
| 180 |
+
...state,
|
| 181 |
+
toast,
|
| 182 |
+
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
|
| 183 |
+
}
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
export { useToast, toast }
|