Files
company-ai-platform/app/core/config.py
JiuContinent 19e59e83cc ```
feat: 添加数据库迁移脚本并更新Dockerfile配置

- 在Dockerfile中添加alembic配置文件和目录的复制指令
- 更新alembic/env.py注册新的模块模型:events、workflows、writebacks
- 生成完整的初始数据库schema迁移脚本,包含以下表:
  - approval_requests, attendance_records, audit_logs, domain_events
  - expenses, feishu_event_receipts, fund_accounts, legacy_sync_runs
  - official_writeback_runs, performance_metrics, policies, procurements
  - projects, report_push_runs, risk_event_actions, risk_events
  - standards, suppliers, work_reports, work_tasks, workflow_actions
  - workflow_instances等21个数据表结构定义
- 在API路由器中添加新模块的路由:events、workflows、writebacks、observability
```
2026-07-08 14:08:03 +08:00

182 lines
7.2 KiB
Python

import json
from functools import lru_cache
from typing import Annotated, Any
from pydantic import Field, field_validator
from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict
from app.core.constants import (
ActorValue,
ConfigErrorDetail,
DEFAULT_MODEL_PROVIDER,
DEFAULT_OPENCLAW_ACTION_JSON,
)
class Settings(BaseSettings):
"""Runtime settings loaded from environment variables and `.env`."""
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
app_name: str = "Company AI Management Platform"
app_env: str = "local"
debug: bool = False
api_prefix: str = "/api/v1"
api_key: str | None = None
api_actor: str = ActorValue.API
api_keys: list[dict[str, Any]] = Field(default_factory=list)
audit_api_key: str | None = None
audit_api_actor: str = ActorValue.AUDITOR
audit_api_keys: list[dict[str, Any]] = Field(default_factory=list)
approval_api_key: str | None = None
approval_api_actor: str = ActorValue.APPROVER
approval_api_keys: list[dict[str, Any]] = Field(default_factory=list)
cors_origins: list[str] = Field(default_factory=lambda: ["*"])
mask_sensitive_responses: bool = True
masked_response_fields: list[str] = Field(default_factory=list)
database_url: str = "sqlite:///./company_ai.db"
legacy_database_url: str | None = None
legacy_project_query: str | None = None
legacy_task_query: str | None = None
legacy_allowed_queries: dict[str, str] = Field(default_factory=dict)
legacy_project_code_prefix: str = "LEGACY"
legacy_task_code_prefix: str = "LEGACY-TASK"
redis_url: str = "redis://127.0.0.1:6379/0"
feishu_base_url: str = "https://open.feishu.cn/open-apis"
feishu_app_id: str | None = None
feishu_app_secret: str | None = None
feishu_verification_token: str | None = None
feishu_encrypt_key: str | None = None
feishu_default_chat_id: str | None = None
feishu_approval_approver_ids: Annotated[list[str], NoDecode] = Field(default_factory=list)
model_provider: str = DEFAULT_MODEL_PROVIDER
openclaw_base_url: str = "http://127.0.0.1:2070"
openclaw_http_url: str | None = None
openclaw_ws_url: str | None = None
openclaw_api_key: str | None = None
openclaw_gateway_token: str | None = None
openclaw_allowed_tools: Annotated[list[str], NoDecode] = Field(default_factory=list)
openclaw_allowed_actions: Annotated[list[str], NoDecode] = Field(
default_factory=lambda: [DEFAULT_OPENCLAW_ACTION_JSON]
)
hermes_base_url: str = "http://127.0.0.1:2073/v1"
hermes_api_key: str | None = None
hermes_model: str = "hermes-agent"
hermes_session_id: str | None = None
direct_llm_base_url: str = "https://api.openai.com/v1"
direct_llm_api_key: str | None = None
direct_llm_model: str = "gpt-4.1-mini"
scheduler_enabled: bool = False
task_queue_enabled: bool = False
task_queue_always_eager: bool = False
legacy_sync_enabled: bool = False
celery_result_backend_url: str | None = None
daily_brief_cron_hour: int = 9
daily_brief_cron_minute: int = 0
weekly_project_report_day_of_week: str = "mon"
weekly_project_report_cron_hour: int = 9
weekly_project_report_cron_minute: int = 30
legacy_project_sync_cron_hour: int = 2
legacy_project_sync_cron_minute: int = 0
legacy_task_sync_cron_hour: int = 2
legacy_task_sync_cron_minute: int = 30
official_writeback_enabled: bool = False
official_api_base_url: str | None = None
official_api_token: str | None = None
official_api_timeout_seconds: float = 10.0
@field_validator("cors_origins", mode="before")
@classmethod
def parse_cors_origins(cls, value: Any) -> list[str]:
if isinstance(value, list):
return [str(item).strip() for item in value if str(item).strip()]
if value is None:
return []
text = str(value).strip()
if text.startswith("["):
data = json.loads(text)
if not isinstance(data, list):
raise ValueError(ConfigErrorDetail.CORS_ORIGINS_FORMAT)
return [str(item).strip() for item in data if str(item).strip()]
return [item.strip() for item in text.split(",") if item.strip()]
@field_validator(
"openclaw_allowed_tools",
"openclaw_allowed_actions",
"feishu_approval_approver_ids",
mode="before",
)
@classmethod
def parse_csv_list(cls, value: str | list[str] | None) -> list[str]:
if value is None:
return []
if isinstance(value, list):
return [str(item).strip() for item in value if str(item).strip()]
text = value.strip()
if not text:
return []
if text.startswith("["):
data = json.loads(text)
if not isinstance(data, list):
raise ValueError(ConfigErrorDetail.CORS_ORIGINS_FORMAT)
return [str(item).strip() for item in data if str(item).strip()]
return [item.strip() for item in text.split(",") if item.strip()]
@field_validator("masked_response_fields", mode="before")
@classmethod
def parse_masked_response_fields(cls, value: Any) -> list[str]:
if isinstance(value, list):
return [str(item).strip() for item in value if str(item).strip()]
if value is None:
return []
text = str(value).strip()
if not text:
return []
if text.startswith("["):
data = json.loads(text)
if not isinstance(data, list):
raise ValueError(ConfigErrorDetail.CORS_ORIGINS_FORMAT)
return [str(item).strip() for item in data if str(item).strip()]
return [item.strip() for item in text.split(",") if item.strip()]
@field_validator("api_keys", "audit_api_keys", "approval_api_keys", mode="before")
@classmethod
def parse_service_keys(cls, value: Any) -> list[dict[str, Any]]:
if value is None or value == "":
return []
if isinstance(value, list):
return [dict(item) for item in value if isinstance(item, dict)]
if isinstance(value, str):
data = json.loads(value)
if not isinstance(data, list):
raise ValueError(ConfigErrorDetail.SERVICE_KEYS_FORMAT)
if not all(isinstance(item, dict) for item in data):
raise ValueError(ConfigErrorDetail.SERVICE_KEYS_FORMAT)
return [dict(item) for item in data]
raise ValueError(ConfigErrorDetail.SERVICE_KEYS_FORMAT)
@field_validator("legacy_allowed_queries", mode="before")
@classmethod
def parse_legacy_allowed_queries(cls, value: Any) -> dict[str, str]:
if value is None or value == "":
return {}
if isinstance(value, dict):
return {str(key): str(item) for key, item in value.items()}
if isinstance(value, str):
data = json.loads(value)
if not isinstance(data, dict):
raise ValueError(ConfigErrorDetail.LEGACY_ALLOWED_QUERIES_FORMAT)
return {str(key): str(item) for key, item in data.items()}
raise ValueError(ConfigErrorDetail.LEGACY_ALLOWED_QUERIES_FORMAT)
@lru_cache
def get_settings() -> Settings:
"""Return cached application settings."""
return Settings()