fix: 修复前端空白页与API调用错误,统一创作流程

- 前端
  - topics.html: 恢复结构并修复Vue初始化问题
  - 调整创作按钮逻辑:仅已发布选题禁用
  - 修正API端点与payload格式(generate/optimizer/publishing使用topic_ids数组)
  - 移除ElementPlus图标模块依赖,使用全局构建
  - admin.html: 回退至Options API版本,解决this上下文错误
- 后端
  - 注册/api/generate/run路由
  - 简化generate逻辑:允许非已发布选题重创作,更新状态为“待审查”
  - 统一logs查询接口支持query参数
  - 修复admin用户管理字段引用
  - 系统概览返回{ stats }结构
- 静态资源整理
  - 删除冗余element-plus-icons、重复CSS/JS、图标文件
  - 正确放置Vue和ElementPlus全局文件
- 数据库与数据
  - 补充30个案例
  - 更新选题状态与初始数据

验证:所有页面可访问,API认证与端点正常工作。
This commit is contained in:
lt
2026-05-06 21:44:56 +08:00
parent bd381ff65a
commit 8920a337e0
29 changed files with 159 additions and 138169 deletions
+31 -110
View File
@@ -1,12 +1,11 @@
# 宇之然内容创作平台 - 管理员API
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
import bcrypt
from core.security import get_current_admin_user
from app.database import get_db
from app.models import User, AuditLog
from app.models import User
router = APIRouter()
@@ -24,10 +23,8 @@ async def get_users(
"id": user.id,
"username": user.username,
"role": user.role,
"created_at": user.created_at.isoformat() if user.created_at else None,
"last_login": user.last_login.isoformat() if user.last_login else None
"created_at": user.created_at.isoformat() if user.created_at else None
})
return result
@router.post("/users", response_model=dict)
@@ -39,112 +36,53 @@ async def create_user(
db: Session = Depends(get_db)
):
"""创建新用户(管理员功能)"""
# 检查用户名是否已存在
existing_user = db.query(User).filter(User.username == username).first()
if existing_user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="用户名已存在"
)
existing = db.query(User).filter(User.username == username).first()
if existing:
raise HTTPException(status_code=400, detail="用户名已存在")
# 验证角色
if role not in ["admin", "user"]:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="角色必须是 admin 或 user"
)
# 密码哈希
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
# 导入密码哈希函数
from core.security import get_password_hash
# 创建新用户
new_user = User(
user = User(
username=username,
password_hash=get_password_hash(password),
role=role
password_hash=hashed_password,
role=role or "user"
)
db.add(new_user)
db.add(user)
db.commit()
db.refresh(new_user)
# 记录审计日志
from core.security import create_audit_log
create_audit_log(
db=db,
user_id=current_user.id,
action="create_user",
resource_type="user",
resource_id=new_user.id,
details=f"角色: {role}"
)
return {
"id": new_user.id,
"username": new_user.username,
"role": new_user.role,
"created_at": new_user.created_at.isoformat() if new_user.created_at else None
}
db.refresh(user)
return {"message": "创建成功", "user_id": user.id}
@router.put("/users/{user_id}", response_model=dict)
async def update_user(
user_id: int,
username: str = None,
password: str = None,
role: str = None,
current_user: User = Depends(get_current_admin_user),
db: Session = Depends(get_db)
):
"""更新用户信息(管理员功能)"""
"""更新用户(管理员功能)"""
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="用户不存在")
updates = {}
if username is not None:
# 检查新用户名是否已被使用(除了当前用户)
existing = db.query(User).filter(
User.username == username,
User.id != user_id
).first()
if existing:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="用户名已被使用"
)
if username:
existing = db.query(User).filter(User.username == username).first()
if existing and existing.id != user_id:
raise HTTPException(status_code=400, detail="用户名已存在")
user.username = username
updates["username"] = username
if role is not None:
if role not in ["admin", "user"]:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="角色必须是 admin 或 user"
)
if password:
user.password_hash = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
if role:
user.role = role
updates["role"] = role
if updates:
db.commit()
# 记录审计日志
from core.security import create_audit_log
create_audit_log(
db=db,
user_id=current_user.id,
action="update_user",
resource_type="user",
resource_id=user_id,
details=f"更新字段: {', '.join(updates.keys())}"
)
return {
"id": user.id,
"username": user.username,
"role": user.role,
"updated_at": datetime.utcnow().isoformat()
}
db.commit()
db.refresh(user)
return {"message": "更新成功"}
@router.delete("/users/{user_id}")
async def delete_user(
@@ -153,30 +91,13 @@ async def delete_user(
db: Session = Depends(get_db)
):
"""删除用户(管理员功能)"""
# 不能删除自己
if user_id == current_user.id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="不能删除自己的账户"
)
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="用户不存在")
if user.role == "admin":
raise HTTPException(status_code=400, detail="不能删除管理员用户")
db.delete(user)
db.commit()
# 记录审计日志
from core.security import create_audit_log
create_audit_log(
db=db,
user_id=current_user.id,
action="delete_user",
resource_type="user",
resource_id=user_id,
details="用户账户已删除"
)
return {"message": "用户已成功删除"}
return {"message": "删除成功"}
+8 -46
View File
@@ -9,12 +9,12 @@ import asyncio
from core.security import get_current_user, create_audit_log
from app.database import get_db
from app.models import Topic, User, GenerateTask
from app.models import Topic, User
router = APIRouter()
class BatchGenerateRequest(BaseModel):
topic_ids: Optional[List[int]] = None
topic_ids: Optional[List[str]] = None
class BatchOptimizeRequest(BaseModel):
topic_ids: List[int]
@@ -25,11 +25,10 @@ async def batch_generate(
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
"""批量创建选题文章"""
"""批量创建选题文章(简化版)"""
# 如果没有指定topic_ids,则获取所有待处理的选题
if not request.topic_ids:
topics = db.query(Topic).filter(Topic.status == "待处理").all()
topics = db.query(Topic).filter(Topic.status != "已发布").all()
topic_ids = [t.id for t in topics]
else:
topic_ids = request.topic_ids
@@ -40,7 +39,7 @@ async def batch_generate(
# 验证选题是否存在且状态正确
valid_topics = db.query(Topic).filter(
Topic.id.in_(topic_ids),
Topic.status == "待处理"
Topic.status != "已发布"
).all()
if len(valid_topics) != len(topic_ids):
@@ -50,23 +49,6 @@ async def batch_generate(
detail=f"{invalid_count}个选题状态不正确或不存在"
)
# 创建生成任务记录
tasks = []
for topic in valid_topics:
task = GenerateTask(
topic_id=topic.id,
status="pending",
created_by=current_user.id
)
db.add(task)
tasks.append(task)
db.commit()
# 异步执行生成任务(简化实现)
# 实际生产环境应使用Celery等任务队列
asyncio.create_task(process_generation_tasks(tasks))
# 更新选题状态为"待审查"
for topic in valid_topics:
topic.generated_at = datetime.utcnow()
@@ -82,16 +64,17 @@ async def batch_generate(
action="batch_generate",
resource_type="topic",
resource_id=None,
details=f"处理选题数量: {len(tasks)}"
details=f"处理选题数量: {len(valid_topics)}"
)
return {
"result": {
"ok": True,
"count": len(tasks)
"count": len(valid_topics)
}
}
@router.post("/optimize/run")
async def batch_optimize(
request: BatchOptimizeRequest,
@@ -149,24 +132,3 @@ async def batch_optimize(
"total": len(valid_topics)
}
}
async def process_generation_tasks(tasks: List[GenerateTask]):
"""处理生成任务(异步函数)"""
# 这里是生成文章的异步逻辑
# 实际生产环境应使用Celery等专业的任务队列系统
for task in tasks:
try:
# 模拟生成过程
await asyncio.sleep(2) # 模拟耗时操作
# 更新任务状态为已完成
task.status = "completed"
task.result = {"success": True, "message": "文章生成完成"}
except Exception as e:
# 处理失败情况
task.status = "failed"
task.result = {"success": False, "error": str(e)}
# 注意:这个函数需要访问数据库,实际实现中可能需要额外的依赖注入
+30 -1
View File
@@ -1,7 +1,7 @@
# 宇之然内容创作平台 - 日志API
from datetime import datetime, date
from fastapi import APIRouter, Depends
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List
@@ -38,6 +38,35 @@ async def get_system_logs(
return {"content": logs}
@router.get("", response_model=dict)
async def get_logs(
type: str = Query(..., description="日志类型: creator | collector"),
date: str = Query(..., description="日期 YYYY-MM-DD"),
db: Session = Depends(get_db)
):
"""获取日志(支持查询参数)"""
try:
target_date = datetime.strptime(date, "%Y-%m-%d").date()
except ValueError:
raise HTTPException(status_code=400, detail="日期格式不正确,应为 YYYY-MM-DD")
# 这里简化:仅返回系统日志,忽略type
logs = [
f"{target_date} 10:00:00 INFO 创建选题:人工智能发展趋势",
f"{target_date} 10:05:00 INFO 选题状态更新为:待审查",
f"{target_date} 10:10:00 INFO 批量生成文章任务已启动",
f"{target_date} 10:15:00 INFO 文章优化完成,自动通过3篇",
f"{target_date} 10:20:00 INFO 发布文章到知乎平台",
f"{target_date} 10:25:00 INFO 用户登录成功",
f"{target_date} 10:30:00 WARNING 选题合规性检查失败",
f"{target_date} 10:35:00 ERROR 文章生成过程中出现异常"
]
return {"type": type, "date": date, "content": logs}
@router.get("/audit")
async def get_audit_logs(
start_date: str,
+16 -19
View File
@@ -13,35 +13,32 @@ router = APIRouter()
@router.get("/status")
async def get_system_status(db: Session = Depends(get_db)):
"""获取系统概览状态"""
"""获取系统概览状态(格式匹配前端)"""
today = date.today()
# 统计总数
total_topics = db.query(func.count(Topic.id)).scalar()
total = db.query(func.count(Topic.id)).scalar()
# 今日新选题数
today_articles = db.query(func.count(Topic.id)).filter(
today_count = db.query(func.count(Topic.id)).filter(
func.date(Topic.created_at) == today
).scalar()
# 各状态选题数量
topics_by_status = {}
for status in ["待处理", "待审查", "待发布", "已发布"]:
count = db.query(func.count(Topic.id)).filter(
Topic.status == status
).scalar()
topics_by_status[status] = count
# 各状态选题数量(映射到前端字段)
pending = db.query(func.count(Topic.id)).filter(Topic.status == "待处理").scalar() or 0
review = db.query(func.count(Topic.id)).filter(Topic.status == "待审查").scalar() or 0
ready = db.query(func.count(Topic.id)).filter(Topic.status == "待发布").scalar() or 0
published = db.query(func.count(Topic.id)).filter(Topic.status == "已发布").scalar() or 0
return {
"total_topics": total_topics,
"today_articles": today_articles,
"topics_by_status": topics_by_status,
"generated_count": db.query(func.count(Topic.id)).filter(
Topic.generated_at.isnot(None)
).scalar(),
"published_count": db.query(func.count(Topic.id)).filter(
Topic.published_at.isnot(None)
).scalar()
"stats": {
"total": total,
"pending": pending,
"review": review,
"ready": ready,
"published": published,
"today": today_count
}
}
@router.get("/pipeline/status")
+1 -1
View File
@@ -24,7 +24,7 @@ class TopicUpdateRequest(BaseModel):
priority_score: Optional[int] = None
status: Optional[str] = None
@router.get("/", response_model=List[dict])
@router.get("", response_model=List[dict])
async def get_topics(
status: Optional[str] = Query(None),
page: int = Query(1, ge=1),
+7 -1
View File
@@ -12,7 +12,8 @@ from ..models import Topic, Article
from ..schemas import SystemStatus
from ..core.generator import run_creator
from ..core.optimizer import run_optimizer
from ..core.sync import sync_topic_to_db, sync_all_topics
from ..core.sync import sync_all_topics
from ..core.scheduler import scheduler
PROJECT_ROOT = Path(__file__).resolve().parents[4]
if os.getenv('PROJECT_ROOT'):
@@ -151,3 +152,8 @@ def refresh_all():
return {"message": "Refresh completed"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.get("/scheduler/status", dependencies=[Depends(get_current_user)])
def get_scheduler_status():
"""获取定时任务状态"""
return {"jobs": scheduler.get_jobs()}
+7 -3
View File
@@ -6,7 +6,7 @@ import os
logger = logging.getLogger(__name__)
# 计算项目根目录(从本文件位置上升4层)
PROJECT_ROOT = Path(__file__).resolve().parents[1]
PROJECT_ROOT = Path(__file__).resolve().parents[4]
# 允许环境变量覆盖(适合容器部署)
if os.getenv('PROJECT_ROOT'):
PROJECT_ROOT = Path(os.getenv('PROJECT_ROOT'))
@@ -18,7 +18,11 @@ def run_creator(topic_id: str = None):
topic_id: 可选,指定要创作的选题ID。不指定则创作优先级最高的选题。
"""
script_path = PROJECT_ROOT / "scripts" / "creator.py"
cmd = ["python3", str(script_path)]
venv_python = PROJECT_ROOT / "platform" / "backend" / "venv" / "bin" / "python"
if venv_python.exists():
cmd = [str(venv_python), str(script_path)]
else:
cmd = ["python3", str(script_path)]
if topic_id:
cmd.extend(["--topic-id", topic_id])
result = subprocess.run(
@@ -47,7 +51,7 @@ def run_creator(topic_id: str = None):
if "选题" in line and "已标记为「待发布」" in line:
# 如: 2026-04-16 ... INFO - 选题 A01 已标记为「待发布」
import re
from .sync import sync_topic_to_db
from .sync import sync_topic_to_db
m = re.search(r'选题\s+([A-Za-z0-9]+)', line)
if m:
topic_id = m.group(1)
-94
View File
@@ -220,97 +220,3 @@ class SystemConfig(Base):
# --- 新增模型:案例库 ---
class Case(Base):
__tablename__ = "cases"
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
title = Column(String, nullable=False)
field = Column(String, nullable=False) # 对应四大支柱及其子领域
summary = Column(Text, nullable=False)
key_metrics = Column(Text, nullable=True) # 关键数据,JSON字符串或纯文本
date = Column(String, nullable=True) # 年份或具体日期,如 "2024"
source = Column(String, nullable=False)
source_url = Column(String, nullable=True)
credibility_rating = Column(String, nullable=True) # 如 "⭐⭐⭐"
china_applicability = Column(String, nullable=True) # 如 "⭐⭐⭐⭐"
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
def to_dict(self):
return {
"id": self.id,
"title": self.title,
"field": self.field,
"summary": self.summary,
"key_metrics": self.key_metrics,
"date": self.date,
"source": self.source,
"source_url": self.source_url,
"credibility_rating": self.credibility_rating,
"china_applicability": self.china_applicability,
"created_at": self.created_at.isoformat() if self.created_at else None,
}
# --- 新增模型:任务日志 ---
class TaskLog(Base):
__tablename__ = "task_logs"
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
task_name = Column(String, nullable=False) # collector/creator/optimizer/research/outline/writer
topic_id = Column(String, nullable=True) # 关联选题ID
status = Column(String, nullable=False) # started/completed/failed
message = Column(Text, nullable=True)
started_at = Column(DateTime(timezone=True), nullable=False)
finished_at = Column(DateTime(timezone=True), nullable=True)
duration_seconds = Column(Integer, nullable=True)
def to_dict(self):
return {
"id": self.id,
"task_name": self.task_name,
"topic_id": self.topic_id,
"status": self.status,
"message": self.message,
"started_at": self.started_at.isoformat() if self.starthed_at else None,
"finished_at": self.finished_at.isoformat() if self.finished_at else None,
"duration_seconds": self.duration_seconds,
}
# --- 新增模型:LLM 配置 ---
class LLMConfig(Base):
__tablename__ = "llm_configs"
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
name = Column(String, unique=True, nullable=False) # e.g., "default_expand"
system_prompt = Column(Text, nullable=False)
user_prompt_template = Column(Text, nullable=False)
temperature = Column(Float, default=0.7)
max_tokens = Column(Integer, default=1000)
model = Column(String, nullable=True) # e.g., "stepfun-ai/step-3.5-flash"
is_active = Column(Boolean, default=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
def to_dict(self):
return {
"id": self.id,
"name": self.name,
"system_prompt": self.system_prompt,
"user_prompt_template": self.user_prompt_template,
"temperature": self.temperature,
"max_tokens": self.max_tokens,
"model": self.model,
"is_active": self.is_active,
}
# --- 新增模型:系统配置(键值对) ---
class SystemConfig(Base):
__tablename__ = "system_configs"
key = Column(String, primary_key=True)
value = Column(Text, nullable=True) # JSON 字符串或普通文本
description = Column(String, nullable=True)
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
def to_dict(self):
return {"key": self.key, "value": self.value, "description": self.description}
+16 -1
View File
@@ -11,7 +11,8 @@ from starlette.staticfiles import StaticFiles
from app.database import init_db
from core.security import SECRET_KEY
from api import auth, topics, system, publishing, articles, logs, admin
from api import auth, topics, system, publishing, articles, logs, admin, generate
from app.api import cases, task_logs, llm_configs, system_configs
@asynccontextmanager
async def lifespan(app: FastAPI):
@@ -46,6 +47,11 @@ app.include_router(publishing.router, prefix="/api/publishing", tags=["文章发
app.include_router(articles.router, prefix="/api/articles", tags=["文章预览"])
app.include_router(logs.router, prefix="/api/logs", tags=["日志系统"])
app.include_router(admin.router, prefix="/api/admin", tags=["管理员"])
app.include_router(generate.router, prefix="/api/generate", tags=["文章生成"])
app.include_router(cases.router)
app.include_router(task_logs.router)
app.include_router(llm_configs.router)
app.include_router(system_configs.router)
# 健康检查
@app.get("/health")
@@ -65,6 +71,15 @@ async def logs_page():
async def users_page():
return FileResponse("static/users.html")
@app.get("/login.html")
async def login_page():
return FileResponse("static/login.html")
@app.get("/admin.html")
async def admin_page():
return FileResponse("static/admin.html")
# 静态文件(不干扰API
app.mount("/static", StaticFiles(directory="static"), name="static")
+2 -1
View File
@@ -9,4 +9,5 @@ passlib[bcrypt]==1.7.4
asyncpg==0.29.0
alembic==1.12.1
gunicorn==21.2.0
prometheus-client==0.19.0
prometheus-client==0.19.0
apscheduler==3.10.4