feat: 添加飞书用户模块和订阅功能支持

- 新增feishu_users模块用于处理飞书用户身份验证和权限管理
- 新增subscriptions模块用于处理订阅相关功能
- 新增personalization模块用于个性化服务
- 在alembic迁移配置中注册新的模型模块
- 在API路由器中添加feishu_users和subscriptions路由
- 实现事件调度服务的改进,包括错误处理和状态更新优化
- 添加飞书命令处理的权限检查机制
- 实现飞书应用票据事件处理
- 改进审计日志记录功能
```
This commit is contained in:
2026-07-27 08:02:17 +08:00
parent db751f03b4
commit d7db84571d
148 changed files with 17110 additions and 765 deletions
@@ -12,6 +12,7 @@ from app.tasks.constants import (
TASK_RUN_LIFECYCLE,
TASK_RUN_MARKET_CLOSE,
TASK_RUN_MARKET_REPORT,
TASK_RUN_SUBSCRIPTION_CYCLE,
)
from app.core.background.task_queue.dispatcher import dispatch_task
from app.core.background.task_queue.events import enqueue_event_dispatch
@@ -30,6 +31,7 @@ from app.core.background.task_queue.reports import (
enqueue_work_weekly_push,
)
from app.core.background.task_queue.risk import enqueue_risk_event_generation
from app.core.background.task_queue.subscriptions import enqueue_subscription_cycle
__all__ = [
@@ -46,6 +48,7 @@ __all__ = [
"TASK_RUN_LIFECYCLE",
"TASK_RUN_MARKET_CLOSE",
"TASK_RUN_MARKET_REPORT",
"TASK_RUN_SUBSCRIPTION_CYCLE",
"dispatch_task",
"enqueue_attendance_summary_push",
"enqueue_daily_brief_push",
@@ -58,6 +61,7 @@ __all__ = [
"enqueue_project_weekly_push",
"enqueue_risk_progress_push",
"enqueue_risk_event_generation",
"enqueue_subscription_cycle",
"enqueue_work_daily_push",
"enqueue_work_weekly_push",
]
+23 -10
View File
@@ -5,6 +5,7 @@ from app.core.config import get_settings
from app.core.constants import ActorValue
from app.core.database import SessionLocal
from app.application.pipelines import LifecyclePipelineService
from app.modules.workflows.constants import WorkflowStatus, WorkflowType
def enqueue_lifecycle_report(
@@ -28,16 +29,28 @@ def enqueue_lifecycle_report(
if get_settings().task_queue_enabled:
from app.tasks import celery_app
result = celery_app.signature(
TASK_RUN_LIFECYCLE,
kwargs={
"report_type": report_type,
"receive_id": receive_id,
"receive_id_type": receive_id_type,
"force": force,
"actor": actor,
},
).apply_async()
try:
result = celery_app.signature(
TASK_RUN_LIFECYCLE,
kwargs={
"report_type": report_type,
"receive_id": receive_id,
"receive_id_type": receive_id_type,
"force": force,
"actor": actor,
},
).apply_async()
except Exception as exc:
service.workflows.start_or_update(
workflow_type=WorkflowType.LIFECYCLE_REPORT,
aggregate_type="report_period",
aggregate_id=period_key,
status_value=WorkflowStatus.FAILED,
action="enqueue_failed",
actor=actor,
payload={"error": str(exc)[:2000]},
)
raise
return {
"workflow_code": workflow.code,
"period_key": period_key,
+24 -16
View File
@@ -1,5 +1,6 @@
from collections.abc import Callable
from typing import Any
from uuid import uuid4
from app.tasks.constants import (
TASK_PUSH_ATTENDANCE_SUMMARY,
@@ -173,37 +174,44 @@ def _queue_celery_report_push(
from app.modules.reports.services import ReportService
from app.tasks import celery_app
task_id = uuid4().hex
db = SessionLocal()
try:
push_run = ReportService(db).create_push_run(
service = ReportService(db)
push_run = service.create_push_run(
report_type=report_type,
title=title,
receive_id=receive_id,
receive_id_type=receive_id_type,
actor=actor,
status=ReportPushStatus.QUEUED,
task_id=task_id,
)
async_result = celery_app.signature(
task_name,
kwargs={
"receive_id": receive_id,
"receive_id_type": receive_id_type,
"actor": actor,
"push_run_code": push_run.code,
},
).apply_async()
ReportService(db).update_push_run(
push_run.code,
ReportPushStatus.QUEUED,
task_id=async_result.id,
)
try:
celery_app.signature(
task_name,
kwargs={
"receive_id": receive_id,
"receive_id_type": receive_id_type,
"actor": actor,
"push_run_code": push_run.code,
},
).apply_async(task_id=task_id)
except Exception as exc:
service.update_push_run(
push_run.code,
ReportPushStatus.FAILED,
task_id=task_id,
error_message=str(exc),
)
raise
finally:
db.close()
return {
"queued": True,
"mode": "celery",
"task_name": task_name,
"task_id": async_result.id,
"task_id": task_id,
"push_run_code": push_run.code,
}
@@ -0,0 +1,14 @@
from app.application.delivery.subscriptions import run_subscription_cycle
from app.core.background.task_queue.dispatcher import dispatch_task
from app.core.constants import ActorValue
from app.tasks.constants import TASK_RUN_SUBSCRIPTION_CYCLE
def enqueue_subscription_cycle(
actor: str = ActorValue.SCHEDULER,
) -> dict:
return dispatch_task(
TASK_RUN_SUBSCRIPTION_CYCLE,
{"actor": actor},
lambda: run_subscription_cycle(actor=actor),
)
+66 -6
View File
@@ -1,6 +1,7 @@
import json
import os
from functools import lru_cache
from typing import Annotated, Any
from typing import Annotated, Any, Literal
from pydantic import Field, field_validator, model_validator
from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict
@@ -12,11 +13,22 @@ from app.core.constants import (
DEFAULT_OPENCLAW_ACTION_JSON,
)
_DOTENV_DISABLED = os.getenv("COMPANY_AI_DISABLE_DOTENV", "").strip().lower() in {
"1",
"true",
"yes",
"on",
}
class Settings(BaseSettings):
"""Runtime settings loaded from environment variables and `.env`."""
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
model_config = SettingsConfigDict(
env_file=None if _DOTENV_DISABLED else ".env",
env_file_encoding="utf-8",
extra="ignore",
)
app_name: str = "Company AI Management Platform"
app_env: str = "local"
@@ -45,9 +57,14 @@ class Settings(BaseSettings):
feishu_base_url: str = "https://open.feishu.cn/open-apis"
feishu_app_id: str | None = None
feishu_app_secret: str | None = None
feishu_app_type: Literal["self", "store"] = "self"
feishu_app_ticket: str | None = None
feishu_verification_token: str | None = None
feishu_encrypt_key: str | None = None
feishu_default_chat_id: str | None = None
feishu_default_tenant_key: str | None = None
feishu_user_features_enabled: bool = False
feishu_admin_identities: 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
@@ -109,6 +126,7 @@ class Settings(BaseSettings):
event_dispatch_lock_seconds: int = 300
event_dispatch_cron_minute: str = "*/5"
heartbeat_interval_seconds: int = 60
heartbeat_retention_seconds: int = Field(default=86400, ge=1)
ai_memory_enabled: bool = True
ai_memory_auto_write_enabled: bool = True
ai_memory_recall_limit: int = 5
@@ -135,6 +153,8 @@ class Settings(BaseSettings):
ai_memory_forbidden_keys: list[str] = Field(
default_factory=lambda: [
"authorization",
"app_access_token",
"app_ticket",
"api_key",
"apikey",
"access_token",
@@ -147,6 +167,7 @@ class Settings(BaseSettings):
"direct_llm_api_key",
"market_data_token",
"feishu_app_secret",
"feishu_app_ticket",
"feishu_verification_token",
]
)
@@ -166,11 +187,20 @@ class Settings(BaseSettings):
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(
"feishu_app_type",
mode="before",
)
@classmethod
def normalize_feishu_app_type(cls, value: Any) -> str:
return str(value or "self").strip().lower()
@field_validator(
"openclaw_allowed_tools",
"openclaw_allowed_actions",
"ai_memory_forbidden_keys",
"ai_memory_blocked_content_terms",
"feishu_admin_identities",
mode="before",
)
@classmethod
@@ -240,19 +270,49 @@ class Settings(BaseSettings):
def validate_production_safety(self) -> "Settings":
if self.app_env.lower() not in {"prod", "production"}:
return self
def _enabled_keys(
legacy_key: str | None,
configured_keys: list[dict[str, Any]],
) -> set[str]:
values: set[str] = set()
if legacy_key and legacy_key.strip():
values.add(legacy_key)
for item in configured_keys:
enabled = item.get("enabled", True)
if not isinstance(enabled, bool):
enabled = str(enabled).strip().lower() not in {
"0", "false", "no", "off", "disabled"
}
key = item.get("key")
if enabled and key is not None and str(key).strip():
values.add(str(key))
return values
errors: list[str] = []
api_key_values = _enabled_keys(self.api_key, self.api_keys)
audit_key_values = _enabled_keys(self.audit_api_key, self.audit_api_keys)
if self.database_url.startswith("sqlite"):
errors.append("DATABASE_URL must use PostgreSQL in production")
if not self.api_key and not any(item.get("key") for item in self.api_keys):
if not api_key_values:
errors.append("API_KEY or API_KEYS is required in production")
if not self.audit_api_key and not any(
item.get("key") for item in self.audit_api_keys
):
if not audit_key_values:
errors.append("AUDIT_API_KEY or AUDIT_API_KEYS is required in production")
if api_key_values & audit_key_values:
errors.append(
"API_KEY/API_KEYS and AUDIT_API_KEY/AUDIT_API_KEYS cannot overlap in production"
)
if "*" in self.cors_origins:
errors.append("CORS_ORIGINS cannot contain '*' in production")
if self.debug:
errors.append("DEBUG must be false in production")
if not self.mask_sensitive_responses:
errors.append("MASK_SENSITIVE_RESPONSES must be true in production")
if not self.read_only_mode:
errors.append("READ_ONLY_MODE must be true in production")
if self.feishu_user_features_enabled and not self.feishu_admin_identities:
errors.append(
"FEISHU_ADMIN_IDENTITIES is required when Feishu user features are enabled"
)
if errors:
raise ValueError("; ".join(errors))
return self
+36 -1
View File
@@ -6,26 +6,61 @@ from app.core.config import get_settings
MASKED_VALUE = "[MASKED]"
SENSITIVE_RESPONSE_KEYS = frozenset(
{
"access_token",
"account_number",
"api_key",
"apikey",
"app_access_token",
"app_ticket",
"audit_api_key",
"authorization",
"bank_account",
"card_no",
"client_secret",
"cookie",
"direct_llm_api_key",
"email",
"encrypt_key",
"feishu_app_secret",
"feishu_app_ticket",
"feishu_encrypt_key",
"feishu_verification_token",
"hermes_api_key",
"id_card",
"market_data_token",
"mobile",
"openclaw_api_key",
"openclaw_gateway_token",
"password",
"payment_account",
"phone",
"private_key",
"refresh_token",
"secret",
"secret_key",
"set-cookie",
"set_cookie",
"tenant_access_token",
"token",
"x-api-key",
"x-audit-api-key",
"x_api_key",
"x_audit_api_key",
}
)
NORMALIZED_SENSITIVE_RESPONSE_KEYS = frozenset(
"".join(character for character in key.casefold() if character.isalnum())
for key in SENSITIVE_RESPONSE_KEYS
)
def is_sensitive_key(key: str) -> bool:
"""Return whether a key matches a built-in sensitive field name."""
normalized = "".join(
character for character in key.casefold() if character.isalnum()
)
return normalized in NORMALIZED_SENSITIVE_RESPONSE_KEYS
def mask_configured(value: Any, domain: str | None = None) -> Any:
@@ -61,7 +96,7 @@ def mask_sensitive(
def _should_mask(key: str, domain: str | None, configured_fields: set[str]) -> bool:
field = key.lower()
if field in SENSITIVE_RESPONSE_KEYS or field in configured_fields:
if is_sensitive_key(key) or field in configured_fields:
return True
if f"*.{field}" in configured_fields:
return True
-14
View File
@@ -1,21 +1,7 @@
from app.core.security.api_keys import ApiPrincipal, require_api_key, require_audit_api_key
from app.core.security.operation_guard import (
READ_ONLY_OPERATION_DISABLED,
require_operations_enabled,
)
from app.core.security.operation_policy import (
OperationsDisabledError,
business_mutations_enabled,
ensure_business_mutations_enabled,
)
__all__ = [
"ApiPrincipal",
"OperationsDisabledError",
"READ_ONLY_OPERATION_DISABLED",
"business_mutations_enabled",
"ensure_business_mutations_enabled",
"require_api_key",
"require_audit_api_key",
"require_operations_enabled",
]
-16
View File
@@ -1,16 +0,0 @@
from fastapi import HTTPException, status
from app.core.security.operation_policy import business_mutations_enabled
READ_ONLY_OPERATION_DISABLED = "This service is read-only; data mutation operations are disabled"
def require_operations_enabled(detail: str = READ_ONLY_OPERATION_DISABLED) -> None:
"""Reject mutation-oriented endpoints when the product is running read-only."""
if not business_mutations_enabled():
raise HTTPException(
status_code=status.HTTP_405_METHOD_NOT_ALLOWED,
detail=detail,
)
-20
View File
@@ -1,20 +0,0 @@
from app.core.config import get_settings
class OperationsDisabledError(RuntimeError):
"""Raised when a business mutation is attempted in read-only mode."""
def business_mutations_enabled() -> bool:
"""Return whether platform-owned business ledgers may be mutated."""
return not get_settings().read_only_mode
def ensure_business_mutations_enabled() -> None:
"""Enforce read-only policy outside the HTTP transport layer."""
if not business_mutations_enabled():
raise OperationsDisabledError(
"Business mutations are disabled while READ_ONLY_MODE is enabled"
)