merge: 并入同事的场外申购/推广/行情/NL2SQL 线(11 提交、334 文件)

冲突仅 3 个文件,全部取并集(双方都没有需要丢弃的改动):
- app/main.py:import 双方路由(我方 knowledge_management + 同事的 offsite_fund/
  promotion_material);include_router 段本已自动合并
- app/service/agent/bootstrap.py:import 与工具注册均取并集
  (query_customer_profile + query_financial_data 都注册)
- tests/integration/test_config_release_mysql.py:outbox 清理同时保留
  架构师的 event_type 限定(防误删其它域 outbox 行)与同事新增的 peer_release_id

同事这轮带入:11 个 alembic 迁移(建 offsite_* / promotion_* 等表)、
场外申购与推广素材 Agent、financial NL2SQL 工具。
注意:本库尚无 offsite_*/promotion_* 表,跑相关测试前需要执行 alembic upgrade。

边界核对:同事的场外代码未写入场内交易表(fin_sim_order/fin_capital_flow/fin_cash_ledger),
符合 AGENTS.md 规则 8。
This commit is contained in:
qyqy
2026-09-11 18:56:26 +08:00
118 changed files with 18967 additions and 191 deletions
+6 -2
View File
@@ -5,6 +5,7 @@ from app.api.dependencies.auth import build_request_context
from app.api.dependencies.database import get_session
from app.api.dependencies.rate_limit import enforce_rate_limit
from app.api.schemas.conversations import FeedbackRequest
from app.api.views.envelope import envelope, list_envelope
from app.core.contracts import RequestContext
from app.core.cursor import parse_cursor
from app.service.conversation_service import ConversationService
@@ -28,9 +29,10 @@ async def list_messages(
`400 INVALID_CURSOR`,而不是被静默忽略后返回第一页。
"""
before = parse_cursor(cursor)
return await ConversationService(session).messages(
page = await ConversationService(session).messages(
session_id, context, limit, before=before
)
return list_envelope(page, context)
@router.post("/conversation-messages/{message_id}/feedback", status_code=status.HTTP_201_CREATED)
@@ -40,5 +42,7 @@ async def create_feedback(
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, object]:
return await ConversationService(session).feedback(
# 与消息列表同理:§3.3 的信封由 Controller 统一套,service 只负责业务数据。
data = await ConversationService(session).feedback(
message_id, context, payload.rating, payload.feedback_type, payload.feedback_content)
return envelope(data, context)
+5 -1
View File
@@ -2,6 +2,7 @@ from fastapi import APIRouter, Depends, Path
from app.api.dependencies.auth import build_request_context
from app.api.dependencies.rate_limit import enforce_rate_limit
from app.api.views.envelope import envelope
from app.core.contracts import RequestContext
from app.service.knowledge_service import KnowledgeReferenceService
@@ -14,4 +15,7 @@ async def resolve_reference(
reference_token: str = Path(min_length=20, max_length=300),
context: RequestContext = Depends(build_request_context), # noqa: B008
) -> dict[str, object]:
return await KnowledgeReferenceService().resolve(context, reference_token)
# §3.3:成功响应也要有 `meta.trace_id`。此前这里直接返回资源对象,客户端拿不到
# 本次请求的追踪标识,出问题时无法与服务端日志对上。
data = await KnowledgeReferenceService().resolve(context, reference_token)
return envelope(data, context)
+223
View File
@@ -0,0 +1,223 @@
"""场外基金运营接口。"""
from typing import Any
from fastapi import APIRouter, Depends, Query, Response
from fastapi.responses import FileResponse
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.dependencies.auth import build_request_context
from app.api.dependencies.database import get_session
from app.api.schemas.offsite_fund import (
OffsiteConfirmRequest,
OffsiteNl2SqlCorrectionRequest,
OffsiteNotificationRequest,
OffsiteNotificationSendRequest,
OffsiteRecalculateRequest,
OffsiteRecognitionCorrectionRequest,
OffsiteRecognitionRetryRequest,
OffsiteRuleRecalculationRequest,
OffsiteTriggerNl2SqlRequest,
)
from app.core.contracts import RequestContext
from app.service.offsite_fund_service import OffsiteFundService
router = APIRouter(prefix="/api/v1/offsite-fund", tags=["offsite-fund"])
operation_router = APIRouter(prefix="/api", tags=["offsite-fund"])
@router.get("/mails")
async def list_mails(
page: int = Query(default=1, ge=1),
page_size: int = Query(default=20, ge=1, le=100),
sender: str | None = Query(default=None, min_length=3, max_length=255),
status: str | None = Query(default=None, min_length=1, max_length=32),
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
return await OffsiteFundService(session).list_mails(
context, page, page_size, sender, status
)
@router.get("/mails/{mail_id}")
async def get_mail(
mail_id: str,
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
return await OffsiteFundService(session).get_mail(mail_id, context)
@router.get("/mails/{mail_id}/recognition-fields")
async def get_mail_recognition_fields(
mail_id: str,
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
"""读取邮件内全部附件的 OCR 识别字段:只读查询,不触发重新识别。"""
return await OffsiteFundService(session).mail_recognition_fields(mail_id, context)
@router.put("/mails/{mail_id}/recognition-fields")
async def save_mail_recognition_fields(
mail_id: str,
payload: OffsiteRecognitionCorrectionRequest,
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
"""保存 OCR 识别字段的人工修正值:只新增修正记录,不覆盖 Agent 原始识别值。"""
return await OffsiteFundService(session).save_recognition_corrections(
mail_id,
[(item.attachment_id, item.fields) for item in payload.attachments],
payload.operator_id,
context,
)
@router.get("/documents/{task_id}/nl2sql-fields")
async def get_document_nl2sql_fields(
task_id: str,
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
"""读取单据核对使用的 NL2SQL 返回字段:只读查询,不触发新的查询。"""
return await OffsiteFundService(session).nl2sql_fields(task_id, context)
@router.put("/documents/{task_id}/nl2sql-fields")
async def save_document_nl2sql_fields(
task_id: str,
payload: OffsiteNl2SqlCorrectionRequest,
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
"""保存 NL2SQL 返回字段的人工修正值:只新增修正记录,不改写查询记录。"""
return await OffsiteFundService(session).save_nl2sql_corrections(
task_id, payload.fields, payload.operator_id, context
)
@router.get("/documents/{task_id}/rule-results")
async def get_document_rule_results(
task_id: str,
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
"""读取单据规则判定结果:只读查询,不触发查询或重新判定。"""
return await OffsiteFundService(session).rule_results(task_id, context)
@router.post("/documents/{task_id}/rule-results/recalculations")
async def recalculate_document_rule_results(
task_id: str,
payload: OffsiteRuleRecalculationRequest,
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
"""用已落库的识别字段和查询结果重新判定规则:不重新识别、不重新调用 NL2SQL。"""
return await OffsiteFundService(session).recalculate_rule_results(
task_id, payload.operator_id, context
)
@router.get("/mailbox-status")
async def mailbox_status(
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
"""收件箱状态:游标锁死时前端据此弹出告警。"""
return await OffsiteFundService(session).mailbox_status(context)
@router.get("/attachments/{attachment_id}/file", response_model=None)
async def open_attachment_file(
attachment_id: str,
disposition: str = Query(default="inline", pattern="^(inline|attachment)$"),
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> Response | dict[str, Any]:
"""按附件编号返回原始文件:PDF/图片默认内联预览,其余类型转为下载。"""
result = await OffsiteFundService(session).open_attachment_file(
attachment_id, disposition, context
)
if isinstance(result, dict):
return result
return FileResponse(
result.path,
media_type=result.media_type,
filename=result.filename,
content_disposition_type=result.disposition,
headers={"X-Content-Type-Options": "nosniff"},
)
@router.post("/documents/{task_id}/confirmations")
async def confirm_document(
task_id: str,
payload: OffsiteConfirmRequest,
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
return await OffsiteFundService(session).confirm_document(
task_id, payload.decision, payload.operator_id, context)
@router.post("/documents/{task_id}/recognition-retries")
async def retry_document_recognition(
task_id: str,
payload: OffsiteRecognitionRetryRequest,
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
return await OffsiteFundService(session).retry_document_recognition(
task_id, payload.operator_id, context
)
@router.post("/documents/{task_id}/notifications")
async def create_notification(
task_id: str,
payload: OffsiteNotificationRequest,
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
return await OffsiteFundService(session).create_notification(
task_id, payload.notification_type, payload.operator_id, context)
@router.post("/notifications/{notification_id}/send")
async def send_notification(
notification_id: int,
payload: OffsiteNotificationSendRequest,
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
return await OffsiteFundService(session).send_notification(
notification_id,
payload.operator_id,
payload.operator_confirmed,
payload.final_content,
context,
)
@router.post("/settlement-statistics/recalculate")
async def recalculate_statistics(
payload: OffsiteRecalculateRequest,
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
return await OffsiteFundService(session).recalculate_statistics(
payload.fund_code, payload.application_date, context)
@operation_router.post("/tasks/{task_id}/trigger-agent-nl2sql")
async def trigger_agent_nl2sql(
task_id: str,
payload: OffsiteTriggerNl2SqlRequest,
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
return await OffsiteFundService(session).trigger_agent_nl2sql(
task_id, payload.operator_id, payload.manual_confirmed, context)
+110
View File
@@ -0,0 +1,110 @@
"""产品推介材料接口。"""
from typing import Any
from fastapi import APIRouter, Depends, File, Header, Query, UploadFile
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.dependencies.auth import build_request_context
from app.api.dependencies.database import get_session
from app.api.schemas.promotion_material import (
PromotionDeliveryRequest,
PromotionGenerationRequest,
PromotionInputsUpdate,
PromotionReviewRequest,
PromotionTaskCreate,
)
from app.core.contracts import RequestContext
from app.service.promotion_material_service import PromotionMaterialService
router = APIRouter(
prefix="/api/v1/fund-promotion-materials",
tags=["fund-promotion-materials"],
)
@router.post("")
async def create_task(
payload: PromotionTaskCreate,
context: RequestContext = Depends(build_request_context), # noqa: B008
key: str | None = Header(default=None, alias="Idempotency-Key"),
) -> dict[str, Any]:
return await PromotionMaterialService().create_task(payload, context, key)
@router.put("/{task_no}/inputs")
async def update_inputs(
task_no: str,
payload: PromotionInputsUpdate,
context: RequestContext = Depends(build_request_context), # noqa: B008
key: str | None = Header(default=None, alias="Idempotency-Key"),
) -> dict[str, Any]:
return await PromotionMaterialService().update_inputs(task_no, payload, context, key)
@router.post("/{task_no}/attachments")
async def add_attachment(
task_no: str,
file: UploadFile = File(...), # noqa: B008
attachment_type: str = Query(...),
context: RequestContext = Depends(build_request_context), # noqa: B008
key: str | None = Header(default=None, alias="Idempotency-Key"),
) -> dict[str, Any]:
payload = await file.read()
return await PromotionMaterialService().add_attachment(
task_no,
attachment_type,
file.filename or "attachment",
file.content_type or "application/octet-stream",
payload,
context,
key,
)
@router.post("/{task_no}/generations")
async def generate_material(
task_no: str,
payload: PromotionGenerationRequest,
context: RequestContext = Depends(build_request_context), # noqa: B008
key: str | None = Header(default=None, alias="Idempotency-Key"),
) -> dict[str, Any]:
return await PromotionMaterialService().generate(task_no, payload, context, key)
@router.get("/{task_no}/compliance-checks")
async def compliance_checks(
task_no: str,
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
return await PromotionMaterialService(session).compliance_checks(task_no, context)
@router.get("/{task_no}")
async def get_task(
task_no: str,
context: RequestContext = Depends(build_request_context), # noqa: B008
session: AsyncSession = Depends(get_session), # noqa: B008
) -> dict[str, Any]:
return await PromotionMaterialService(session).get_task(task_no, context)
@router.post("/{task_no}/reviews")
async def review_material(
task_no: str,
payload: PromotionReviewRequest,
context: RequestContext = Depends(build_request_context), # noqa: B008
key: str | None = Header(default=None, alias="Idempotency-Key"),
) -> dict[str, Any]:
return await PromotionMaterialService().review(task_no, payload, context, key)
@router.post("/{task_no}/deliveries")
async def deliver_material(
task_no: str,
payload: PromotionDeliveryRequest,
context: RequestContext = Depends(build_request_context), # noqa: B008
key: str | None = Header(default=None, alias="Idempotency-Key"),
) -> dict[str, Any]:
return await PromotionMaterialService().deliver(task_no, payload, context, key)
+4 -25
View File
@@ -24,6 +24,8 @@ from app.api.schemas.risk import (
RiskEvidenceSource,
RiskNotificationPageQuery,
)
from app.api.views.envelope import envelope as _envelope
from app.api.views.envelope import list_envelope as _list_envelope
from app.core.contracts import RequestContext
from app.core.errors import SseNotAcceptableError
from app.infrastructure.db import mysql_scan_lock
@@ -304,28 +306,5 @@ async def send_risk_daily_report_mail(
return _envelope(data, context)
def _envelope(data: object, context: RequestContext) -> dict[str, object]:
return {
"data": data,
"meta": {"trace_id": context.trace_id},
}
def _list_envelope(page: dict[str, Any], context: RequestContext) -> dict[str, object]:
"""列表资源的信封(docs/05 §3.3)。
§3.3 的列表样例是 `data` 为**纯数组**、游标与 `has_more` 放在 `meta` 里,并且明确
「业务接口不得增加其他顶层字段」。而 `RiskQueryService._page` 返回的是
`{items, next_cursor, has_more}` —— 整体塞进 `data` 后,游标跑进了**业务数据**里、
`meta` 只剩 trace_id,两处都不符合契约。
这里统一拆包;service 侧不必改(它继续返回那个内部结构,只是不再直接当 `data` 用)。
"""
return {
"data": page.get("items") or [],
"meta": {
"trace_id": context.trace_id,
"next_cursor": page.get("next_cursor"),
"has_more": bool(page.get("has_more")),
},
}
# `_envelope` / `_list_envelope` 已抽到 `app/api/views/envelope.py`,与客服链路共用同一份
# §3.3 实现 —— 两处各写一份的结果就是其中一处漏了 `meta`。