diff --git a/AUTO_CODE_REVIEW_REPORT.md b/AUTO_CODE_REVIEW_REPORT.md index b38747e..4a4d442 100644 --- a/AUTO_CODE_REVIEW_REPORT.md +++ b/AUTO_CODE_REVIEW_REPORT.md @@ -1213,3 +1213,8 @@ - `/root/.openclaw/workspace/projects/insightflow/backend/workflow_manager.py:18` - 未使用的导入: urllib.parse - `/root/.openclaw/workspace/projects/insightflow/backend/plugin_manager.py:14` - 未使用的导入: urllib.parse + + +## Git 提交结果 + +✅ 提交并推送成功 diff --git a/backend/ai_manager.py b/backend/ai_manager.py index 5a6e92e..94ce570 100644 --- a/backend/ai_manager.py +++ b/backend/ai_manager.py @@ -27,6 +27,7 @@ import httpx # Database path DB_PATH = os.path.join(os.path.dirname(__file__), "insightflow.db") + class ModelType(StrEnum): """模型类型""" @@ -35,6 +36,7 @@ class ModelType(StrEnum): SUMMARIZATION = "summarization" # 摘要 PREDICTION = "prediction" # 预测 + class ModelStatus(StrEnum): """模型状态""" @@ -44,6 +46,7 @@ class ModelStatus(StrEnum): FAILED = "failed" ARCHIVED = "archived" + class MultimodalProvider(StrEnum): """多模态模型提供商""" @@ -52,6 +55,7 @@ class MultimodalProvider(StrEnum): GEMINI = "gemini-pro-vision" KIMI_VL = "kimi-vl" + class PredictionType(StrEnum): """预测类型""" @@ -60,6 +64,7 @@ class PredictionType(StrEnum): ENTITY_GROWTH = "entity_growth" # 实体增长预测 RELATION_EVOLUTION = "relation_evolution" # 关系演变预测 + @dataclass class CustomModel: """自定义模型""" @@ -79,6 +84,7 @@ class CustomModel: trained_at: str | None created_by: str + @dataclass class TrainingSample: """训练样本""" @@ -90,6 +96,7 @@ class TrainingSample: metadata: dict created_at: str + @dataclass class MultimodalAnalysis: """多模态分析结果""" @@ -106,6 +113,7 @@ class MultimodalAnalysis: cost: float created_at: str + @dataclass class KnowledgeGraphRAG: """基于知识图谱的 RAG 配置""" @@ -122,6 +130,7 @@ class KnowledgeGraphRAG: created_at: str updated_at: str + @dataclass class RAGQuery: """RAG 查询记录""" @@ -137,6 +146,7 @@ class RAGQuery: latency_ms: int created_at: str + @dataclass class PredictionModel: """预测模型""" @@ -156,6 +166,7 @@ class PredictionModel: created_at: str updated_at: str + @dataclass class PredictionResult: """预测结果""" @@ -171,6 +182,7 @@ class PredictionResult: is_correct: bool | None created_at: str + @dataclass class SmartSummary: """智能摘要""" @@ -188,6 +200,7 @@ class SmartSummary: tokens_used: int created_at: str + class AIManager: """AI 能力管理主类""" @@ -1487,9 +1500,11 @@ class AIManager: created_at=row["created_at"], ) + # Singleton instance _ai_manager = None + def get_ai_manager() -> AIManager: global _ai_manager if _ai_manager is None: diff --git a/backend/api_key_manager.py b/backend/api_key_manager.py index 40236ab..219cd3f 100644 --- a/backend/api_key_manager.py +++ b/backend/api_key_manager.py @@ -15,11 +15,13 @@ from enum import Enum DB_PATH = os.getenv("DB_PATH", "/app/data/insightflow.db") + class ApiKeyStatus(Enum): ACTIVE = "active" REVOKED = "revoked" EXPIRED = "expired" + @dataclass class ApiKey: id: str @@ -37,6 +39,7 @@ class ApiKey: revoked_reason: str | None total_calls: int = 0 + class ApiKeyManager: """API Key 管理器""" @@ -522,9 +525,11 @@ class ApiKeyManager: total_calls=row["total_calls"], ) + # 全局实例 _api_key_manager: ApiKeyManager | None = None + def get_api_key_manager() -> ApiKeyManager: """获取 API Key 管理器实例""" global _api_key_manager diff --git a/backend/collaboration_manager.py b/backend/collaboration_manager.py index 77a936d..40f99a4 100644 --- a/backend/collaboration_manager.py +++ b/backend/collaboration_manager.py @@ -11,6 +11,7 @@ from datetime import datetime, timedelta from enum import Enum from typing import Any + class SharePermission(Enum): """分享权限级别""" @@ -19,6 +20,7 @@ class SharePermission(Enum): EDIT = "edit" # 可编辑 ADMIN = "admin" # 管理员 + class CommentTargetType(Enum): """评论目标类型""" @@ -27,6 +29,7 @@ class CommentTargetType(Enum): TRANSCRIPT = "transcript" # 转录文本评论 PROJECT = "project" # 项目级评论 + class ChangeType(Enum): """变更类型""" @@ -36,6 +39,7 @@ class ChangeType(Enum): MERGE = "merge" # 合并 SPLIT = "split" # 拆分 + @dataclass class ProjectShare: """项目分享链接""" @@ -54,6 +58,7 @@ class ProjectShare: allow_download: bool # 允许下载 allow_export: bool # 允许导出 + @dataclass class Comment: """评论/批注""" @@ -74,6 +79,7 @@ class Comment: mentions: list[str] # 提及的用户 attachments: list[dict] # 附件 + @dataclass class ChangeRecord: """变更记录""" @@ -95,6 +101,7 @@ class ChangeRecord: reverted_at: str | None # 回滚时间 reverted_by: str | None # 回滚者 + @dataclass class TeamMember: """团队成员""" @@ -110,6 +117,7 @@ class TeamMember: last_active_at: str | None # 最后活跃时间 permissions: list[str] # 具体权限列表 + @dataclass class TeamSpace: """团队空间""" @@ -124,6 +132,7 @@ class TeamSpace: project_count: int settings: dict[str, Any] # 团队设置 + class CollaborationManager: """协作管理主类""" @@ -982,9 +991,11 @@ class CollaborationManager: ) self.db.conn.commit() + # 全局协作管理器实例 _collaboration_manager = None + def get_collaboration_manager(db_manager=None) -> None: """获取协作管理器单例""" global _collaboration_manager diff --git a/backend/db_manager.py b/backend/db_manager.py index 1ac8a29..a035b69 100644 --- a/backend/db_manager.py +++ b/backend/db_manager.py @@ -14,6 +14,7 @@ from datetime import datetime DB_PATH = os.getenv("DB_PATH", "/app/data/insightflow.db") + @dataclass class Project: id: str @@ -22,6 +23,7 @@ class Project: created_at: str = "" updated_at: str = "" + @dataclass class Entity: id: str @@ -42,6 +44,7 @@ class Entity: if self.attributes is None: self.attributes = {} + @dataclass class AttributeTemplate: """属性模板定义""" @@ -62,6 +65,7 @@ class AttributeTemplate: if self.options is None: self.options = [] + @dataclass class EntityAttribute: """实体属性值""" @@ -82,6 +86,7 @@ class EntityAttribute: if self.options is None: self.options = [] + @dataclass class AttributeHistory: """属性变更历史""" @@ -95,6 +100,7 @@ class AttributeHistory: changed_at: str = "" change_reason: str = "" + @dataclass class EntityMention: id: str @@ -105,6 +111,7 @@ class EntityMention: text_snippet: str confidence: float = 1.0 + class DatabaseManager: def __init__(self, db_path: str = DB_PATH): self.db_path = db_path @@ -1385,9 +1392,11 @@ class DatabaseManager: conn.close() return stats + # Singleton instance _db_manager = None + def get_db_manager() -> DatabaseManager: global _db_manager if _db_manager is None: diff --git a/backend/developer_ecosystem_manager.py b/backend/developer_ecosystem_manager.py index 74729c2..928527e 100644 --- a/backend/developer_ecosystem_manager.py +++ b/backend/developer_ecosystem_manager.py @@ -21,6 +21,7 @@ from enum import StrEnum # Database path DB_PATH = os.path.join(os.path.dirname(__file__), "insightflow.db") + class SDKLanguage(StrEnum): """SDK 语言类型""" @@ -31,6 +32,7 @@ class SDKLanguage(StrEnum): JAVA = "java" RUST = "rust" + class SDKStatus(StrEnum): """SDK 状态""" @@ -40,6 +42,7 @@ class SDKStatus(StrEnum): DEPRECATED = "deprecated" # 已弃用 ARCHIVED = "archived" # 已归档 + class TemplateCategory(StrEnum): """模板分类""" @@ -50,6 +53,7 @@ class TemplateCategory(StrEnum): TECH = "tech" # 科技 GENERAL = "general" # 通用 + class TemplateStatus(StrEnum): """模板状态""" @@ -59,6 +63,7 @@ class TemplateStatus(StrEnum): PUBLISHED = "published" # 已发布 UNLISTED = "unlisted" # 未列出 + class PluginStatus(StrEnum): """插件状态""" @@ -69,6 +74,7 @@ class PluginStatus(StrEnum): PUBLISHED = "published" # 已发布 SUSPENDED = "suspended" # 已暂停 + class PluginCategory(StrEnum): """插件分类""" @@ -79,6 +85,7 @@ class PluginCategory(StrEnum): SECURITY = "security" # 安全 CUSTOM = "custom" # 自定义 + class DeveloperStatus(StrEnum): """开发者认证状态""" @@ -88,6 +95,7 @@ class DeveloperStatus(StrEnum): CERTIFIED = "certified" # 已认证(高级) SUSPENDED = "suspended" # 已暂停 + @dataclass class SDKRelease: """SDK 发布""" @@ -113,6 +121,7 @@ class SDKRelease: published_at: str | None created_by: str + @dataclass class SDKVersion: """SDK 版本历史""" @@ -129,6 +138,7 @@ class SDKVersion: download_count: int created_at: str + @dataclass class TemplateMarketItem: """模板市场项目""" @@ -160,6 +170,7 @@ class TemplateMarketItem: updated_at: str published_at: str | None + @dataclass class TemplateReview: """模板评价""" @@ -175,6 +186,7 @@ class TemplateReview: created_at: str updated_at: str + @dataclass class PluginMarketItem: """插件市场项目""" @@ -213,6 +225,7 @@ class PluginMarketItem: reviewed_at: str | None review_notes: str | None + @dataclass class PluginReview: """插件评价""" @@ -228,6 +241,7 @@ class PluginReview: created_at: str updated_at: str + @dataclass class DeveloperProfile: """开发者档案""" @@ -251,6 +265,7 @@ class DeveloperProfile: updated_at: str verified_at: str | None + @dataclass class DeveloperRevenue: """开发者收益""" @@ -268,6 +283,7 @@ class DeveloperRevenue: transaction_id: str created_at: str + @dataclass class CodeExample: """代码示例""" @@ -290,6 +306,7 @@ class CodeExample: created_at: str updated_at: str + @dataclass class APIDocumentation: """API 文档生成记录""" @@ -303,6 +320,7 @@ class APIDocumentation: generated_at: str generated_by: str + @dataclass class DeveloperPortalConfig: """开发者门户配置""" @@ -326,6 +344,7 @@ class DeveloperPortalConfig: created_at: str updated_at: str + class DeveloperEcosystemManager: """开发者生态系统管理主类""" @@ -2031,9 +2050,11 @@ class DeveloperEcosystemManager: updated_at=row["updated_at"], ) + # Singleton instance _developer_ecosystem_manager = None + def get_developer_ecosystem_manager() -> DeveloperEcosystemManager: """获取开发者生态系统管理器单例""" global _developer_ecosystem_manager diff --git a/backend/document_processor.py b/backend/document_processor.py index b057d22..1fdff29 100644 --- a/backend/document_processor.py +++ b/backend/document_processor.py @@ -7,6 +7,7 @@ Document Processor - Phase 3 import io import os + class DocumentProcessor: """文档处理器 - 提取 PDF/DOCX 文本""" @@ -155,6 +156,7 @@ class DocumentProcessor: ext = os.path.splitext(filename.lower())[1] return ext in self.supported_formats + # 简单的文本提取器(不需要外部依赖) class SimpleTextExtractor: """简单的文本提取器,用于测试""" @@ -171,6 +173,7 @@ class SimpleTextExtractor: return content.decode("latin-1", errors="ignore") + if __name__ == "__main__": # 测试 processor = DocumentProcessor() diff --git a/backend/enterprise_manager.py b/backend/enterprise_manager.py index 4f3876d..68b1b06 100644 --- a/backend/enterprise_manager.py +++ b/backend/enterprise_manager.py @@ -21,6 +21,7 @@ from typing import Any logger = logging.getLogger(__name__) + class SSOProvider(StrEnum): """SSO 提供商类型""" @@ -32,6 +33,7 @@ class SSOProvider(StrEnum): GOOGLE = "google" # Google Workspace CUSTOM_SAML = "custom_saml" # 自定义 SAML + class SSOStatus(StrEnum): """SSO 配置状态""" @@ -40,6 +42,7 @@ class SSOStatus(StrEnum): ACTIVE = "active" # 已启用 ERROR = "error" # 配置错误 + class SCIMSyncStatus(StrEnum): """SCIM 同步状态""" @@ -48,6 +51,7 @@ class SCIMSyncStatus(StrEnum): SUCCESS = "success" # 同步成功 FAILED = "failed" # 同步失败 + class AuditLogExportFormat(StrEnum): """审计日志导出格式""" @@ -56,6 +60,7 @@ class AuditLogExportFormat(StrEnum): PDF = "pdf" XLSX = "xlsx" + class DataRetentionAction(StrEnum): """数据保留策略动作""" @@ -63,6 +68,7 @@ class DataRetentionAction(StrEnum): DELETE = "delete" # 删除 ANONYMIZE = "anonymize" # 匿名化 + class ComplianceStandard(StrEnum): """合规标准""" @@ -72,6 +78,7 @@ class ComplianceStandard(StrEnum): HIPAA = "hipaa" PCI_DSS = "pci_dss" + @dataclass class SSOConfig: """SSO 配置数据类""" @@ -104,6 +111,7 @@ class SSOConfig: last_tested_at: datetime | None last_error: str | None + @dataclass class SCIMConfig: """SCIM 配置数据类""" @@ -128,6 +136,7 @@ class SCIMConfig: created_at: datetime updated_at: datetime + @dataclass class SCIMUser: """SCIM 用户数据类""" @@ -147,6 +156,7 @@ class SCIMUser: created_at: datetime updated_at: datetime + @dataclass class AuditLogExport: """审计日志导出记录""" @@ -171,6 +181,7 @@ class AuditLogExport: completed_at: datetime | None error_message: str | None + @dataclass class DataRetentionPolicy: """数据保留策略""" @@ -198,6 +209,7 @@ class DataRetentionPolicy: created_at: datetime updated_at: datetime + @dataclass class DataRetentionJob: """数据保留任务""" @@ -215,6 +227,7 @@ class DataRetentionJob: details: dict[str, Any] created_at: datetime + @dataclass class SAMLAuthRequest: """SAML 认证请求""" @@ -229,6 +242,7 @@ class SAMLAuthRequest: used: bool used_at: datetime | None + @dataclass class SAMLAuthResponse: """SAML 认证响应""" @@ -245,6 +259,7 @@ class SAMLAuthResponse: processed_at: datetime | None created_at: datetime + class EnterpriseManager: """企业级功能管理器""" @@ -2181,9 +2196,11 @@ class EnterpriseManager: ), ) + # 全局实例 _enterprise_manager = None + def get_enterprise_manager(db_path: str = "insightflow.db") -> EnterpriseManager: """获取 EnterpriseManager 单例""" global _enterprise_manager diff --git a/backend/entity_aligner.py b/backend/entity_aligner.py index 73f6d97..9c50cb9 100644 --- a/backend/entity_aligner.py +++ b/backend/entity_aligner.py @@ -15,6 +15,7 @@ import numpy as np KIMI_API_KEY = os.getenv("KIMI_API_KEY", "") KIMI_BASE_URL = os.getenv("KIMI_BASE_URL", "https://api.kimi.com/coding") + @dataclass class EntityEmbedding: entity_id: str @@ -22,6 +23,7 @@ class EntityEmbedding: definition: str embedding: list[float] + class EntityAligner: """实体对齐器 - 使用 embedding 进行相似度匹配""" @@ -316,6 +318,7 @@ class EntityAligner: return [] + # 简单的字符串相似度计算(不使用 embedding) def simple_similarity(str1: str, str2: str) -> float: """ @@ -347,6 +350,7 @@ def simple_similarity(str1: str, str2: str) -> float: return SequenceMatcher(None, s1, s2).ratio() + if __name__ == "__main__": # 测试 aligner = EntityAligner() diff --git a/backend/export_manager.py b/backend/export_manager.py index 4b5d450..dfb8678 100644 --- a/backend/export_manager.py +++ b/backend/export_manager.py @@ -36,6 +36,7 @@ try: except ImportError: REPORTLAB_AVAILABLE = False + @dataclass class ExportEntity: id: str @@ -46,6 +47,7 @@ class ExportEntity: mention_count: int attributes: dict[str, Any] + @dataclass class ExportRelation: id: str @@ -55,6 +57,7 @@ class ExportRelation: confidence: float evidence: str + @dataclass class ExportTranscript: id: str @@ -64,6 +67,7 @@ class ExportTranscript: segments: list[dict] entity_mentions: list[dict] + class ExportManager: """导出管理器 - 处理各种导出需求""" @@ -605,9 +609,11 @@ class ExportManager: return json.dumps(data, ensure_ascii=False, indent=2) + # 全局导出管理器实例 _export_manager = None + def get_export_manager(db_manager=None) -> None: """获取导出管理器实例""" global _export_manager diff --git a/backend/growth_manager.py b/backend/growth_manager.py index b4aa80a..f79f9fe 100644 --- a/backend/growth_manager.py +++ b/backend/growth_manager.py @@ -28,6 +28,7 @@ import httpx # Database path DB_PATH = os.path.join(os.path.dirname(__file__), "insightflow.db") + class EventType(StrEnum): """事件类型""" @@ -43,6 +44,7 @@ class EventType(StrEnum): INVITE_ACCEPTED = "invite_accepted" # 接受邀请 REFERRAL_REWARD = "referral_reward" # 推荐奖励 + class ExperimentStatus(StrEnum): """实验状态""" @@ -52,6 +54,7 @@ class ExperimentStatus(StrEnum): COMPLETED = "completed" # 已完成 ARCHIVED = "archived" # 已归档 + class TrafficAllocationType(StrEnum): """流量分配类型""" @@ -59,6 +62,7 @@ class TrafficAllocationType(StrEnum): STRATIFIED = "stratified" # 分层分配 TARGETED = "targeted" # 定向分配 + class EmailTemplateType(StrEnum): """邮件模板类型""" @@ -70,6 +74,7 @@ class EmailTemplateType(StrEnum): REFERRAL = "referral" # 推荐邀请 NEWSLETTER = "newsletter" # 新闻通讯 + class EmailStatus(StrEnum): """邮件状态""" @@ -83,6 +88,7 @@ class EmailStatus(StrEnum): BOUNCED = "bounced" # 退信 FAILED = "failed" # 失败 + class WorkflowTriggerType(StrEnum): """工作流触发类型""" @@ -94,6 +100,7 @@ class WorkflowTriggerType(StrEnum): MILESTONE = "milestone" # 里程碑 CUSTOM_EVENT = "custom_event" # 自定义事件 + class ReferralStatus(StrEnum): """推荐状态""" @@ -102,6 +109,7 @@ class ReferralStatus(StrEnum): REWARDED = "rewarded" # 已奖励 EXPIRED = "expired" # 已过期 + @dataclass class AnalyticsEvent: """分析事件""" @@ -120,6 +128,7 @@ class AnalyticsEvent: utm_medium: str | None utm_campaign: str | None + @dataclass class UserProfile: """用户画像""" @@ -139,6 +148,7 @@ class UserProfile: created_at: datetime updated_at: datetime + @dataclass class Funnel: """转化漏斗""" @@ -151,6 +161,7 @@ class Funnel: created_at: datetime updated_at: datetime + @dataclass class FunnelAnalysis: """漏斗分析结果""" @@ -163,6 +174,7 @@ class FunnelAnalysis: overall_conversion: float # 总体转化率 drop_off_points: list[dict] # 流失点 + @dataclass class Experiment: """A/B 测试实验""" @@ -187,6 +199,7 @@ class Experiment: updated_at: datetime created_by: str + @dataclass class ExperimentResult: """实验结果""" @@ -204,6 +217,7 @@ class ExperimentResult: uplift: float # 提升幅度 created_at: datetime + @dataclass class EmailTemplate: """邮件模板""" @@ -224,6 +238,7 @@ class EmailTemplate: created_at: datetime updated_at: datetime + @dataclass class EmailCampaign: """邮件营销活动""" @@ -245,6 +260,7 @@ class EmailCampaign: completed_at: datetime | None created_at: datetime + @dataclass class EmailLog: """邮件发送记录""" @@ -266,6 +282,7 @@ class EmailLog: error_message: str | None created_at: datetime + @dataclass class AutomationWorkflow: """自动化工作流""" @@ -282,6 +299,7 @@ class AutomationWorkflow: created_at: datetime updated_at: datetime + @dataclass class ReferralProgram: """推荐计划""" @@ -301,6 +319,7 @@ class ReferralProgram: created_at: datetime updated_at: datetime + @dataclass class Referral: """推荐记录""" @@ -321,6 +340,7 @@ class Referral: expires_at: datetime created_at: datetime + @dataclass class TeamIncentive: """团队升级激励""" @@ -338,6 +358,7 @@ class TeamIncentive: is_active: bool created_at: datetime + class GrowthManager: """运营与增长管理主类""" @@ -2126,9 +2147,11 @@ class GrowthManager: created_at=row["created_at"], ) + # Singleton instance _growth_manager = None + def get_growth_manager() -> GrowthManager: global _growth_manager if _growth_manager is None: diff --git a/backend/image_processor.py b/backend/image_processor.py index 3be30e7..96cb013 100644 --- a/backend/image_processor.py +++ b/backend/image_processor.py @@ -33,6 +33,7 @@ try: except ImportError: PYTESSERACT_AVAILABLE = False + @dataclass class ImageEntity: """图片中检测到的实体""" @@ -42,6 +43,7 @@ class ImageEntity: confidence: float bbox: tuple[int, int, int, int] | None = None # (x, y, width, height) + @dataclass class ImageRelation: """图片中检测到的关系""" @@ -51,6 +53,7 @@ class ImageRelation: relation_type: str confidence: float + @dataclass class ImageProcessingResult: """图片处理结果""" @@ -66,6 +69,7 @@ class ImageProcessingResult: success: bool error_message: str = "" + @dataclass class BatchProcessingResult: """批量图片处理结果""" @@ -75,6 +79,7 @@ class BatchProcessingResult: success_count: int failed_count: int + class ImageProcessor: """图片处理器 - 处理各种类型图片""" @@ -548,9 +553,11 @@ class ImageProcessor: print(f"Thumbnail generation error: {e}") return image_data + # Singleton instance _image_processor = None + def get_image_processor(temp_dir: str = None) -> ImageProcessor: """获取图片处理器单例""" global _image_processor diff --git a/backend/knowledge_reasoner.py b/backend/knowledge_reasoner.py index 39747f0..7924d08 100644 --- a/backend/knowledge_reasoner.py +++ b/backend/knowledge_reasoner.py @@ -15,6 +15,7 @@ import httpx KIMI_API_KEY = os.getenv("KIMI_API_KEY", "") KIMI_BASE_URL = os.getenv("KIMI_BASE_URL", "https://api.kimi.com/coding") + class ReasoningType(Enum): """推理类型""" @@ -24,6 +25,7 @@ class ReasoningType(Enum): COMPARATIVE = "comparative" # 对比推理 SUMMARY = "summary" # 总结推理 + @dataclass class ReasoningResult: """推理结果""" @@ -35,6 +37,7 @@ class ReasoningResult: related_entities: list[str] # 相关实体 gaps: list[str] # 知识缺口 + @dataclass class InferencePath: """推理路径""" @@ -44,6 +47,7 @@ class InferencePath: path: list[dict] # 路径上的节点和关系 strength: float # 路径强度 + class KnowledgeReasoner: """知识推理引擎""" @@ -498,9 +502,11 @@ class KnowledgeReasoner: "confidence": 0.5, } + # Singleton instance _reasoner = None + def get_knowledge_reasoner() -> KnowledgeReasoner: global _reasoner if _reasoner is None: diff --git a/backend/llm_client.py b/backend/llm_client.py index ed4c2a4..bffe2c6 100644 --- a/backend/llm_client.py +++ b/backend/llm_client.py @@ -15,11 +15,13 @@ import httpx KIMI_API_KEY = os.getenv("KIMI_API_KEY", "") KIMI_BASE_URL = os.getenv("KIMI_BASE_URL", "https://api.kimi.com/coding") + @dataclass class ChatMessage: role: str content: str + @dataclass class EntityExtractionResult: name: str @@ -27,6 +29,7 @@ class EntityExtractionResult: definition: str confidence: float + @dataclass class RelationExtractionResult: source: str @@ -34,6 +37,7 @@ class RelationExtractionResult: type: str confidence: float + class LLMClient: """Kimi API 客户端""" @@ -249,9 +253,11 @@ class LLMClient: messages = [ChatMessage(role="user", content=prompt)] return await self.chat(messages, temperature=0.3) + # Singleton instance _llm_client = None + def get_llm_client() -> LLMClient: global _llm_client if _llm_client is None: diff --git a/backend/localization_manager.py b/backend/localization_manager.py index ce09299..ad50d99 100644 --- a/backend/localization_manager.py +++ b/backend/localization_manager.py @@ -35,6 +35,7 @@ except ImportError: logger = logging.getLogger(__name__) + class LanguageCode(StrEnum): """支持的语言代码""" @@ -51,6 +52,7 @@ class LanguageCode(StrEnum): AR = "ar" HI = "hi" + class RegionCode(StrEnum): """区域代码""" @@ -62,6 +64,7 @@ class RegionCode(StrEnum): LATIN_AMERICA = "latam" MIDDLE_EAST = "me" + class DataCenterRegion(StrEnum): """数据中心区域""" @@ -75,6 +78,7 @@ class DataCenterRegion(StrEnum): CN_NORTH = "cn-north" CN_EAST = "cn-east" + class PaymentProvider(StrEnum): """支付提供商""" @@ -91,6 +95,7 @@ class PaymentProvider(StrEnum): SEPA = "sepa" UNIONPAY = "unionpay" + class CalendarType(StrEnum): """日历类型""" @@ -102,6 +107,7 @@ class CalendarType(StrEnum): PERSIAN = "persian" BUDDHIST = "buddhist" + @dataclass class Translation: id: str @@ -116,6 +122,7 @@ class Translation: reviewed_by: str | None reviewed_at: datetime | None + @dataclass class LanguageConfig: code: str @@ -133,6 +140,7 @@ class LanguageConfig: first_day_of_week: int calendar_type: str + @dataclass class DataCenter: id: str @@ -147,6 +155,7 @@ class DataCenter: created_at: datetime updated_at: datetime + @dataclass class TenantDataCenterMapping: id: str @@ -158,6 +167,7 @@ class TenantDataCenterMapping: created_at: datetime updated_at: datetime + @dataclass class LocalizedPaymentMethod: id: str @@ -175,6 +185,7 @@ class LocalizedPaymentMethod: created_at: datetime updated_at: datetime + @dataclass class CountryConfig: code: str @@ -196,6 +207,7 @@ class CountryConfig: vat_rate: float | None is_active: bool + @dataclass class TimezoneConfig: id: str @@ -206,6 +218,7 @@ class TimezoneConfig: region: str is_active: bool + @dataclass class CurrencyConfig: code: str @@ -217,6 +230,7 @@ class CurrencyConfig: thousands_separator: str is_active: bool + @dataclass class LocalizationSettings: id: str @@ -236,6 +250,7 @@ class LocalizationSettings: created_at: datetime updated_at: datetime + class LocalizationManager: DEFAULT_LANGUAGES = { LanguageCode.EN: { @@ -731,33 +746,37 @@ class LocalizationManager: cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS translations ( - id TEXT PRIMARY KEY, key TEXT NOT NULL, language TEXT NOT NULL, value TEXT NOT NULL, - namespace TEXT DEFAULT 'common', context TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + id TEXT PRIMARY KEY, key TEXT NOT NULL, language TEXT NOT NULL, + value TEXT NOT NULL, namespace TEXT DEFAULT 'common', context TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, is_reviewed INTEGER DEFAULT 0, reviewed_by TEXT, reviewed_at TIMESTAMP, UNIQUE(key, language, namespace) ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS language_configs ( - code TEXT PRIMARY KEY, name TEXT NOT NULL, name_local TEXT NOT NULL, is_rtl INTEGER DEFAULT 0, - is_active INTEGER DEFAULT 1, is_default INTEGER DEFAULT 0, fallback_language TEXT, - date_format TEXT, time_format TEXT, datetime_format TEXT, number_format TEXT, - currency_format TEXT, first_day_of_week INTEGER DEFAULT 1, calendar_type TEXT DEFAULT 'gregorian' + code TEXT PRIMARY KEY, name TEXT NOT NULL, name_local TEXT NOT NULL, + is_rtl INTEGER DEFAULT 0, is_active INTEGER DEFAULT 1, is_default INTEGER DEFAULT 0, + fallback_language TEXT, date_format TEXT, time_format TEXT, datetime_format TEXT, + number_format TEXT, currency_format TEXT, first_day_of_week INTEGER DEFAULT 1, + calendar_type TEXT DEFAULT 'gregorian' ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS data_centers ( - id TEXT PRIMARY KEY, region_code TEXT NOT NULL UNIQUE, name TEXT NOT NULL, location TEXT NOT NULL, - endpoint TEXT NOT NULL, status TEXT DEFAULT 'active', priority INTEGER DEFAULT 1, - supported_regions TEXT DEFAULT '[]', capabilities TEXT DEFAULT '{}', - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + id TEXT PRIMARY KEY, region_code TEXT NOT NULL UNIQUE, name TEXT NOT NULL, + location TEXT NOT NULL, endpoint TEXT NOT NULL, status TEXT DEFAULT 'active', + priority INTEGER DEFAULT 1, supported_regions TEXT DEFAULT '[]', + capabilities TEXT DEFAULT '{}', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS tenant_data_center_mappings ( id TEXT PRIMARY KEY, tenant_id TEXT NOT NULL UNIQUE, primary_dc_id TEXT NOT NULL, secondary_dc_id TEXT, region_code TEXT NOT NULL, data_residency TEXT DEFAULT 'regional', - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE, FOREIGN KEY (primary_dc_id) REFERENCES data_centers(id), FOREIGN KEY (secondary_dc_id) REFERENCES data_centers(id) @@ -765,20 +784,23 @@ class LocalizationManager: """) cursor.execute(""" CREATE TABLE IF NOT EXISTS localized_payment_methods ( - id TEXT PRIMARY KEY, provider TEXT NOT NULL UNIQUE, name TEXT NOT NULL, name_local TEXT DEFAULT '{}', - supported_countries TEXT DEFAULT '[]', supported_currencies TEXT DEFAULT '[]', - is_active INTEGER DEFAULT 1, config TEXT DEFAULT '{}', icon_url TEXT, display_order INTEGER DEFAULT 0, + id TEXT PRIMARY KEY, provider TEXT NOT NULL UNIQUE, name TEXT NOT NULL, + name_local TEXT DEFAULT '{}', supported_countries TEXT DEFAULT '[]', + supported_currencies TEXT DEFAULT '[]', is_active INTEGER DEFAULT 1, + config TEXT DEFAULT '{}', icon_url TEXT, display_order INTEGER DEFAULT 0, min_amount REAL, max_amount REAL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS country_configs ( - code TEXT PRIMARY KEY, code3 TEXT NOT NULL, name TEXT NOT NULL, name_local TEXT DEFAULT '{}', - region TEXT NOT NULL, default_language TEXT NOT NULL, supported_languages TEXT DEFAULT '[]', - default_currency TEXT NOT NULL, supported_currencies TEXT DEFAULT '[]', timezone TEXT NOT NULL, - calendar_type TEXT DEFAULT 'gregorian', date_format TEXT, time_format TEXT, number_format TEXT, - address_format TEXT, phone_format TEXT, vat_rate REAL, is_active INTEGER DEFAULT 1 + code TEXT PRIMARY KEY, code3 TEXT NOT NULL, name TEXT NOT NULL, + name_local TEXT DEFAULT '{}', region TEXT NOT NULL, default_language TEXT NOT NULL, + supported_languages TEXT DEFAULT '[]', default_currency TEXT NOT NULL, + supported_currencies TEXT DEFAULT '[]', timezone TEXT NOT NULL, + calendar_type TEXT DEFAULT 'gregorian', date_format TEXT, time_format TEXT, + number_format TEXT, address_format TEXT, phone_format TEXT, vat_rate REAL, + is_active INTEGER DEFAULT 1 ) """) cursor.execute(""" @@ -1667,8 +1689,10 @@ class LocalizationManager: ), ) + _localization_manager = None + def get_localization_manager(db_path: str = "insightflow.db") -> LocalizationManager: global _localization_manager if _localization_manager is None: diff --git a/backend/main.py b/backend/main.py index af704ca..d316f13 100644 --- a/backend/main.py +++ b/backend/main.py @@ -406,6 +406,7 @@ ADMIN_PATHS = { # Master Key(用于管理所有 API Keys) MASTER_KEY = os.getenv("INSIGHTFLOW_MASTER_KEY", "") + async def verify_api_key(request: Request, x_api_key: str | None = Header(None, alias="X-API-Key")): """ 验证 API Key 的依赖函数 @@ -461,6 +462,7 @@ async def verify_api_key(request: Request, x_api_key: str | None = Header(None, return {"type": "api_key", "key_id": api_key.id, "permissions": api_key.permissions} + async def rate_limit_middleware(request: Request, call_next): """ 限流中间件 @@ -547,6 +549,7 @@ async def rate_limit_middleware(request: Request, call_next): return response + # 添加限流中间件 app.middleware("http")(rate_limit_middleware) @@ -554,12 +557,14 @@ app.middleware("http")(rate_limit_middleware) # API Key 相关模型 + class ApiKeyCreate(BaseModel): name: str = Field(..., description="API Key 名称/描述") permissions: list[str] = Field(default=["read"], description="权限列表: read, write, delete") rate_limit: int = Field(default=60, description="每分钟请求限制") expires_days: int | None = Field(default=None, description="过期天数(可选)") + class ApiKeyResponse(BaseModel): id: str key_preview: str @@ -572,19 +577,23 @@ class ApiKeyResponse(BaseModel): last_used_at: str | None total_calls: int + class ApiKeyCreateResponse(BaseModel): api_key: str = Field(..., description="API Key(仅显示一次,请妥善保存)") info: ApiKeyResponse + class ApiKeyListResponse(BaseModel): keys: list[ApiKeyResponse] total: int + class ApiKeyUpdate(BaseModel): name: str | None = None permissions: list[str] | None = None rate_limit: int | None = None + class ApiCallStats(BaseModel): total_calls: int success_calls: int @@ -593,11 +602,13 @@ class ApiCallStats(BaseModel): max_response_time_ms: int min_response_time_ms: int + class ApiStatsResponse(BaseModel): summary: ApiCallStats endpoints: list[dict] daily: list[dict] + class ApiCallLog(BaseModel): id: int endpoint: str @@ -609,16 +620,19 @@ class ApiCallLog(BaseModel): error_message: str created_at: str + class ApiLogsResponse(BaseModel): logs: list[ApiCallLog] total: int + class RateLimitStatus(BaseModel): limit: int remaining: int reset_time: int window: str + # 原有模型(保留) class EntityModel(BaseModel): id: str @@ -627,12 +641,14 @@ class EntityModel(BaseModel): definition: str | None = "" aliases: list[str] = [] + class TranscriptSegment(BaseModel): start: float end: float text: str speaker: str | None = "Speaker A" + class AnalysisResult(BaseModel): transcript_id: str project_id: str @@ -641,42 +657,52 @@ class AnalysisResult(BaseModel): full_text: str created_at: str + class ProjectCreate(BaseModel): name: str description: str = "" + class EntityUpdate(BaseModel): name: str | None = None type: str | None = None definition: str | None = None aliases: list[str] | None = None + class RelationCreate(BaseModel): source_entity_id: str target_entity_id: str relation_type: str evidence: str | None = "" + class TranscriptUpdate(BaseModel): full_text: str + class AgentQuery(BaseModel): query: str stream: bool = False + class AgentCommand(BaseModel): command: str + class EntityMergeRequest(BaseModel): source_entity_id: str target_entity_id: str + class GlossaryTermCreate(BaseModel): term: str pronunciation: str | None = "" + # ==================== Phase 7: Workflow Pydantic Models ==================== + class WorkflowCreate(BaseModel): name: str = Field(..., description="工作流名称") description: str = Field(default="", description="工作流描述") @@ -690,6 +716,7 @@ class WorkflowCreate(BaseModel): config: dict = Field(default_factory=dict, description="工作流配置") webhook_ids: list[str] = Field(default_factory=list, description="关联的Webhook ID列表") + class WorkflowUpdate(BaseModel): name: str | None = None description: str | None = None @@ -700,6 +727,7 @@ class WorkflowUpdate(BaseModel): config: dict | None = None webhook_ids: list[str] | None = None + class WorkflowResponse(BaseModel): id: str name: str @@ -720,10 +748,12 @@ class WorkflowResponse(BaseModel): success_count: int fail_count: int + class WorkflowListResponse(BaseModel): workflows: list[WorkflowResponse] total: int + class WorkflowTaskCreate(BaseModel): name: str = Field(..., description="任务名称") task_type: str = Field( @@ -736,6 +766,7 @@ class WorkflowTaskCreate(BaseModel): retry_count: int = Field(default=3, description="重试次数") retry_delay: int = Field(default=5, description="重试延迟(秒)") + class WorkflowTaskUpdate(BaseModel): name: str | None = None task_type: str | None = None @@ -746,6 +777,7 @@ class WorkflowTaskUpdate(BaseModel): retry_count: int | None = None retry_delay: int | None = None + class WorkflowTaskResponse(BaseModel): id: str workflow_id: str @@ -760,6 +792,7 @@ class WorkflowTaskResponse(BaseModel): created_at: str updated_at: str + class WebhookCreate(BaseModel): name: str = Field(..., description="Webhook名称") webhook_type: str = Field(..., description="Webhook类型: feishu, dingtalk, slack, custom") @@ -768,6 +801,7 @@ class WebhookCreate(BaseModel): headers: dict = Field(default_factory=dict, description="自定义请求头") template: str = Field(default="", description="消息模板") + class WebhookUpdate(BaseModel): name: str | None = None webhook_type: str | None = None @@ -777,6 +811,7 @@ class WebhookUpdate(BaseModel): template: str | None = None is_active: bool | None = None + class WebhookResponse(BaseModel): id: str name: str @@ -791,10 +826,12 @@ class WebhookResponse(BaseModel): success_count: int fail_count: int + class WebhookListResponse(BaseModel): webhooks: list[WebhookResponse] total: int + class WorkflowLogResponse(BaseModel): id: str workflow_id: str @@ -808,13 +845,16 @@ class WorkflowLogResponse(BaseModel): error_message: str created_at: str + class WorkflowLogListResponse(BaseModel): logs: list[WorkflowLogResponse] total: int + class WorkflowTriggerRequest(BaseModel): input_data: dict = Field(default_factory=dict, description="工作流输入数据") + class WorkflowTriggerResponse(BaseModel): success: bool workflow_id: str @@ -822,6 +862,7 @@ class WorkflowTriggerResponse(BaseModel): results: dict duration_ms: int + class WorkflowStatsResponse(BaseModel): total: int success: int @@ -830,6 +871,7 @@ class WorkflowStatsResponse(BaseModel): avg_duration_ms: float daily: list[dict] + # API Keys KIMI_API_KEY = os.getenv("KIMI_API_KEY", "") KIMI_BASE_URL = os.getenv("KIMI_BASE_URL", "https://api.kimi.com/coding") @@ -837,24 +879,29 @@ KIMI_BASE_URL = os.getenv("KIMI_BASE_URL", "https://api.kimi.com/coding") # Phase 3: Entity Aligner singleton _aligner = None + def get_aligner(): global _aligner if _aligner is None and ALIGNER_AVAILABLE: _aligner = EntityAligner() return _aligner + # Phase 3: Document Processor singleton _doc_processor = None + def get_doc_processor(): global _doc_processor if _doc_processor is None and DOC_PROCESSOR_AVAILABLE: _doc_processor = DocumentProcessor() return _doc_processor + # Phase 7 Task 4: Collaboration Manager singleton _collaboration_manager = None + def get_collab_manager(): global _collaboration_manager if _collaboration_manager is None and COLLABORATION_AVAILABLE: @@ -862,8 +909,10 @@ def get_collab_manager(): _collaboration_manager = get_collaboration_manager(db) return _collaboration_manager + # Phase 2: Entity Edit API + @app.put("/api/v1/entities/{entity_id}", tags=["Entities"]) async def update_entity(entity_id: str, update: EntityUpdate, _=Depends(verify_api_key)): """更新实体信息(名称、类型、定义、别名)""" @@ -887,6 +936,7 @@ async def update_entity(entity_id: str, update: EntityUpdate, _=Depends(verify_a "aliases": updated.aliases, } + @app.delete("/api/v1/entities/{entity_id}", tags=["Entities"]) async def delete_entity(entity_id: str, _=Depends(verify_api_key)): """删除实体""" @@ -901,6 +951,7 @@ async def delete_entity(entity_id: str, _=Depends(verify_api_key)): db.delete_entity(entity_id) return {"success": True, "message": f"Entity {entity_id} deleted"} + @app.post("/api/v1/entities/{entity_id}/merge", tags=["Entities"]) async def merge_entities_endpoint( entity_id: str, merge_req: EntityMergeRequest, _=Depends(verify_api_key) @@ -930,8 +981,10 @@ async def merge_entities_endpoint( }, } + # Phase 2: Relation Edit API + @app.post("/api/v1/projects/{project_id}/relations", tags=["Relations"]) async def create_relation_endpoint( project_id: str, relation: RelationCreate, _=Depends(verify_api_key) @@ -965,6 +1018,7 @@ async def create_relation_endpoint( "success": True, } + @app.delete("/api/v1/relations/{relation_id}", tags=["Relations"]) async def delete_relation(relation_id: str, _=Depends(verify_api_key)): """删除关系""" @@ -975,6 +1029,7 @@ async def delete_relation(relation_id: str, _=Depends(verify_api_key)): db.delete_relation(relation_id) return {"success": True, "message": f"Relation {relation_id} deleted"} + @app.put("/api/v1/relations/{relation_id}", tags=["Relations"]) async def update_relation(relation_id: str, relation: RelationCreate, _=Depends(verify_api_key)): """更新关系""" @@ -993,8 +1048,10 @@ async def update_relation(relation_id: str, relation: RelationCreate, _=Depends( "success": True, } + # Phase 2: Transcript Edit API + @app.get("/api/v1/transcripts/{transcript_id}", tags=["Transcripts"]) async def get_transcript(transcript_id: str, _=Depends(verify_api_key)): """获取转录详情""" @@ -1009,6 +1066,7 @@ async def get_transcript(transcript_id: str, _=Depends(verify_api_key)): return transcript + @app.put("/api/v1/transcripts/{transcript_id}", tags=["Transcripts"]) async def update_transcript( transcript_id: str, update: TranscriptUpdate, _=Depends(verify_api_key) @@ -1031,8 +1089,10 @@ async def update_transcript( "success": True, } + # Phase 2: Manual Entity Creation + class ManualEntityCreate(BaseModel): name: str type: str = "OTHER" @@ -1041,6 +1101,7 @@ class ManualEntityCreate(BaseModel): start_pos: int | None = None end_pos: int | None = None + @app.post("/api/v1/projects/{project_id}/entities", tags=["Entities"]) async def create_manual_entity( project_id: str, entity: ManualEntityCreate, _=Depends(verify_api_key) @@ -1093,6 +1154,7 @@ async def create_manual_entity( "success": True, } + def transcribe_audio(audio_data: bytes, filename: str) -> dict: """转录音频:OSS上传 + 听悟转录""" @@ -1123,6 +1185,7 @@ def transcribe_audio(audio_data: bytes, filename: str) -> dict: logger.warning(f"Tingwu failed: {e}") return mock_transcribe() + def mock_transcribe() -> dict: """Mock 转录结果""" return { @@ -1137,6 +1200,7 @@ def mock_transcribe() -> dict: ], } + def extract_entities_with_llm(text: str) -> tuple[list[dict], list[dict]]: """使用 Kimi API 提取实体和关系 @@ -1191,6 +1255,7 @@ def extract_entities_with_llm(text: str) -> tuple[list[dict], list[dict]]: return [], [] + def align_entity(project_id: str, name: str, db, definition: str = "") -> Optional["Entity"]: """实体对齐 - Phase 3: 使用 embedding 对齐""" # 1. 首先尝试精确匹配 @@ -1212,8 +1277,10 @@ def align_entity(project_id: str, name: str, db, definition: str = "") -> Option return None + # API Endpoints + @app.post("/api/v1/projects", response_model=dict, tags=["Projects"]) async def create_project(project: ProjectCreate, _=Depends(verify_api_key)): """创建新项目""" @@ -1225,6 +1292,7 @@ async def create_project(project: ProjectCreate, _=Depends(verify_api_key)): p = db.create_project(project_id, project.name, project.description) return {"id": p.id, "name": p.name, "description": p.description} + @app.get("/api/v1/projects", tags=["Projects"]) async def list_projects(_=Depends(verify_api_key)): """列出所有项目""" @@ -1235,6 +1303,7 @@ async def list_projects(_=Depends(verify_api_key)): projects = db.list_projects() return [{"id": p.id, "name": p.name, "description": p.description} for p in projects] + @app.post("/api/v1/projects/{project_id}/upload", response_model=AnalysisResult, tags=["Projects"]) async def upload_audio(project_id: str, file: UploadFile = File(...), _=Depends(verify_api_key)): """上传音频到指定项目 - Phase 3: 支持多文件融合""" @@ -1346,8 +1415,10 @@ async def upload_audio(project_id: str, file: UploadFile = File(...), _=Depends( created_at=datetime.now().isoformat(), ) + # Phase 3: Document Upload API + @app.post("/api/v1/projects/{project_id}/upload-document") async def upload_document(project_id: str, file: UploadFile = File(...), _=Depends(verify_api_key)): """上传 PDF/DOCX 文档到指定项目""" @@ -1467,8 +1538,10 @@ async def upload_document(project_id: str, file: UploadFile = File(...), _=Depen "created_at": datetime.now().isoformat(), } + # Phase 3: Knowledge Base API + @app.get("/api/v1/projects/{project_id}/knowledge-base") async def get_knowledge_base(project_id: str, _=Depends(verify_api_key)): """获取项目知识库 - 包含所有实体、关系、术语表""" @@ -1561,8 +1634,10 @@ async def get_knowledge_base(project_id: str, _=Depends(verify_api_key)): ], } + # Phase 3: Glossary API + @app.post("/api/v1/projects/{project_id}/glossary") async def add_glossary_term(project_id: str, term: GlossaryTermCreate, _=Depends(verify_api_key)): """添加术语到项目术语表""" @@ -1580,6 +1655,7 @@ async def add_glossary_term(project_id: str, term: GlossaryTermCreate, _=Depends return {"id": term_id, "term": term.term, "pronunciation": term.pronunciation, "success": True} + @app.get("/api/v1/projects/{project_id}/glossary") async def get_glossary(project_id: str, _=Depends(verify_api_key)): """获取项目术语表""" @@ -1590,6 +1666,7 @@ async def get_glossary(project_id: str, _=Depends(verify_api_key)): glossary = db.list_glossary(project_id) return glossary + @app.delete("/api/v1/glossary/{term_id}") async def delete_glossary_term(term_id: str, _=Depends(verify_api_key)): """删除术语""" @@ -1600,8 +1677,10 @@ async def delete_glossary_term(term_id: str, _=Depends(verify_api_key)): db.delete_glossary_term(term_id) return {"success": True} + # Phase 3: Entity Alignment API + @app.post("/api/v1/projects/{project_id}/align-entities") async def align_project_entities( project_id: str, threshold: float = 0.85, _=Depends(verify_api_key) @@ -1639,6 +1718,7 @@ async def align_project_entities( return {"success": True, "merged_count": merged_count, "merged_pairs": merged_pairs} + @app.get("/api/v1/projects/{project_id}/entities") async def get_project_entities(project_id: str, _=Depends(verify_api_key)): """获取项目的全局实体列表""" @@ -1658,6 +1738,7 @@ async def get_project_entities(project_id: str, _=Depends(verify_api_key)): for e in entities ] + @app.get("/api/v1/projects/{project_id}/relations") async def get_project_relations(project_id: str, _=Depends(verify_api_key)): """获取项目的实体关系列表""" @@ -1684,6 +1765,7 @@ async def get_project_relations(project_id: str, _=Depends(verify_api_key)): for r in relations ] + @app.get("/api/v1/projects/{project_id}/transcripts") async def get_project_transcripts(project_id: str, _=Depends(verify_api_key)): """获取项目的转录列表""" @@ -1705,6 +1787,7 @@ async def get_project_transcripts(project_id: str, _=Depends(verify_api_key)): for t in transcripts ] + @app.get("/api/v1/entities/{entity_id}/mentions") async def get_entity_mentions(entity_id: str, _=Depends(verify_api_key)): """获取实体的所有提及位置""" @@ -1725,8 +1808,10 @@ async def get_entity_mentions(entity_id: str, _=Depends(verify_api_key)): for m in mentions ] + # Health check - Legacy endpoint (deprecated, use /api/v1/health) + @app.get("/health") async def legacy_health_check(): return { @@ -1746,8 +1831,10 @@ async def legacy_health_check(): "plugin_manager_available": PLUGIN_MANAGER_AVAILABLE, } + # ==================== Phase 4: Agent 助手 API ==================== + @app.post("/api/v1/projects/{project_id}/agent/query") async def agent_query(project_id: str, query: AgentQuery, _=Depends(verify_api_key)): """Agent RAG 问答""" @@ -1804,6 +1891,7 @@ async def agent_query(project_id: str, query: AgentQuery, _=Depends(verify_api_k answer = await llm.rag_query(query.query, context, project_context) return {"answer": answer, "project_id": project_id} + @app.post("/api/v1/projects/{project_id}/agent/command") async def agent_command(project_id: str, command: AgentCommand, _=Depends(verify_api_key)): """Agent 指令执行 - 解析并执行自然语言指令""" @@ -1896,6 +1984,7 @@ async def agent_command(project_id: str, command: AgentCommand, _=Depends(verify return result + @app.get("/api/v1/projects/{project_id}/agent/suggest") async def agent_suggest(project_id: str, _=Depends(verify_api_key)): """获取 Agent 建议 - 基于项目数据提供洞察""" @@ -1932,8 +2021,10 @@ async def agent_suggest(project_id: str, _=Depends(verify_api_key)): return {"suggestions": []} + # ==================== Phase 4: 知识溯源 API ==================== + @app.get("/api/v1/relations/{relation_id}/provenance") async def get_relation_provenance(relation_id: str, _=Depends(verify_api_key)): """获取关系的知识溯源信息""" @@ -1962,6 +2053,7 @@ async def get_relation_provenance(relation_id: str, _=Depends(verify_api_key)): ), } + @app.get("/api/v1/entities/{entity_id}/details") async def get_entity_details(entity_id: str, _=Depends(verify_api_key)): """获取实体详情,包含所有提及位置""" @@ -1976,6 +2068,7 @@ async def get_entity_details(entity_id: str, _=Depends(verify_api_key)): return entity + @app.get("/api/v1/entities/{entity_id}/evolution") async def get_entity_evolution(entity_id: str, _=Depends(verify_api_key)): """分析实体的演变和态度变化""" @@ -2008,8 +2101,10 @@ async def get_entity_evolution(entity_id: str, _=Depends(verify_api_key)): ], } + # ==================== Phase 4: 实体管理增强 API ==================== + @app.get("/api/v1/projects/{project_id}/entities/search") async def search_entities(project_id: str, q: str, _=Depends(verify_api_key)): """搜索实体""" @@ -2022,8 +2117,10 @@ async def search_entities(project_id: str, q: str, _=Depends(verify_api_key)): {"id": e.id, "name": e.name, "type": e.type, "definition": e.definition} for e in entities ] + # ==================== Phase 5: 时间线视图 API ==================== + @app.get("/api/v1/projects/{project_id}/timeline") async def get_project_timeline( project_id: str, @@ -2045,6 +2142,7 @@ async def get_project_timeline( return {"project_id": project_id, "events": timeline, "total_count": len(timeline)} + @app.get("/api/v1/projects/{project_id}/timeline/summary") async def get_timeline_summary(project_id: str, _=Depends(verify_api_key)): """获取项目时间线摘要统计""" @@ -2060,6 +2158,7 @@ async def get_timeline_summary(project_id: str, _=Depends(verify_api_key)): return {"project_id": project_id, "project_name": project.name, **summary} + @app.get("/api/v1/entities/{entity_id}/timeline") async def get_entity_timeline(entity_id: str, _=Depends(verify_api_key)): """获取单个实体的时间线""" @@ -2081,13 +2180,16 @@ async def get_entity_timeline(entity_id: str, _=Depends(verify_api_key)): "total_count": len(timeline), } + # ==================== Phase 5: 知识推理与问答增强 API ==================== + class ReasoningQuery(BaseModel): query: str reasoning_depth: str = "medium" # shallow/medium/deep stream: bool = False + @app.post("/api/v1/projects/{project_id}/reasoning/query") async def reasoning_query(project_id: str, query: ReasoningQuery, _=Depends(verify_api_key)): """ @@ -2141,6 +2243,7 @@ async def reasoning_query(project_id: str, query: ReasoningQuery, _=Depends(veri "project_id": project_id, } + @app.post("/api/v1/projects/{project_id}/reasoning/inference-path") async def find_inference_path( project_id: str, start_entity: str, end_entity: str, _=Depends(verify_api_key) @@ -2186,9 +2289,11 @@ async def find_inference_path( "total_paths": len(paths), } + class SummaryRequest(BaseModel): summary_type: str = "comprehensive" # comprehensive/executive/technical/risk + @app.post("/api/v1/projects/{project_id}/reasoning/summary") async def project_summary(project_id: str, req: SummaryRequest, _=Depends(verify_api_key)): """ @@ -2229,8 +2334,10 @@ async def project_summary(project_id: str, req: SummaryRequest, _=Depends(verify return {"project_id": project_id, "summary_type": req.summary_type, **summary**summary} + # ==================== Phase 5: 实体属性扩展 API ==================== + class AttributeTemplateCreate(BaseModel): name: str type: str # text, number, date, select, multiselect, boolean @@ -2240,6 +2347,7 @@ class AttributeTemplateCreate(BaseModel): is_required: bool = False sort_order: int = 0 + class AttributeTemplateUpdate(BaseModel): name: str | None = None type: str | None = None @@ -2249,6 +2357,7 @@ class AttributeTemplateUpdate(BaseModel): is_required: bool | None = None sort_order: int | None = None + class EntityAttributeSet(BaseModel): name: str type: str @@ -2257,10 +2366,12 @@ class EntityAttributeSet(BaseModel): options: list[str] | None = None change_reason: str | None = "" + class EntityAttributeBatchSet(BaseModel): attributes: list[EntityAttributeSet] change_reason: str | None = "" + # 属性模板管理 API @app.post("/api/v1/projects/{project_id}/attribute-templates") async def create_attribute_template_endpoint( @@ -2298,6 +2409,7 @@ async def create_attribute_template_endpoint( "success": True, } + @app.get("/api/v1/projects/{project_id}/attribute-templates") async def list_attribute_templates_endpoint(project_id: str, _=Depends(verify_api_key)): """列出项目的所有属性模板""" @@ -2321,6 +2433,7 @@ async def list_attribute_templates_endpoint(project_id: str, _=Depends(verify_ap for t in templates ] + @app.get("/api/v1/attribute-templates/{template_id}") async def get_attribute_template_endpoint(template_id: str, _=Depends(verify_api_key)): """获取属性模板详情""" @@ -2344,6 +2457,7 @@ async def get_attribute_template_endpoint(template_id: str, _=Depends(verify_api "sort_order": template.sort_order, } + @app.put("/api/v1/attribute-templates/{template_id}") async def update_attribute_template_endpoint( template_id: str, update: AttributeTemplateUpdate, _=Depends(verify_api_key) @@ -2362,6 +2476,7 @@ async def update_attribute_template_endpoint( return {"id": updated.id, "name": updated.name, "type": updated.type, "success": True} + @app.delete("/api/v1/attribute-templates/{template_id}") async def delete_attribute_template_endpoint(template_id: str, _=Depends(verify_api_key)): """删除属性模板""" @@ -2373,6 +2488,7 @@ async def delete_attribute_template_endpoint(template_id: str, _=Depends(verify_ return {"success": True, "message": f"Template {template_id} deleted"} + # 实体属性值管理 API @app.post("/api/v1/entities/{entity_id}/attributes") async def set_entity_attribute_endpoint( @@ -2477,6 +2593,7 @@ async def set_entity_attribute_endpoint( "success": True, } + @app.post("/api/v1/entities/{entity_id}/attributes/batch") async def batch_set_entity_attributes_endpoint( entity_id: str, batch: EntityAttributeBatchSet, _=Depends(verify_api_key) @@ -2520,6 +2637,7 @@ async def batch_set_entity_attributes_endpoint( "success": True, } + @app.get("/api/v1/entities/{entity_id}/attributes") async def get_entity_attributes_endpoint(entity_id: str, _=Depends(verify_api_key)): """获取实体的所有属性值""" @@ -2544,6 +2662,7 @@ async def get_entity_attributes_endpoint(entity_id: str, _=Depends(verify_api_ke for a in attrs ] + @app.delete("/api/v1/entities/{entity_id}/attributes/{template_id}") async def delete_entity_attribute_endpoint( entity_id: str, template_id: str, reason: str | None = "", _=Depends(verify_api_key) @@ -2557,6 +2676,7 @@ async def delete_entity_attribute_endpoint( return {"success": True, "message": "Attribute deleted"} + # 属性历史 API @app.get("/api/v1/entities/{entity_id}/attributes/history") async def get_entity_attribute_history_endpoint( @@ -2582,6 +2702,7 @@ async def get_entity_attribute_history_endpoint( for h in history ] + @app.get("/api/v1/attribute-templates/{template_id}/history") async def get_template_history_endpoint( template_id: str, limit: int = 50, _=Depends(verify_api_key) @@ -2607,6 +2728,7 @@ async def get_template_history_endpoint( for h in history ] + # 属性筛选搜索 API @app.get("/api/v1/projects/{project_id}/entities/search-by-attributes") async def search_entities_by_attributes_endpoint( @@ -2643,8 +2765,10 @@ async def search_entities_by_attributes_endpoint( for e in entities ] + # ==================== 导出功能 API ==================== + @app.get("/api/v1/projects/{project_id}/export/graph-svg") async def export_graph_svg_endpoint(project_id: str, _=Depends(verify_api_key)): """导出知识图谱为 SVG""" @@ -2698,6 +2822,7 @@ async def export_graph_svg_endpoint(project_id: str, _=Depends(verify_api_key)): headers={"Content-Disposition": f"attachment; filename=insightflow-graph-{project_id}.svg"}, ) + @app.get("/api/v1/projects/{project_id}/export/graph-png") async def export_graph_png_endpoint(project_id: str, _=Depends(verify_api_key)): """导出知识图谱为 PNG""" @@ -2751,6 +2876,7 @@ async def export_graph_png_endpoint(project_id: str, _=Depends(verify_api_key)): headers={"Content-Disposition": f"attachment; filename=insightflow-graph-{project_id}.png"}, ) + @app.get("/api/v1/projects/{project_id}/export/entities-excel") async def export_entities_excel_endpoint(project_id: str, _=Depends(verify_api_key)): """导出实体数据为 Excel""" @@ -2791,6 +2917,7 @@ async def export_entities_excel_endpoint(project_id: str, _=Depends(verify_api_k }, ) + @app.get("/api/v1/projects/{project_id}/export/entities-csv") async def export_entities_csv_endpoint(project_id: str, _=Depends(verify_api_key)): """导出实体数据为 CSV""" @@ -2831,6 +2958,7 @@ async def export_entities_csv_endpoint(project_id: str, _=Depends(verify_api_key }, ) + @app.get("/api/v1/projects/{project_id}/export/relations-csv") async def export_relations_csv_endpoint(project_id: str, _=Depends(verify_api_key)): """导出关系数据为 CSV""" @@ -2869,6 +2997,7 @@ async def export_relations_csv_endpoint(project_id: str, _=Depends(verify_api_ke }, ) + @app.get("/api/v1/projects/{project_id}/export/report-pdf") async def export_report_pdf_endpoint(project_id: str, _=Depends(verify_api_key)): """导出项目报告为 PDF""" @@ -2951,6 +3080,7 @@ async def export_report_pdf_endpoint(project_id: str, _=Depends(verify_api_key)) }, ) + @app.get("/api/v1/projects/{project_id}/export/project-json") async def export_project_json_endpoint(project_id: str, _=Depends(verify_api_key)): """导出完整项目数据为 JSON""" @@ -3023,6 +3153,7 @@ async def export_project_json_endpoint(project_id: str, _=Depends(verify_api_key }, ) + @app.get("/api/v1/transcripts/{transcript_id}/export/markdown") async def export_transcript_markdown_endpoint(transcript_id: str, _=Depends(verify_api_key)): """导出转录文本为 Markdown""" @@ -3082,20 +3213,25 @@ async def export_transcript_markdown_endpoint(transcript_id: str, _=Depends(veri }, ) + # ==================== Neo4j Graph Database API ==================== + class Neo4jSyncRequest(BaseModel): project_id: str + class PathQueryRequest(BaseModel): source_entity_id: str target_entity_id: str max_depth: int = 10 + class GraphQueryRequest(BaseModel): entity_ids: list[str] depth: int = 1 + @app.get("/api/v1/neo4j/status") async def neo4j_status(_=Depends(verify_api_key)): """获取 Neo4j 连接状态""" @@ -3114,6 +3250,7 @@ async def neo4j_status(_=Depends(verify_api_key)): except Exception as e: return {"available": True, "connected": False, "message": str(e)} + @app.post("/api/v1/neo4j/sync") async def neo4j_sync_project(request: Neo4jSyncRequest, _=Depends(verify_api_key)): """同步项目数据到 Neo4j""" @@ -3178,6 +3315,7 @@ async def neo4j_sync_project(request: Neo4jSyncRequest, _=Depends(verify_api_key "message": f"Synced {len(entities_data)} entities and {len(relations_data)} relations to Neo4j", } + @app.get("/api/v1/projects/{project_id}/graph/stats") async def get_graph_stats(project_id: str, _=Depends(verify_api_key)): """获取项目图统计信息""" @@ -3191,6 +3329,7 @@ async def get_graph_stats(project_id: str, _=Depends(verify_api_key)): stats = manager.get_graph_stats(project_id) return stats + @app.post("/api/v1/graph/shortest-path") async def find_shortest_path(request: PathQueryRequest, _=Depends(verify_api_key)): """查找两个实体之间的最短路径""" @@ -3213,6 +3352,7 @@ async def find_shortest_path(request: PathQueryRequest, _=Depends(verify_api_key "path": {"nodes": path.nodes, "relationships": path.relationships, "length": path.length}, } + @app.post("/api/v1/graph/paths") async def find_all_paths(request: PathQueryRequest, _=Depends(verify_api_key)): """查找两个实体之间的所有路径""" @@ -3234,6 +3374,7 @@ async def find_all_paths(request: PathQueryRequest, _=Depends(verify_api_key)): ], } + @app.get("/api/v1/entities/{entity_id}/neighbors") async def get_entity_neighbors( entity_id: str, relation_type: str = None, limit: int = 50, _=Depends(verify_api_key) @@ -3249,6 +3390,7 @@ async def get_entity_neighbors( neighbors = manager.find_neighbors(entity_id, relation_type, limit) return {"entity_id": entity_id, "count": len(neighbors), "neighbors": neighbors} + @app.get("/api/v1/entities/{entity_id1}/common-neighbors/{entity_id2}") async def get_common_neighbors(entity_id1: str, entity_id2: str, _=Depends(verify_api_key)): """获取两个实体的共同邻居""" @@ -3267,6 +3409,7 @@ async def get_common_neighbors(entity_id1: str, entity_id2: str, _=Depends(verif "common_neighbors": common, } + @app.get("/api/v1/projects/{project_id}/graph/centrality") async def get_centrality_analysis( project_id: str, metric: str = "degree", _=Depends(verify_api_key) @@ -3294,6 +3437,7 @@ async def get_centrality_analysis( ], } + @app.get("/api/v1/projects/{project_id}/graph/communities") async def get_communities(project_id: str, _=Depends(verify_api_key)): """获取社区发现结果""" @@ -3313,6 +3457,7 @@ async def get_communities(project_id: str, _=Depends(verify_api_key)): ], } + @app.post("/api/v1/graph/subgraph") async def get_subgraph(request: GraphQueryRequest, _=Depends(verify_api_key)): """获取子图""" @@ -3326,8 +3471,10 @@ async def get_subgraph(request: GraphQueryRequest, _=Depends(verify_api_key)): subgraph = manager.get_subgraph(request.entity_ids, request.depth) return subgraph + # ==================== Phase 6: API Key Management Endpoints ==================== + @app.post("/api/v1/api-keys", response_model=ApiKeyCreateResponse, tags=["API Keys"]) async def create_api_key(request: ApiKeyCreate, _=Depends(verify_api_key)): """ @@ -3365,6 +3512,7 @@ async def create_api_key(request: ApiKeyCreate, _=Depends(verify_api_key)): ), ) + @app.get("/api/v1/api-keys", response_model=ApiKeyListResponse, tags=["API Keys"]) async def list_api_keys( status: str | None = None, limit: int = 100, offset: int = 0, _=Depends(verify_api_key) @@ -3401,6 +3549,7 @@ async def list_api_keys( total=len(keys), ) + @app.get("/api/v1/api-keys/{key_id}", response_model=ApiKeyResponse, tags=["API Keys"]) async def get_api_key(key_id: str, _=Depends(verify_api_key)): """获取单个 API Key 详情""" @@ -3426,6 +3575,7 @@ async def get_api_key(key_id: str, _=Depends(verify_api_key)): total_calls=key.total_calls, ) + @app.patch("/api/v1/api-keys/{key_id}", response_model=ApiKeyResponse, tags=["API Keys"]) async def update_api_key(key_id: str, request: ApiKeyUpdate, _=Depends(verify_api_key)): """ @@ -3470,6 +3620,7 @@ async def update_api_key(key_id: str, request: ApiKeyUpdate, _=Depends(verify_ap total_calls=key.total_calls, ) + @app.delete("/api/v1/api-keys/{key_id}", tags=["API Keys"]) async def revoke_api_key(key_id: str, reason: str = "", _=Depends(verify_api_key)): """ @@ -3488,6 +3639,7 @@ async def revoke_api_key(key_id: str, reason: str = "", _=Depends(verify_api_key return {"success": True, "message": f"API Key {key_id} revoked"} + @app.get("/api/v1/api-keys/{key_id}/stats", response_model=ApiStatsResponse, tags=["API Keys"]) async def get_api_key_stats(key_id: str, days: int = 30, _=Depends(verify_api_key)): """ @@ -3511,6 +3663,7 @@ async def get_api_key_stats(key_id: str, days: int = 30, _=Depends(verify_api_ke summary=ApiCallStats(**stats["summary"]), endpoints=stats["endpoints"], daily=stats["daily"] ) + @app.get("/api/v1/api-keys/{key_id}/logs", response_model=ApiLogsResponse, tags=["API Keys"]) async def get_api_key_logs( key_id: str, limit: int = 100, offset: int = 0, _=Depends(verify_api_key) @@ -3551,6 +3704,7 @@ async def get_api_key_logs( total=len(logs), ) + @app.get("/api/v1/rate-limit/status", response_model=RateLimitStatus, tags=["API Keys"]) async def get_rate_limit_status(request: Request, _=Depends(verify_api_key)): """获取当前请求的限流状态""" @@ -3577,13 +3731,16 @@ async def get_rate_limit_status(request: Request, _=Depends(verify_api_key)): limit=limit, remaining=info.remaining, reset_time=info.reset_time, window="minute" ) + # ==================== Phase 6: System Endpoints ==================== + @app.get("/api/v1/health", tags=["System"]) async def api_health_check(): """健康检查端点""" return {"status": "healthy", "version": "0.7.0", "timestamp": datetime.now().isoformat()} + @app.get("/api/v1/status", tags=["System"]) async def system_status(): """系统状态信息""" @@ -3613,11 +3770,13 @@ async def system_status(): return status + # ==================== Phase 7: Workflow Automation Endpoints ==================== # Workflow Manager singleton _workflow_manager = None + def get_workflow_manager_instance(): global _workflow_manager if _workflow_manager is None and WORKFLOW_AVAILABLE and DB_AVAILABLE: @@ -3628,6 +3787,7 @@ def get_workflow_manager_instance(): _workflow_manager.start() return _workflow_manager + @app.post("/api/v1/workflows", response_model=WorkflowResponse, tags=["Workflows"]) async def create_workflow_endpoint(request: WorkflowCreate, _=Depends(verify_api_key)): """ @@ -3692,6 +3852,7 @@ async def create_workflow_endpoint(request: WorkflowCreate, _=Depends(verify_api except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/workflows", response_model=WorkflowListResponse, tags=["Workflows"]) async def list_workflows_endpoint( project_id: str | None = None, @@ -3733,6 +3894,7 @@ async def list_workflows_endpoint( total=len(workflows), ) + @app.get("/api/v1/workflows/{workflow_id}", response_model=WorkflowResponse, tags=["Workflows"]) async def get_workflow_endpoint(workflow_id: str, _=Depends(verify_api_key)): """获取单个工作流详情""" @@ -3766,6 +3928,7 @@ async def get_workflow_endpoint(workflow_id: str, _=Depends(verify_api_key)): fail_count=workflow.fail_count, ) + @app.patch("/api/v1/workflows/{workflow_id}", response_model=WorkflowResponse, tags=["Workflows"]) async def update_workflow_endpoint( workflow_id: str, request: WorkflowUpdate, _=Depends(verify_api_key) @@ -3803,6 +3966,7 @@ async def update_workflow_endpoint( fail_count=updated.fail_count, ) + @app.delete("/api/v1/workflows/{workflow_id}", tags=["Workflows"]) async def delete_workflow_endpoint(workflow_id: str, _=Depends(verify_api_key)): """删除工作流""" @@ -3817,6 +3981,7 @@ async def delete_workflow_endpoint(workflow_id: str, _=Depends(verify_api_key)): return {"success": True, "message": "Workflow deleted successfully"} + @app.post( "/api/v1/workflows/{workflow_id}/trigger", response_model=WorkflowTriggerResponse, @@ -3848,6 +4013,7 @@ async def trigger_workflow_endpoint( except Exception as e: raise HTTPException(status_code=500, detail=str(e)) + @app.get( "/api/v1/workflows/{workflow_id}/logs", response_model=WorkflowLogListResponse, @@ -3887,6 +4053,7 @@ async def get_workflow_logs_endpoint( total=len(logs), ) + @app.get( "/api/v1/workflows/{workflow_id}/stats", response_model=WorkflowStatsResponse, @@ -3902,8 +4069,10 @@ async def get_workflow_stats_endpoint(workflow_id: str, days: int = 30, _=Depend return WorkflowStatsResponse(**stats) + # ==================== Phase 7: Webhook Endpoints ==================== + @app.post("/api/v1/webhooks", response_model=WebhookResponse, tags=["Webhooks"]) async def create_webhook_endpoint(request: WebhookCreate, _=Depends(verify_api_key)): """ @@ -3950,6 +4119,7 @@ async def create_webhook_endpoint(request: WebhookCreate, _=Depends(verify_api_k except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/webhooks", response_model=WebhookListResponse, tags=["Webhooks"]) async def list_webhooks_endpoint(_=Depends(verify_api_key)): """获取 Webhook 列表""" @@ -3980,6 +4150,7 @@ async def list_webhooks_endpoint(_=Depends(verify_api_key)): total=len(webhooks), ) + @app.get("/api/v1/webhooks/{webhook_id}", response_model=WebhookResponse, tags=["Webhooks"]) async def get_webhook_endpoint(webhook_id: str, _=Depends(verify_api_key)): """获取单个 Webhook 详情""" @@ -4007,6 +4178,7 @@ async def get_webhook_endpoint(webhook_id: str, _=Depends(verify_api_key)): fail_count=webhook.fail_count, ) + @app.patch("/api/v1/webhooks/{webhook_id}", response_model=WebhookResponse, tags=["Webhooks"]) async def update_webhook_endpoint( webhook_id: str, request: WebhookUpdate, _=Depends(verify_api_key) @@ -4038,6 +4210,7 @@ async def update_webhook_endpoint( fail_count=updated.fail_count, ) + @app.delete("/api/v1/webhooks/{webhook_id}", tags=["Webhooks"]) async def delete_webhook_endpoint(webhook_id: str, _=Depends(verify_api_key)): """删除 Webhook 配置""" @@ -4052,6 +4225,7 @@ async def delete_webhook_endpoint(webhook_id: str, _=Depends(verify_api_key)): return {"success": True, "message": "Webhook deleted successfully"} + @app.post("/api/v1/webhooks/{webhook_id}/test", tags=["Webhooks"]) async def test_webhook_endpoint(webhook_id: str, _=Depends(verify_api_key)): """测试 Webhook 配置""" @@ -4082,8 +4256,10 @@ async def test_webhook_endpoint(webhook_id: str, _=Depends(verify_api_key)): else: raise HTTPException(status_code=400, detail="Webhook test failed") + # ==================== Phase 7: Multimodal Support Endpoints ==================== + # Pydantic Models for Multimodal API class VideoUploadResponse(BaseModel): video_id: str @@ -4095,6 +4271,7 @@ class VideoUploadResponse(BaseModel): ocr_text_preview: str message: str + class ImageUploadResponse(BaseModel): image_id: str project_id: str @@ -4105,6 +4282,7 @@ class ImageUploadResponse(BaseModel): entity_count: int status: str + class MultimodalEntityLinkResponse(BaseModel): link_id: str source_entity_id: str @@ -4115,16 +4293,19 @@ class MultimodalEntityLinkResponse(BaseModel): confidence: float evidence: str + class MultimodalAlignmentRequest(BaseModel): project_id: str threshold: float = 0.85 + class MultimodalAlignmentResponse(BaseModel): project_id: str aligned_count: int links: list[MultimodalEntityLinkResponse] message: str + class MultimodalStatsResponse(BaseModel): project_id: str video_count: int @@ -4133,6 +4314,7 @@ class MultimodalStatsResponse(BaseModel): cross_modal_links: int modality_distribution: dict[str, int] + @app.post( "/api/v1/projects/{project_id}/upload-video", response_model=VideoUploadResponse, @@ -4315,6 +4497,7 @@ async def upload_video_endpoint( message="Video processed successfully", ) + @app.post( "/api/v1/projects/{project_id}/upload-image", response_model=ImageUploadResponse, @@ -4463,6 +4646,7 @@ async def upload_image_endpoint( status="completed", ) + @app.post("/api/v1/projects/{project_id}/upload-images-batch", tags=["Multimodal"]) async def upload_images_batch_endpoint( project_id: str, files: list[UploadFile] = File(...), _=Depends(verify_api_key) @@ -4547,6 +4731,7 @@ async def upload_images_batch_endpoint( "results": results, } + @app.post( "/api/v1/projects/{project_id}/multimodal/align", response_model=MultimodalAlignmentResponse, @@ -4655,6 +4840,7 @@ async def align_multimodal_entities_endpoint( message=f"Successfully aligned {len(saved_links)} cross-modal entity pairs", ) + @app.get( "/api/v1/projects/{project_id}/multimodal/stats", response_model=MultimodalStatsResponse, @@ -4718,6 +4904,7 @@ async def get_multimodal_stats_endpoint(project_id: str, _=Depends(verify_api_ke modality_distribution=modality_dist, ) + @app.get("/api/v1/projects/{project_id}/videos", tags=["Multimodal"]) async def list_project_videos_endpoint(project_id: str, _=Depends(verify_api_key)): """获取项目的视频列表""" @@ -4754,6 +4941,7 @@ async def list_project_videos_endpoint(project_id: str, _=Depends(verify_api_key for v in videos ] + @app.get("/api/v1/projects/{project_id}/images", tags=["Multimodal"]) async def list_project_images_endpoint(project_id: str, _=Depends(verify_api_key)): """获取项目的图片列表""" @@ -4791,6 +4979,7 @@ async def list_project_images_endpoint(project_id: str, _=Depends(verify_api_key for img in images ] + @app.get("/api/v1/videos/{video_id}/frames", tags=["Multimodal"]) async def get_video_frames_endpoint(video_id: str, _=Depends(verify_api_key)): """获取视频的关键帧列表""" @@ -4820,6 +5009,7 @@ async def get_video_frames_endpoint(video_id: str, _=Depends(verify_api_key)): for f in frames ] + @app.get("/api/v1/entities/{entity_id}/multimodal-mentions", tags=["Multimodal"]) async def get_entity_multimodal_mentions_endpoint(entity_id: str, _=Depends(verify_api_key)): """获取实体的多模态提及信息""" @@ -4854,6 +5044,7 @@ async def get_entity_multimodal_mentions_endpoint(entity_id: str, _=Depends(veri for m in mentions ] + @app.get("/api/v1/projects/{project_id}/multimodal/suggest-merges", tags=["Multimodal"]) async def suggest_multimodal_merges_endpoint(project_id: str, _=Depends(verify_api_key)): """ @@ -4937,8 +5128,10 @@ async def suggest_multimodal_merges_endpoint(project_id: str, _=Depends(verify_a ], } + # ==================== Phase 7: Multimodal Support API ==================== + class VideoUploadResponse(BaseModel): video_id: str filename: str @@ -4951,6 +5144,7 @@ class VideoUploadResponse(BaseModel): status: str message: str + class ImageUploadResponse(BaseModel): image_id: str filename: str @@ -4959,6 +5153,7 @@ class ImageUploadResponse(BaseModel): status: str message: str + class MultimodalEntityLinkResponse(BaseModel): link_id: str entity_id: str @@ -4968,12 +5163,15 @@ class MultimodalEntityLinkResponse(BaseModel): evidence: str modalities: list[str] + class MultimodalProfileResponse(BaseModel): entity_id: str entity_name: str + # ==================== Phase 7 Task 7: Plugin Management Pydantic Models ==================== + class PluginCreate(BaseModel): name: str = Field(..., description="插件名称") plugin_type: str = Field( @@ -4983,11 +5181,13 @@ class PluginCreate(BaseModel): project_id: str = Field(..., description="关联项目ID") config: dict = Field(default_factory=dict, description="插件配置") + class PluginUpdate(BaseModel): name: str | None = None status: str | None = None # active, inactive, error, pending config: dict | None = None + class PluginResponse(BaseModel): id: str name: str @@ -5000,16 +5200,19 @@ class PluginResponse(BaseModel): last_used_at: str | None use_count: int + class PluginListResponse(BaseModel): plugins: list[PluginResponse] total: int + class ChromeExtensionTokenCreate(BaseModel): name: str = Field(..., description="令牌名称") project_id: str | None = Field(default=None, description="关联项目ID") permissions: list[str] = Field(default=["read"], description="权限列表: read, write, delete") expires_days: int | None = Field(default=None, description="过期天数") + class ChromeExtensionTokenResponse(BaseModel): id: str token: str = Field(..., description="令牌(仅显示一次)") @@ -5019,6 +5222,7 @@ class ChromeExtensionTokenResponse(BaseModel): expires_at: str | None created_at: str + class ChromeExtensionImportRequest(BaseModel): token: str = Field(..., description="Chrome扩展令牌") url: str = Field(..., description="网页URL") @@ -5026,6 +5230,7 @@ class ChromeExtensionImportRequest(BaseModel): content: str = Field(..., description="网页正文内容") html_content: str | None = Field(default=None, description="HTML内容(可选)") + class BotSessionCreate(BaseModel): session_id: str = Field(..., description="群ID或会话ID") session_name: str = Field(..., description="会话名称") @@ -5033,6 +5238,7 @@ class BotSessionCreate(BaseModel): webhook_url: str = Field(default="", description="Webhook URL") secret: str = Field(default="", description="签名密钥") + class BotSessionResponse(BaseModel): id: str bot_type: str @@ -5045,16 +5251,19 @@ class BotSessionResponse(BaseModel): last_message_at: str | None message_count: int + class BotMessageRequest(BaseModel): session_id: str = Field(..., description="会话ID") msg_type: str = Field(default="text", description="消息类型: text, audio, file") content: dict = Field(default_factory=dict, description="消息内容") + class BotMessageResponse(BaseModel): success: bool response: str error: str | None = None + class WebhookEndpointCreate(BaseModel): name: str = Field(..., description="端点名称") endpoint_type: str = Field(..., description="端点类型: zapier, make, custom") @@ -5064,6 +5273,7 @@ class WebhookEndpointCreate(BaseModel): auth_config: dict = Field(default_factory=dict, description="认证配置") trigger_events: list[str] = Field(default_factory=list, description="触发事件列表") + class WebhookEndpointResponse(BaseModel): id: str name: str @@ -5077,11 +5287,13 @@ class WebhookEndpointResponse(BaseModel): last_triggered_at: str | None trigger_count: int + class WebhookTestResponse(BaseModel): success: bool endpoint_id: str message: str + class WebDAVSyncCreate(BaseModel): name: str = Field(..., description="同步配置名称") project_id: str = Field(..., description="关联项目ID") @@ -5094,6 +5306,7 @@ class WebDAVSyncCreate(BaseModel): ) sync_interval: int = Field(default=3600, description="同步间隔(秒)") + class WebDAVSyncResponse(BaseModel): id: str name: str @@ -5109,10 +5322,12 @@ class WebDAVSyncResponse(BaseModel): created_at: str sync_count: int + class WebDAVTestResponse(BaseModel): success: bool message: str + class WebDAVSyncResult(BaseModel): success: bool message: str @@ -5121,9 +5336,11 @@ class WebDAVSyncResult(BaseModel): remote_path: str | None = None error: str | None = None + # Plugin Manager singleton _plugin_manager_instance = None + def get_plugin_manager_instance(): global _plugin_manager_instance if _plugin_manager_instance is None and PLUGIN_MANAGER_AVAILABLE and DB_AVAILABLE: @@ -5131,8 +5348,10 @@ def get_plugin_manager_instance(): _plugin_manager_instance = get_plugin_manager(db) return _plugin_manager_instance + # ==================== Phase 7 Task 7: Plugin Management Endpoints ==================== + @app.post("/api/v1/plugins", response_model=PluginResponse, tags=["Plugins"]) async def create_plugin_endpoint(request: PluginCreate, _=Depends(verify_api_key)): """ @@ -5175,6 +5394,7 @@ async def create_plugin_endpoint(request: PluginCreate, _=Depends(verify_api_key use_count=created.use_count, ) + @app.get("/api/v1/plugins", response_model=PluginListResponse, tags=["Plugins"]) async def list_plugins_endpoint( project_id: str | None = None, @@ -5208,6 +5428,7 @@ async def list_plugins_endpoint( total=len(plugins), ) + @app.get("/api/v1/plugins/{plugin_id}", response_model=PluginResponse, tags=["Plugins"]) async def get_plugin_endpoint(plugin_id: str, _=Depends(verify_api_key)): """获取插件详情""" @@ -5233,6 +5454,7 @@ async def get_plugin_endpoint(plugin_id: str, _=Depends(verify_api_key)): use_count=plugin.use_count, ) + @app.patch("/api/v1/plugins/{plugin_id}", response_model=PluginResponse, tags=["Plugins"]) async def update_plugin_endpoint(plugin_id: str, request: PluginUpdate, _=Depends(verify_api_key)): """更新插件""" @@ -5260,6 +5482,7 @@ async def update_plugin_endpoint(plugin_id: str, request: PluginUpdate, _=Depend use_count=updated.use_count, ) + @app.delete("/api/v1/plugins/{plugin_id}", tags=["Plugins"]) async def delete_plugin_endpoint(plugin_id: str, _=Depends(verify_api_key)): """删除插件""" @@ -5274,8 +5497,10 @@ async def delete_plugin_endpoint(plugin_id: str, _=Depends(verify_api_key)): return {"success": True, "message": "Plugin deleted successfully"} + # ==================== Phase 7 Task 7: Chrome Extension Endpoints ==================== + @app.post( "/api/v1/plugins/chrome/tokens", response_model=ChromeExtensionTokenResponse, @@ -5315,6 +5540,7 @@ async def create_chrome_token_endpoint( created_at=token.created_at, ) + @app.get("/api/v1/plugins/chrome/tokens", tags=["Chrome Extension"]) async def list_chrome_tokens_endpoint(project_id: str | None = None, _=Depends(verify_api_key)): """列出 Chrome 扩展令牌""" @@ -5347,6 +5573,7 @@ async def list_chrome_tokens_endpoint(project_id: str | None = None, _=Depends(v "total": len(tokens), } + @app.delete("/api/v1/plugins/chrome/tokens/{token_id}", tags=["Chrome Extension"]) async def revoke_chrome_token_endpoint(token_id: str, _=Depends(verify_api_key)): """撤销 Chrome 扩展令牌""" @@ -5366,6 +5593,7 @@ async def revoke_chrome_token_endpoint(token_id: str, _=Depends(verify_api_key)) return {"success": True, "message": "Token revoked successfully"} + @app.post("/api/v1/plugins/chrome/import", tags=["Chrome Extension"]) async def chrome_import_webpage_endpoint(request: ChromeExtensionImportRequest): """ @@ -5401,8 +5629,10 @@ async def chrome_import_webpage_endpoint(request: ChromeExtensionImportRequest): return result + # ==================== Phase 7 Task 7: Bot Endpoints ==================== + @app.post("/api/v1/plugins/bot/feishu/sessions", response_model=BotSessionResponse, tags=["Bot"]) async def create_feishu_session_endpoint(request: BotSessionCreate, _=Depends(verify_api_key)): """创建飞书机器人会话""" @@ -5436,6 +5666,7 @@ async def create_feishu_session_endpoint(request: BotSessionCreate, _=Depends(ve message_count=session.message_count, ) + @app.post("/api/v1/plugins/bot/dingtalk/sessions", response_model=BotSessionResponse, tags=["Bot"]) async def create_dingtalk_session_endpoint(request: BotSessionCreate, _=Depends(verify_api_key)): """创建钉钉机器人会话""" @@ -5469,6 +5700,7 @@ async def create_dingtalk_session_endpoint(request: BotSessionCreate, _=Depends( message_count=session.message_count, ) + @app.get("/api/v1/plugins/bot/{bot_type}/sessions", tags=["Bot"]) async def list_bot_sessions_endpoint( bot_type: str, project_id: str | None = None, _=Depends(verify_api_key) @@ -5509,6 +5741,7 @@ async def list_bot_sessions_endpoint( "total": len(sessions), } + @app.post("/api/v1/plugins/bot/{bot_type}/webhook", tags=["Bot"]) async def bot_webhook_endpoint(bot_type: str, request: Request): """ @@ -5560,6 +5793,7 @@ async def bot_webhook_endpoint(bot_type: str, request: Request): return result + @app.post("/api/v1/plugins/bot/{bot_type}/sessions/{session_id}/send", tags=["Bot"]) async def send_bot_message_endpoint( bot_type: str, session_id: str, message: str, _=Depends(verify_api_key) @@ -5588,8 +5822,10 @@ async def send_bot_message_endpoint( return {"success": success, "message": "Message sent" if success else "Failed to send message"} + # ==================== Phase 7 Task 7: Integration Endpoints ==================== + @app.post( "/api/v1/plugins/integrations/zapier", response_model=WebhookEndpointResponse, @@ -5629,6 +5865,7 @@ async def create_zapier_endpoint(request: WebhookEndpointCreate, _=Depends(verif trigger_count=endpoint.trigger_count, ) + @app.post( "/api/v1/plugins/integrations/make", response_model=WebhookEndpointResponse, @@ -5668,6 +5905,7 @@ async def create_make_endpoint(request: WebhookEndpointCreate, _=Depends(verify_ trigger_count=endpoint.trigger_count, ) + @app.get("/api/v1/plugins/integrations/{endpoint_type}", tags=["Integrations"]) async def list_integration_endpoints_endpoint( endpoint_type: str, project_id: str | None = None, _=Depends(verify_api_key) @@ -5710,6 +5948,7 @@ async def list_integration_endpoints_endpoint( "total": len(endpoints), } + @app.post( "/api/v1/plugins/integrations/{endpoint_id}/test", response_model=WebhookTestResponse, @@ -5739,6 +5978,7 @@ async def test_integration_endpoint(endpoint_id: str, _=Depends(verify_api_key)) success=result["success"], endpoint_id=endpoint_id, message=result["message"] ) + @app.post("/api/v1/plugins/integrations/{endpoint_id}/trigger", tags=["Integrations"]) async def trigger_integration_endpoint( endpoint_id: str, event_type: str, data: dict, _=Depends(verify_api_key) @@ -5767,8 +6007,10 @@ async def trigger_integration_endpoint( "message": "Triggered successfully" if success else "Trigger failed", } + # ==================== Phase 7 Task 7: WebDAV Endpoints ==================== + @app.post("/api/v1/plugins/webdav", response_model=WebDAVSyncResponse, tags=["WebDAV"]) async def create_webdav_sync_endpoint(request: WebDAVSyncCreate, _=Depends(verify_api_key)): """ @@ -5812,6 +6054,7 @@ async def create_webdav_sync_endpoint(request: WebDAVSyncCreate, _=Depends(verif sync_count=sync.sync_count, ) + @app.get("/api/v1/plugins/webdav", tags=["WebDAV"]) async def list_webdav_syncs_endpoint(project_id: str | None = None, _=Depends(verify_api_key)): """列出 WebDAV 同步配置""" @@ -5848,6 +6091,7 @@ async def list_webdav_syncs_endpoint(project_id: str | None = None, _=Depends(ve "total": len(syncs), } + @app.post( "/api/v1/plugins/webdav/{sync_id}/test", response_model=WebDAVTestResponse, tags=["WebDAV"] ) @@ -5873,6 +6117,7 @@ async def test_webdav_connection_endpoint(sync_id: str, _=Depends(verify_api_key message=result.get("message") or result.get("error", "Unknown result"), ) + @app.post("/api/v1/plugins/webdav/{sync_id}/sync", response_model=WebDAVSyncResult, tags=["WebDAV"]) async def sync_webdav_endpoint(sync_id: str, _=Depends(verify_api_key)): """执行 WebDAV 同步""" @@ -5900,6 +6145,7 @@ async def sync_webdav_endpoint(sync_id: str, _=Depends(verify_api_key)): error=result.get("error"), ) + @app.delete("/api/v1/plugins/webdav/{sync_id}", tags=["WebDAV"]) async def delete_webdav_sync_endpoint(sync_id: str, _=Depends(verify_api_key)): """删除 WebDAV 同步配置""" @@ -5919,6 +6165,7 @@ async def delete_webdav_sync_endpoint(sync_id: str, _=Depends(verify_api_key)): return {"success": True, "message": "WebDAV sync configuration deleted"} + @app.get("/api/v1/openapi.json", include_in_schema=False) async def get_openapi(): """获取 OpenAPI 规范""" @@ -5932,6 +6179,7 @@ async def get_openapi(): tags=app.openapi_tags, ) + # Serve frontend - MUST be last to not override API routes app.mount("/", StaticFiles(directory="frontend", html=True), name="frontend") @@ -5940,12 +6188,14 @@ if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000) + class PluginCreateRequest(BaseModel): name: str plugin_type: str project_id: str | None = None config: dict | None = {} + class PluginResponse(BaseModel): id: str name: str @@ -5955,6 +6205,7 @@ class PluginResponse(BaseModel): api_key: str created_at: str + class BotSessionResponse(BaseModel): id: str plugin_id: str @@ -5967,6 +6218,7 @@ class BotSessionResponse(BaseModel): created_at: str last_message_at: str | None + class WebhookEndpointResponse(BaseModel): id: str plugin_id: str @@ -5978,6 +6230,7 @@ class WebhookEndpointResponse(BaseModel): trigger_count: int created_at: str + class WebDAVSyncResponse(BaseModel): id: str plugin_id: str @@ -5993,6 +6246,7 @@ class WebDAVSyncResponse(BaseModel): last_sync_at: str | None created_at: str + class ChromeClipRequest(BaseModel): url: str title: str @@ -6001,6 +6255,7 @@ class ChromeClipRequest(BaseModel): meta: dict | None = {} project_id: str | None = None + class ChromeClipResponse(BaseModel): clip_id: str project_id: str @@ -6009,6 +6264,7 @@ class ChromeClipResponse(BaseModel): status: str message: str + class BotMessagePayload(BaseModel): platform: str session_id: str @@ -6018,16 +6274,19 @@ class BotMessagePayload(BaseModel): content: str project_id: str | None = None + class BotMessageResult(BaseModel): success: bool reply: str | None = None session_id: str action: str | None = None + class WebhookPayload(BaseModel): event: str data: dict + @app.post("/api/v1/plugins", response_model=PluginResponse, tags=["Plugins"]) async def create_plugin(request: PluginCreateRequest, api_key: str = Depends(verify_api_key)): """创建插件""" @@ -6052,6 +6311,7 @@ async def create_plugin(request: PluginCreateRequest, api_key: str = Depends(ver created_at=plugin.created_at, ) + @app.get("/api/v1/plugins", tags=["Plugins"]) async def list_plugins( project_id: str | None = None, @@ -6080,6 +6340,7 @@ async def list_plugins( ] } + @app.get("/api/v1/plugins/{plugin_id}", response_model=PluginResponse, tags=["Plugins"]) async def get_plugin(plugin_id: str, api_key: str = Depends(verify_api_key)): """获取插件详情""" @@ -6102,6 +6363,7 @@ async def get_plugin(plugin_id: str, api_key: str = Depends(verify_api_key)): created_at=plugin.created_at, ) + @app.delete("/api/v1/plugins/{plugin_id}", tags=["Plugins"]) async def delete_plugin(plugin_id: str, api_key: str = Depends(verify_api_key)): """删除插件""" @@ -6113,6 +6375,7 @@ async def delete_plugin(plugin_id: str, api_key: str = Depends(verify_api_key)): return {"success": True, "message": "Plugin deleted"} + @app.post("/api/v1/plugins/{plugin_id}/regenerate-key", tags=["Plugins"]) async def regenerate_plugin_key(plugin_id: str, api_key: str = Depends(verify_api_key)): """重新生成插件 API Key""" @@ -6124,8 +6387,10 @@ async def regenerate_plugin_key(plugin_id: str, api_key: str = Depends(verify_ap return {"success": True, "api_key": new_key} + # ==================== Chrome Extension API ==================== + @app.post( "/api/v1/plugins/chrome/clip", response_model=ChromeClipResponse, tags=["Chrome Extension"] ) @@ -6197,8 +6462,10 @@ URL: {request.url} message="Content saved successfully", ) + # ==================== Bot API ==================== + @app.post("/api/v1/bots/webhook/{platform}", response_model=BotMessageResponse, tags=["Bot"]) async def bot_webhook( platform: str, request: Request, x_signature: str | None = Header(None, alias="X-Signature") @@ -6234,6 +6501,7 @@ async def bot_webhook( action="reply", ) + @app.get("/api/v1/bots/sessions", response_model=list[BotSessionResponse], tags=["Bot"]) async def list_bot_sessions( plugin_id: str | None = None, @@ -6263,8 +6531,10 @@ async def list_bot_sessions( for s in sessions ] + # ==================== Webhook Integration API ==================== + @app.post( "/api/v1/webhook-endpoints", response_model=WebhookEndpointResponse, tags=["Integrations"] ) @@ -6301,6 +6571,7 @@ async def create_integration_webhook_endpoint( created_at=endpoint.created_at, ) + @app.get( "/api/v1/webhook-endpoints", response_model=list[WebhookEndpointResponse], tags=["Integrations"] ) @@ -6329,6 +6600,7 @@ async def list_webhook_endpoints( for e in endpoints ] + @app.post("/webhook/{endpoint_type}/{token}", tags=["Integrations"]) async def receive_webhook( endpoint_type: str, @@ -6379,8 +6651,10 @@ async def receive_webhook( return {"success": True, "endpoint_id": endpoint.id, "received_at": datetime.now().isoformat()} + # ==================== WebDAV API ==================== + @app.post("/api/v1/webdav-syncs", response_model=WebDAVSyncResponse, tags=["WebDAV"]) async def create_webdav_sync( plugin_id: str, @@ -6429,6 +6703,7 @@ async def create_webdav_sync( created_at=sync.created_at, ) + @app.get("/api/v1/webdav-syncs", response_model=list[WebDAVSyncResponse], tags=["WebDAV"]) async def list_webdav_syncs(plugin_id: str | None = None, api_key: str = Depends(verify_api_key)): """列出 WebDAV 同步配置""" @@ -6457,6 +6732,7 @@ async def list_webdav_syncs(plugin_id: str | None = None, api_key: str = Depends for s in syncs ] + @app.post("/api/v1/webdav-syncs/{sync_id}/test", tags=["WebDAV"]) async def test_webdav_connection(sync_id: str, api_key: str = Depends(verify_api_key)): """测试 WebDAV 连接""" @@ -6477,6 +6753,7 @@ async def test_webdav_connection(sync_id: str, api_key: str = Depends(verify_api return {"success": success, "message": message} + @app.post("/api/v1/webdav-syncs/{sync_id}/sync", tags=["WebDAV"]) async def trigger_webdav_sync(sync_id: str, api_key: str = Depends(verify_api_key)): """手动触发 WebDAV 同步""" @@ -6498,8 +6775,10 @@ async def trigger_webdav_sync(sync_id: str, api_key: str = Depends(verify_api_ke return {"success": True, "sync_id": sync_id, "status": "running", "message": "Sync started"} + # ==================== Plugin Activity Logs ==================== + @app.get("/api/v1/plugins/{plugin_id}/logs", tags=["Plugins"]) async def get_plugin_logs( plugin_id: str, @@ -6527,8 +6806,10 @@ async def get_plugin_logs( ] } + # ==================== Phase 7 Task 3: Security & Compliance API ==================== + # Pydantic models for security API class AuditLogResponse(BaseModel): id: str @@ -6542,15 +6823,18 @@ class AuditLogResponse(BaseModel): error_message: str | None = None created_at: str + class AuditStatsResponse(BaseModel): total_actions: int success_count: int failure_count: int action_breakdown: dict[str, dict[str, int]] + class EncryptionEnableRequest(BaseModel): master_password: str + class EncryptionConfigResponse(BaseModel): id: str project_id: str @@ -6559,6 +6843,7 @@ class EncryptionConfigResponse(BaseModel): created_at: str updated_at: str + class MaskingRuleCreateRequest(BaseModel): name: str rule_type: str # phone, email, id_card, bank_card, name, address, custom @@ -6567,6 +6852,7 @@ class MaskingRuleCreateRequest(BaseModel): description: str | None = None priority: int = 0 + class MaskingRuleResponse(BaseModel): id: str project_id: str @@ -6580,15 +6866,18 @@ class MaskingRuleResponse(BaseModel): created_at: str updated_at: str + class MaskingApplyRequest(BaseModel): text: str rule_types: list[str] | None = None + class MaskingApplyResponse(BaseModel): original_text: str masked_text: str applied_rules: list[str] + class AccessPolicyCreateRequest(BaseModel): name: str description: str | None = None @@ -6599,6 +6888,7 @@ class AccessPolicyCreateRequest(BaseModel): max_access_count: int | None = None require_approval: bool = False + class AccessPolicyResponse(BaseModel): id: str project_id: str @@ -6614,11 +6904,13 @@ class AccessPolicyResponse(BaseModel): created_at: str updated_at: str + class AccessRequestCreateRequest(BaseModel): policy_id: str request_reason: str | None = None expires_hours: int = 24 + class AccessRequestResponse(BaseModel): id: str policy_id: str @@ -6630,8 +6922,10 @@ class AccessRequestResponse(BaseModel): expires_at: str | None = None created_at: str + # ==================== Audit Logs API ==================== + @app.get("/api/v1/audit-logs", response_model=list[AuditLogResponse], tags=["Security"]) async def get_audit_logs( user_id: str | None = None, @@ -6678,6 +6972,7 @@ async def get_audit_logs( for log in logs ] + @app.get("/api/v1/audit-logs/stats", response_model=AuditStatsResponse, tags=["Security"]) async def get_audit_stats( start_time: str | None = None, @@ -6693,8 +6988,10 @@ async def get_audit_stats( return AuditStatsResponse(**stats) + # ==================== Encryption API ==================== + @app.post( "/api/v1/projects/{project_id}/encryption/enable", response_model=EncryptionConfigResponse, @@ -6722,6 +7019,7 @@ async def enable_project_encryption( except RuntimeError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.post("/api/v1/projects/{project_id}/encryption/disable", tags=["Security"]) async def disable_project_encryption( project_id: str, request: EncryptionEnableRequest, api_key: str = Depends(verify_api_key) @@ -6738,6 +7036,7 @@ async def disable_project_encryption( return {"success": True, "message": "Encryption disabled successfully"} + @app.post("/api/v1/projects/{project_id}/encryption/verify", tags=["Security"]) async def verify_encryption_password( project_id: str, request: EncryptionEnableRequest, api_key: str = Depends(verify_api_key) @@ -6751,6 +7050,7 @@ async def verify_encryption_password( return {"valid": is_valid} + @app.get( "/api/v1/projects/{project_id}/encryption", response_model=Optional[EncryptionConfigResponse], @@ -6776,8 +7076,10 @@ async def get_encryption_config(project_id: str, api_key: str = Depends(verify_a updated_at=config.updated_at, ) + # ==================== Data Masking API ==================== + @app.post( "/api/v1/projects/{project_id}/masking-rules", response_model=MaskingRuleResponse, @@ -6821,6 +7123,7 @@ async def create_masking_rule( updated_at=rule.updated_at, ) + @app.get( "/api/v1/projects/{project_id}/masking-rules", response_model=list[MaskingRuleResponse], @@ -6853,6 +7156,7 @@ async def get_masking_rules( for rule in rules ] + @app.put("/api/v1/masking-rules/{rule_id}", response_model=MaskingRuleResponse, tags=["Security"]) async def update_masking_rule( rule_id: str, @@ -6903,6 +7207,7 @@ async def update_masking_rule( updated_at=rule.updated_at, ) + @app.delete("/api/v1/masking-rules/{rule_id}", tags=["Security"]) async def delete_masking_rule(rule_id: str, api_key: str = Depends(verify_api_key)): """删除脱敏规则""" @@ -6917,6 +7222,7 @@ async def delete_masking_rule(rule_id: str, api_key: str = Depends(verify_api_ke return {"success": True, "message": "Masking rule deleted"} + @app.post( "/api/v1/projects/{project_id}/masking/apply", response_model=MaskingApplyResponse, @@ -6946,8 +7252,10 @@ async def apply_masking( original_text=request.text, masked_text=masked_text, applied_rules=applied_rules ) + # ==================== Data Access Policy API ==================== + @app.post( "/api/v1/projects/{project_id}/access-policies", response_model=AccessPolicyResponse, @@ -6992,6 +7300,7 @@ async def create_access_policy( updated_at=policy.updated_at, ) + @app.get( "/api/v1/projects/{project_id}/access-policies", response_model=list[AccessPolicyResponse], @@ -7028,6 +7337,7 @@ async def get_access_policies( for policy in policies ] + @app.post("/api/v1/access-policies/{policy_id}/check", tags=["Security"]) async def check_access_permission( policy_id: str, user_id: str, user_ip: str | None = None, api_key: str = Depends(verify_api_key) @@ -7041,8 +7351,10 @@ async def check_access_permission( return {"allowed": allowed, "reason": reason if not allowed else None} + # ==================== Access Request API ==================== + @app.post("/api/v1/access-requests", response_model=AccessRequestResponse, tags=["Security"]) async def create_access_request( request: AccessRequestCreateRequest, @@ -7074,6 +7386,7 @@ async def create_access_request( created_at=access_request.created_at, ) + @app.post( "/api/v1/access-requests/{request_id}/approve", response_model=AccessRequestResponse, @@ -7107,6 +7420,7 @@ async def approve_access_request( created_at=access_request.created_at, ) + @app.post( "/api/v1/access-requests/{request_id}/reject", response_model=AccessRequestResponse, @@ -7137,12 +7451,14 @@ async def reject_access_request( created_at=access_request.created_at, ) + # ========================================== # Phase 7 Task 4: 协作与共享 API # ========================================== # ----- 请求模型 ----- + class ShareLinkCreate(BaseModel): permission: str = "read_only" # read_only, comment, edit, admin expires_in_days: int | None = None @@ -7151,10 +7467,12 @@ class ShareLinkCreate(BaseModel): allow_download: bool = False allow_export: bool = False + class ShareLinkVerify(BaseModel): token: str password: str | None = None + class CommentCreate(BaseModel): target_type: str # entity, relation, transcript, project target_id: str @@ -7162,23 +7480,29 @@ class CommentCreate(BaseModel): content: str mentions: list[str] | None = None + class CommentUpdate(BaseModel): content: str + class CommentResolve(BaseModel): resolved: bool + class TeamMemberInvite(BaseModel): user_id: str user_name: str user_email: str role: str = "viewer" # owner, admin, editor, viewer, commenter + class TeamMemberRoleUpdate(BaseModel): role: str + # ----- 项目分享 ----- + @app.post("/api/v1/projects/{project_id}/shares") async def create_share_link( project_id: str, request: ShareLinkCreate, created_by: str = "current_user" @@ -7209,6 +7533,7 @@ async def create_share_link( "share_url": f"/share/{share.token}", } + @app.get("/api/v1/projects/{project_id}/shares") async def list_project_shares(project_id: str): """列出项目的所有分享链接""" @@ -7237,6 +7562,7 @@ async def list_project_shares(project_id: str): ] } + @app.post("/api/v1/shares/verify") async def verify_share_link(request: ShareLinkVerify): """验证分享链接""" @@ -7260,6 +7586,7 @@ async def verify_share_link(request: ShareLinkVerify): "allow_export": share.allow_export, } + @app.get("/api/v1/shares/{token}/access") async def access_shared_project(token: str, password: str | None = None): """通过分享链接访问项目""" @@ -7297,6 +7624,7 @@ async def access_shared_project(token: str, password: str | None = None): "allow_export": share.allow_export, } + @app.delete("/api/v1/shares/{share_id}") async def revoke_share_link(share_id: str, revoked_by: str = "current_user"): """撤销分享链接""" @@ -7311,8 +7639,10 @@ async def revoke_share_link(share_id: str, revoked_by: str = "current_user"): return {"success": True, "message": "Share link revoked"} + # ----- 评论和批注 ----- + @app.post("/api/v1/projects/{project_id}/comments") async def add_comment( project_id: str, request: CommentCreate, author: str = "current_user", author_name: str = "User" @@ -7345,6 +7675,7 @@ async def add_comment( "resolved": comment.resolved, } + @app.get("/api/v1/{target_type}/{target_id}/comments") async def get_comments(target_type: str, target_id: str, include_resolved: bool = True): """获取评论列表""" @@ -7373,6 +7704,7 @@ async def get_comments(target_type: str, target_id: str, include_resolved: bool ], } + @app.get("/api/v1/projects/{project_id}/comments") async def get_project_comments(project_id: str, limit: int = 50, offset: int = 0): """获取项目下的所有评论""" @@ -7400,6 +7732,7 @@ async def get_project_comments(project_id: str, limit: int = 50, offset: int = 0 ], } + @app.put("/api/v1/comments/{comment_id}") async def update_comment(comment_id: str, request: CommentUpdate, updated_by: str = "current_user"): """更新评论""" @@ -7414,6 +7747,7 @@ async def update_comment(comment_id: str, request: CommentUpdate, updated_by: st return {"id": comment.id, "content": comment.content, "updated_at": comment.updated_at} + @app.post("/api/v1/comments/{comment_id}/resolve") async def resolve_comment(comment_id: str, resolved_by: str = "current_user"): """标记评论为已解决""" @@ -7428,6 +7762,7 @@ async def resolve_comment(comment_id: str, resolved_by: str = "current_user"): return {"success": True, "message": "Comment resolved"} + @app.delete("/api/v1/comments/{comment_id}") async def delete_comment(comment_id: str, deleted_by: str = "current_user"): """删除评论""" @@ -7442,8 +7777,10 @@ async def delete_comment(comment_id: str, deleted_by: str = "current_user"): return {"success": True, "message": "Comment deleted"} + # ----- 变更历史 ----- + @app.get("/api/v1/projects/{project_id}/history") async def get_change_history( project_id: str, @@ -7480,6 +7817,7 @@ async def get_change_history( ], } + @app.get("/api/v1/projects/{project_id}/history/stats") async def get_change_history_stats(project_id: str): """获取变更统计""" @@ -7491,6 +7829,7 @@ async def get_change_history_stats(project_id: str): return stats + @app.get("/api/v1/{entity_type}/{entity_id}/versions") async def get_entity_versions(entity_type: str, entity_id: str): """获取实体版本历史""" @@ -7517,6 +7856,7 @@ async def get_entity_versions(entity_type: str, entity_id: str): ], } + @app.post("/api/v1/history/{record_id}/revert") async def revert_change(record_id: str, reverted_by: str = "current_user"): """回滚变更""" @@ -7531,8 +7871,10 @@ async def revert_change(record_id: str, reverted_by: str = "current_user"): return {"success": True, "message": "Change reverted"} + # ----- 团队成员 ----- + @app.post("/api/v1/projects/{project_id}/members") async def invite_team_member( project_id: str, request: TeamMemberInvite, invited_by: str = "current_user" @@ -7561,6 +7903,7 @@ async def invite_team_member( "permissions": member.permissions, } + @app.get("/api/v1/projects/{project_id}/members") async def list_team_members(project_id: str): """列出团队成员""" @@ -7587,6 +7930,7 @@ async def list_team_members(project_id: str): ], } + @app.put("/api/v1/members/{member_id}/role") async def update_member_role( member_id: str, request: TeamMemberRoleUpdate, updated_by: str = "current_user" @@ -7603,6 +7947,7 @@ async def update_member_role( return {"success": True, "message": "Member role updated"} + @app.delete("/api/v1/members/{member_id}") async def remove_team_member(member_id: str, removed_by: str = "current_user"): """移除团队成员""" @@ -7617,6 +7962,7 @@ async def remove_team_member(member_id: str, removed_by: str = "current_user"): return {"success": True, "message": "Member removed"} + @app.get("/api/v1/projects/{project_id}/permissions") async def check_project_permissions(project_id: str, user_id: str = "current_user"): """检查用户权限""" @@ -7637,8 +7983,10 @@ async def check_project_permissions(project_id: str, user_id: str = "current_use return {"has_access": True, "role": user_member.role, "permissions": user_member.permissions} + # ==================== Phase 7 Task 6: Advanced Search & Discovery ==================== + class FullTextSearchRequest(BaseModel): """全文搜索请求""" @@ -7647,6 +7995,7 @@ class FullTextSearchRequest(BaseModel): operator: str = "AND" # AND, OR, NOT limit: int = 20 + class SemanticSearchRequest(BaseModel): """语义搜索请求""" @@ -7655,6 +8004,7 @@ class SemanticSearchRequest(BaseModel): threshold: float = 0.7 limit: int = 20 + @app.post("/api/v1/search/fulltext", tags=["Search"]) async def fulltext_search( project_id: str, request: FullTextSearchRequest, _=Depends(verify_api_key) @@ -7695,6 +8045,7 @@ async def fulltext_search( ], } + @app.post("/api/v1/search/semantic", tags=["Search"]) async def semantic_search( project_id: str, request: SemanticSearchRequest, _=Depends(verify_api_key) @@ -7723,6 +8074,7 @@ async def semantic_search( ], } + @app.get("/api/v1/entities/{entity_id}/paths/{target_entity_id}", tags=["Search"]) async def find_entity_paths( entity_id: str, @@ -7763,6 +8115,7 @@ async def find_entity_paths( ], } + @app.get("/api/v1/entities/{entity_id}/network", tags=["Search"]) async def get_entity_network(entity_id: str, depth: int = 2, _=Depends(verify_api_key)): """获取实体关系网络""" @@ -7774,6 +8127,7 @@ async def get_entity_network(entity_id: str, depth: int = 2, _=Depends(verify_ap return network + @app.get("/api/v1/projects/{project_id}/knowledge-gaps", tags=["Search"]) async def detect_knowledge_gaps(project_id: str, _=Depends(verify_api_key)): """检测知识缺口""" @@ -7803,6 +8157,7 @@ async def detect_knowledge_gaps(project_id: str, _=Depends(verify_api_key)): ], } + @app.post("/api/v1/projects/{project_id}/search/index", tags=["Search"]) async def index_project_for_search(project_id: str, _=Depends(verify_api_key)): """为项目创建搜索索引""" @@ -7817,8 +8172,10 @@ async def index_project_for_search(project_id: str, _=Depends(verify_api_key)): else: raise HTTPException(status_code=500, detail="Failed to index project") + # ==================== Phase 7 Task 8: Performance & Scaling ==================== + @app.get("/api/v1/cache/stats", tags=["Performance"]) async def get_cache_stats(_=Depends(verify_api_key)): """获取缓存统计""" @@ -7838,6 +8195,7 @@ async def get_cache_stats(_=Depends(verify_api_key)): "expired_count": stats.expired_count, } + @app.post("/api/v1/cache/clear", tags=["Performance"]) async def clear_cache(pattern: str | None = None, _=Depends(verify_api_key)): """清除缓存""" @@ -7852,6 +8210,7 @@ async def clear_cache(pattern: str | None = None, _=Depends(verify_api_key)): else: raise HTTPException(status_code=500, detail="Failed to clear cache") + @app.get("/api/v1/performance/metrics", tags=["Performance"]) async def get_performance_metrics( metric_type: str | None = None, @@ -7888,6 +8247,7 @@ async def get_performance_metrics( ], } + @app.get("/api/v1/performance/summary", tags=["Performance"]) async def get_performance_summary(hours: int = 24, _=Depends(verify_api_key)): """获取性能汇总统计""" @@ -7899,6 +8259,7 @@ async def get_performance_summary(hours: int = 24, _=Depends(verify_api_key)): return summary + @app.get("/api/v1/tasks/{task_id}/status", tags=["Performance"]) async def get_task_status(task_id: str, _=Depends(verify_api_key)): """获取任务状态""" @@ -7926,6 +8287,7 @@ async def get_task_status(task_id: str, _=Depends(verify_api_key)): "priority": task.priority, } + @app.get("/api/v1/tasks", tags=["Performance"]) async def list_tasks( project_id: str | None = None, @@ -7956,6 +8318,7 @@ async def list_tasks( ], } + @app.post("/api/v1/tasks/{task_id}/cancel", tags=["Performance"]) async def cancel_task(task_id: str, _=Depends(verify_api_key)): """取消任务""" @@ -7972,6 +8335,7 @@ async def cancel_task(task_id: str, _=Depends(verify_api_key)): status_code=400, detail="Failed to cancel task or task already completed" ) + @app.get("/api/v1/shards", tags=["Performance"]) async def list_shards(_=Depends(verify_api_key)): """列出数据库分片""" @@ -7994,25 +8358,30 @@ async def list_shards(_=Depends(verify_api_key)): ], } + # ============================================ # Phase 8: Multi-Tenant SaaS APIs # ============================================ + class CreateTenantRequest(BaseModel): name: str description: str | None = None tier: str = "free" + class UpdateTenantRequest(BaseModel): name: str | None = None description: str | None = None tier: str | None = None status: str | None = None + class AddDomainRequest(BaseModel): domain: str is_primary: bool = False + class UpdateBrandingRequest(BaseModel): logo_url: str | None = None favicon_url: str | None = None @@ -8022,13 +8391,16 @@ class UpdateBrandingRequest(BaseModel): custom_js: str | None = None login_page_bg: str | None = None + class InviteMemberRequest(BaseModel): email: str role: str = "member" + class UpdateMemberRequest(BaseModel): role: str | None = None + # Tenant Management APIs @app.post("/api/v1/tenants", tags=["Tenants"]) async def create_tenant( @@ -8056,6 +8428,7 @@ async def create_tenant( except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/tenants", tags=["Tenants"]) async def list_my_tenants( user_id: str = Header(..., description="当前用户ID"), _=Depends(verify_api_key) @@ -8068,6 +8441,7 @@ async def list_my_tenants( tenants = manager.get_user_tenants(user_id) return {"tenants": tenants} + @app.get("/api/v1/tenants/{tenant_id}", tags=["Tenants"]) async def get_tenant(tenant_id: str, _=Depends(verify_api_key)): """获取租户详情""" @@ -8093,6 +8467,7 @@ async def get_tenant(tenant_id: str, _=Depends(verify_api_key)): "resource_limits": tenant.resource_limits, } + @app.put("/api/v1/tenants/{tenant_id}", tags=["Tenants"]) async def update_tenant(tenant_id: str, request: UpdateTenantRequest, _=Depends(verify_api_key)): """更新租户信息""" @@ -8120,6 +8495,7 @@ async def update_tenant(tenant_id: str, request: UpdateTenantRequest, _=Depends( "updated_at": tenant.updated_at.isoformat(), } + @app.delete("/api/v1/tenants/{tenant_id}", tags=["Tenants"]) async def delete_tenant(tenant_id: str, _=Depends(verify_api_key)): """删除租户""" @@ -8134,6 +8510,7 @@ async def delete_tenant(tenant_id: str, _=Depends(verify_api_key)): return {"message": "Tenant deleted successfully"} + # Domain Management APIs @app.post("/api/v1/tenants/{tenant_id}/domains", tags=["Tenants"]) async def add_domain(tenant_id: str, request: AddDomainRequest, _=Depends(verify_api_key)): @@ -8162,6 +8539,7 @@ async def add_domain(tenant_id: str, request: AddDomainRequest, _=Depends(verify except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/tenants/{tenant_id}/domains", tags=["Tenants"]) async def list_domains(tenant_id: str, _=Depends(verify_api_key)): """列出租户的所有域名""" @@ -8186,6 +8564,7 @@ async def list_domains(tenant_id: str, _=Depends(verify_api_key)): ] } + @app.post("/api/v1/tenants/{tenant_id}/domains/{domain_id}/verify", tags=["Tenants"]) async def verify_domain(tenant_id: str, domain_id: str, _=Depends(verify_api_key)): """验证域名所有权""" @@ -8200,6 +8579,7 @@ async def verify_domain(tenant_id: str, domain_id: str, _=Depends(verify_api_key "message": "Domain verified successfully" if success else "Domain verification failed", } + @app.delete("/api/v1/tenants/{tenant_id}/domains/{domain_id}", tags=["Tenants"]) async def remove_domain(tenant_id: str, domain_id: str, _=Depends(verify_api_key)): """移除域名绑定""" @@ -8214,6 +8594,7 @@ async def remove_domain(tenant_id: str, domain_id: str, _=Depends(verify_api_key return {"message": "Domain removed successfully"} + # Branding APIs @app.get("/api/v1/tenants/{tenant_id}/branding", tags=["Tenants"]) async def get_branding(tenant_id: str, _=Depends(verify_api_key)): @@ -8245,6 +8626,7 @@ async def get_branding(tenant_id: str, _=Depends(verify_api_key)): "login_page_bg": branding.login_page_bg, } + @app.put("/api/v1/tenants/{tenant_id}/branding", tags=["Tenants"]) async def update_branding( tenant_id: str, request: UpdateBrandingRequest, _=Depends(verify_api_key) @@ -8274,6 +8656,7 @@ async def update_branding( "updated_at": branding.updated_at.isoformat(), } + @app.get("/api/v1/tenants/{tenant_id}/branding.css", tags=["Tenants"]) async def get_branding_css(tenant_id: str): """获取租户品牌 CSS(公开端点,无需认证)""" @@ -8287,6 +8670,7 @@ async def get_branding_css(tenant_id: str): return PlainTextResponse(content=css, media_type="text/css") + # Member Management APIs @app.post("/api/v1/tenants/{tenant_id}/members", tags=["Tenants"]) async def invite_member( @@ -8315,6 +8699,7 @@ async def invite_member( except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/tenants/{tenant_id}/members", tags=["Tenants"]) async def list_members(tenant_id: str, status: str | None = None, _=Depends(verify_api_key)): """列出租户成员""" @@ -8341,6 +8726,7 @@ async def list_members(tenant_id: str, status: str | None = None, _=Depends(veri ] } + @app.put("/api/v1/tenants/{tenant_id}/members/{member_id}", tags=["Tenants"]) async def update_member( tenant_id: str, member_id: str, request: UpdateMemberRequest, _=Depends(verify_api_key) @@ -8357,6 +8743,7 @@ async def update_member( return {"message": "Member updated successfully"} + @app.delete("/api/v1/tenants/{tenant_id}/members/{member_id}", tags=["Tenants"]) async def remove_member(tenant_id: str, member_id: str, _=Depends(verify_api_key)): """移除成员""" @@ -8371,6 +8758,7 @@ async def remove_member(tenant_id: str, member_id: str, _=Depends(verify_api_key return {"message": "Member removed successfully"} + # Usage & Limits APIs @app.get("/api/v1/tenants/{tenant_id}/usage", tags=["Tenants"]) async def get_tenant_usage(tenant_id: str, _=Depends(verify_api_key)): @@ -8383,6 +8771,7 @@ async def get_tenant_usage(tenant_id: str, _=Depends(verify_api_key)): return stats + @app.get("/api/v1/tenants/{tenant_id}/limits/{resource_type}", tags=["Tenants"]) async def check_resource_limit(tenant_id: str, resource_type: str, _=Depends(verify_api_key)): """检查特定资源是否超限""" @@ -8400,6 +8789,7 @@ async def check_resource_limit(tenant_id: str, resource_type: str, _=Depends(ver "usage_percentage": round(current / limit * 100, 2) if limit > 0 else 0, } + # Public tenant resolution API (for custom domains) @app.get("/api/v1/resolve-tenant", tags=["Tenants"]) async def resolve_tenant_by_domain(domain: str): @@ -8427,6 +8817,7 @@ async def resolve_tenant_by_domain(domain: str): }, } + @app.get("/api/v1/health", tags=["System"]) async def detailed_health_check(): """健康检查""" @@ -8472,8 +8863,10 @@ async def detailed_health_check(): return health + # ==================== Phase 8: Multi-Tenant SaaS API ==================== + # Pydantic Models for Tenant API class TenantCreate(BaseModel): name: str = Field(..., description="租户名称") @@ -8484,6 +8877,7 @@ class TenantCreate(BaseModel): ) billing_email: str = Field(default="", description="计费邮箱") + class TenantUpdate(BaseModel): name: str | None = None description: str | None = None @@ -8493,6 +8887,7 @@ class TenantUpdate(BaseModel): max_projects: int | None = None max_members: int | None = None + class TenantResponse(BaseModel): id: str name: str @@ -8508,9 +8903,11 @@ class TenantResponse(BaseModel): created_at: str updated_at: str + class TenantDomainCreate(BaseModel): domain: str = Field(..., description="自定义域名") + class TenantDomainResponse(BaseModel): id: str tenant_id: str @@ -8522,6 +8919,7 @@ class TenantDomainResponse(BaseModel): created_at: str verified_at: str | None + class TenantBrandingUpdate(BaseModel): logo_url: str | None = None logo_dark_url: str | None = None @@ -8542,11 +8940,13 @@ class TenantBrandingUpdate(BaseModel): login_page_description: str | None = None footer_text: str | None = None + class TenantMemberInvite(BaseModel): email: str = Field(..., description="被邀请者邮箱") name: str = Field(default="", description="被邀请者姓名") role: str = Field(default="viewer", description="角色: owner, admin, editor, viewer, guest") + class TenantMemberResponse(BaseModel): id: str tenant_id: str @@ -8561,11 +8961,13 @@ class TenantMemberResponse(BaseModel): last_active_at: str | None created_at: str + class TenantRoleCreate(BaseModel): name: str = Field(..., description="角色名称") description: str = Field(default="", description="角色描述") permissions: list[str] = Field(default_factory=list, description="权限列表") + class TenantRoleResponse(BaseModel): id: str tenant_id: str @@ -8575,6 +8977,7 @@ class TenantRoleResponse(BaseModel): is_system: bool created_at: str + class TenantStatsResponse(BaseModel): tenant_id: str project_count: int @@ -8583,6 +8986,7 @@ class TenantStatsResponse(BaseModel): api_calls_today: int api_calls_month: int + # Tenant API Endpoints @app.post("/api/v1/tenants", response_model=TenantResponse, tags=["Tenants"]) async def create_tenant_endpoint(tenant: TenantCreate, request: Request, _=Depends(verify_api_key)): @@ -8610,6 +9014,7 @@ async def create_tenant_endpoint(tenant: TenantCreate, request: Request, _=Depen except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/tenants", response_model=list[TenantResponse], tags=["Tenants"]) async def list_tenants_endpoint( status: str | None = None, @@ -8632,6 +9037,7 @@ async def list_tenants_endpoint( ) return [t.to_dict() for t in tenants] + @app.get("/api/v1/tenants/{tenant_id}", response_model=TenantResponse, tags=["Tenants"]) async def get_tenant_endpoint(tenant_id: str, _=Depends(verify_api_key)): """获取租户详情""" @@ -8646,6 +9052,7 @@ async def get_tenant_endpoint(tenant_id: str, _=Depends(verify_api_key)): return tenant.to_dict() + @app.get("/api/v1/tenants/slug/{slug}", response_model=TenantResponse, tags=["Tenants"]) async def get_tenant_by_slug_endpoint(slug: str, _=Depends(verify_api_key)): """根据 slug 获取租户""" @@ -8660,6 +9067,7 @@ async def get_tenant_by_slug_endpoint(slug: str, _=Depends(verify_api_key)): return tenant.to_dict() + @app.put("/api/v1/tenants/{tenant_id}", response_model=TenantResponse, tags=["Tenants"]) async def update_tenant_endpoint(tenant_id: str, update: TenantUpdate, _=Depends(verify_api_key)): """更新租户信息""" @@ -8679,6 +9087,7 @@ async def update_tenant_endpoint(tenant_id: str, update: TenantUpdate, _=Depends except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.delete("/api/v1/tenants/{tenant_id}", tags=["Tenants"]) async def delete_tenant_endpoint(tenant_id: str, _=Depends(verify_api_key)): """删除租户(标记为过期)""" @@ -8693,6 +9102,7 @@ async def delete_tenant_endpoint(tenant_id: str, _=Depends(verify_api_key)): return {"success": True, "message": f"Tenant {tenant_id} deleted"} + # Tenant Domain API @app.post( "/api/v1/tenants/{tenant_id}/domains", response_model=TenantDomainResponse, tags=["Tenants"] @@ -8717,6 +9127,7 @@ async def add_tenant_domain_endpoint( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get( "/api/v1/tenants/{tenant_id}/domains", response_model=list[TenantDomainResponse], @@ -8731,6 +9142,7 @@ async def list_tenant_domains_endpoint(tenant_id: str, _=Depends(verify_api_key) domains = tenant_manager.get_tenant_domains(tenant_id) return [d.to_dict() for d in domains] + @app.post("/api/v1/tenants/{tenant_id}/domains/{domain_id}/verify", tags=["Tenants"]) async def verify_tenant_domain_endpoint(tenant_id: str, domain_id: str, _=Depends(verify_api_key)): """验证域名 DNS 记录""" @@ -8745,6 +9157,7 @@ async def verify_tenant_domain_endpoint(tenant_id: str, domain_id: str, _=Depend return {"success": True, "message": "Domain verified successfully"} + @app.post("/api/v1/tenants/{tenant_id}/domains/{domain_id}/activate", tags=["Tenants"]) async def activate_tenant_domain_endpoint( tenant_id: str, domain_id: str, _=Depends(verify_api_key) @@ -8761,6 +9174,7 @@ async def activate_tenant_domain_endpoint( return {"success": True, "message": "Domain activated successfully"} + @app.delete("/api/v1/tenants/{tenant_id}/domains/{domain_id}", tags=["Tenants"]) async def remove_tenant_domain_endpoint(tenant_id: str, domain_id: str, _=Depends(verify_api_key)): """移除域名绑定""" @@ -8775,6 +9189,7 @@ async def remove_tenant_domain_endpoint(tenant_id: str, domain_id: str, _=Depend return {"success": True, "message": "Domain removed successfully"} + # Tenant Branding API @app.get("/api/v1/tenants/{tenant_id}/branding", tags=["Tenants"]) async def get_tenant_branding_endpoint(tenant_id: str, _=Depends(verify_api_key)): @@ -8790,6 +9205,7 @@ async def get_tenant_branding_endpoint(tenant_id: str, _=Depends(verify_api_key) return branding.to_dict() + @app.put("/api/v1/tenants/{tenant_id}/branding", tags=["Tenants"]) async def update_tenant_branding_endpoint( tenant_id: str, branding: TenantBrandingUpdate, _=Depends(verify_api_key) @@ -8809,6 +9225,7 @@ async def update_tenant_branding_endpoint( return updated.to_dict() + @app.get("/api/v1/tenants/{tenant_id}/branding/theme.css", tags=["Tenants"]) async def get_tenant_theme_css_endpoint(tenant_id: str): """获取租户主题 CSS(公开访问)""" @@ -8823,6 +9240,7 @@ async def get_tenant_theme_css_endpoint(tenant_id: str): return PlainTextResponse(content=branding.get_theme_css(), media_type="text/css") + # Tenant Member API @app.post( "/api/v1/tenants/{tenant_id}/members/invite", @@ -8855,6 +9273,7 @@ async def invite_tenant_member_endpoint( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.post("/api/v1/tenants/members/accept-invitation", tags=["Tenants"]) async def accept_invitation_endpoint(token: str, user_id: str): """接受邀请加入租户""" @@ -8869,6 +9288,7 @@ async def accept_invitation_endpoint(token: str, user_id: str): return member.to_dict() + @app.get( "/api/v1/tenants/{tenant_id}/members", response_model=list[TenantMemberResponse], @@ -8889,6 +9309,7 @@ async def list_tenant_members_endpoint( members = tenant_manager.list_members(tenant_id, status=status_enum, role=role_enum) return [m.to_dict() for m in members] + @app.put("/api/v1/tenants/{tenant_id}/members/{member_id}/role", tags=["Tenants"]) async def update_member_role_endpoint( tenant_id: str, member_id: str, role: str, request: Request, _=Depends(verify_api_key) @@ -8917,6 +9338,7 @@ async def update_member_role_endpoint( except ValueError as e: raise HTTPException(status_code=403, detail=str(e)) + @app.delete("/api/v1/tenants/{tenant_id}/members/{member_id}", tags=["Tenants"]) async def remove_tenant_member_endpoint( tenant_id: str, member_id: str, request: Request, _=Depends(verify_api_key) @@ -8940,6 +9362,7 @@ async def remove_tenant_member_endpoint( except ValueError as e: raise HTTPException(status_code=403, detail=str(e)) + # Tenant Role API @app.get( "/api/v1/tenants/{tenant_id}/roles", response_model=list[TenantRoleResponse], tags=["Tenants"] @@ -8953,6 +9376,7 @@ async def list_tenant_roles_endpoint(tenant_id: str, _=Depends(verify_api_key)): roles = tenant_manager.list_roles(tenant_id) return [r.to_dict() for r in roles] + @app.post("/api/v1/tenants/{tenant_id}/roles", response_model=TenantRoleResponse, tags=["Tenants"]) async def create_tenant_role_endpoint( tenant_id: str, role: TenantRoleCreate, _=Depends(verify_api_key) @@ -8974,6 +9398,7 @@ async def create_tenant_role_endpoint( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.put("/api/v1/tenants/{tenant_id}/roles/{role_id}/permissions", tags=["Tenants"]) async def update_role_permissions_endpoint( tenant_id: str, role_id: str, permissions: list[str], _=Depends(verify_api_key) @@ -8992,6 +9417,7 @@ async def update_role_permissions_endpoint( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.delete("/api/v1/tenants/{tenant_id}/roles/{role_id}", tags=["Tenants"]) async def delete_tenant_role_endpoint(tenant_id: str, role_id: str, _=Depends(verify_api_key)): """删除自定义角色""" @@ -9008,6 +9434,7 @@ async def delete_tenant_role_endpoint(tenant_id: str, role_id: str, _=Depends(ve except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/tenants/permissions", tags=["Tenants"]) async def list_tenant_permissions_endpoint(_=Depends(verify_api_key)): """获取所有可用的租户权限列表""" @@ -9019,6 +9446,7 @@ async def list_tenant_permissions_endpoint(_=Depends(verify_api_key)): "permissions": [{"id": k, "name": v} for k, v in tenant_manager.PERMISSION_NAMES.items()] } + # Tenant Resolution API @app.get("/api/v1/tenants/resolve", tags=["Tenants"]) async def resolve_tenant_endpoint( @@ -9039,6 +9467,7 @@ async def resolve_tenant_endpoint( return tenant.to_dict() + @app.get("/api/v1/tenants/{tenant_id}/context", tags=["Tenants"]) async def get_tenant_context_endpoint(tenant_id: str, _=Depends(verify_api_key)): """获取租户完整上下文""" @@ -9053,10 +9482,12 @@ async def get_tenant_context_endpoint(tenant_id: str, _=Depends(verify_api_key)) return context + # ============================================ # Phase 8 Task 2: Subscription & Billing APIs # ============================================ + # Pydantic Models for Subscription API class CreateSubscriptionRequest(BaseModel): plan_id: str = Field(..., description="订阅计划ID") @@ -9066,40 +9497,48 @@ class CreateSubscriptionRequest(BaseModel): ) trial_days: int = Field(default=0, description="试用天数") + class ChangePlanRequest(BaseModel): new_plan_id: str = Field(..., description="新计划ID") prorate: bool = Field(default=True, description="是否按比例计算差价") + class CancelSubscriptionRequest(BaseModel): at_period_end: bool = Field(default=True, description="是否在周期结束时取消") + class CreatePaymentRequest(BaseModel): amount: float = Field(..., description="支付金额") currency: str = Field(default="CNY", description="货币") provider: str = Field(..., description="支付提供商: stripe/alipay/wechat") payment_method: str | None = Field(default=None, description="支付方式") + class RequestRefundRequest(BaseModel): payment_id: str = Field(..., description="支付记录ID") amount: float = Field(..., description="退款金额") reason: str = Field(..., description="退款原因") + class ProcessRefundRequest(BaseModel): action: str = Field(..., description="操作: approve/reject") reason: str | None = Field(default=None, description="拒绝原因(拒绝时必填)") + class RecordUsageRequest(BaseModel): resource_type: str = Field(..., description="资源类型: transcription/storage/api_call/export") quantity: float = Field(..., description="使用量") unit: str = Field(..., description="单位: minutes/mb/count/page") description: str | None = Field(default=None, description="描述") + class CreateCheckoutSessionRequest(BaseModel): plan_id: str = Field(..., description="计划ID") billing_cycle: str = Field(default="monthly", description="计费周期") success_url: str = Field(..., description="支付成功回调URL") cancel_url: str = Field(..., description="支付取消回调URL") + # Subscription Plan APIs @app.get("/api/v1/subscription-plans", tags=["Subscriptions"]) async def list_subscription_plans( @@ -9131,6 +9570,7 @@ async def list_subscription_plans( ] } + @app.get("/api/v1/subscription-plans/{plan_id}", tags=["Subscriptions"]) async def get_subscription_plan(plan_id: str, _=Depends(verify_api_key)): """获取订阅计划详情""" @@ -9157,6 +9597,7 @@ async def get_subscription_plan(plan_id: str, _=Depends(verify_api_key)): "created_at": plan.created_at.isoformat(), } + # Subscription APIs @app.post("/api/v1/tenants/{tenant_id}/subscription", tags=["Subscriptions"]) async def create_subscription( @@ -9195,6 +9636,7 @@ async def create_subscription( except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/tenants/{tenant_id}/subscription", tags=["Subscriptions"]) async def get_tenant_subscription(tenant_id: str, _=Depends(verify_api_key)): """获取租户当前订阅""" @@ -9231,6 +9673,7 @@ async def get_tenant_subscription(tenant_id: str, _=Depends(verify_api_key)): } } + @app.put("/api/v1/tenants/{tenant_id}/subscription/change-plan", tags=["Subscriptions"]) async def change_subscription_plan( tenant_id: str, request: ChangePlanRequest, _=Depends(verify_api_key) @@ -9261,6 +9704,7 @@ async def change_subscription_plan( except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + @app.post("/api/v1/tenants/{tenant_id}/subscription/cancel", tags=["Subscriptions"]) async def cancel_subscription( tenant_id: str, request: CancelSubscriptionRequest, _=Depends(verify_api_key) @@ -9290,6 +9734,7 @@ async def cancel_subscription( except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + # Usage APIs @app.post("/api/v1/tenants/{tenant_id}/usage", tags=["Subscriptions"]) async def record_usage(tenant_id: str, request: RecordUsageRequest, _=Depends(verify_api_key)): @@ -9316,6 +9761,7 @@ async def record_usage(tenant_id: str, request: RecordUsageRequest, _=Depends(ve "recorded_at": record.recorded_at.isoformat(), } + @app.get("/api/v1/tenants/{tenant_id}/usage", tags=["Subscriptions"]) async def get_usage_summary( tenant_id: str, @@ -9336,6 +9782,7 @@ async def get_usage_summary( return summary + # Payment APIs @app.get("/api/v1/tenants/{tenant_id}/payments", tags=["Subscriptions"]) async def list_payments( @@ -9370,6 +9817,7 @@ async def list_payments( "total": len(payments), } + @app.get("/api/v1/tenants/{tenant_id}/payments/{payment_id}", tags=["Subscriptions"]) async def get_payment(tenant_id: str, payment_id: str, _=Depends(verify_api_key)): """获取支付记录详情""" @@ -9399,6 +9847,7 @@ async def get_payment(tenant_id: str, payment_id: str, _=Depends(verify_api_key) "created_at": payment.created_at.isoformat(), } + # Invoice APIs @app.get("/api/v1/tenants/{tenant_id}/invoices", tags=["Subscriptions"]) async def list_invoices( @@ -9436,6 +9885,7 @@ async def list_invoices( "total": len(invoices), } + @app.get("/api/v1/tenants/{tenant_id}/invoices/{invoice_id}", tags=["Subscriptions"]) async def get_invoice(tenant_id: str, invoice_id: str, _=Depends(verify_api_key)): """获取发票详情""" @@ -9466,6 +9916,7 @@ async def get_invoice(tenant_id: str, invoice_id: str, _=Depends(verify_api_key) "created_at": invoice.created_at.isoformat(), } + # Refund APIs @app.post("/api/v1/tenants/{tenant_id}/refunds", tags=["Subscriptions"]) async def request_refund( @@ -9500,6 +9951,7 @@ async def request_refund( except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/tenants/{tenant_id}/refunds", tags=["Subscriptions"]) async def list_refunds( tenant_id: str, @@ -9535,6 +9987,7 @@ async def list_refunds( "total": len(refunds), } + @app.post("/api/v1/tenants/{tenant_id}/refunds/{refund_id}/process", tags=["Subscriptions"]) async def process_refund( tenant_id: str, @@ -9576,6 +10029,7 @@ async def process_refund( else: raise HTTPException(status_code=400, detail="Invalid action") + # Billing History API @app.get("/api/v1/tenants/{tenant_id}/billing-history", tags=["Subscriptions"]) async def get_billing_history( @@ -9614,6 +10068,7 @@ async def get_billing_history( "total": len(history), } + # Payment Provider Integration APIs @app.post("/api/v1/tenants/{tenant_id}/checkout/stripe", tags=["Subscriptions"]) async def create_stripe_checkout( @@ -9638,6 +10093,7 @@ async def create_stripe_checkout( except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + @app.post("/api/v1/tenants/{tenant_id}/checkout/alipay", tags=["Subscriptions"]) async def create_alipay_order( tenant_id: str, @@ -9660,6 +10116,7 @@ async def create_alipay_order( except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + @app.post("/api/v1/tenants/{tenant_id}/checkout/wechat", tags=["Subscriptions"]) async def create_wechat_order( tenant_id: str, @@ -9682,6 +10139,7 @@ async def create_wechat_order( except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + # Webhook Handlers @app.post("/webhooks/stripe", tags=["Subscriptions"]) async def stripe_webhook(request: Request): @@ -9699,6 +10157,7 @@ async def stripe_webhook(request: Request): else: raise HTTPException(status_code=400, detail="Webhook processing failed") + @app.post("/webhooks/alipay", tags=["Subscriptions"]) async def alipay_webhook(request: Request): """支付宝 Webhook 处理""" @@ -9715,6 +10174,7 @@ async def alipay_webhook(request: Request): else: raise HTTPException(status_code=400, detail="Webhook processing failed") + @app.post("/webhooks/wechat", tags=["Subscriptions"]) async def wechat_webhook(request: Request): """微信支付 Webhook 处理""" @@ -9731,10 +10191,12 @@ async def wechat_webhook(request: Request): else: raise HTTPException(status_code=400, detail="Webhook processing failed") + # ==================== Phase 8: Enterprise Features API ==================== # Pydantic Models for Enterprise + class SSOConfigCreate(BaseModel): provider: str = Field( ..., description="SSO 提供商: wechat_work/dingtalk/feishu/okta/azure_ad/google/custom_saml" @@ -9756,6 +10218,7 @@ class SSOConfigCreate(BaseModel): default_role: str = Field(default="member", description="默认角色") domain_restriction: list[str] = Field(default_factory=list, description="允许的邮箱域名") + class SSOConfigUpdate(BaseModel): entity_id: str | None = None sso_url: str | None = None @@ -9775,6 +10238,7 @@ class SSOConfigUpdate(BaseModel): domain_restriction: list[str] | None = None status: str | None = None + class SCIMConfigCreate(BaseModel): provider: str = Field(..., description="身份提供商") scim_base_url: str = Field(..., description="SCIM 服务端地址") @@ -9783,6 +10247,7 @@ class SCIMConfigCreate(BaseModel): attribute_mapping: dict[str, str] | None = Field(default=None, description="属性映射") sync_rules: dict[str, Any] | None = Field(default=None, description="同步规则") + class SCIMConfigUpdate(BaseModel): scim_base_url: str | None = None scim_token: str | None = None @@ -9791,6 +10256,7 @@ class SCIMConfigUpdate(BaseModel): sync_rules: dict[str, Any] | None = None status: str | None = None + class AuditExportCreate(BaseModel): export_format: str = Field(..., description="导出格式: json/csv/pdf/xlsx") start_date: str = Field(..., description="开始日期 (ISO 格式)") @@ -9800,6 +10266,7 @@ class AuditExportCreate(BaseModel): default=None, description="合规标准: soc2/iso27001/gdpr/hipaa/pci_dss" ) + class RetentionPolicyCreate(BaseModel): name: str = Field(..., description="策略名称") description: str | None = Field(default=None, description="策略描述") @@ -9815,6 +10282,7 @@ class RetentionPolicyCreate(BaseModel): archive_location: str | None = Field(default=None, description="归档位置") archive_encryption: bool = Field(default=True, description="归档加密") + class RetentionPolicyUpdate(BaseModel): name: str | None = None description: str | None = None @@ -9828,8 +10296,10 @@ class RetentionPolicyUpdate(BaseModel): archive_encryption: bool | None = None is_active: bool | None = None + # SSO/SAML APIs + @app.post("/api/v1/tenants/{tenant_id}/sso-configs", tags=["Enterprise"]) async def create_sso_config_endpoint( tenant_id: str, config: SSOConfigCreate, _=Depends(verify_api_key) @@ -9878,6 +10348,7 @@ async def create_sso_config_endpoint( except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/tenants/{tenant_id}/sso-configs", tags=["Enterprise"]) async def list_sso_configs_endpoint(tenant_id: str, _=Depends(verify_api_key)): """列出租户的所有 SSO 配置""" @@ -9905,6 +10376,7 @@ async def list_sso_configs_endpoint(tenant_id: str, _=Depends(verify_api_key)): "total": len(configs), } + @app.get("/api/v1/tenants/{tenant_id}/sso-configs/{config_id}", tags=["Enterprise"]) async def get_sso_config_endpoint(tenant_id: str, config_id: str, _=Depends(verify_api_key)): """获取 SSO 配置详情""" @@ -9938,6 +10410,7 @@ async def get_sso_config_endpoint(tenant_id: str, config_id: str, _=Depends(veri "updated_at": config.updated_at.isoformat(), } + @app.put("/api/v1/tenants/{tenant_id}/sso-configs/{config_id}", tags=["Enterprise"]) async def update_sso_config_endpoint( tenant_id: str, config_id: str, update: SSOConfigUpdate, _=Depends(verify_api_key) @@ -9962,6 +10435,7 @@ async def update_sso_config_endpoint( "updated_at": updated.updated_at.isoformat(), } + @app.delete("/api/v1/tenants/{tenant_id}/sso-configs/{config_id}", tags=["Enterprise"]) async def delete_sso_config_endpoint(tenant_id: str, config_id: str, _=Depends(verify_api_key)): """删除 SSO 配置""" @@ -9977,6 +10451,7 @@ async def delete_sso_config_endpoint(tenant_id: str, config_id: str, _=Depends(v manager.delete_sso_config(config_id) return {"success": True} + @app.get("/api/v1/tenants/{tenant_id}/sso-configs/{config_id}/metadata", tags=["Enterprise"]) async def get_sso_metadata_endpoint( tenant_id: str, @@ -10003,8 +10478,10 @@ async def get_sso_metadata_endpoint( "slo_url": f"{base_url}/api/v1/sso/saml/{tenant_id}/slo", } + # SCIM APIs + @app.post("/api/v1/tenants/{tenant_id}/scim-configs", tags=["Enterprise"]) async def create_scim_config_endpoint( tenant_id: str, config: SCIMConfigCreate, _=Depends(verify_api_key) @@ -10038,6 +10515,7 @@ async def create_scim_config_endpoint( except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/tenants/{tenant_id}/scim-configs", tags=["Enterprise"]) async def get_scim_config_endpoint(tenant_id: str, _=Depends(verify_api_key)): """获取租户的 SCIM 配置""" @@ -10063,6 +10541,7 @@ async def get_scim_config_endpoint(tenant_id: str, _=Depends(verify_api_key)): "created_at": config.created_at.isoformat(), } + @app.put("/api/v1/tenants/{tenant_id}/scim-configs/{config_id}", tags=["Enterprise"]) async def update_scim_config_endpoint( tenant_id: str, config_id: str, update: SCIMConfigUpdate, _=Depends(verify_api_key) @@ -10087,6 +10566,7 @@ async def update_scim_config_endpoint( "updated_at": updated.updated_at.isoformat(), } + @app.post("/api/v1/tenants/{tenant_id}/scim-configs/{config_id}/sync", tags=["Enterprise"]) async def sync_scim_users_endpoint(tenant_id: str, config_id: str, _=Depends(verify_api_key)): """执行 SCIM 用户同步""" @@ -10103,6 +10583,7 @@ async def sync_scim_users_endpoint(tenant_id: str, config_id: str, _=Depends(ver return result + @app.get("/api/v1/tenants/{tenant_id}/scim-users", tags=["Enterprise"]) async def list_scim_users_endpoint( tenant_id: str, @@ -10133,8 +10614,10 @@ async def list_scim_users_endpoint( "total": len(users), } + # Audit Log Export APIs + @app.post("/api/v1/tenants/{tenant_id}/audit-exports", tags=["Enterprise"]) async def create_audit_export_endpoint( tenant_id: str, @@ -10176,6 +10659,7 @@ async def create_audit_export_endpoint( except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/tenants/{tenant_id}/audit-exports", tags=["Enterprise"]) async def list_audit_exports_endpoint( tenant_id: str, @@ -10209,6 +10693,7 @@ async def list_audit_exports_endpoint( "total": len(exports), } + @app.get("/api/v1/tenants/{tenant_id}/audit-exports/{export_id}", tags=["Enterprise"]) async def get_audit_export_endpoint(tenant_id: str, export_id: str, _=Depends(verify_api_key)): """获取审计日志导出详情""" @@ -10240,6 +10725,7 @@ async def get_audit_export_endpoint(tenant_id: str, export_id: str, _=Depends(ve "error_message": export.error_message, } + @app.post("/api/v1/tenants/{tenant_id}/audit-exports/{export_id}/download", tags=["Enterprise"]) async def download_audit_export_endpoint( tenant_id: str, @@ -10269,8 +10755,10 @@ async def download_audit_export_endpoint( "expires_at": export.expires_at.isoformat() if export.expires_at else None, } + # Data Retention Policy APIs + @app.post("/api/v1/tenants/{tenant_id}/retention-policies", tags=["Enterprise"]) async def create_retention_policy_endpoint( tenant_id: str, policy: RetentionPolicyCreate, _=Depends(verify_api_key) @@ -10311,6 +10799,7 @@ async def create_retention_policy_endpoint( except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/tenants/{tenant_id}/retention-policies", tags=["Enterprise"]) async def list_retention_policies_endpoint( tenant_id: str, @@ -10341,6 +10830,7 @@ async def list_retention_policies_endpoint( "total": len(policies), } + @app.get("/api/v1/tenants/{tenant_id}/retention-policies/{policy_id}", tags=["Enterprise"]) async def get_retention_policy_endpoint(tenant_id: str, policy_id: str, _=Depends(verify_api_key)): """获取数据保留策略详情""" @@ -10375,6 +10865,7 @@ async def get_retention_policy_endpoint(tenant_id: str, policy_id: str, _=Depend "created_at": policy.created_at.isoformat(), } + @app.put("/api/v1/tenants/{tenant_id}/retention-policies/{policy_id}", tags=["Enterprise"]) async def update_retention_policy_endpoint( tenant_id: str, policy_id: str, update: RetentionPolicyUpdate, _=Depends(verify_api_key) @@ -10395,6 +10886,7 @@ async def update_retention_policy_endpoint( return {"id": updated.id, "updated_at": updated.updated_at.isoformat()} + @app.delete("/api/v1/tenants/{tenant_id}/retention-policies/{policy_id}", tags=["Enterprise"]) async def delete_retention_policy_endpoint( tenant_id: str, policy_id: str, _=Depends(verify_api_key) @@ -10412,6 +10904,7 @@ async def delete_retention_policy_endpoint( manager.delete_retention_policy(policy_id) return {"success": True} + @app.post("/api/v1/tenants/{tenant_id}/retention-policies/{policy_id}/execute", tags=["Enterprise"]) async def execute_retention_policy_endpoint( tenant_id: str, policy_id: str, _=Depends(verify_api_key) @@ -10436,6 +10929,7 @@ async def execute_retention_policy_endpoint( "created_at": job.created_at.isoformat(), } + @app.get("/api/v1/tenants/{tenant_id}/retention-policies/{policy_id}/jobs", tags=["Enterprise"]) async def list_retention_jobs_endpoint( tenant_id: str, @@ -10472,10 +10966,12 @@ async def list_retention_jobs_endpoint( "total": len(jobs), } + # ============================================ # Phase 8 Task 7: Globalization & Localization API # ============================================ + # Pydantic Models for Localization API class TranslationCreate(BaseModel): key: str = Field(..., description="翻译键") @@ -10483,10 +10979,12 @@ class TranslationCreate(BaseModel): namespace: str = Field(default="common", description="命名空间") context: str | None = Field(default=None, description="上下文说明") + class TranslationUpdate(BaseModel): value: str = Field(..., description="翻译值") context: str | None = Field(default=None, description="上下文说明") + class LocalizationSettingsCreate(BaseModel): default_language: str = Field(default="en", description="默认语言") supported_languages: list[str] = Field(default=["en"], description="支持的语言列表") @@ -10496,6 +10994,7 @@ class LocalizationSettingsCreate(BaseModel): region_code: str = Field(default="global", description="区域代码") data_residency: str = Field(default="regional", description="数据驻留策略") + class LocalizationSettingsUpdate(BaseModel): default_language: str | None = None supported_languages: list[str] | None = None @@ -10505,28 +11004,34 @@ class LocalizationSettingsUpdate(BaseModel): region_code: str | None = None data_residency: str | None = None + class DataCenterMappingRequest(BaseModel): region_code: str = Field(..., description="区域代码") data_residency: str = Field(default="regional", description="数据驻留策略") + class FormatDateTimeRequest(BaseModel): timestamp: str = Field(..., description="ISO格式时间戳") timezone: str | None = Field(default=None, description="目标时区") format_type: str = Field(default="datetime", description="格式类型: date/time/datetime") + class FormatNumberRequest(BaseModel): number: float = Field(..., description="数字") decimal_places: int | None = Field(default=None, description="小数位数") + class FormatCurrencyRequest(BaseModel): amount: float = Field(..., description="金额") currency: str = Field(..., description="货币代码") + class ConvertTimezoneRequest(BaseModel): timestamp: str = Field(..., description="ISO格式时间戳") from_tz: str = Field(..., description="源时区") to_tz: str = Field(..., description="目标时区") + # Translation APIs @app.get("/api/v1/translations/{language}/{key}", tags=["Localization"]) async def get_translation( @@ -10547,6 +11052,7 @@ async def get_translation( return {"key": key, "language": language, "namespace": namespace, "value": value} + @app.post("/api/v1/translations/{language}", tags=["Localization"]) async def create_translation(language: str, request: TranslationCreate, _=Depends(verify_api_key)): """创建/更新翻译""" @@ -10571,6 +11077,7 @@ async def create_translation(language: str, request: TranslationCreate, _=Depend "created_at": translation.created_at.isoformat(), } + @app.put("/api/v1/translations/{language}/{key}", tags=["Localization"]) async def update_translation( language: str, @@ -10601,6 +11108,7 @@ async def update_translation( "updated_at": translation.updated_at.isoformat(), } + @app.delete("/api/v1/translations/{language}/{key}", tags=["Localization"]) async def delete_translation( language: str, @@ -10620,6 +11128,7 @@ async def delete_translation( return {"success": True, "message": "Translation deleted"} + @app.get("/api/v1/translations", tags=["Localization"]) async def list_translations( language: str | None = Query(default=None, description="语言代码"), @@ -10651,6 +11160,7 @@ async def list_translations( "total": len(translations), } + # Language APIs @app.get("/api/v1/languages", tags=["Localization"]) async def list_languages(active_only: bool = Query(default=True, description="仅返回激活的语言")): @@ -10679,6 +11189,7 @@ async def list_languages(active_only: bool = Query(default=True, description=" "total": len(languages), } + @app.get("/api/v1/languages/{code}", tags=["Localization"]) async def get_language(code: str): """获取语言详情""" @@ -10708,6 +11219,7 @@ async def get_language(code: str): "calendar_type": lang.calendar_type, } + # Data Center APIs @app.get("/api/v1/data-centers", tags=["Localization"]) async def list_data_centers( @@ -10738,6 +11250,7 @@ async def list_data_centers( "total": len(data_centers), } + @app.get("/api/v1/data-centers/{dc_id}", tags=["Localization"]) async def get_data_center(dc_id: str): """获取数据中心详情""" @@ -10762,6 +11275,7 @@ async def get_data_center(dc_id: str): "capabilities": dc.capabilities, } + @app.get("/api/v1/tenants/{tenant_id}/data-center", tags=["Localization"]) async def get_tenant_data_center(tenant_id: str, _=Depends(verify_api_key)): """获取租户数据中心配置""" @@ -10808,6 +11322,7 @@ async def get_tenant_data_center(tenant_id: str, _=Depends(verify_api_key)): "created_at": mapping.created_at.isoformat(), } + @app.post("/api/v1/tenants/{tenant_id}/data-center", tags=["Localization"]) async def set_tenant_data_center( tenant_id: str, request: DataCenterMappingRequest, _=Depends(verify_api_key) @@ -10829,6 +11344,7 @@ async def set_tenant_data_center( "created_at": mapping.created_at.isoformat(), } + # Payment Method APIs @app.get("/api/v1/payment-methods", tags=["Localization"]) async def list_payment_methods( @@ -10862,6 +11378,7 @@ async def list_payment_methods( "total": len(methods), } + @app.get("/api/v1/payment-methods/localized", tags=["Localization"]) async def get_localized_payment_methods( country_code: str = Query(..., description="国家代码"), @@ -10876,6 +11393,7 @@ async def get_localized_payment_methods( return {"country_code": country_code, "language": language, "payment_methods": methods} + # Country APIs @app.get("/api/v1/countries", tags=["Localization"]) async def list_countries( @@ -10907,6 +11425,7 @@ async def list_countries( "total": len(countries), } + @app.get("/api/v1/countries/{code}", tags=["Localization"]) async def get_country(code: str): """获取国家详情""" @@ -10934,6 +11453,7 @@ async def get_country(code: str): "vat_rate": country.vat_rate, } + # Localization Settings APIs @app.get("/api/v1/tenants/{tenant_id}/localization", tags=["Localization"]) async def get_localization_settings(tenant_id: str, _=Depends(verify_api_key)): @@ -10964,6 +11484,7 @@ async def get_localization_settings(tenant_id: str, _=Depends(verify_api_key)): "updated_at": settings.updated_at.isoformat(), } + @app.post("/api/v1/tenants/{tenant_id}/localization", tags=["Localization"]) async def create_localization_settings( tenant_id: str, request: LocalizationSettingsCreate, _=Depends(verify_api_key) @@ -10997,6 +11518,7 @@ async def create_localization_settings( "created_at": settings.created_at.isoformat(), } + @app.put("/api/v1/tenants/{tenant_id}/localization", tags=["Localization"]) async def update_localization_settings( tenant_id: str, request: LocalizationSettingsUpdate, _=Depends(verify_api_key) @@ -11026,6 +11548,7 @@ async def update_localization_settings( "updated_at": settings.updated_at.isoformat(), } + # Formatting APIs @app.post("/api/v1/format/datetime", tags=["Localization"]) async def format_datetime_endpoint( @@ -11054,6 +11577,7 @@ async def format_datetime_endpoint( "format_type": request.format_type, } + @app.post("/api/v1/format/number", tags=["Localization"]) async def format_number_endpoint( request: FormatNumberRequest, language: str = Query(default="en", description="语言代码") @@ -11069,6 +11593,7 @@ async def format_number_endpoint( return {"original": request.number, "formatted": formatted, "language": language} + @app.post("/api/v1/format/currency", tags=["Localization"]) async def format_currency_endpoint( request: FormatCurrencyRequest, language: str = Query(default="en", description="语言代码") @@ -11089,6 +11614,7 @@ async def format_currency_endpoint( "language": language, } + @app.post("/api/v1/convert/timezone", tags=["Localization"]) async def convert_timezone_endpoint(request: ConvertTimezoneRequest): """转换时区""" @@ -11111,6 +11637,7 @@ async def convert_timezone_endpoint(request: ConvertTimezoneRequest): "converted": converted.isoformat(), } + @app.get("/api/v1/detect/locale", tags=["Localization"]) async def detect_locale( accept_language: str | None = Header(default=None, description="Accept-Language 头"), @@ -11127,6 +11654,7 @@ async def detect_locale( return preferences + @app.get("/api/v1/calendar/{calendar_type}", tags=["Localization"]) async def get_calendar_info( calendar_type: str, @@ -11142,10 +11670,12 @@ async def get_calendar_info( return info + # ============================================ # Phase 8 Task 4: AI 能力增强 API # ============================================ + class CreateCustomModelRequest(BaseModel): name: str description: str @@ -11153,24 +11683,29 @@ class CreateCustomModelRequest(BaseModel): training_data: dict hyperparameters: dict = Field(default_factory=lambda: {"epochs": 10, "learning_rate": 0.001}) + class AddTrainingSampleRequest(BaseModel): text: str entities: list[dict] metadata: dict = Field(default_factory=dict) + class TrainModelRequest(BaseModel): model_id: str + class PredictRequest(BaseModel): model_id: str text: str + class MultimodalAnalysisRequest(BaseModel): provider: str input_type: str input_urls: list[str] prompt: str + class CreateKGRAGRequest(BaseModel): name: str description: str @@ -11178,16 +11713,19 @@ class CreateKGRAGRequest(BaseModel): retrieval_config: dict generation_config: dict + class KGRAGQueryRequest(BaseModel): rag_id: str query: str + class SmartSummaryRequest(BaseModel): source_type: str source_id: str summary_type: str content_data: dict + class CreatePredictionModelRequest(BaseModel): name: str prediction_type: str @@ -11195,15 +11733,18 @@ class CreatePredictionModelRequest(BaseModel): features: list[str] model_config: dict + class PredictDataRequest(BaseModel): model_id: str input_data: dict + class PredictionFeedbackRequest(BaseModel): prediction_id: str actual_value: str is_correct: bool + # 自定义模型管理 API @app.post("/api/v1/tenants/{tenant_id}/ai/custom-models", tags=["AI Enhancement"]) async def create_custom_model( @@ -11237,6 +11778,7 @@ async def create_custom_model( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/tenants/{tenant_id}/ai/custom-models", tags=["AI Enhancement"]) async def list_custom_models( tenant_id: str, @@ -11268,6 +11810,7 @@ async def list_custom_models( ] } + @app.get("/api/v1/ai/custom-models/{model_id}", tags=["AI Enhancement"]) async def get_custom_model(model_id: str): """获取自定义模型详情""" @@ -11296,6 +11839,7 @@ async def get_custom_model(model_id: str): "created_by": model.created_by, } + @app.post("/api/v1/ai/custom-models/{model_id}/samples", tags=["AI Enhancement"]) async def add_training_sample(model_id: str, request: AddTrainingSampleRequest): """添加训练样本""" @@ -11316,6 +11860,7 @@ async def add_training_sample(model_id: str, request: AddTrainingSampleRequest): "created_at": sample.created_at, } + @app.get("/api/v1/ai/custom-models/{model_id}/samples", tags=["AI Enhancement"]) async def get_training_samples(model_id: str): """获取训练样本""" @@ -11338,6 +11883,7 @@ async def get_training_samples(model_id: str): ] } + @app.post("/api/v1/ai/custom-models/{model_id}/train", tags=["AI Enhancement"]) async def train_custom_model(model_id: str): """训练自定义模型""" @@ -11357,6 +11903,7 @@ async def train_custom_model(model_id: str): except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.post("/api/v1/ai/custom-models/predict", tags=["AI Enhancement"]) async def predict_with_custom_model(request: PredictRequest): """使用自定义模型预测""" @@ -11371,6 +11918,7 @@ async def predict_with_custom_model(request: PredictRequest): except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + # 多模态分析 API @app.post( "/api/v1/tenants/{tenant_id}/projects/{project_id}/ai/multimodal", tags=["AI Enhancement"] @@ -11404,6 +11952,7 @@ async def analyze_multimodal(tenant_id: str, project_id: str, request: Multimoda except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/tenants/{tenant_id}/ai/multimodal", tags=["AI Enhancement"]) async def list_multimodal_analyses( tenant_id: str, project_id: str | None = Query(default=None, description="项目ID过滤") @@ -11432,6 +11981,7 @@ async def list_multimodal_analyses( ] } + # 知识图谱 RAG API @app.post("/api/v1/tenants/{tenant_id}/projects/{project_id}/ai/kg-rag", tags=["AI Enhancement"]) async def create_kg_rag(tenant_id: str, project_id: str, request: CreateKGRAGRequest): @@ -11459,6 +12009,7 @@ async def create_kg_rag(tenant_id: str, project_id: str, request: CreateKGRAGReq "created_at": rag.created_at, } + @app.get("/api/v1/tenants/{tenant_id}/ai/kg-rag", tags=["AI Enhancement"]) async def list_kg_rags( tenant_id: str, project_id: str | None = Query(default=None, description="项目ID过滤") @@ -11484,6 +12035,7 @@ async def list_kg_rags( ] } + @app.post("/api/v1/ai/kg-rag/query", tags=["AI Enhancement"]) async def query_kg_rag( request: KGRAGQueryRequest, @@ -11518,6 +12070,7 @@ async def query_kg_rag( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + # 智能摘要 API @app.post("/api/v1/tenants/{tenant_id}/projects/{project_id}/ai/summarize", tags=["AI Enhancement"]) async def generate_smart_summary(tenant_id: str, project_id: str, request: SmartSummaryRequest): @@ -11549,6 +12102,7 @@ async def generate_smart_summary(tenant_id: str, project_id: str, request: Smart "created_at": summary.created_at, } + @app.get("/api/v1/tenants/{tenant_id}/projects/{project_id}/ai/summaries", tags=["AI Enhancement"]) async def list_smart_summaries( tenant_id: str, @@ -11565,6 +12119,7 @@ async def list_smart_summaries( # 这里需要从数据库查询,暂时返回空列表 return {"summaries": []} + # 预测模型 API @app.post( "/api/v1/tenants/{tenant_id}/projects/{project_id}/ai/prediction-models", @@ -11602,6 +12157,7 @@ async def create_prediction_model( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/tenants/{tenant_id}/ai/prediction-models", tags=["AI Enhancement"]) async def list_prediction_models( tenant_id: str, project_id: str | None = Query(default=None, description="项目ID过滤") @@ -11631,6 +12187,7 @@ async def list_prediction_models( ] } + @app.get("/api/v1/ai/prediction-models/{model_id}", tags=["AI Enhancement"]) async def get_prediction_model(model_id: str): """获取预测模型详情""" @@ -11659,6 +12216,7 @@ async def get_prediction_model(model_id: str): "created_at": model.created_at, } + @app.post("/api/v1/ai/prediction-models/{model_id}/train", tags=["AI Enhancement"]) async def train_prediction_model( model_id: str, historical_data: list[dict] = Body(..., description="历史训练数据") @@ -11679,6 +12237,7 @@ async def train_prediction_model( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.post("/api/v1/ai/prediction-models/predict", tags=["AI Enhancement"]) async def predict(request: PredictDataRequest): """进行预测""" @@ -11703,6 +12262,7 @@ async def predict(request: PredictDataRequest): except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/ai/prediction-models/{model_id}/results", tags=["AI Enhancement"]) async def get_prediction_results( model_id: str, limit: int = Query(default=100, description="返回结果数量限制") @@ -11731,6 +12291,7 @@ async def get_prediction_results( ] } + @app.post("/api/v1/ai/prediction-results/feedback", tags=["AI Enhancement"]) async def update_prediction_feedback(request: PredictionFeedbackRequest): """更新预测反馈""" @@ -11746,8 +12307,10 @@ async def update_prediction_feedback(request: PredictionFeedbackRequest): return {"status": "success", "message": "Feedback updated"} + # ==================== Phase 8 Task 5: Growth & Analytics Endpoints ==================== + # Pydantic Models for Growth API class TrackEventRequest(BaseModel): tenant_id: str @@ -11762,11 +12325,13 @@ class TrackEventRequest(BaseModel): utm_medium: str | None = None utm_campaign: str | None = None + class CreateFunnelRequest(BaseModel): name: str description: str = "" steps: list[dict] # [{"name": "", "event_name": ""}] + class CreateExperimentRequest(BaseModel): name: str description: str = "" @@ -11780,16 +12345,19 @@ class CreateExperimentRequest(BaseModel): min_sample_size: int = 100 confidence_level: float = 0.95 + class AssignVariantRequest(BaseModel): user_id: str user_attributes: dict = Field(default_factory=dict) + class RecordMetricRequest(BaseModel): variant_id: str user_id: str metric_name: str metric_value: float + class CreateEmailTemplateRequest(BaseModel): name: str template_type: str # welcome, onboarding, feature_announcement, churn_recovery, etc. @@ -11801,12 +12369,14 @@ class CreateEmailTemplateRequest(BaseModel): from_email: str = "noreply@insightflow.io" reply_to: str | None = None + class CreateCampaignRequest(BaseModel): name: str template_id: str recipients: list[dict] # [{"user_id": "", "email": ""}] scheduled_at: str | None = None + class CreateAutomationWorkflowRequest(BaseModel): name: str description: str = "" @@ -11814,6 +12384,7 @@ class CreateAutomationWorkflowRequest(BaseModel): trigger_conditions: dict = Field(default_factory=dict) actions: list[dict] # [{"type": "send_email", "template_id": ""}] + class CreateReferralProgramRequest(BaseModel): name: str description: str = "" @@ -11825,10 +12396,12 @@ class CreateReferralProgramRequest(BaseModel): referral_code_length: int = 8 expiry_days: int = 30 + class ApplyReferralCodeRequest(BaseModel): referral_code: str referee_id: str + class CreateTeamIncentiveRequest(BaseModel): name: str description: str = "" @@ -11839,17 +12412,21 @@ class CreateTeamIncentiveRequest(BaseModel): valid_from: str valid_until: str + # Growth Manager singleton _growth_manager = None + def get_growth_manager_instance(): global _growth_manager if _growth_manager is None and GROWTH_MANAGER_AVAILABLE: _growth_manager = GrowthManager() return _growth_manager + # ==================== 用户行为分析 API ==================== + @app.post("/api/v1/analytics/track", tags=["Growth & Analytics"]) async def track_event_endpoint(request: TrackEventRequest): """ @@ -11887,6 +12464,7 @@ async def track_event_endpoint(request: TrackEventRequest): except Exception as e: raise HTTPException(status_code=500, detail=str(e)) + @app.get("/api/v1/analytics/dashboard/{tenant_id}", tags=["Growth & Analytics"]) async def get_analytics_dashboard(tenant_id: str): """获取实时分析仪表板数据""" @@ -11898,6 +12476,7 @@ async def get_analytics_dashboard(tenant_id: str): return dashboard + @app.get("/api/v1/analytics/summary/{tenant_id}", tags=["Growth & Analytics"]) async def get_analytics_summary( tenant_id: str, start_date: str | None = None, end_date: str | None = None @@ -11915,6 +12494,7 @@ async def get_analytics_summary( return summary + @app.get("/api/v1/analytics/user-profile/{tenant_id}/{user_id}", tags=["Growth & Analytics"]) async def get_user_profile(tenant_id: str, user_id: str): """获取用户画像""" @@ -11940,8 +12520,10 @@ async def get_user_profile(tenant_id: str, user_id: str): "engagement_score": profile.engagement_score, } + # ==================== 转化漏斗 API ==================== + @app.post("/api/v1/analytics/funnels", tags=["Growth & Analytics"]) async def create_funnel_endpoint(request: CreateFunnelRequest, created_by: str = "system"): """创建转化漏斗""" @@ -11968,6 +12550,7 @@ async def create_funnel_endpoint(request: CreateFunnelRequest, created_by: str = "created_at": funnel.created_at, } + @app.get("/api/v1/analytics/funnels/{funnel_id}/analyze", tags=["Growth & Analytics"]) async def analyze_funnel_endpoint( funnel_id: str, period_start: str | None = None, period_end: str | None = None @@ -11996,6 +12579,7 @@ async def analyze_funnel_endpoint( "drop_off_points": analysis.drop_off_points, } + @app.get("/api/v1/analytics/retention/{tenant_id}", tags=["Growth & Analytics"]) async def calculate_retention( tenant_id: str, @@ -12015,8 +12599,10 @@ async def calculate_retention( return retention + # ==================== A/B 测试 API ==================== + @app.post("/api/v1/experiments", tags=["Growth & Analytics"]) async def create_experiment_endpoint(request: CreateExperimentRequest, created_by: str = "system"): """创建 A/B 测试实验""" @@ -12054,6 +12640,7 @@ async def create_experiment_endpoint(request: CreateExperimentRequest, created_b except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/experiments", tags=["Growth & Analytics"]) async def list_experiments(status: str | None = None): """列出实验""" @@ -12081,6 +12668,7 @@ async def list_experiments(status: str | None = None): ] } + @app.get("/api/v1/experiments/{experiment_id}", tags=["Growth & Analytics"]) async def get_experiment_endpoint(experiment_id: str): """获取实验详情""" @@ -12107,6 +12695,7 @@ async def get_experiment_endpoint(experiment_id: str): "end_date": experiment.end_date.isoformat() if experiment.end_date else None, } + @app.post("/api/v1/experiments/{experiment_id}/assign", tags=["Growth & Analytics"]) async def assign_variant_endpoint(experiment_id: str, request: AssignVariantRequest): """为用户分配实验变体""" @@ -12126,6 +12715,7 @@ async def assign_variant_endpoint(experiment_id: str, request: AssignVariantRequ return {"experiment_id": experiment_id, "user_id": request.user_id, "variant_id": variant_id} + @app.post("/api/v1/experiments/{experiment_id}/metrics", tags=["Growth & Analytics"]) async def record_experiment_metric_endpoint(experiment_id: str, request: RecordMetricRequest): """记录实验指标""" @@ -12144,6 +12734,7 @@ async def record_experiment_metric_endpoint(experiment_id: str, request: RecordM return {"success": True} + @app.get("/api/v1/experiments/{experiment_id}/analyze", tags=["Growth & Analytics"]) async def analyze_experiment_endpoint(experiment_id: str): """分析实验结果""" @@ -12159,6 +12750,7 @@ async def analyze_experiment_endpoint(experiment_id: str): return result + @app.post("/api/v1/experiments/{experiment_id}/start", tags=["Growth & Analytics"]) async def start_experiment_endpoint(experiment_id: str): """启动实验""" @@ -12178,6 +12770,7 @@ async def start_experiment_endpoint(experiment_id: str): "start_date": experiment.start_date.isoformat() if experiment.start_date else None, } + @app.post("/api/v1/experiments/{experiment_id}/stop", tags=["Growth & Analytics"]) async def stop_experiment_endpoint(experiment_id: str): """停止实验""" @@ -12197,8 +12790,10 @@ async def stop_experiment_endpoint(experiment_id: str): "end_date": experiment.end_date.isoformat() if experiment.end_date else None, } + # ==================== 邮件营销 API ==================== + @app.post("/api/v1/email/templates", tags=["Growth & Analytics"]) async def create_email_template_endpoint(request: CreateEmailTemplateRequest): """创建邮件模板""" @@ -12233,6 +12828,7 @@ async def create_email_template_endpoint(request: CreateEmailTemplateRequest): except Exception as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/email/templates", tags=["Growth & Analytics"]) async def list_email_templates(template_type: str | None = None): """列出邮件模板""" @@ -12259,6 +12855,7 @@ async def list_email_templates(template_type: str | None = None): ] } + @app.get("/api/v1/email/templates/{template_id}", tags=["Growth & Analytics"]) async def get_email_template_endpoint(template_id: str): """获取邮件模板详情""" @@ -12283,6 +12880,7 @@ async def get_email_template_endpoint(template_id: str): "from_email": template.from_email, } + @app.post("/api/v1/email/templates/{template_id}/render", tags=["Growth & Analytics"]) async def render_template_endpoint(template_id: str, variables: dict): """渲染邮件模板""" @@ -12298,6 +12896,7 @@ async def render_template_endpoint(template_id: str, variables: dict): return rendered + @app.post("/api/v1/email/campaigns", tags=["Growth & Analytics"]) async def create_email_campaign_endpoint(request: CreateCampaignRequest): """创建邮件营销活动""" @@ -12326,6 +12925,7 @@ async def create_email_campaign_endpoint(request: CreateCampaignRequest): "scheduled_at": campaign.scheduled_at, } + @app.post("/api/v1/email/campaigns/{campaign_id}/send", tags=["Growth & Analytics"]) async def send_campaign_endpoint(campaign_id: str): """发送邮件营销活动""" @@ -12341,6 +12941,7 @@ async def send_campaign_endpoint(campaign_id: str): return result + @app.post("/api/v1/email/workflows", tags=["Growth & Analytics"]) async def create_automation_workflow_endpoint(request: CreateAutomationWorkflowRequest): """创建自动化工作流""" @@ -12367,8 +12968,10 @@ async def create_automation_workflow_endpoint(request: CreateAutomationWorkflowR "created_at": workflow.created_at, } + # ==================== 推荐系统 API ==================== + @app.post("/api/v1/referral/programs", tags=["Growth & Analytics"]) async def create_referral_program_endpoint(request: CreateReferralProgramRequest): """创建推荐计划""" @@ -12401,6 +13004,7 @@ async def create_referral_program_endpoint(request: CreateReferralProgramRequest "is_active": program.is_active, } + @app.post("/api/v1/referral/programs/{program_id}/generate-code", tags=["Growth & Analytics"]) async def generate_referral_code_endpoint(program_id: str, referrer_id: str): """生成推荐码""" @@ -12422,6 +13026,7 @@ async def generate_referral_code_endpoint(program_id: str, referrer_id: str): "expires_at": referral.expires_at.isoformat(), } + @app.post("/api/v1/referral/apply", tags=["Growth & Analytics"]) async def apply_referral_code_endpoint(request: ApplyReferralCodeRequest): """应用推荐码""" @@ -12437,6 +13042,7 @@ async def apply_referral_code_endpoint(request: ApplyReferralCodeRequest): return {"success": True, "message": "Referral code applied successfully"} + @app.get("/api/v1/referral/programs/{program_id}/stats", tags=["Growth & Analytics"]) async def get_referral_stats_endpoint(program_id: str): """获取推荐统计""" @@ -12449,6 +13055,7 @@ async def get_referral_stats_endpoint(program_id: str): return stats + @app.post("/api/v1/team-incentives", tags=["Growth & Analytics"]) async def create_team_incentive_endpoint(request: CreateTeamIncentiveRequest): """创建团队升级激励""" @@ -12481,6 +13088,7 @@ async def create_team_incentive_endpoint(request: CreateTeamIncentiveRequest): "valid_until": incentive.valid_until.isoformat(), } + @app.get("/api/v1/team-incentives/check", tags=["Growth & Analytics"]) async def check_team_incentive_eligibility(tenant_id: str, current_tier: str, team_size: int): """检查团队激励资格""" @@ -12503,6 +13111,7 @@ async def check_team_incentive_eligibility(tenant_id: str, current_tier: str, te ] } + # Serve frontend - MUST be last to not override API routes # ============================================ @@ -12526,6 +13135,7 @@ except ImportError as e: print(f"Developer Ecosystem Manager import error: {e}") DEVELOPER_ECOSYSTEM_AVAILABLE = False + # Pydantic Models for Developer Ecosystem API class SDKReleaseCreate(BaseModel): name: str @@ -12542,6 +13152,7 @@ class SDKReleaseCreate(BaseModel): file_size: int = 0 checksum: str = "" + class SDKReleaseUpdate(BaseModel): name: str | None = None description: str | None = None @@ -12551,6 +13162,7 @@ class SDKReleaseUpdate(BaseModel): repository_url: str | None = None status: str | None = None + class SDKVersionCreate(BaseModel): version: str is_lts: bool = False @@ -12559,6 +13171,7 @@ class SDKVersionCreate(BaseModel): checksum: str = "" file_size: int = 0 + class TemplateCreate(BaseModel): name: str description: str @@ -12576,11 +13189,13 @@ class TemplateCreate(BaseModel): file_size: int = 0 checksum: str = "" + class TemplateReviewCreate(BaseModel): rating: int = Field(..., ge=1, le=5) comment: str = "" is_verified_purchase: bool = False + class PluginCreate(BaseModel): name: str description: str @@ -12601,11 +13216,13 @@ class PluginCreate(BaseModel): file_size: int = 0 checksum: str = "" + class PluginReviewCreate(BaseModel): rating: int = Field(..., ge=1, le=5) comment: str = "" is_verified_purchase: bool = False + class DeveloperProfileCreate(BaseModel): display_name: str email: str @@ -12614,6 +13231,7 @@ class DeveloperProfileCreate(BaseModel): github_url: str | None = None avatar_url: str | None = None + class DeveloperProfileUpdate(BaseModel): display_name: str | None = None bio: str | None = None @@ -12621,6 +13239,7 @@ class DeveloperProfileUpdate(BaseModel): github_url: str | None = None avatar_url: str | None = None + class CodeExampleCreate(BaseModel): title: str description: str = "" @@ -12632,6 +13251,7 @@ class CodeExampleCreate(BaseModel): sdk_id: str | None = None api_endpoints: list[str] = Field(default_factory=list) + class PortalConfigCreate(BaseModel): name: str description: str = "" @@ -12648,17 +13268,21 @@ class PortalConfigCreate(BaseModel): discord_url: str | None = None api_base_url: str = "https://api.insightflow.io" + # Developer Ecosystem Manager singleton _developer_ecosystem_manager = None + def get_developer_ecosystem_manager_instance(): global _developer_ecosystem_manager if _developer_ecosystem_manager is None and DEVELOPER_ECOSYSTEM_AVAILABLE: _developer_ecosystem_manager = DeveloperEcosystemManager() return _developer_ecosystem_manager + # ==================== SDK Release & Management API ==================== + @app.post("/api/v1/developer/sdks", tags=["Developer Ecosystem"]) async def create_sdk_release_endpoint( request: SDKReleaseCreate, created_by: str = Header(default="system", description="创建者ID") @@ -12699,6 +13323,7 @@ async def create_sdk_release_endpoint( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/developer/sdks", tags=["Developer Ecosystem"]) async def list_sdk_releases_endpoint( language: str | None = Query(default=None, description="SDK语言过滤"), @@ -12733,6 +13358,7 @@ async def list_sdk_releases_endpoint( ] } + @app.get("/api/v1/developer/sdks/{sdk_id}", tags=["Developer Ecosystem"]) async def get_sdk_release_endpoint(sdk_id: str): """获取 SDK 发布详情""" @@ -12766,6 +13392,7 @@ async def get_sdk_release_endpoint(sdk_id: str): "published_at": sdk.published_at, } + @app.put("/api/v1/developer/sdks/{sdk_id}", tags=["Developer Ecosystem"]) async def update_sdk_release_endpoint(sdk_id: str, request: SDKReleaseUpdate): """更新 SDK 发布""" @@ -12787,6 +13414,7 @@ async def update_sdk_release_endpoint(sdk_id: str, request: SDKReleaseUpdate): "updated_at": sdk.updated_at, } + @app.post("/api/v1/developer/sdks/{sdk_id}/publish", tags=["Developer Ecosystem"]) async def publish_sdk_release_endpoint(sdk_id: str): """发布 SDK""" @@ -12801,6 +13429,7 @@ async def publish_sdk_release_endpoint(sdk_id: str): return {"id": sdk.id, "status": sdk.status.value, "published_at": sdk.published_at} + @app.post("/api/v1/developer/sdks/{sdk_id}/download", tags=["Developer Ecosystem"]) async def increment_sdk_download_endpoint(sdk_id: str): """记录 SDK 下载""" @@ -12812,6 +13441,7 @@ async def increment_sdk_download_endpoint(sdk_id: str): return {"success": True, "message": "Download counted"} + @app.get("/api/v1/developer/sdks/{sdk_id}/versions", tags=["Developer Ecosystem"]) async def get_sdk_versions_endpoint(sdk_id: str): """获取 SDK 版本历史""" @@ -12835,6 +13465,7 @@ async def get_sdk_versions_endpoint(sdk_id: str): ] } + @app.post("/api/v1/developer/sdks/{sdk_id}/versions", tags=["Developer Ecosystem"]) async def add_sdk_version_endpoint(sdk_id: str, request: SDKVersionCreate): """添加 SDK 版本""" @@ -12861,8 +13492,10 @@ async def add_sdk_version_endpoint(sdk_id: str, request: SDKVersionCreate): "created_at": version.created_at, } + # ==================== Template Market API ==================== + @app.post("/api/v1/developer/templates", tags=["Developer Ecosystem"]) async def create_template_endpoint( request: TemplateCreate, @@ -12907,6 +13540,7 @@ async def create_template_endpoint( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/developer/templates", tags=["Developer Ecosystem"]) async def list_templates_endpoint( category: str | None = Query(default=None, description="分类过滤"), @@ -12956,6 +13590,7 @@ async def list_templates_endpoint( ] } + @app.get("/api/v1/developer/templates/{template_id}", tags=["Developer Ecosystem"]) async def get_template_endpoint(template_id: str): """获取模板详情""" @@ -12992,6 +13627,7 @@ async def get_template_endpoint(template_id: str): "created_at": template.created_at, } + @app.post("/api/v1/developer/templates/{template_id}/approve", tags=["Developer Ecosystem"]) async def approve_template_endpoint(template_id: str, reviewed_by: str = Header(default="system")): """审核通过模板""" @@ -13006,6 +13642,7 @@ async def approve_template_endpoint(template_id: str, reviewed_by: str = Header( return {"id": template.id, "status": template.status.value} + @app.post("/api/v1/developer/templates/{template_id}/publish", tags=["Developer Ecosystem"]) async def publish_template_endpoint(template_id: str): """发布模板""" @@ -13024,6 +13661,7 @@ async def publish_template_endpoint(template_id: str): "published_at": template.published_at, } + @app.post("/api/v1/developer/templates/{template_id}/reject", tags=["Developer Ecosystem"]) async def reject_template_endpoint(template_id: str, reason: str = ""): """拒绝模板""" @@ -13038,6 +13676,7 @@ async def reject_template_endpoint(template_id: str, reason: str = ""): return {"id": template.id, "status": template.status.value} + @app.post("/api/v1/developer/templates/{template_id}/install", tags=["Developer Ecosystem"]) async def install_template_endpoint(template_id: str): """安装模板""" @@ -13049,6 +13688,7 @@ async def install_template_endpoint(template_id: str): return {"success": True, "message": "Template installed"} + @app.post("/api/v1/developer/templates/{template_id}/reviews", tags=["Developer Ecosystem"]) async def add_template_review_endpoint( template_id: str, @@ -13078,6 +13718,7 @@ async def add_template_review_endpoint( "created_at": review.created_at, } + @app.get("/api/v1/developer/templates/{template_id}/reviews", tags=["Developer Ecosystem"]) async def get_template_reviews_endpoint( template_id: str, limit: int = Query(default=50, description="返回数量限制") @@ -13104,8 +13745,10 @@ async def get_template_reviews_endpoint( ] } + # ==================== Plugin Market API ==================== + @app.post("/api/v1/developer/plugins", tags=["Developer Ecosystem"]) async def create_developer_plugin_endpoint( request: PluginCreate, @@ -13154,6 +13797,7 @@ async def create_developer_plugin_endpoint( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/developer/plugins", tags=["Developer Ecosystem"]) async def list_developer_plugins_endpoint( category: str | None = Query(default=None, description="分类过滤"), @@ -13200,6 +13844,7 @@ async def list_developer_plugins_endpoint( ] } + @app.get("/api/v1/developer/plugins/{plugin_id}", tags=["Developer Ecosystem"]) async def get_developer_plugin_endpoint(plugin_id: str): """获取插件详情""" @@ -13239,6 +13884,7 @@ async def get_developer_plugin_endpoint(plugin_id: str): "created_at": plugin.created_at, } + @app.post("/api/v1/developer/plugins/{plugin_id}/review", tags=["Developer Ecosystem"]) async def review_plugin_endpoint( plugin_id: str, @@ -13268,6 +13914,7 @@ async def review_plugin_endpoint( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.post("/api/v1/developer/plugins/{plugin_id}/publish", tags=["Developer Ecosystem"]) async def publish_plugin_endpoint(plugin_id: str): """发布插件""" @@ -13282,6 +13929,7 @@ async def publish_plugin_endpoint(plugin_id: str): return {"id": plugin.id, "status": plugin.status.value, "published_at": plugin.published_at} + @app.post("/api/v1/developer/plugins/{plugin_id}/install", tags=["Developer Ecosystem"]) async def install_plugin_endpoint(plugin_id: str, active: bool = True): """安装插件""" @@ -13293,6 +13941,7 @@ async def install_plugin_endpoint(plugin_id: str, active: bool = True): return {"success": True, "message": "Plugin installed"} + @app.post("/api/v1/developer/plugins/{plugin_id}/reviews", tags=["Developer Ecosystem"]) async def add_plugin_review_endpoint( plugin_id: str, @@ -13322,6 +13971,7 @@ async def add_plugin_review_endpoint( "created_at": review.created_at, } + @app.get("/api/v1/developer/plugins/{plugin_id}/reviews", tags=["Developer Ecosystem"]) async def get_plugin_reviews_endpoint( plugin_id: str, limit: int = Query(default=50, description="返回数量限制") @@ -13348,8 +13998,10 @@ async def get_plugin_reviews_endpoint( ] } + # ==================== Developer Revenue Sharing API ==================== + @app.get("/api/v1/developer/revenues/{developer_id}", tags=["Developer Ecosystem"]) async def get_developer_revenues_endpoint( developer_id: str, @@ -13383,6 +14035,7 @@ async def get_developer_revenues_endpoint( ] } + @app.get("/api/v1/developer/revenues/{developer_id}/summary", tags=["Developer Ecosystem"]) async def get_developer_revenue_summary_endpoint(developer_id: str): """获取开发者收益汇总""" @@ -13394,8 +14047,10 @@ async def get_developer_revenue_summary_endpoint(developer_id: str): return summary + # ==================== Developer Profile & Management API ==================== + @app.post("/api/v1/developer/profiles", tags=["Developer Ecosystem"]) async def create_developer_profile_endpoint(request: DeveloperProfileCreate): """创建开发者档案""" @@ -13425,6 +14080,7 @@ async def create_developer_profile_endpoint(request: DeveloperProfileCreate): "created_at": profile.created_at, } + @app.get("/api/v1/developer/profiles/{developer_id}", tags=["Developer Ecosystem"]) async def get_developer_profile_endpoint(developer_id: str): """获取开发者档案""" @@ -13456,6 +14112,7 @@ async def get_developer_profile_endpoint(developer_id: str): "verified_at": profile.verified_at, } + @app.get("/api/v1/developer/profiles/user/{user_id}", tags=["Developer Ecosystem"]) async def get_developer_profile_by_user_endpoint(user_id: str): """通过用户ID获取开发者档案""" @@ -13477,6 +14134,7 @@ async def get_developer_profile_by_user_endpoint(user_id: str): "total_downloads": profile.total_downloads, } + @app.put("/api/v1/developer/profiles/{developer_id}", tags=["Developer Ecosystem"]) async def update_developer_profile_endpoint(developer_id: str, request: DeveloperProfileUpdate): """更新开发者档案""" @@ -13485,6 +14143,7 @@ async def update_developer_profile_endpoint(developer_id: str, request: Develope return {"message": "Profile update endpoint - to be implemented"} + @app.post("/api/v1/developer/profiles/{developer_id}/verify", tags=["Developer Ecosystem"]) async def verify_developer_endpoint( developer_id: str, @@ -13511,6 +14170,7 @@ async def verify_developer_endpoint( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.post("/api/v1/developer/profiles/{developer_id}/update-stats", tags=["Developer Ecosystem"]) async def update_developer_stats_endpoint(developer_id: str): """更新开发者统计信息""" @@ -13522,8 +14182,10 @@ async def update_developer_stats_endpoint(developer_id: str): return {"success": True, "message": "Developer stats updated"} + # ==================== Code Examples API ==================== + @app.post("/api/v1/developer/code-examples", tags=["Developer Ecosystem"]) async def create_code_example_endpoint( request: CodeExampleCreate, @@ -13559,6 +14221,7 @@ async def create_code_example_endpoint( "created_at": example.created_at, } + @app.get("/api/v1/developer/code-examples", tags=["Developer Ecosystem"]) async def list_code_examples_endpoint( language: str | None = Query(default=None, description="编程语言过滤"), @@ -13592,6 +14255,7 @@ async def list_code_examples_endpoint( ] } + @app.get("/api/v1/developer/code-examples/{example_id}", tags=["Developer Ecosystem"]) async def get_code_example_endpoint(example_id: str): """获取代码示例详情""" @@ -13624,6 +14288,7 @@ async def get_code_example_endpoint(example_id: str): "created_at": example.created_at, } + @app.post("/api/v1/developer/code-examples/{example_id}/copy", tags=["Developer Ecosystem"]) async def copy_code_example_endpoint(example_id: str): """复制代码示例""" @@ -13635,8 +14300,10 @@ async def copy_code_example_endpoint(example_id: str): return {"success": True, "message": "Code copied"} + # ==================== API Documentation API ==================== + @app.get("/api/v1/developer/api-docs", tags=["Developer Ecosystem"]) async def get_latest_api_documentation_endpoint(): """获取最新 API 文档""" @@ -13657,6 +14324,7 @@ async def get_latest_api_documentation_endpoint(): "generated_by": doc.generated_by, } + @app.get("/api/v1/developer/api-docs/{doc_id}", tags=["Developer Ecosystem"]) async def get_api_documentation_endpoint(doc_id: str): """获取 API 文档详情""" @@ -13680,8 +14348,10 @@ async def get_api_documentation_endpoint(doc_id: str): "generated_by": doc.generated_by, } + # ==================== Developer Portal API ==================== + @app.post("/api/v1/developer/portal-configs", tags=["Developer Ecosystem"]) async def create_portal_config_endpoint(request: PortalConfigCreate): """创建开发者门户配置""" @@ -13715,6 +14385,7 @@ async def create_portal_config_endpoint(request: PortalConfigCreate): "created_at": config.created_at, } + @app.get("/api/v1/developer/portal-configs", tags=["Developer Ecosystem"]) async def get_active_portal_config_endpoint(): """获取活跃的开发者门户配置""" @@ -13744,6 +14415,7 @@ async def get_active_portal_config_endpoint(): "is_active": config.is_active, } + @app.get("/api/v1/developer/portal-configs/{config_id}", tags=["Developer Ecosystem"]) async def get_portal_config_endpoint(config_id: str): """获取开发者门户配置""" @@ -13768,17 +14440,20 @@ async def get_portal_config_endpoint(config_id: str): "is_active": config.is_active, } + # ==================== Phase 8 Task 8: Operations & Monitoring Endpoints ==================== # Ops Manager singleton _ops_manager = None + def get_ops_manager_instance(): global _ops_manager if _ops_manager is None and OPS_MANAGER_AVAILABLE: _ops_manager = get_ops_manager() return _ops_manager + # Pydantic Models for Ops API class AlertRuleCreate(BaseModel): name: str = Field(..., description="告警规则名称") @@ -13794,6 +14469,7 @@ class AlertRuleCreate(BaseModel): labels: dict = Field(default_factory=dict, description="标签") annotations: dict = Field(default_factory=dict, description="注释") + class AlertRuleResponse(BaseModel): id: str name: str @@ -13812,6 +14488,7 @@ class AlertRuleResponse(BaseModel): created_at: str updated_at: str + class AlertChannelCreate(BaseModel): name: str = Field(..., description="渠道名称") channel_type: str = Field( @@ -13823,6 +14500,7 @@ class AlertChannelCreate(BaseModel): default_factory=lambda: ["p0", "p1", "p2", "p3"], description="过滤的告警级别" ) + class AlertChannelResponse(BaseModel): id: str name: str @@ -13835,6 +14513,7 @@ class AlertChannelResponse(BaseModel): last_used_at: str | None created_at: str + class AlertResponse(BaseModel): id: str rule_id: str @@ -13851,6 +14530,7 @@ class AlertResponse(BaseModel): acknowledged_by: str | None suppression_count: int + class HealthCheckCreate(BaseModel): name: str = Field(..., description="健康检查名称") target_type: str = Field(..., description="目标类型: service, database, api") @@ -13861,6 +14541,7 @@ class HealthCheckCreate(BaseModel): timeout: int = Field(default=10, description="超时时间(秒)") retry_count: int = Field(default=3, description="重试次数") + class HealthCheckResponse(BaseModel): id: str name: str @@ -13872,6 +14553,7 @@ class HealthCheckResponse(BaseModel): is_enabled: bool created_at: str + class AutoScalingPolicyCreate(BaseModel): name: str = Field(..., description="策略名称") resource_type: str = Field( @@ -13886,6 +14568,7 @@ class AutoScalingPolicyCreate(BaseModel): scale_down_step: int = Field(default=1, description="缩容步长") cooldown_period: int = Field(default=300, description="冷却时间(秒)") + class BackupJobCreate(BaseModel): name: str = Field(..., description="备份任务名称") backup_type: str = Field(..., description="备份类型: full, incremental, differential") @@ -13897,6 +14580,7 @@ class BackupJobCreate(BaseModel): compression_enabled: bool = Field(default=True, description="是否压缩") storage_location: str | None = Field(default=None, description="存储位置") + # Alert Rules API @app.post( "/api/v1/ops/alert-rules", response_model=AlertRuleResponse, tags=["Operations & Monitoring"] @@ -13949,6 +14633,7 @@ async def create_alert_rule_endpoint( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/ops/alert-rules", tags=["Operations & Monitoring"]) async def list_alert_rules_endpoint( tenant_id: str, is_enabled: bool | None = None, _=Depends(verify_api_key) @@ -13982,6 +14667,7 @@ async def list_alert_rules_endpoint( for rule in rules ] + @app.get( "/api/v1/ops/alert-rules/{rule_id}", response_model=AlertRuleResponse, @@ -14017,6 +14703,7 @@ async def get_alert_rule_endpoint(rule_id: str, _=Depends(verify_api_key)): updated_at=rule.updated_at, ) + @app.patch( "/api/v1/ops/alert-rules/{rule_id}", response_model=AlertRuleResponse, @@ -14052,6 +14739,7 @@ async def update_alert_rule_endpoint(rule_id: str, updates: dict, _=Depends(veri updated_at=rule.updated_at, ) + @app.delete("/api/v1/ops/alert-rules/{rule_id}", tags=["Operations & Monitoring"]) async def delete_alert_rule_endpoint(rule_id: str, _=Depends(verify_api_key)): """删除告警规则""" @@ -14066,6 +14754,7 @@ async def delete_alert_rule_endpoint(rule_id: str, _=Depends(verify_api_key)): return {"success": True, "message": "Alert rule deleted"} + # Alert Channels API @app.post( "/api/v1/ops/alert-channels", @@ -14105,6 +14794,7 @@ async def create_alert_channel_endpoint( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/ops/alert-channels", tags=["Operations & Monitoring"]) async def list_alert_channels_endpoint(tenant_id: str, _=Depends(verify_api_key)): """列出租户的告警渠道""" @@ -14130,6 +14820,7 @@ async def list_alert_channels_endpoint(tenant_id: str, _=Depends(verify_api_key) for channel in channels ] + @app.post("/api/v1/ops/alert-channels/{channel_id}/test", tags=["Operations & Monitoring"]) async def test_alert_channel_endpoint(channel_id: str, _=Depends(verify_api_key)): """测试告警渠道""" @@ -14144,6 +14835,7 @@ async def test_alert_channel_endpoint(channel_id: str, _=Depends(verify_api_key) else: raise HTTPException(status_code=400, detail="Failed to send test alert") + # Alerts API @app.get("/api/v1/ops/alerts", tags=["Operations & Monitoring"]) async def list_alerts_endpoint( @@ -14184,6 +14876,7 @@ async def list_alerts_endpoint( for alert in alerts ] + @app.post("/api/v1/ops/alerts/{alert_id}/acknowledge", tags=["Operations & Monitoring"]) async def acknowledge_alert_endpoint( alert_id: str, user_id: str = "system", _=Depends(verify_api_key) @@ -14200,6 +14893,7 @@ async def acknowledge_alert_endpoint( return {"success": True, "message": "Alert acknowledged"} + @app.post("/api/v1/ops/alerts/{alert_id}/resolve", tags=["Operations & Monitoring"]) async def resolve_alert_endpoint(alert_id: str, _=Depends(verify_api_key)): """解决告警""" @@ -14214,6 +14908,7 @@ async def resolve_alert_endpoint(alert_id: str, _=Depends(verify_api_key)): return {"success": True, "message": "Alert resolved"} + # Resource Metrics API @app.post("/api/v1/ops/resource-metrics", tags=["Operations & Monitoring"]) async def record_resource_metric_endpoint( @@ -14254,6 +14949,7 @@ async def record_resource_metric_endpoint( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/ops/resource-metrics", tags=["Operations & Monitoring"]) async def get_resource_metrics_endpoint( tenant_id: str, metric_name: str, seconds: int = 3600, _=Depends(verify_api_key) @@ -14278,6 +14974,7 @@ async def get_resource_metrics_endpoint( for m in metrics ] + # Capacity Planning API @app.post("/api/v1/ops/capacity-plans", tags=["Operations & Monitoring"]) async def create_capacity_plan_endpoint( @@ -14317,6 +15014,7 @@ async def create_capacity_plan_endpoint( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/ops/capacity-plans", tags=["Operations & Monitoring"]) async def list_capacity_plans_endpoint(tenant_id: str, _=Depends(verify_api_key)): """获取容量规划列表""" @@ -14341,6 +15039,7 @@ async def list_capacity_plans_endpoint(tenant_id: str, _=Depends(verify_api_key) for plan in plans ] + # Auto Scaling API @app.post("/api/v1/ops/auto-scaling-policies", tags=["Operations & Monitoring"]) async def create_auto_scaling_policy_endpoint( @@ -14382,6 +15081,7 @@ async def create_auto_scaling_policy_endpoint( except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) + @app.get("/api/v1/ops/auto-scaling-policies", tags=["Operations & Monitoring"]) async def list_auto_scaling_policies_endpoint(tenant_id: str, _=Depends(verify_api_key)): """获取自动扩缩容策略列表""" @@ -14405,6 +15105,7 @@ async def list_auto_scaling_policies_endpoint(tenant_id: str, _=Depends(verify_a for policy in policies ] + @app.get("/api/v1/ops/scaling-events", tags=["Operations & Monitoring"]) async def list_scaling_events_endpoint( tenant_id: str, policy_id: str | None = None, limit: int = 100, _=Depends(verify_api_key) @@ -14431,6 +15132,7 @@ async def list_scaling_events_endpoint( for event in events ] + # Health Check API @app.post( "/api/v1/ops/health-checks", @@ -14470,6 +15172,7 @@ async def create_health_check_endpoint( created_at=check.created_at, ) + @app.get("/api/v1/ops/health-checks", tags=["Operations & Monitoring"]) async def list_health_checks_endpoint(tenant_id: str, _=Depends(verify_api_key)): """获取健康检查列表""" @@ -14494,6 +15197,7 @@ async def list_health_checks_endpoint(tenant_id: str, _=Depends(verify_api_key)) for check in checks ] + @app.post("/api/v1/ops/health-checks/{check_id}/execute", tags=["Operations & Monitoring"]) async def execute_health_check_endpoint(check_id: str, _=Depends(verify_api_key)): """执行健康检查""" @@ -14512,6 +15216,7 @@ async def execute_health_check_endpoint(check_id: str, _=Depends(verify_api_key) "checked_at": result.checked_at, } + # Backup API @app.post("/api/v1/ops/backup-jobs", tags=["Operations & Monitoring"]) async def create_backup_job_endpoint( @@ -14546,6 +15251,7 @@ async def create_backup_job_endpoint( "created_at": job.created_at, } + @app.get("/api/v1/ops/backup-jobs", tags=["Operations & Monitoring"]) async def list_backup_jobs_endpoint(tenant_id: str, _=Depends(verify_api_key)): """获取备份任务列表""" @@ -14568,6 +15274,7 @@ async def list_backup_jobs_endpoint(tenant_id: str, _=Depends(verify_api_key)): for job in jobs ] + @app.post("/api/v1/ops/backup-jobs/{job_id}/execute", tags=["Operations & Monitoring"]) async def execute_backup_endpoint(job_id: str, _=Depends(verify_api_key)): """执行备份""" @@ -14588,6 +15295,7 @@ async def execute_backup_endpoint(job_id: str, _=Depends(verify_api_key)): "storage_path": record.storage_path, } + @app.get("/api/v1/ops/backup-records", tags=["Operations & Monitoring"]) async def list_backup_records_endpoint( tenant_id: str, job_id: str | None = None, limit: int = 100, _=Depends(verify_api_key) @@ -14613,6 +15321,7 @@ async def list_backup_records_endpoint( for record in records ] + # Cost Optimization API @app.post("/api/v1/ops/cost-reports", tags=["Operations & Monitoring"]) async def generate_cost_report_endpoint( @@ -14636,6 +15345,7 @@ async def generate_cost_report_endpoint( "created_at": report.created_at, } + @app.get("/api/v1/ops/idle-resources", tags=["Operations & Monitoring"]) async def get_idle_resources_endpoint(tenant_id: str, _=Depends(verify_api_key)): """获取闲置资源列表""" @@ -14660,6 +15370,7 @@ async def get_idle_resources_endpoint(tenant_id: str, _=Depends(verify_api_key)) for resource in idle_resources ] + @app.post("/api/v1/ops/cost-optimization-suggestions", tags=["Operations & Monitoring"]) async def generate_cost_optimization_suggestions_endpoint( tenant_id: str, _=Depends(verify_api_key) @@ -14688,6 +15399,7 @@ async def generate_cost_optimization_suggestions_endpoint( for suggestion in suggestions ] + @app.get("/api/v1/ops/cost-optimization-suggestions", tags=["Operations & Monitoring"]) async def list_cost_optimization_suggestions_endpoint( tenant_id: str, is_applied: bool | None = None, _=Depends(verify_api_key) @@ -14715,6 +15427,7 @@ async def list_cost_optimization_suggestions_endpoint( for suggestion in suggestions ] + @app.post( "/api/v1/ops/cost-optimization-suggestions/{suggestion_id}/apply", tags=["Operations & Monitoring"], @@ -14743,5 +15456,6 @@ async def apply_cost_optimization_suggestion_endpoint( }, } + if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000) diff --git a/backend/multimodal_entity_linker.py b/backend/multimodal_entity_linker.py index d2f94c3..f99d835 100644 --- a/backend/multimodal_entity_linker.py +++ b/backend/multimodal_entity_linker.py @@ -14,6 +14,7 @@ try: except ImportError: NUMPY_AVAILABLE = False + @dataclass class MultimodalEntity: """多模态实体""" @@ -32,6 +33,7 @@ class MultimodalEntity: if self.modality_features is None: self.modality_features = {} + @dataclass class EntityLink: """实体关联""" @@ -46,6 +48,7 @@ class EntityLink: confidence: float evidence: str + @dataclass class AlignmentResult: """对齐结果""" @@ -56,6 +59,7 @@ class AlignmentResult: match_type: str # exact, fuzzy, embedding confidence: float + @dataclass class FusionResult: """知识融合结果""" @@ -66,6 +70,7 @@ class FusionResult: source_modalities: list[str] confidence: float + class MultimodalEntityLinker: """多模态实体关联器 - 跨模态实体对齐和知识融合""" @@ -507,9 +512,11 @@ class MultimodalEntityLinker: else 0, } + # Singleton instance _multimodal_entity_linker = None + def get_multimodal_entity_linker(similarity_threshold: float = 0.85) -> MultimodalEntityLinker: """获取多模态实体关联器单例""" global _multimodal_entity_linker diff --git a/backend/multimodal_processor.py b/backend/multimodal_processor.py index 7131c4b..741f1a0 100644 --- a/backend/multimodal_processor.py +++ b/backend/multimodal_processor.py @@ -35,6 +35,7 @@ try: except ImportError: FFMPEG_AVAILABLE = False + @dataclass class VideoFrame: """视频关键帧数据类""" @@ -52,6 +53,7 @@ class VideoFrame: if self.entities_detected is None: self.entities_detected = [] + @dataclass class VideoInfo: """视频信息数据类""" @@ -75,6 +77,7 @@ class VideoInfo: if self.metadata is None: self.metadata = {} + @dataclass class VideoProcessingResult: """视频处理结果""" @@ -87,6 +90,7 @@ class VideoProcessingResult: success: bool error_message: str = "" + class MultimodalProcessor: """多模态处理器 - 处理视频文件""" @@ -445,9 +449,11 @@ class MultimodalProcessor: shutil.rmtree(dir_path) os.makedirs(dir_path, exist_ok=True) + # Singleton instance _multimodal_processor = None + def get_multimodal_processor(temp_dir: str = None, frame_interval: int = 5) -> MultimodalProcessor: """获取多模态处理器单例""" global _multimodal_processor diff --git a/backend/neo4j_manager.py b/backend/neo4j_manager.py index 874d6ff..c79bfdc 100644 --- a/backend/neo4j_manager.py +++ b/backend/neo4j_manager.py @@ -26,6 +26,7 @@ except ImportError: NEO4J_AVAILABLE = False logger.warning("Neo4j driver not installed. Neo4j features will be disabled.") + @dataclass class GraphEntity: """图数据库中的实体节点""" @@ -44,6 +45,7 @@ class GraphEntity: if self.properties is None: self.properties = {} + @dataclass class GraphRelation: """图数据库中的关系边""" @@ -59,6 +61,7 @@ class GraphRelation: if self.properties is None: self.properties = {} + @dataclass class PathResult: """路径查询结果""" @@ -68,6 +71,7 @@ class PathResult: length: int total_weight: float = 0.0 + @dataclass class CommunityResult: """社区发现结果""" @@ -77,6 +81,7 @@ class CommunityResult: size: int density: float = 0.0 + @dataclass class CentralityResult: """中心性分析结果""" @@ -86,6 +91,7 @@ class CentralityResult: score: float rank: int = 0 + class Neo4jManager: """Neo4j 图数据库管理器""" @@ -962,9 +968,11 @@ class Neo4jManager: return {"nodes": nodes, "relationships": relationships} + # 全局单例 _neo4j_manager = None + def get_neo4j_manager() -> Neo4jManager: """获取 Neo4j 管理器单例""" global _neo4j_manager @@ -972,6 +980,7 @@ def get_neo4j_manager() -> Neo4jManager: _neo4j_manager = Neo4jManager() return _neo4j_manager + def close_neo4j_manager() -> None: """关闭 Neo4j 连接""" global _neo4j_manager @@ -979,6 +988,7 @@ def close_neo4j_manager() -> None: _neo4j_manager.close() _neo4j_manager = None + # 便捷函数 def sync_project_to_neo4j( project_id: str, project_name: str, entities: list[dict], relations: list[dict] @@ -1033,6 +1043,7 @@ def sync_project_to_neo4j( f"Synced project {project_id} to Neo4j: {len(entities)} entities, {len(relations)} relations" ) + if __name__ == "__main__": # 测试代码 logging.basicConfig(level=logging.INFO) diff --git a/backend/ops_manager.py b/backend/ops_manager.py index ce08c90..d73b2cf 100644 --- a/backend/ops_manager.py +++ b/backend/ops_manager.py @@ -29,6 +29,7 @@ import httpx # Database path DB_PATH = os.path.join(os.path.dirname(__file__), "insightflow.db") + class AlertSeverity(StrEnum): """告警严重级别 P0-P3""" @@ -37,6 +38,7 @@ class AlertSeverity(StrEnum): P2 = "p2" # 一般 - 部分功能受影响,需要4小时内处理 P3 = "p3" # 轻微 - 非核心功能问题,24小时内处理 + class AlertStatus(StrEnum): """告警状态""" @@ -45,6 +47,7 @@ class AlertStatus(StrEnum): ACKNOWLEDGED = "acknowledged" # 已确认 SUPPRESSED = "suppressed" # 已抑制 + class AlertChannelType(StrEnum): """告警渠道类型""" @@ -57,6 +60,7 @@ class AlertChannelType(StrEnum): SMS = "sms" WEBHOOK = "webhook" + class AlertRuleType(StrEnum): """告警规则类型""" @@ -65,6 +69,7 @@ class AlertRuleType(StrEnum): PREDICTIVE = "predictive" # 预测性告警 COMPOSITE = "composite" # 复合告警 + class ResourceType(StrEnum): """资源类型""" @@ -77,6 +82,7 @@ class ResourceType(StrEnum): CACHE = "cache" QUEUE = "queue" + class ScalingAction(StrEnum): """扩缩容动作""" @@ -84,6 +90,7 @@ class ScalingAction(StrEnum): SCALE_DOWN = "scale_down" # 缩容 MAINTAIN = "maintain" # 保持 + class HealthStatus(StrEnum): """健康状态""" @@ -92,6 +99,7 @@ class HealthStatus(StrEnum): UNHEALTHY = "unhealthy" UNKNOWN = "unknown" + class BackupStatus(StrEnum): """备份状态""" @@ -101,6 +109,7 @@ class BackupStatus(StrEnum): FAILED = "failed" VERIFIED = "verified" + @dataclass class AlertRule: """告警规则""" @@ -124,6 +133,7 @@ class AlertRule: updated_at: str created_by: str + @dataclass class AlertChannel: """告警渠道配置""" @@ -141,6 +151,7 @@ class AlertChannel: created_at: str updated_at: str + @dataclass class Alert: """告警实例""" @@ -164,6 +175,7 @@ class Alert: notification_sent: dict[str, bool] # 渠道发送状态 suppression_count: int # 抑制计数 + @dataclass class AlertSuppressionRule: """告警抑制规则""" @@ -177,6 +189,7 @@ class AlertSuppressionRule: created_at: str expires_at: str | None + @dataclass class AlertGroup: """告警聚合组""" @@ -188,6 +201,7 @@ class AlertGroup: created_at: str updated_at: str + @dataclass class ResourceMetric: """资源指标""" @@ -202,6 +216,7 @@ class ResourceMetric: timestamp: str metadata: dict + @dataclass class CapacityPlan: """容量规划""" @@ -217,6 +232,7 @@ class CapacityPlan: estimated_cost: float created_at: str + @dataclass class AutoScalingPolicy: """自动扩缩容策略""" @@ -237,6 +253,7 @@ class AutoScalingPolicy: created_at: str updated_at: str + @dataclass class ScalingEvent: """扩缩容事件""" @@ -254,6 +271,7 @@ class ScalingEvent: completed_at: str | None error_message: str | None + @dataclass class HealthCheck: """健康检查配置""" @@ -274,6 +292,7 @@ class HealthCheck: created_at: str updated_at: str + @dataclass class HealthCheckResult: """健康检查结果""" @@ -287,6 +306,7 @@ class HealthCheckResult: details: dict checked_at: str + @dataclass class FailoverConfig: """故障转移配置""" @@ -304,6 +324,7 @@ class FailoverConfig: created_at: str updated_at: str + @dataclass class FailoverEvent: """故障转移事件""" @@ -319,6 +340,7 @@ class FailoverEvent: completed_at: str | None rolled_back_at: str | None + @dataclass class BackupJob: """备份任务""" @@ -338,6 +360,7 @@ class BackupJob: created_at: str updated_at: str + @dataclass class BackupRecord: """备份记录""" @@ -354,6 +377,7 @@ class BackupRecord: error_message: str | None storage_path: str + @dataclass class CostReport: """成本报告""" @@ -368,6 +392,7 @@ class CostReport: anomalies: list[dict] # 异常检测 created_at: str + @dataclass class ResourceUtilization: """资源利用率""" @@ -383,6 +408,7 @@ class ResourceUtilization: report_date: str recommendations: list[str] + @dataclass class IdleResource: """闲置资源""" @@ -399,6 +425,7 @@ class IdleResource: recommendation: str detected_at: str + @dataclass class CostOptimizationSuggestion: """成本优化建议""" @@ -418,6 +445,7 @@ class CostOptimizationSuggestion: created_at: str applied_at: str | None + class OpsManager: """运维与监控管理主类""" @@ -3065,9 +3093,11 @@ class OpsManager: applied_at=row["applied_at"], ) + # Singleton instance _ops_manager = None + def get_ops_manager() -> OpsManager: global _ops_manager if _ops_manager is None: diff --git a/backend/oss_uploader.py b/backend/oss_uploader.py index 8ce7d35..83de463 100644 --- a/backend/oss_uploader.py +++ b/backend/oss_uploader.py @@ -9,6 +9,7 @@ from datetime import datetime import oss2 + class OSSUploader: def __init__(self): self.access_key = os.getenv("ALI_ACCESS_KEY") @@ -40,9 +41,11 @@ class OSSUploader: """删除 OSS 对象""" self.bucket.delete_object(object_name) + # 单例 _oss_uploader = None + def get_oss_uploader() -> OSSUploader: global _oss_uploader if _oss_uploader is None: diff --git a/backend/performance_manager.py b/backend/performance_manager.py index 264f572..3fe9e82 100644 --- a/backend/performance_manager.py +++ b/backend/performance_manager.py @@ -42,6 +42,7 @@ except ImportError: # ==================== 数据模型 ==================== + @dataclass class CacheStats: """缓存统计数据模型""" @@ -58,6 +59,7 @@ class CacheStats: if self.total_requests > 0: self.hit_rate = round(self.hits / self.total_requests, 4) + @dataclass class CacheEntry: """缓存条目数据模型""" @@ -70,6 +72,7 @@ class CacheEntry: last_accessed: float = 0 size_bytes: int = 0 + @dataclass class PerformanceMetric: """性能指标数据模型""" @@ -91,6 +94,7 @@ class PerformanceMetric: "metadata": self.metadata, } + @dataclass class TaskInfo: """任务信息数据模型""" @@ -122,6 +126,7 @@ class TaskInfo: "max_retries": self.max_retries, } + @dataclass class ShardInfo: """分片信息数据模型""" @@ -134,8 +139,10 @@ class ShardInfo: created_at: str = "" last_accessed: str = "" + # ==================== Redis 缓存层 ==================== + class CacheManager: """ 缓存管理器 @@ -592,8 +599,10 @@ class CacheManager: return count + # ==================== 数据库分片 ==================== + class DatabaseSharding: """ 数据库分片管理器 @@ -893,8 +902,10 @@ class DatabaseSharding: "message": "Rebalancing analysis completed", } + # ==================== 异步任务队列 ==================== + class TaskQueue: """ 异步任务队列管理器 @@ -1276,8 +1287,10 @@ class TaskQueue: "backend": "celery" if self.use_celery else "memory", } + # ==================== 性能监控 ==================== + class PerformanceMonitor: """ 性能监控器 @@ -1594,8 +1607,10 @@ class PerformanceMonitor: return deleted + # ==================== 性能装饰器 ==================== + def cached( cache_manager: CacheManager, key_prefix: str = "", @@ -1640,6 +1655,7 @@ def cached( return decorator + def monitored(monitor: PerformanceMonitor, metric_type: str, endpoint: str | None = None) -> None: """ 性能监控装饰器 @@ -1667,8 +1683,10 @@ def monitored(monitor: PerformanceMonitor, metric_type: str, endpoint: str | Non return decorator + # ==================== 性能管理器 ==================== + class PerformanceManager: """ 性能管理器 - 统一入口 @@ -1730,9 +1748,11 @@ class PerformanceManager: return stats + # 单例模式 _performance_manager = None + def get_performance_manager( db_path: str = "insightflow.db", redis_url: str | None = None, enable_sharding: bool = False ) -> PerformanceManager: diff --git a/backend/plugin_manager.py b/backend/plugin_manager.py index 5bcfc84..4933edb 100644 --- a/backend/plugin_manager.py +++ b/backend/plugin_manager.py @@ -28,6 +28,7 @@ try: except ImportError: WEBDAV_AVAILABLE = False + class PluginType(Enum): """插件类型""" @@ -39,6 +40,7 @@ class PluginType(Enum): WEBDAV = "webdav" CUSTOM = "custom" + class PluginStatus(Enum): """插件状态""" @@ -47,6 +49,7 @@ class PluginStatus(Enum): ERROR = "error" PENDING = "pending" + @dataclass class Plugin: """插件配置""" @@ -62,6 +65,7 @@ class Plugin: last_used_at: str | None = None use_count: int = 0 + @dataclass class PluginConfig: """插件详细配置""" @@ -74,6 +78,7 @@ class PluginConfig: created_at: str = "" updated_at: str = "" + @dataclass class BotSession: """机器人会话""" @@ -91,6 +96,7 @@ class BotSession: last_message_at: str | None = None message_count: int = 0 + @dataclass class WebhookEndpoint: """Webhook 端点配置(Zapier/Make集成)""" @@ -109,6 +115,7 @@ class WebhookEndpoint: last_triggered_at: str | None = None trigger_count: int = 0 + @dataclass class WebDAVSync: """WebDAV 同步配置""" @@ -130,6 +137,7 @@ class WebDAVSync: updated_at: str = "" sync_count: int = 0 + @dataclass class ChromeExtensionToken: """Chrome 扩展令牌""" @@ -146,6 +154,7 @@ class ChromeExtensionToken: use_count: int = 0 is_revoked: bool = False + class PluginManager: """插件管理主类""" @@ -385,6 +394,7 @@ class PluginManager: conn.commit() conn.close() + class ChromeExtensionHandler: """Chrome 扩展处理器""" @@ -588,6 +598,7 @@ class ChromeExtensionHandler: "content_length": len(content), } + class BotHandler: """飞书/钉钉机器人处理器""" @@ -915,6 +926,7 @@ class BotHandler: ) return response.status_code == 200 + class WebhookIntegration: """Zapier/Make Webhook 集成""" @@ -1137,6 +1149,7 @@ class WebhookIntegration: "message": "Test event sent successfully" if success else "Failed to send test event", } + class WebDAVSyncManager: """WebDAV 同步管理""" @@ -1397,9 +1410,11 @@ class WebDAVSyncManager: return {"success": False, "error": str(e)} + # Singleton instance _plugin_manager = None + def get_plugin_manager(db_manager=None) -> None: """获取 PluginManager 单例""" global _plugin_manager diff --git a/backend/rate_limiter.py b/backend/rate_limiter.py index 86badd0..f0e9049 100644 --- a/backend/rate_limiter.py +++ b/backend/rate_limiter.py @@ -12,6 +12,7 @@ from collections.abc import Callable from dataclasses import dataclass from functools import wraps + @dataclass class RateLimitConfig: """限流配置""" @@ -20,6 +21,7 @@ class RateLimitConfig: burst_size: int = 10 # 突发请求数 window_size: int = 60 # 窗口大小(秒) + @dataclass class RateLimitInfo: """限流信息""" @@ -29,6 +31,7 @@ class RateLimitInfo: reset_time: int # 重置时间戳 retry_after: int # 需要等待的秒数 + class SlidingWindowCounter: """滑动窗口计数器""" @@ -60,6 +63,7 @@ class SlidingWindowCounter: for k in old_keys: self.requests.pop(k, None) + class RateLimiter: """API 限流器""" @@ -155,9 +159,11 @@ class RateLimiter: self.counters.clear() self.configs.clear() + # 全局限流器实例 _rate_limiter: RateLimiter | None = None + def get_rate_limiter() -> RateLimiter: """获取限流器实例""" global _rate_limiter @@ -165,6 +171,7 @@ def get_rate_limiter() -> RateLimiter: _rate_limiter = RateLimiter() return _rate_limiter + # 限流装饰器(用于函数级别限流) def rate_limit(requests_per_minute: int = 60, key_func: Callable | None = None) -> None: """ @@ -208,5 +215,6 @@ def rate_limit(requests_per_minute: int = 60, key_func: Callable | None = None) return decorator + class RateLimitExceeded(Exception): """限流异常""" diff --git a/backend/search_manager.py b/backend/search_manager.py index 8853f27..a56aba7 100644 --- a/backend/search_manager.py +++ b/backend/search_manager.py @@ -19,6 +19,7 @@ from dataclasses import dataclass, field from datetime import datetime from enum import Enum + class SearchOperator(Enum): """搜索操作符""" @@ -26,6 +27,7 @@ class SearchOperator(Enum): OR = "OR" NOT = "NOT" + # 尝试导入 sentence-transformers 用于语义搜索 try: from sentence_transformers import SentenceTransformer @@ -37,6 +39,7 @@ except ImportError: # ==================== 数据模型 ==================== + @dataclass class SearchResult: """搜索结果数据模型""" @@ -60,6 +63,7 @@ class SearchResult: "metadata": self.metadata, } + @dataclass class SemanticSearchResult: """语义搜索结果数据模型""" @@ -85,6 +89,7 @@ class SemanticSearchResult: result["embedding_dim"] = len(self.embedding) return result + @dataclass class EntityPath: """实体关系路径数据模型""" @@ -114,6 +119,7 @@ class EntityPath: "path_description": self.path_description, } + @dataclass class KnowledgeGap: """知识缺口数据模型""" @@ -141,6 +147,7 @@ class KnowledgeGap: "metadata": self.metadata, } + @dataclass class SearchIndex: """搜索索引数据模型""" @@ -154,6 +161,7 @@ class SearchIndex: created_at: str updated_at: str + @dataclass class TextEmbedding: """文本 Embedding 数据模型""" @@ -166,8 +174,10 @@ class TextEmbedding: model_name: str created_at: str + # ==================== 全文搜索 ==================== + class FullTextSearch: """ 全文搜索模块 @@ -776,8 +786,10 @@ class FullTextSearch: conn.close() return stats + # ==================== 语义搜索 ==================== + class SemanticSearch: """ 语义搜索模块 @@ -1138,8 +1150,10 @@ class SemanticSearch: print(f"删除 embedding 失败: {e}") return False + # ==================== 实体关系路径发现 ==================== + class EntityPathDiscovery: """ 实体关系路径发现模块 @@ -1609,8 +1623,10 @@ class EntityPathDiscovery: bridge_scores.sort(key=lambda x: x["bridge_score"], reverse=True) return bridge_scores[:20] # 返回前20 + # ==================== 知识缺口识别 ==================== + class KnowledgeGapDetection: """ 知识缺口识别模块 @@ -2013,8 +2029,10 @@ class KnowledgeGapDetection: return recommendations + # ==================== 搜索管理器 ==================== + class SearchManager: """ 搜索管理器 - 统一入口 @@ -2187,9 +2205,11 @@ class SearchManager: "semantic_search_available": self.semantic_search.is_available(), } + # 单例模式 _search_manager = None + def get_search_manager(db_path: str = "insightflow.db") -> SearchManager: """获取搜索管理器单例""" global _search_manager @@ -2197,6 +2217,7 @@ def get_search_manager(db_path: str = "insightflow.db") -> SearchManager: _search_manager = SearchManager(db_path) return _search_manager + # 便捷函数 def fulltext_search( query: str, project_id: str | None = None, limit: int = 20 @@ -2205,6 +2226,7 @@ def fulltext_search( manager = get_search_manager() return manager.fulltext_search.search(query, project_id, limit=limit) + def semantic_search( query: str, project_id: str | None = None, top_k: int = 10 ) -> list[SemanticSearchResult]: @@ -2212,11 +2234,13 @@ def semantic_search( manager = get_search_manager() return manager.semantic_search.search(query, project_id, top_k=top_k) + def find_entity_path(source_id: str, target_id: str, max_depth: int = 5) -> EntityPath | None: """查找实体路径便捷函数""" manager = get_search_manager() return manager.path_discovery.find_shortest_path(source_id, target_id, max_depth) + def detect_knowledge_gaps(project_id: str) -> list[KnowledgeGap]: """知识缺口检测便捷函数""" manager = get_search_manager() diff --git a/backend/security_manager.py b/backend/security_manager.py index de2907d..600d763 100644 --- a/backend/security_manager.py +++ b/backend/security_manager.py @@ -25,6 +25,7 @@ except ImportError: CRYPTO_AVAILABLE = False print("Warning: cryptography not available, encryption features disabled") + class AuditActionType(Enum): """审计动作类型""" @@ -47,6 +48,7 @@ class AuditActionType(Enum): WEBHOOK_SEND = "webhook_send" BOT_MESSAGE = "bot_message" + class DataSensitivityLevel(Enum): """数据敏感度级别""" @@ -55,6 +57,7 @@ class DataSensitivityLevel(Enum): CONFIDENTIAL = "confidential" # 机密 SECRET = "secret" # 绝密 + class MaskingRuleType(Enum): """脱敏规则类型""" @@ -66,6 +69,7 @@ class MaskingRuleType(Enum): ADDRESS = "address" # 地址 CUSTOM = "custom" # 自定义 + @dataclass class AuditLog: """审计日志条目""" @@ -87,6 +91,7 @@ class AuditLog: def to_dict(self) -> dict[str, Any]: return asdict(self) + @dataclass class EncryptionConfig: """加密配置""" @@ -104,6 +109,7 @@ class EncryptionConfig: def to_dict(self) -> dict[str, Any]: return asdict(self) + @dataclass class MaskingRule: """脱敏规则""" @@ -123,6 +129,7 @@ class MaskingRule: def to_dict(self) -> dict[str, Any]: return asdict(self) + @dataclass class DataAccessPolicy: """数据访问策略""" @@ -144,6 +151,7 @@ class DataAccessPolicy: def to_dict(self) -> dict[str, Any]: return asdict(self) + @dataclass class AccessRequest: """访问请求(用于需要审批的访问)""" @@ -161,6 +169,7 @@ class AccessRequest: def to_dict(self) -> dict[str, Any]: return asdict(self) + class SecurityManager: """安全管理器""" @@ -1229,9 +1238,11 @@ class SecurityManager: created_at=row[8], ) + # 全局安全管理器实例 _security_manager = None + def get_security_manager(db_path: str = "insightflow.db") -> SecurityManager: """获取安全管理器实例""" global _security_manager diff --git a/backend/subscription_manager.py b/backend/subscription_manager.py index 08a5ac0..166febf 100644 --- a/backend/subscription_manager.py +++ b/backend/subscription_manager.py @@ -21,6 +21,7 @@ from typing import Any logger = logging.getLogger(__name__) + class SubscriptionStatus(StrEnum): """订阅状态""" @@ -31,6 +32,7 @@ class SubscriptionStatus(StrEnum): TRIAL = "trial" # 试用中 PENDING = "pending" # 待支付 + class PaymentProvider(StrEnum): """支付提供商""" @@ -39,6 +41,7 @@ class PaymentProvider(StrEnum): WECHAT = "wechat" # 微信支付 BANK_TRANSFER = "bank_transfer" # 银行转账 + class PaymentStatus(StrEnum): """支付状态""" @@ -49,6 +52,7 @@ class PaymentStatus(StrEnum): REFUNDED = "refunded" # 已退款 PARTIAL_REFUNDED = "partial_refunded" # 部分退款 + class InvoiceStatus(StrEnum): """发票状态""" @@ -59,6 +63,7 @@ class InvoiceStatus(StrEnum): VOID = "void" # 作废 CREDIT_NOTE = "credit_note" # 贷项通知单 + class RefundStatus(StrEnum): """退款状态""" @@ -68,6 +73,7 @@ class RefundStatus(StrEnum): COMPLETED = "completed" # 已完成 FAILED = "failed" # 失败 + @dataclass class SubscriptionPlan: """订阅计划数据类""" @@ -86,6 +92,7 @@ class SubscriptionPlan: updated_at: datetime metadata: dict[str, Any] + @dataclass class Subscription: """订阅数据类""" @@ -106,6 +113,7 @@ class Subscription: updated_at: datetime metadata: dict[str, Any] + @dataclass class UsageRecord: """用量记录数据类""" @@ -120,6 +128,7 @@ class UsageRecord: description: str | None metadata: dict[str, Any] + @dataclass class Payment: """支付记录数据类""" @@ -141,6 +150,7 @@ class Payment: created_at: datetime updated_at: datetime + @dataclass class Invoice: """发票数据类""" @@ -164,6 +174,7 @@ class Invoice: created_at: datetime updated_at: datetime + @dataclass class Refund: """退款数据类""" @@ -186,6 +197,7 @@ class Refund: created_at: datetime updated_at: datetime + @dataclass class BillingHistory: """账单历史数据类""" @@ -201,6 +213,7 @@ class BillingHistory: created_at: datetime metadata: dict[str, Any] + class SubscriptionManager: """订阅与计费管理器""" @@ -2187,9 +2200,11 @@ class SubscriptionManager: metadata=json.loads(row["metadata"] or "{}"), ) + # 全局订阅管理器实例 subscription_manager = None + def get_subscription_manager(db_path: str = "insightflow.db") -> SubscriptionManager: """获取订阅管理器实例(单例模式)""" global subscription_manager diff --git a/backend/tenant_manager.py b/backend/tenant_manager.py index 7965c5e..3d375b1 100644 --- a/backend/tenant_manager.py +++ b/backend/tenant_manager.py @@ -23,6 +23,7 @@ from typing import Any logger = logging.getLogger(__name__) + class TenantLimits: """租户资源限制常量""" @@ -42,6 +43,7 @@ class TenantLimits: UNLIMITED = -1 + class TenantStatus(StrEnum): """租户状态""" @@ -51,6 +53,7 @@ class TenantStatus(StrEnum): EXPIRED = "expired" # 过期 PENDING = "pending" # 待激活 + class TenantTier(StrEnum): """租户订阅层级""" @@ -58,6 +61,7 @@ class TenantTier(StrEnum): PRO = "pro" # 专业版 ENTERPRISE = "enterprise" # 企业版 + class TenantRole(StrEnum): """租户角色""" @@ -66,6 +70,7 @@ class TenantRole(StrEnum): MEMBER = "member" # 成员 VIEWER = "viewer" # 查看者 + class DomainStatus(StrEnum): """域名状态""" @@ -74,6 +79,7 @@ class DomainStatus(StrEnum): FAILED = "failed" # 验证失败 EXPIRED = "expired" # 已过期 + @dataclass class Tenant: """租户数据类""" @@ -92,6 +98,7 @@ class Tenant: resource_limits: dict[str, Any] # 资源限制 metadata: dict[str, Any] # 元数据 + @dataclass class TenantDomain: """租户域名数据类""" @@ -109,6 +116,7 @@ class TenantDomain: ssl_enabled: bool # SSL 是否启用 ssl_expires_at: datetime | None + @dataclass class TenantBranding: """租户品牌配置数据类""" @@ -126,6 +134,7 @@ class TenantBranding: created_at: datetime updated_at: datetime + @dataclass class TenantMember: """租户成员数据类""" @@ -142,6 +151,7 @@ class TenantMember: last_active_at: datetime | None status: str # active/pending/suspended + @dataclass class TenantPermission: """租户权限定义数据类""" @@ -156,6 +166,7 @@ class TenantPermission: conditions: dict | None # 条件限制 created_at: datetime + class TenantManager: """租户管理器 - 多租户 SaaS 架构核心""" @@ -1599,8 +1610,10 @@ class TenantManager: status=row["status"], ) + # ==================== 租户上下文管理 ==================== + class TenantContext: """租户上下文管理器 - 用于请求级别的租户隔离""" @@ -1633,9 +1646,11 @@ class TenantContext: cls._current_tenant_id = None cls._current_user_id = None + # 全局租户管理器实例 tenant_manager = None + def get_tenant_manager(db_path: str = "insightflow.db") -> TenantManager: """获取租户管理器实例(单例模式)""" global tenant_manager diff --git a/backend/test_phase7_task6_8.py b/backend/test_phase7_task6_8.py index 2c632a3..6cd872f 100644 --- a/backend/test_phase7_task6_8.py +++ b/backend/test_phase7_task6_8.py @@ -20,6 +20,7 @@ from search_manager import ( # 添加 backend 到路径 sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + def test_fulltext_search(): """测试全文搜索""" print("\n" + "=" * 60) @@ -62,6 +63,7 @@ def test_fulltext_search(): print("\n✓ 全文搜索测试完成") return True + def test_semantic_search(): """测试语义搜索""" print("\n" + "=" * 60) @@ -97,6 +99,7 @@ def test_semantic_search(): print("\n✓ 语义搜索测试完成") return True + def test_entity_path_discovery(): """测试实体路径发现""" print("\n" + "=" * 60) @@ -115,6 +118,7 @@ def test_entity_path_discovery(): print("\n✓ 实体路径发现测试完成") return True + def test_knowledge_gap_detection(): """测试知识缺口识别""" print("\n" + "=" * 60) @@ -133,6 +137,7 @@ def test_knowledge_gap_detection(): print("\n✓ 知识缺口识别测试完成") return True + def test_cache_manager(): """测试缓存管理器""" print("\n" + "=" * 60) @@ -180,6 +185,7 @@ def test_cache_manager(): print("\n✓ 缓存管理器测试完成") return True + def test_task_queue(): """测试任务队列""" print("\n" + "=" * 60) @@ -220,6 +226,7 @@ def test_task_queue(): print("\n✓ 任务队列测试完成") return True + def test_performance_monitor(): """测试性能监控""" print("\n" + "=" * 60) @@ -266,6 +273,7 @@ def test_performance_monitor(): print("\n✓ 性能监控测试完成") return True + def test_search_manager(): """测试搜索管理器""" print("\n" + "=" * 60) @@ -286,6 +294,7 @@ def test_search_manager(): print("\n✓ 搜索管理器测试完成") return True + def test_performance_manager(): """测试性能管理器""" print("\n" + "=" * 60) @@ -310,6 +319,7 @@ def test_performance_manager(): print("\n✓ 性能管理器测试完成") return True + def run_all_tests(): """运行所有测试""" print("\n" + "=" * 60) @@ -396,6 +406,7 @@ def run_all_tests(): return passed == total + if __name__ == "__main__": success = run_all_tests() sys.exit(0 if success else 1) diff --git a/backend/test_phase8_task1.py b/backend/test_phase8_task1.py index 7387a0f..b014b62 100644 --- a/backend/test_phase8_task1.py +++ b/backend/test_phase8_task1.py @@ -17,6 +17,7 @@ from tenant_manager import get_tenant_manager sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + def test_tenant_management(): """测试租户管理功能""" print("=" * 60) @@ -64,6 +65,7 @@ def test_tenant_management(): return tenant.id + def test_domain_management(tenant_id: str): """测试域名管理功能""" print("\n" + "=" * 60) @@ -109,6 +111,7 @@ def test_domain_management(tenant_id: str): return domain.id + def test_branding_management(tenant_id: str): """测试品牌白标功能""" print("\n" + "=" * 60) @@ -148,6 +151,7 @@ def test_branding_management(tenant_id: str): return branding.id + def test_member_management(tenant_id: str): """测试成员管理功能""" print("\n" + "=" * 60) @@ -202,6 +206,7 @@ def test_member_management(tenant_id: str): return member1.id, member2.id + def test_usage_tracking(tenant_id: str): """测试资源使用统计功能""" print("\n" + "=" * 60) @@ -243,6 +248,7 @@ def test_usage_tracking(tenant_id: str): return stats + def cleanup(tenant_id: str, domain_id: str, member_ids: list): """清理测试数据""" print("\n" + "=" * 60) @@ -266,6 +272,7 @@ def cleanup(tenant_id: str, domain_id: str, member_ids: list): manager.delete_tenant(tenant_id) print(f"✅ 租户已删除: {tenant_id}") + def main(): """主测试函数""" print("\n" + "=" * 60) @@ -303,5 +310,6 @@ def main(): except Exception as e: print(f"⚠️ 清理失败: {e}") + if __name__ == "__main__": main() diff --git a/backend/test_phase8_task2.py b/backend/test_phase8_task2.py index e4d84b2..f6f749e 100644 --- a/backend/test_phase8_task2.py +++ b/backend/test_phase8_task2.py @@ -11,6 +11,7 @@ from subscription_manager import PaymentProvider, SubscriptionManager sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + def test_subscription_manager(): """测试订阅管理器""" print("=" * 60) @@ -223,6 +224,7 @@ def test_subscription_manager(): os.remove(db_path) print(f"\n清理临时数据库: {db_path}") + if __name__ == "__main__": try: test_subscription_manager() diff --git a/backend/test_phase8_task4.py b/backend/test_phase8_task4.py index 4e51d35..6305dfc 100644 --- a/backend/test_phase8_task4.py +++ b/backend/test_phase8_task4.py @@ -13,6 +13,7 @@ from ai_manager import ModelType, PredictionType, get_ai_manager # Add backend directory to path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + def test_custom_model(): """测试自定义模型功能""" print("\n=== 测试自定义模型 ===") @@ -87,6 +88,7 @@ def test_custom_model(): return model.id + async def test_train_and_predict(model_id: str): """测试训练和预测""" print("\n=== 测试模型训练和预测 ===") @@ -113,6 +115,7 @@ async def test_train_and_predict(model_id: str): except Exception as e: print(f" 预测失败: {e}") + def test_prediction_models(): """测试预测模型""" print("\n=== 测试预测模型 ===") @@ -154,6 +157,7 @@ def test_prediction_models(): return trend_model.id, anomaly_model.id + async def test_predictions(trend_model_id: str, anomaly_model_id: str): """测试预测功能""" print("\n=== 测试预测功能 ===") @@ -188,6 +192,7 @@ async def test_predictions(trend_model_id: str, anomaly_model_id: str): ) print(f" 检测结果: {anomaly_result.prediction_data}") + def test_kg_rag(): """测试知识图谱 RAG""" print("\n=== 测试知识图谱 RAG ===") @@ -217,6 +222,7 @@ def test_kg_rag(): return rag.id + async def test_kg_rag_query(rag_id: str): """测试 RAG 查询""" print("\n=== 测试知识图谱 RAG 查询 ===") @@ -287,6 +293,7 @@ async def test_kg_rag_query(rag_id: str): except Exception as e: print(f" 查询失败: {e}") + async def test_smart_summary(): """测试智能摘要""" print("\n=== 测试智能摘要 ===") @@ -334,6 +341,7 @@ async def test_smart_summary(): except Exception as e: print(f" 生成失败: {e}") + async def main(): """主测试函数""" print("=" * 60) @@ -372,5 +380,6 @@ async def main(): traceback.print_exc() + if __name__ == "__main__": asyncio.run(main()) diff --git a/backend/test_phase8_task5.py b/backend/test_phase8_task5.py index 1223357..793f0a6 100644 --- a/backend/test_phase8_task5.py +++ b/backend/test_phase8_task5.py @@ -32,6 +32,7 @@ backend_dir = os.path.dirname(os.path.abspath(__file__)) if backend_dir not in sys.path: sys.path.insert(0, backend_dir) + class TestGrowthManager: """测试 Growth Manager 功能""" @@ -734,10 +735,12 @@ class TestGrowthManager: print("✨ 测试完成!") print("=" * 60) + async def main(): """主函数""" tester = TestGrowthManager() await tester.run_all_tests() + if __name__ == "__main__": asyncio.run(main()) diff --git a/backend/test_phase8_task6.py b/backend/test_phase8_task6.py index 4b0f447..c1816cb 100644 --- a/backend/test_phase8_task6.py +++ b/backend/test_phase8_task6.py @@ -29,6 +29,7 @@ backend_dir = os.path.dirname(os.path.abspath(__file__)) if backend_dir not in sys.path: sys.path.insert(0, backend_dir) + class TestDeveloperEcosystem: """开发者生态系统测试类""" @@ -687,10 +688,12 @@ console.log('Upload complete:', result.id); print("=" * 60) + def main(): """主函数""" test = TestDeveloperEcosystem() test.run_all_tests() + if __name__ == "__main__": main() diff --git a/backend/test_phase8_task8.py b/backend/test_phase8_task8.py index 1aa1977..03f5edb 100644 --- a/backend/test_phase8_task8.py +++ b/backend/test_phase8_task8.py @@ -30,6 +30,7 @@ backend_dir = os.path.dirname(os.path.abspath(__file__)) if backend_dir not in sys.path: sys.path.insert(0, backend_dir) + class TestOpsManager: """测试运维与监控管理器""" @@ -721,10 +722,12 @@ class TestOpsManager: print("=" * 60) + def main(): """主函数""" test = TestOpsManager() test.run_all_tests() + if __name__ == "__main__": main() diff --git a/backend/tingwu_client.py b/backend/tingwu_client.py index 7f27a28..5bc2420 100644 --- a/backend/tingwu_client.py +++ b/backend/tingwu_client.py @@ -8,6 +8,7 @@ import time from datetime import datetime from typing import Any + class TingwuClient: def __init__(self): self.access_key = os.getenv("ALI_ACCESS_KEY", "") diff --git a/backend/workflow_manager.py b/backend/workflow_manager.py index 06fe3b9..2d28d95 100644 --- a/backend/workflow_manager.py +++ b/backend/workflow_manager.py @@ -33,6 +33,7 @@ from apscheduler.triggers.interval import IntervalTrigger logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) + class WorkflowStatus(Enum): """工作流状态""" @@ -41,6 +42,7 @@ class WorkflowStatus(Enum): ERROR = "error" COMPLETED = "completed" + class WorkflowType(Enum): """工作流类型""" @@ -50,6 +52,7 @@ class WorkflowType(Enum): SCHEDULED_REPORT = "scheduled_report" # 定时报告 CUSTOM = "custom" # 自定义工作流 + class WebhookType(Enum): """Webhook 类型""" @@ -58,6 +61,7 @@ class WebhookType(Enum): SLACK = "slack" CUSTOM = "custom" + class TaskStatus(Enum): """任务执行状态""" @@ -67,6 +71,7 @@ class TaskStatus(Enum): FAILED = "failed" CANCELLED = "cancelled" + @dataclass class WorkflowTask: """工作流任务定义""" @@ -90,6 +95,7 @@ class WorkflowTask: if not self.updated_at: self.updated_at = self.created_at + @dataclass class WebhookConfig: """Webhook 配置""" @@ -114,6 +120,7 @@ class WebhookConfig: if not self.updated_at: self.updated_at = self.created_at + @dataclass class Workflow: """工作流定义""" @@ -143,6 +150,7 @@ class Workflow: if not self.updated_at: self.updated_at = self.created_at + @dataclass class WorkflowLog: """工作流执行日志""" @@ -163,6 +171,7 @@ class WorkflowLog: if not self.created_at: self.created_at = datetime.now().isoformat() + class WebhookNotifier: """Webhook 通知器 - 支持飞书、钉钉、Slack""" @@ -318,6 +327,7 @@ class WebhookNotifier: """关闭 HTTP 客户端""" await self.http_client.aclose() + class WorkflowManager: """工作流管理器 - 核心管理类""" @@ -1488,9 +1498,11 @@ class WorkflowManager: ] } + # Singleton instance _workflow_manager = None + def get_workflow_manager(db_manager=None) -> WorkflowManager: """获取 WorkflowManager 单例""" global _workflow_manager