feat: GEO/SEO structured data + search ranking tracker

This commit is contained in:
Yuzhiran Dev
2026-06-09 17:18:09 +08:00
parent 23ff63baa9
commit 8595bbc521
26 changed files with 961 additions and 51 deletions
+4
View File
@@ -78,6 +78,8 @@ def update_user(
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="用户不存在")
if admin_user.role != "admin" and user.org_id != admin_user.org_id:
raise HTTPException(status_code=404, detail="用户不存在")
changes = {}
if user_update.username is not None:
@@ -122,6 +124,8 @@ def delete_user(
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="用户不存在")
if admin_user.role != "admin" and user.org_id != admin_user.org_id:
raise HTTPException(status_code=404, detail="用户不存在")
if user.role == "admin":
raise HTTPException(status_code=400, detail="不能删除管理员用户")
+2
View File
@@ -83,6 +83,8 @@ def get_article_detail(article_id: str, current_user: User = Depends(get_current
"topic_title": topic.title if topic else None,
"platform": article.platform,
"file_path": article.file_path,
"title": article.title,
"content": article.content,
"status": article.status,
"compliance_score": article.compliance_score,
"word_count": article.word_count,
+23 -5
View File
@@ -10,7 +10,7 @@ from typing import List, Optional
from ..database import get_db
from ..models import MediaAsset
from ..schemas import MediaAssetCreate, MediaAssetUpdate, MediaAssetResponse
from .auth import get_current_user
from .auth import get_current_user, org_filter
router = APIRouter(prefix="/api/assets", tags=["assets"])
@@ -33,6 +33,9 @@ def list_assets(
current_user=Depends(get_current_user)
):
query = db.query(MediaAsset)
of = org_filter(current_user, MediaAsset)
if of is not True:
query = query.filter(of)
if file_type:
query = query.filter(MediaAsset.file_type == file_type)
@@ -54,7 +57,11 @@ def list_tags(
db: Session = Depends(get_db),
current_user=Depends(get_current_user)
):
assets = db.query(MediaAsset.tags).all()
of = org_filter(current_user, MediaAsset)
base = db.query(MediaAsset)
if of is not True:
base = base.filter(of)
assets = base.with_entities(MediaAsset.tags).all()
all_tags = set()
for a in assets:
if a[0]:
@@ -67,9 +74,13 @@ def get_counts(
db: Session = Depends(get_db),
current_user=Depends(get_current_user)
):
total = db.query(MediaAsset).count()
of = org_filter(current_user, MediaAsset)
base = db.query(MediaAsset)
if of is not True:
base = base.filter(of)
total = base.count()
by_type = {}
rows = db.query(MediaAsset.file_type, func.count(MediaAsset.id)).group_by(MediaAsset.file_type).all()
rows = base.with_entities(MediaAsset.file_type, func.count(MediaAsset.id)).group_by(MediaAsset.file_type).all()
for ftype, cnt in rows:
by_type[ftype] = cnt
return {"total": total, "by_type": by_type}
@@ -120,7 +131,8 @@ async def upload_asset(
alt_text=alt_text,
tags=parsed_tags,
topic_ids=parsed_topic_ids,
uploaded_by=current_user.username
uploaded_by=current_user.username,
org_id=current_user.org_id or "default",
)
db.add(asset)
db.commit()
@@ -138,6 +150,8 @@ def update_asset(
asset = db.query(MediaAsset).filter(MediaAsset.id == asset_id).first()
if not asset:
raise HTTPException(status_code=404, detail="素材不存在")
if current_user.role != "admin" and asset.org_id != current_user.org_id:
raise HTTPException(status_code=404, detail="素材不存在")
for k, v in data.model_dump(exclude_unset=True).items():
setattr(asset, k, v)
@@ -155,6 +169,8 @@ def delete_asset(
asset = db.query(MediaAsset).filter(MediaAsset.id == asset_id).first()
if not asset:
raise HTTPException(status_code=404, detail="素材不存在")
if current_user.role != "admin" and asset.org_id != current_user.org_id:
raise HTTPException(status_code=404, detail="素材不存在")
if os.path.exists(asset.file_path):
try:
@@ -176,6 +192,8 @@ def increment_usage(
asset = db.query(MediaAsset).filter(MediaAsset.id == asset_id).first()
if not asset:
raise HTTPException(status_code=404, detail="素材不存在")
if current_user.role != "admin" and asset.org_id != current_user.org_id:
raise HTTPException(status_code=404, detail="素材不存在")
asset.usage_count = (asset.usage_count or 0) + 1
db.commit()
return {"ok": True, "usage_count": asset.usage_count}
+14 -6
View File
@@ -15,12 +15,15 @@ def list_topics(
page: int = 1,
page_size: int = 20,
status: Optional[str] = None,
field: Optional[str] = None
field: Optional[str] = None,
org_id: Optional[str] = None,
) -> Dict[str, Any]:
"""获取选题列表,支持分页和筛选"""
db = SessionLocal()
try:
query = db.query(Topic)
if org_id:
query = query.filter(Topic.org_id == org_id)
if status:
query = query.filter(Topic.status == status)
if field:
@@ -51,11 +54,14 @@ def list_topics(
db.close()
def get_topic(topic_id: str) -> Dict[str, Any]:
def get_topic(topic_id: str, org_id: Optional[str] = None) -> Dict[str, Any]:
"""获取单个选题详情"""
db = SessionLocal()
try:
t = db.query(Topic).filter(Topic.id == topic_id).first()
query = db.query(Topic).filter(Topic.id == topic_id)
if org_id:
query = query.filter(Topic.org_id == org_id)
t = query.first()
if not t:
return {"error": f"选题 {topic_id} 不存在"}
return {
@@ -191,19 +197,21 @@ def list_system_configs() -> List[Dict[str, Any]]:
ACTION_REGISTRY = {
"list_topics": {
"func": list_topics,
"description": "获取选题列表,支持分页(page, page_size)和筛选(status, field)",
"description": "获取选题列表,支持分页(page, page_size)和筛选(status, field, org_id)",
"params_schema": {
"page": {"type": "integer", "default": 1, "desc": "页码"},
"page_size": {"type": "integer", "default": 20, "desc": "每页条数"},
"status": {"type": "string", "enum": ["pending", "review", "draft", "ready", "published"], "desc": "按状态筛选"},
"field": {"type": "string", "desc": "按领域筛选"}
"field": {"type": "string", "desc": "按领域筛选"},
"org_id": {"type": "string", "desc": "按组织筛选"}
}
},
"get_topic": {
"func": get_topic,
"description": "获取单个选题详情",
"params_schema": {
"topic_id": {"type": "string", "desc": "选题ID,如 A01 或 LIVING-001-26"}
"topic_id": {"type": "string", "desc": "选题ID,如 A01 或 LIVING-001-26"},
"org_id": {"type": "string", "desc": "按组织筛选(可选)"}
}
},
"get_recent_task_logs": {
+9
View File
@@ -120,6 +120,11 @@ def update_entry(
if not entry:
raise HTTPException(status_code=404, detail="日历条目不存在")
if entry.topic_id:
topic = db.query(Topic).filter(Topic.id == entry.topic_id).first()
if topic and current_user.role != "admin" and topic.org_id != current_user.org_id:
raise HTTPException(status_code=404, detail="日历条目不存在")
for k, v in data.model_dump(exclude_unset=True).items():
setattr(entry, k, v)
db.commit()
@@ -147,6 +152,10 @@ def delete_entry(
entry = db.query(ContentCalendar).filter(ContentCalendar.id == entry_id).first()
if not entry:
raise HTTPException(status_code=404, detail="日历条目不存在")
if entry.topic_id:
topic = db.query(Topic).filter(Topic.id == entry.topic_id).first()
if topic and current_user.role != "admin" and topic.org_id != current_user.org_id:
raise HTTPException(status_code=404, detail="日历条目不存在")
db.delete(entry)
db.commit()
return {"ok": True}
+11
View File
@@ -186,6 +186,13 @@ def create_metric(
return metric
def _check_metric_org(metric, current_user, db):
"""Check if metric's topic belongs to user's org"""
topic = db.query(Topic).filter(Topic.id == metric.topic_id).first()
if topic and current_user.role != "admin" and topic.org_id != current_user.org_id:
raise HTTPException(status_code=404, detail="数据记录不存在")
@router.put("/entries/{metric_id}", response_model=ContentMetricsResponse)
def update_metric(
metric_id: int,
@@ -196,6 +203,7 @@ def update_metric(
metric = db.query(ContentMetrics).filter(ContentMetrics.id == metric_id).first()
if not metric:
raise HTTPException(status_code=404, detail="数据记录不存在")
_check_metric_org(metric, current_user, db)
for k, v in data.model_dump(exclude_unset=True).items():
setattr(metric, k, v)
@@ -214,6 +222,7 @@ def delete_metric(
metric = db.query(ContentMetrics).filter(ContentMetrics.id == metric_id).first()
if not metric:
raise HTTPException(status_code=404, detail="数据记录不存在")
_check_metric_org(metric, current_user, db)
db.delete(metric)
db.commit()
return {"ok": True}
@@ -357,6 +366,8 @@ def fetch_zhihu_metrics(
topic = db.query(Topic).filter(Topic.id == data.topic_id).first()
if not topic:
raise HTTPException(status_code=404, detail="选题不存在")
if current_user.role != "admin" and topic.org_id != current_user.org_id:
raise HTTPException(status_code=404, detail="选题不存在")
post_id = _extract_zhihu_post_id(data.zhihu_url)
@@ -0,0 +1,77 @@
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from sqlalchemy import desc, func
from typing import Optional
from datetime import datetime, timedelta, timezone
from ..database import get_db
from ..models import SearchRanking, Article, Topic
from .auth import get_current_user, org_filter
router = APIRouter(prefix="/api/seo", tags=["seo"])
ArticleModel = Article
def _apply_org_filter(query, current_user, db):
of = org_filter(current_user, ArticleModel)
if of is not True:
query = query.join(ArticleModel, SearchRanking.article_id == ArticleModel.id, isouter=True)
query = query.filter(of)
return query
@router.get("/rankings")
def get_rankings(
article_id: Optional[str] = None,
keyword: Optional[str] = None,
days: int = Query(30, ge=1, le=365),
limit: int = Query(50, ge=1, le=200),
db: Session = Depends(get_db),
current_user: dict = Depends(get_current_user),
):
"""获取搜索排名数据"""
query = db.query(SearchRanking)
query = _apply_org_filter(query, current_user, db)
if article_id:
query = query.filter(SearchRanking.article_id == article_id)
if keyword:
query = query.filter(SearchRanking.keyword.ilike(f"%{keyword}%"))
cutoff = datetime.now(timezone.utc) - timedelta(days=days)
query = query.filter(SearchRanking.checked_at >= cutoff)
rankings = query.order_by(desc(SearchRanking.checked_at)).limit(limit).all()
return {"ok": True, "data": [r.to_dict() for r in rankings]}
@router.get("/rankings/overview")
def get_rankings_overview(
days: int = Query(30, ge=1, le=365),
db: Session = Depends(get_db),
current_user: dict = Depends(get_current_user),
):
"""搜索排名概览统计"""
cutoff = datetime.now(timezone.utc) - timedelta(days=days)
base = db.query(SearchRanking)
base = _apply_org_filter(base, current_user, db)
base = base.filter(SearchRanking.checked_at >= cutoff)
total_checks = base.count()
on_page = base.filter(SearchRanking.position.isnot(None)).count()
ai_cited = base.filter(SearchRanking.ai_cited == True).count()
best = base.filter(SearchRanking.position.isnot(None)).order_by(SearchRanking.position).first()
return {
"ok": True,
"data": {
"total_checks": total_checks,
"on_page": on_page,
"ai_cited": ai_cited,
"best_position": best.position if best else None,
"best_keyword": best.keyword if best else None,
}
}
+7 -5
View File
@@ -114,7 +114,7 @@ def _aggregate_status_counts(q):
return counts
@router.get("/status")
def get_status(db: Session = Depends(get_db)):
def get_status(db: Session = Depends(get_db), current_user=Depends(get_current_user)):
total = db.query(Topic).count()
counts = _aggregate_status_counts(db.query(Topic))
today = date.today()
@@ -243,15 +243,16 @@ def get_pipeline_status(db: Session = Depends(get_db), current_user=Depends(get_
return {"topics_count": total, "status_distribution": counts, "pipeline_modules": pipeline_status}
@router.post("/sync/run")
def run_sync():
def run_sync(current_user=Depends(get_current_user)):
try:
sync_all_topics()
return {"message": "Sync completed (DB → JSON backup)"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.post("/optimize-sources/run")
def trigger_optimize_sources():
def trigger_optimize_sources(current_user=Depends(get_current_user)):
try:
from ..core.scheduler import scheduler
def _bg():
@@ -265,8 +266,9 @@ def trigger_optimize_sources():
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@router.post("/metrics-sync/run")
def trigger_metrics_sync():
def trigger_metrics_sync(current_user=Depends(get_current_user)):
try:
from ..core.scheduler import scheduler
def _bg():
@@ -330,7 +332,7 @@ def list_automation_topics(db: Session = Depends(get_db), current_user=Depends(g
raise HTTPException(status_code=500, detail=str(e))
@router.post("/refresh")
def refresh_all():
def refresh_all(current_user=Depends(get_current_user)):
try:
sync_all_topics()
return {"message": "Refresh completed"}
+23
View File
@@ -14,6 +14,16 @@ _creator_semaphore = threading.Semaphore(3)
router = APIRouter(prefix="/api/tasks", tags=["tasks"])
def _check_task_org(task, current_user, db):
"""Check if task's topic belongs to user's org"""
if current_user.role == "admin" or not task.topic_id:
return True
topic = db.query(Topic).filter(Topic.id == task.topic_id).first()
if topic and topic.org_id != current_user.org_id:
raise HTTPException(status_code=404, detail="任务不存在")
return True
@router.get("", response_model=List[ContentTaskResponse])
def list_tasks(
status: Optional[str] = None,
@@ -94,6 +104,7 @@ def get_task(
task = db.query(ContentTask).filter(ContentTask.task_id == task_id).first()
if not task:
raise HTTPException(status_code=404, detail="任务不存在")
_check_task_org(task, current_user, db)
return task
@@ -106,6 +117,7 @@ def start_task(
task = db.query(ContentTask).filter(ContentTask.task_id == task_id).first()
if not task:
raise HTTPException(status_code=404, detail="任务不存在")
_check_task_org(task, current_user, db)
from datetime import datetime, timezone
task.status = "running"
@@ -128,6 +140,7 @@ def update_progress(
task = db.query(ContentTask).filter(ContentTask.task_id == task_id).first()
if not task:
raise HTTPException(status_code=404, detail="任务不存在")
_check_task_org(task, current_user, db)
task.progress = progress
if message:
@@ -148,6 +161,7 @@ def complete_task(
task = db.query(ContentTask).filter(ContentTask.task_id == task_id).first()
if not task:
raise HTTPException(status_code=404, detail="任务不存在")
_check_task_org(task, current_user, db)
from datetime import datetime, timezone
finished = datetime.now(timezone.utc)
@@ -175,6 +189,7 @@ def fail_task(
task = db.query(ContentTask).filter(ContentTask.task_id == task_id).first()
if not task:
raise HTTPException(status_code=404, detail="任务不存在")
_check_task_org(task, current_user, db)
from datetime import datetime, timezone
finished = datetime.now(timezone.utc)
@@ -197,6 +212,7 @@ def cancel_task(
task = db.query(ContentTask).filter(ContentTask.task_id == task_id).first()
if not task:
raise HTTPException(status_code=404, detail="任务不存在")
_check_task_org(task, current_user, db)
task.status = "cancelled"
db.commit()
@@ -406,6 +422,13 @@ def run_creator_task(
):
from datetime import datetime, timezone
if topic_id:
topic = db.query(Topic).filter(Topic.id == topic_id).first()
if not topic:
raise HTTPException(status_code=404, detail="选题不存在")
if current_user.role != "admin" and topic.org_id != current_user.org_id:
raise HTTPException(status_code=404, detail="选题不存在")
now = datetime.now(timezone.utc)
task_id = f"task_{uuid.uuid4().hex[:16]}"
+63 -2
View File
@@ -9,7 +9,9 @@ from ..database import get_db
from ..models import Topic, TopicField, TopicConfigField, Article, ContentMetrics
from ..schemas import (
TopicCreate, TopicUpdate, TopicResponse, TopicScoreRequest,
TopicAnalyzeRequest, TopicAnalyzeResponse,
)
from ..core.nvidia_client import call_llm
from .auth import get_current_user, org_filter
router = APIRouter(prefix="/api/topics", tags=["topics"], dependencies=[Depends(get_current_user)])
@@ -93,6 +95,65 @@ def topic_stats(
}
@router.post("/analyze", response_model=TopicAnalyzeResponse)
def analyze_topic(
data: TopicAnalyzeRequest,
db: Session = Depends(get_db),
current_user=Depends(get_current_user)
):
"""AI 分析用户输入的选题思路,返回结构化的选题信息"""
import json, re
from sqlalchemy import text as sa_text
refs = "\n".join(f"- {link}" for link in data.reference_links) if data.reference_links else ""
prompt_text = f"""你是一个专业的内容策略师。用户提供了一个选题思路,请分析并提炼为结构化的选题信息。
用户输入的原始内容:
{data.raw_input}
参考链接(如有):
{refs}
请输出 JSON(只输出 JSON,不要其他文字):
{{
"title": "优化后的选题标题(20字内,含核心关键词,有吸引力)",
"format": "内容形式(趋势洞察/实操指南/对比分析/案例解读/观点讨论)",
"core_concept": "核心观点(一句话说清独特价值,20字内)",
"audience_pain": "受众痛点(目标读者的真实困惑或需求,20字内)",
"unique_angle": "差异化切入点(与常见文章不同的视角,20字内)",
"tags": ["标签1", "标签2", "标签3", "标签4", "标签5"]
}}"""
try:
resp = call_llm(prompt_text, temperature=0.6, max_tokens=1500)
except Exception as e:
raise HTTPException(status_code=503, detail=f"AI 分析失败: {str(e)}")
# Parse JSON from response
resp = resp.strip()
# Remove markdown code fences if present
resp = re.sub(r'^```(?:json)?\s*', '', resp)
resp = re.sub(r'\s*```$', '', resp)
parsed = json.loads(resp)
field_name = None
if data.field_id:
field = db.query(TopicField).filter(TopicField.id == data.field_id).first()
if field:
field_name = field.name
return TopicAnalyzeResponse(
title=parsed.get("title", ""),
format=parsed.get("format", ""),
core_concept=parsed.get("core_concept", ""),
audience_pain=parsed.get("audience_pain", ""),
unique_angle=parsed.get("unique_angle", ""),
field_name=field_name,
tags=parsed.get("tags", []),
priority="",
)
@router.post("", response_model=TopicResponse)
def create_topic(
data: TopicCreate,
@@ -111,7 +172,7 @@ def create_topic(
else:
topic_id = f"T{datetime.now().strftime('%m%d%H%M')}"
field_name = None
field_name = "未分类"
if data.field_id:
field = db.query(TopicField).filter(TopicField.id == data.field_id).first()
if field:
@@ -164,7 +225,7 @@ def update_topic(
topic.field_id = data.field_id
if data.field_id:
field = db.query(TopicField).filter(TopicField.id == data.field_id).first()
topic.field_name = field.name if field else None
topic.field_name = field.name if field else '未分类'
for k, v in data.model_dump(exclude_unset=True, exclude={"field_id"}).items():
if k == "tags" or k == "custom_data" or k == "scoring_data":
+37
View File
@@ -56,6 +56,7 @@ MODULES = {
"scheduled_metrics_sync": {"name": "📊 指标同步", "cron": "06:00"},
"scheduled_reset_search_usage": {"name": "🔁 搜索用量重置", "cron": "00:05"},
"scheduled_task_monitor": {"name": "⏰ 任务监控", "cron": "*"},
"scheduled_rank_tracker": {"name": "🔍 搜索排名追踪", "cron": "07:00"},
}
LOG_FILE_MAP = {
@@ -67,6 +68,7 @@ LOG_FILE_MAP = {
"scheduled_metrics_sync": "metrics_sync",
"scheduled_reset_search_usage": "reset_search_usage",
"scheduled_task_monitor": "task_monitor",
"scheduled_rank_tracker": "rank_tracker",
}
def _log_to_file(module_id: str, status: str, message: str = None, error_trace: str = None):
@@ -182,6 +184,7 @@ class TaskScheduler:
("scheduled_optimize_sources", self._run_optimize_sources, "信息源优化"),
("scheduled_metrics_sync", self._run_metrics_sync, "指标同步"),
("scheduled_reset_search_usage", self._run_reset_search_usage, "搜索用量重置"),
("scheduled_rank_tracker", self._run_rank_tracker, "搜索排名追踪"),
]
for module_id, fn, name in MODULE_JOBS:
@@ -585,6 +588,40 @@ class TaskScheduler:
started_at=started, finished_at=datetime.now(timezone.utc))
logger.exception("[TaskMonitor] 监控检查失败: %s", e)
def _run_rank_tracker(self):
"""每日搜索排名追踪(Bing 查询关键词排名)"""
started = datetime.now(timezone.utc)
log_id = _log_task("scheduled_rank_tracker", "running", started_at=started)
try:
import subprocess
result = subprocess.run(
[sys.executable, str(PROJECT_ROOT / "scripts" / "rank_tracker.py"), "--engine", "bing"],
capture_output=True, text=True, timeout=300
)
if result.returncode == 0:
try:
data = json.loads(result.stdout.strip())
except json.JSONDecodeError:
data = {}
_log_task("scheduled_rank_tracker", "success", log_id=log_id,
message=f"追踪完成: {data.get('keywords_checked', 0)} 关键词, "
f"{data.get('on_page', 0)} 条有排名",
result_data=data,
started_at=started, finished_at=datetime.now(timezone.utc))
logger.info("[RankTracker] 完成: %s", result.stdout.strip()[:200])
else:
_log_task("scheduled_rank_tracker", "failed", log_id=log_id,
message=f"返回码 {result.returncode}",
error_trace=result.stderr[-500:],
started_at=started, finished_at=datetime.now(timezone.utc))
except Exception as e:
import traceback
_log_task("scheduled_rank_tracker", "failed", log_id=log_id,
message=str(e),
error_trace=traceback.format_exc(),
started_at=started, finished_at=datetime.now(timezone.utc))
logger.exception("[RankTracker] 排名追踪失败: %s", e)
def get_jobs(self):
"""返回当前所有定时任务的状态"""
jobs = []
+3
View File
@@ -56,7 +56,10 @@ def init_db():
conn.execute(text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS images TEXT DEFAULT '{}'"))
for table, col, typ in [
("users", "org_id", "VARCHAR DEFAULT 'default'"),
("articles", "title", "VARCHAR"),
("articles", "content", "TEXT"),
("articles", "updated_at", "TIMESTAMP"),
("media_assets", "org_id", "VARCHAR DEFAULT 'default'"),
("topics", "org_id", "VARCHAR DEFAULT 'default'"),
("topics", "reviewed_at", "TIMESTAMP"),
("platform_configs", "requires_image", "BOOLEAN DEFAULT FALSE"),
+2 -1
View File
@@ -9,7 +9,7 @@ from pathlib import Path
from .database import engine, get_db, init_db
from .models import Base
from .api import topics, system, articles, publishing, auth, admin, audit, optimizer_logs, cases, task_logs, task_configs, prompt_configs, llm_configs, system_configs, topic_config, calendar, metrics, assets, tasks, platform_config, collector_mgmt, assistant, config_items, role_configs, menu_configs, search_providers
from .api import topics, system, articles, publishing, auth, admin, audit, optimizer_logs, cases, task_logs, task_configs, prompt_configs, llm_configs, system_configs, topic_config, calendar, metrics, assets, tasks, platform_config, collector_mgmt, assistant, config_items, role_configs, menu_configs, search_providers, search_rankings
from .initial_data import import_initial_data
from .core.scheduler import scheduler
@@ -104,6 +104,7 @@ app.include_router(role_configs.router)
app.include_router(menu_configs.router)
app.include_router(menu_configs.public_router)
app.include_router(search_providers.router)
app.include_router(search_rankings.router)
# 挂载自动生成的图片(必须先于前端根挂载)
PROJECT_ROOT_DIR = Path(__file__).parent.parent.parent.parent
+35
View File
@@ -282,6 +282,8 @@ class Article(Base):
topic_id = Column(String, ForeignKey("topics.id"), nullable=False)
platform = Column(String, nullable=False)
file_path = Column(String, nullable=False)
title = Column(String, nullable=True)
content = Column(Text, nullable=True)
status = Column(String, default="draft")
created_at = Column(DateTime(timezone=True), server_default=func.now())
compliance_score = Column(Integer)
@@ -410,6 +412,7 @@ class MediaAsset(Base):
topic_ids = Column(JSON, default=list)
usage_count = Column(Integer, default=0)
uploaded_by = Column(String, nullable=True)
org_id = Column(String, default="default", nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
@@ -853,4 +856,36 @@ class CollectorSource(Base):
"sort_order": self.sort_order,
"created_at": self.created_at.isoformat() if self.created_at else None,
"updated_at": self.updated_at.isoformat() if self.updated_at else None,
}
class SearchRanking(Base):
"""搜索排名追踪"""
__tablename__ = "search_rankings"
id = Column(Integer, primary_key=True, index=True, autoincrement=True)
article_id = Column(String, ForeignKey("articles.id"), nullable=True)
topic_id = Column(String, ForeignKey("topics.id"), nullable=True)
keyword = Column(String, nullable=False, index=True)
platform = Column(String, nullable=True)
search_engine = Column(String, default="bing") # bing / baidu / google
position = Column(Integer, nullable=True) # 搜索排名位置(null = 未上榜)
url_found = Column(String, nullable=True) # 被找到的具体 URL
ai_cited = Column(Boolean, default=False) # 是否被 AI 搜索引用
ai_source = Column(String, nullable=True) # AI 搜索来源名称
checked_at = Column(DateTime(timezone=True), server_default=func.now())
def to_dict(self):
return {
"id": self.id,
"article_id": self.article_id,
"topic_id": self.topic_id,
"keyword": self.keyword,
"platform": self.platform,
"search_engine": self.search_engine,
"position": self.position,
"url_found": self.url_found,
"ai_cited": self.ai_cited,
"ai_source": self.ai_source,
"checked_at": self.checked_at.isoformat() if self.checked_at else None,
}
+19
View File
@@ -92,6 +92,23 @@ class TopicCreate(BaseModel):
scoring_data: Dict[str, Any] = {}
class TopicAnalyzeRequest(BaseModel):
raw_input: str = Field(..., min_length=1, description="用户输入的选题思路/内容描述")
reference_links: List[str] = Field(default=[], description="参考链接列表(可选)")
field_id: Optional[int] = Field(default=None, description="所属领域ID(可选)")
class TopicAnalyzeResponse(BaseModel):
title: str
format: str
core_concept: str
audience_pain: str
unique_angle: str
field_name: Optional[str] = None
tags: List[str] = []
priority: str = ""
class TopicUpdate(BaseModel):
field_id: Optional[int] = None
title: Optional[str] = None
@@ -131,6 +148,8 @@ class ArticleBase(BaseModel):
topic_id: str
platform: str
file_path: str
title: Optional[str] = None
content: Optional[str] = None
status: str = "draft"
compliance_score: Optional[int] = None
word_count: Optional[int] = None
+66 -2
View File
@@ -32,6 +32,7 @@
<el-button size="default" :type="activeTab === 'logs' ? 'primary' : ''" @click="switchTab('logs')">运行日志</el-button>
<el-button size="default" :type="activeTab === 'assistant' ? 'primary' : ''" @click="switchTab('assistant')">AI 助手</el-button>
<el-button size="default" :type="activeTab === 'searchproviders' ? 'primary' : ''" @click="switchTab('searchproviders')">搜索API</el-button>
<el-button size="default" :type="activeTab === 'searchrankings' ? 'primary' : ''" @click="switchTab('searchrankings')">搜索排名</el-button>
<el-button size="default" :type="activeTab === 'configitems' ? 'primary' : ''" @click="switchTab('configitems')">配置管理</el-button>
</div>
</div>
@@ -607,6 +608,53 @@
<template #footer><el-button @click="searchProviderTestVisible = false">关闭</el-button></template>
</el-dialog>
<div v-if="activeTab === 'searchrankings'">
<div class="toolbar">
<span style="font-size:13px;color:#909399;">GEO/SEO 搜索排名追踪 — 每日 07:00 自动检查</span>
</div>
<div v-if="rankingsLoading" class="card-loading">加载中...</div>
<template v-else>
<div style="display:flex;gap:16px;margin-bottom:16px;flex-wrap:wrap;">
<div class="stat-card" style="flex:1;min-width:140px;padding:16px;background:#f0f9ff;border-radius:8px;text-align:center;">
<div style="font-size:28px;font-weight:700;color:#409eff;">{{ rankingStats.total_checks }}</div>
<div style="font-size:12px;color:#909399;margin-top:4px;">累计检查关键词</div>
</div>
<div class="stat-card" style="flex:1;min-width:140px;padding:16px;background:#f0fdf4;border-radius:8px;text-align:center;">
<div style="font-size:28px;font-weight:700;color:#67c23a;">{{ rankingStats.on_page }}</div>
<div style="font-size:12px;color:#909399;margin-top:4px;">有排名关键词</div>
</div>
<div class="stat-card" style="flex:1;min-width:140px;padding:16px;background:#fef3f2;border-radius:8px;text-align:center;">
<div style="font-size:28px;font-weight:700;color:#f56c6c;">{{ rankingStats.ai_cited }}</div>
<div style="font-size:12px;color:#909399;margin-top:4px;">AI 搜索引用</div>
</div>
<div class="stat-card" style="flex:1;min-width:140px;padding:16px;background:#fff7e6;border-radius:8px;text-align:center;">
<div style="font-size:28px;font-weight:700;color:#e6a23c;">{{ rankingStats.best_position ? '#' + rankingStats.best_position : '-' }}</div>
<div style="font-size:12px;color:#909399;margin-top:4px;">最佳排名</div>
</div>
</div>
<el-table :data="rankings" style="width:100%" size="small" max-height="500">
<el-table-column prop="keyword" label="关键词" min-width="140" />
<el-table-column prop="platform" label="平台" width="80" />
<el-table-column prop="search_engine" label="引擎" width="70" />
<el-table-column prop="position" label="排名" width="70">
<template #default="{ row }">
<el-tag :type="row.position && row.position <= 3 ? 'success' : row.position ? 'warning' : 'info'" size="small">
{{ row.position ? '#' + row.position : '未上榜' }}
</el-tag>
</template>
</el-table-column>
<el-table-column prop="ai_cited" label="AI引用" width="80">
<template #default="{ row }">
<el-tag :type="row.ai_cited ? 'success' : 'info'" size="small">{{ row.ai_cited ? '是' : '否' }}</el-tag>
</template>
</el-table-column>
<el-table-column prop="url_found" label="匹配 URL" min-width="200" show-overflow-tooltip />
<el-table-column prop="checked_at" label="检查时间" width="160" />
</el-table>
</template>
</div>
<div v-if="activeTab === 'configitems'">
<div class="filter-bar">
<el-button size="default" :type="configSubTab === 'sensitive' ? 'primary' : ''" @click="switchConfigSubTab('sensitive')">🔒 敏感词</el-button>
@@ -634,7 +682,7 @@
<el-tag size="small">{{ row.category || '未分类' }}</el-tag>
</template>
</el-table-column>
<el-table-column label="操作" width="120">
<el-table-column label="操作" width="150">
<template #default="{ row }">
<el-button size="small" @click="editSensitiveWord(row)">编辑</el-button>
<el-button size="small" type="danger" @click="deleteSensitiveWord(row)">删除</el-button>
@@ -682,7 +730,7 @@
<el-tag :type="row.is_active ? 'success' : 'info'" size="small">{{ row.is_active ? '启用' : '停用' }}</el-tag>
</template>
</el-table-column>
<el-table-column label="操作" width="120">
<el-table-column label="操作" width="150">
<template #default="{ row }">
<el-button size="small" @click="editCleanRule(row)">编辑</el-button>
<el-button size="small" type="danger" @click="deleteCleanRule(row)">删除</el-button>
@@ -1270,6 +1318,20 @@ const llmConfigs = ref([]);
return Object.entries(map).sort((a, b) => a[0].localeCompare(b[0]));
});
const rankings = ref([]);
const rankingStats = ref({ total_checks: 0, on_page: 0, ai_cited: 0, best_position: null });
const rankingsLoading = ref(false);
const loadRankings = async () => {
rankingsLoading.value = true;
try {
const resp = await api.get('/api/seo/rankings?limit=100');
rankings.value = resp.data || [];
const overview = await api.get('/api/seo/rankings/overview');
rankingStats.value = overview.data || { total_checks: 0, on_page: 0, ai_cited: 0, best_position: null };
} catch (e) { console.error('加载排名数据失败:', e); }
finally { rankingsLoading.value = false; }
};
const contentCleanRules = ref([]);
const ccrLoading = ref(false);
const ccrDialogVisible = ref(false);
@@ -1319,6 +1381,7 @@ const llmConfigs = ref([]);
users: fetchUsers,
logs: loadLogTypes, orgs: loadOrgs, roles: loadRoles, menus: loadMenus, assistant: loadAssistantConfig,
searchproviders: loadSearchProviders,
searchrankings: loadRankings,
configitems: () => { loadSensitiveWords(); loadContentCleanRules(); },
};
const loadedTabs = new Set([]);
@@ -1378,6 +1441,7 @@ const llmConfigs = ref([]);
sensitiveWords, swLoading, swDialogVisible, swSaving, swForm, editingSwId, loadSensitiveWords, showAddSensitiveWord, editSensitiveWord, saveSensitiveWord, deleteSensitiveWord, configSubTab, switchConfigSubTab,
contentCleanRules, ccrLoading, ccrDialogVisible, ccrDialogTitle, ccrSaving, ccrForm, editingCcrId,
loadContentCleanRules, showAddCleanRule, editCleanRule, saveCleanRule, deleteCleanRule,
rankings, rankingStats, rankingsLoading, loadRankings,
};
}
});
+2 -2
View File
@@ -124,8 +124,8 @@
<el-button v-if="previewFullscreen" size="small" type="danger" @click="previewVisible = false">关闭</el-button>
</div>
</div>
<div style="max-width: 1000px; margin: 0 auto; width: 100%; height: 100%; display: flex; flex-direction: column;">
<iframe v-if="previewArticleData.html_content" :srcdoc="previewArticleData.html_content" class="preview-iframe" style="flex:1; min-height:500px; border:1px solid #ebeef5; border-radius:8px; background:#fff; overflow:auto; padding:0; width:100%;" sandbox></iframe>
<div style="max-width: 1000px; margin: 0 auto; width: 100%; flex: 1; min-height: 0; display: flex; flex-direction: column;">
<iframe v-if="previewArticleData.html_content" :srcdoc="previewArticleData.html_content" class="preview-iframe" style="flex:1; border:1px solid #ebeef5; border-radius:8px; background:#fff; padding:0;" sandbox></iframe>
<div v-else style="padding:60px 20px; text-align:center; color:#909399; font-size:14px;">该文章暂无 HTML 内容</div>
</div>
</div>
+4 -4
View File
@@ -363,13 +363,13 @@ body {
.login-footer a:hover { color: var(--color-accent); }
/* ========== Preview Dialog ========== */
.preview-iframe { box-sizing: border-box; }
.preview-iframe { box-sizing: border-box; height: 100%; width: 100%; }
.preview-dialog-custom.el-dialog {
max-height: calc(100vh - 90px); overflow: hidden; display: flex;
flex-direction: column; margin-top: 0 !important;
}
.preview-dialog-custom.el-dialog .el-dialog__header { padding: var(--spacing-sm) var(--spacing-md); margin: 0; flex-shrink: 0; }
.preview-dialog-custom.el-dialog .el-dialog__body { padding: var(--spacing-md); overflow: hidden; }
.preview-dialog-custom.el-dialog .el-dialog__body { padding: var(--spacing-md); overflow: hidden; flex: 1; min-height: 0; }
.preview-dialog-custom.el-dialog .el-dialog__footer { flex-shrink: 0; padding: var(--spacing-sm) var(--spacing-md); }
.preview-dialog-custom.is-fullscreen { z-index: 100001 !important; }
body:has(.preview-dialog-custom.is-fullscreen) > [class*="el-overlay"] { z-index: 100000 !important; }
@@ -400,11 +400,11 @@ body:has(.preview-dialog-custom.is-fullscreen) > [class*="el-overlay"] { z-index
.el-button--default { padding: 10px 16px !important; }
.el-input__inner { min-height: 38px; }
.preview-iframe { max-height: calc(100vh - 250px) !important; }
.preview-iframe { min-height: 300px; }
.preview-dialog-custom { position: relative; }
}
@media (min-width: 769px) {
.preview-iframe { max-height: calc(100vh - 100px) !important; }
.preview-iframe { min-height: 400px; }
.preview-dialog-custom { position: relative; left: 90px; }
}
+160 -9
View File
@@ -8,8 +8,8 @@
<link rel="stylesheet" href="theme-modern.css">
<style>
.selected-count { color: var(--color-text-secondary); font-size: var(--font-size-body); margin-left: auto; }
.preview-dialog-custom .el-dialog__body { overflow-y: auto; max-height: calc(90vh - 120px); min-height: 400px; padding: 16px 20px; }
.preview-dialog-custom .preview-body { max-height: calc(90vh - 180px); min-height: 300px; overflow: auto; }
.preview-dialog-custom.el-dialog .el-dialog__body { overflow-y: auto; min-height: 400px; padding: 16px 20px; }
.preview-dialog-custom .preview-body { min-height: 300px; overflow: auto; }
.preview-dialog-custom .preview-body img { max-width: 100%; }
.topic-card-list { display: none; }
@media (max-width: 768px) {
@@ -41,10 +41,11 @@
<div class="page-header">
<h2 class="page-title"><el-icon style="vertical-align:-2px;"><IconTopic /></el-icon> 选题管理</h2>
<div class="toolbar">
<el-button type="primary" size="small" @click="refreshAll"><el-icon style="vertical-align:-2px;"><IconRefresh /></el-icon> 批量刷</el-button>
<el-button type="primary" size="small" @click="openCreateDialog"><el-icon style="vertical-align:-2px;"><IconPlus /></el-icon>增选题</el-button>
<el-button size="small" @click="refreshAll"><el-icon style="vertical-align:-2px;"><IconRefresh /></el-icon> 批量刷新</el-button>
<el-button size="small" @click="toggleSelectAll">{{ selectAllLabel }}</el-button>
<el-button type="success" size="small" @click="triggerGenerateSelected" :disabled="selectedTopicIds.length === 0"><el-icon style="vertical-align:-2px;"><IconPlus /></el-icon> 批量创作</el-button>
<el-button type="warning" size="small" @click="triggerReviewSelected" :disabled="selectedTopicIds.length === 0"><el-icon style="vertical-align:-2px;"><IconSearch /></el-icon> 批量审查</el-button>
<el-button type="success" size="small" @click="triggerGenerateSelected" :disabled="selectedTopicIds.length === 0"> 批量创作</el-button>
<el-button type="warning" size="small" @click="triggerReviewSelected" :disabled="selectedTopicIds.length === 0"> 批量审查</el-button>
<span v-if="selectedTopicIds.length > 0" class="selected-count">已选 {{ selectedTopicIds.length }} 项</span>
</div>
</div>
@@ -162,6 +163,82 @@
</div>
</main>
</div>
<el-dialog v-model="createDialogVisible" :title="createStep === 1 ? '新增选题' : 'AI 分析结果'" width="680px" :close-on-click-modal="false" @close="resetCreateDialog">
<template v-if="createStep === 1">
<el-form label-position="top">
<el-form-item label="选题思路 / 内容描述">
<el-input type="textarea" :rows="5" v-model="createForm.raw_input" placeholder="描述你想写的选题方向,可以是大致想法、关键词、或者一句话需求&#10;例如:想写一篇关于旧物换补贴的实操指南,结合最近的碳普惠政策" />
</el-form-item>
<el-form-item label="参考链接(可选,每行一个)">
<el-input type="textarea" :rows="3" v-model="createForm.reference_links" placeholder="https://...&#10;https://..." />
</el-form-item>
<el-form-item label="所属领域(可选)">
<el-select v-model="createForm.field_id" placeholder="选择领域" clearable style="width:100%;">
<el-option v-for="f in fieldOptions" :key="f.id" :label="f.name" :value="f.id" />
</el-select>
</el-form-item>
</el-form>
</template>
<template v-else>
<el-form label-position="top">
<el-form-item label="选题标题">
<el-input v-model="createResult.title" />
</el-form-item>
<el-row :gutter="16">
<el-col :span="12">
<el-form-item label="内容形式">
<el-select v-model="createResult.format" style="width:100%;">
<el-option label="趋势洞察" value="趋势洞察" />
<el-option label="实操指南" value="实操指南" />
<el-option label="对比分析" value="对比分析" />
<el-option label="案例解读" value="案例解读" />
<el-option label="观点讨论" value="观点讨论" />
</el-select>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="优先级">
<el-select v-model="createResult.priority" style="width:100%;">
<el-option label="高" value="高" />
<el-option label="中" value="中" />
<el-option label="低" value="低" />
</el-select>
</el-form-item>
</el-col>
</el-row>
<el-form-item label="核心概念">
<el-input v-model="createResult.core_concept" />
</el-form-item>
<el-form-item label="受众痛点">
<el-input v-model="createResult.audience_pain" />
</el-form-item>
<el-form-item label="独特角度">
<el-input v-model="createResult.unique_angle" />
</el-form-item>
<el-form-item label="标签(回车添加)">
<el-select v-model="createResult.tags" multiple filterable allow-create default-first-option style="width:100%;" placeholder="输入标签后回车添加">
<el-option v-for="t in createResult.tags" :key="t" :label="t" :value="t" />
</el-select>
</el-form-item>
</el-form>
</template>
<template #footer>
<div style="display:flex; justify-content:space-between; width:100%;">
<div>
<el-button v-if="createStep === 2" size="small" @click="createStep = 1">← 返回编辑输入</el-button>
<el-button v-else @click="createDialogVisible = false">取消</el-button>
</div>
<div v-if="createStep === 1">
<el-button type="primary" @click="runAiAnalysis" :loading="analyzing">AI 智能分析</el-button>
</div>
<div v-else>
<el-button @click="saveCreatedTopic('list')">仅保存到选题列表</el-button>
<el-button type="success" @click="saveCreatedTopic('create')" :loading="saving">保存并创作</el-button>
<el-button type="warning" @click="saveCreatedTopic('review')" :loading="saving">保存并审查</el-button>
</div>
</div>
</template>
</el-dialog>
<el-dialog v-model="publishDialogVisible" title="发布确认" width="420px" :close-on-click-modal="false">
<div v-if="publishTopic">
<div style="margin-bottom:16px;">
@@ -253,10 +330,14 @@ const TopicsApp = {
publishPlatforms: { zhihu: true, wechat: true, xiaohongshu: true },
publishing: false,
savingContent: false,
currentPage: 1, pageSize: 10,
sortField: 'created_at', sortOrder: 'ascending',
showSearch: false,
searchForm: { id: '', title: '', field: '', createdStart: null, createdEnd: null, generatedStart: null, generatedEnd: null, reviewedStart: null, reviewedEnd: null, publishedStart: null, publishedEnd: null }
currentPage: 1, pageSize: 10,
sortField: 'created_at', sortOrder: 'ascending',
showSearch: false,
searchForm: { id: '', title: '', field: '', createdStart: null, createdEnd: null, generatedStart: null, generatedEnd: null, reviewedStart: null, reviewedEnd: null, publishedStart: null, publishedEnd: null },
createDialogVisible: false, createStep: 1, analyzing: false, saving: false,
fieldOptions: [],
createForm: { raw_input: '', reference_links: '', field_id: null },
createResult: { title: '', format: '趋势洞察', core_concept: '', audience_pain: '', unique_angle: '', tags: [], priority: '中' }
}
},
computed: {
@@ -558,6 +639,76 @@ const TopicsApp = {
this.$message.error('删除失败: ' + msg);
}
},
async openCreateDialog() {
this.createDialogVisible = true;
this.createStep = 1;
this.createForm = { raw_input: '', reference_links: '', field_id: null };
this.createResult = { title: '', format: '趋势洞察', core_concept: '', audience_pain: '', unique_angle: '', tags: [], priority: '中' };
try {
this.fieldOptions = await this.api('/api/topic-config/fields') || [];
} catch (e) { this.fieldOptions = []; }
},
resetCreateDialog() {
this.createStep = 1; this.analyzing = false; this.saving = false;
},
async runAiAnalysis() {
if (!this.createForm.raw_input.trim()) { this.$message.warning('请输入选题思路'); return; }
this.analyzing = true;
try {
const refs = this.createForm.reference_links.split('\n').map(s => s.trim()).filter(Boolean);
const data = await this.api('/api/topics/analyze', {
method: 'POST',
body: JSON.stringify({
raw_input: this.createForm.raw_input,
reference_links: refs,
field_id: this.createForm.field_id || null
})
});
this.createResult.title = data.title || '';
this.createResult.format = data.format || '趋势洞察';
this.createResult.core_concept = data.core_concept || '';
this.createResult.audience_pain = data.audience_pain || '';
this.createResult.unique_angle = data.unique_angle || '';
this.createResult.tags = data.tags || [];
this.createResult.priority = data.priority || '中';
this.createStep = 2;
this.$message.success('AI 分析完成,请确认选题信息');
} catch (e) { this.$message.error('AI 分析失败: ' + (e.message || '未知错误')); }
finally { this.analyzing = false; }
},
async saveCreatedTopic(action) {
this.saving = true;
try {
const body = {
title: this.createResult.title,
field_id: this.createForm.field_id || null,
format: this.createResult.format,
core_concept: this.createResult.core_concept,
audience_pain: this.createResult.audience_pain,
unique_angle: this.createResult.unique_angle,
tags: this.createResult.tags,
priority: this.createResult.priority,
};
const topic = await this.api('/api/topics', { method: 'POST', body: JSON.stringify(body) });
const topicId = topic.id;
this.createDialogVisible = false;
this.$message.success(`选题 ${topicId} 创建成功`);
await this.fetchTopics();
if (action === 'create') {
try {
await this.api('/api/tasks/run-creator?topic_id=' + topicId, { method: 'POST' });
this.$message.success(`创作任务已启动: ${topic.title}`);
} catch (e) { this.$message.error(`创作启动失败: ${e.message}`); }
} else if (action === 'review') {
try {
await this.api('/api/system/review/run', { method: 'POST', body: JSON.stringify({ topic_ids: [topicId] }) });
this.$message.success(`审查已启动: ${topic.title}`);
} catch (e) { this.$message.error(`审查启动失败: ${e.message}`); }
}
await this.fetchTodayCount();
} catch (e) { this.$message.error('保存选题失败: ' + (e.message || '未知错误')); }
finally { this.saving = false; }
},
switchPlatform(platform) {
if (this.editing) this.cancelEdit();
this.previewPlatform = platform;