Files
syops/backend/app/services/shipping_notice/fulfillment_audit.py
T
hugo 3a9fbac2fc feat(shipping-notice): 新增发货通知自动上传功能与候选资格评估
- 在环境配置中新增 SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED 选项,默认关闭,需显式开启以支持自动上传。
- 引入新的 pytest.ini 文件,增加测试标记以支持自动化测试。
- 删除不再使用的 seed_shipping_notice_agents.py 文件,简化代码库。
- 更新相关 API,增强发货通知与候选资格评估功能,支持多种筛选条件。
- 增强文档与代码注释,反映新的业务逻辑与功能要求。
2026-08-02 19:26:35 +08:00

233 lines
8.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
services/shipping_notice/fulfillment_audit.py
用途:履约关键节点与敏感访问写入统一审计事件的轻量封装。
依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError。
逻辑:由 candidate / decision / fulfillment_workflow / workspace 读取与导出 / Workflow 写路径调用;
默认 strict=True,审计写入失败时抛错,禁止业务成功而审计缺失;访问审计逐次留痕;
自动附带 request_id 与客户端 IP/UA(仅哈希入库);透传 Workflow 软引用字段。
"""
from __future__ import annotations
import logging
from typing import Any
from app.core.errors import ServiceUnavailableError
from app.services.shipping_notice.audit_service import append_shipping_audit_event
_LOGGER = logging.getLogger(__name__)
def _request_id() -> str | None:
"""尽量读取当前请求 ID;Worker 场景允许为空。"""
try:
from flask import g
return str(getattr(g, 'request_id', '') or '') or None
except RuntimeError:
return None
def _client_request_context() -> tuple[str | None, str | None]:
"""
读取当前请求客户端 IP 与 User-Agent(仅供哈希入库)。
核心逻辑:优先 X-Forwarded-For 首段;无请求上下文时返回 (None, None)。
"""
try:
from flask import request
forwarded = str(request.headers.get('X-Forwarded-For') or '').split(',')[0].strip()
ip = forwarded or str(request.remote_addr or '').strip() or None
ua = str(request.headers.get('User-Agent') or '').strip() or None
return ip, ua
except RuntimeError:
return None, None
def resolve_request_audit_context() -> dict[str, str | None]:
"""
解析当前 HTTP 请求的审计关联上下文。
核心逻辑:合并 request_id 与原始 IP/UA(供 append 侧哈希);无 Flask 请求时全空。
Returns:
含 request_id / client_ip / user_agent 的字典;值均可为 None。
"""
client_ip, user_agent = _client_request_context()
return {
'request_id': _request_id(),
'client_ip': client_ip,
'user_agent': user_agent,
}
def record_fulfillment_audit(
*,
event_type: str,
aggregate_type: str,
aggregate_id: str,
action: str,
actor_type: str = 'user',
actor_id: str | int | None = None,
run_no: str | None = None,
task_no: str | None = None,
document_id: str | int | None = None,
review_case_no: str | None = None,
conversation_id: str | None = None,
workflow_id: str | None = None,
workflow_item_id: str | None = None,
workflow_item_version_id: str | None = None,
version_no: int | None = None,
owner_user_id: str | int | None = None,
reason_code: str | None = None,
reason: str | None = None,
result: str = 'success',
error_code: str | None = None,
before: dict[str, Any] | None = None,
after: dict[str, Any] | None = None,
metadata: dict[str, Any] | None = None,
source: str = 'api',
strict: bool = True,
sensitivity_level: str | None = None,
) -> None:
"""
追加履约审计。
核心逻辑:默认与业务同事务写入;strict=True 时失败抛错,保证必须留存;
自动附带 request_id 与客户端 IP/UA 哈希;透传 Workflow 软引用。
Args:
event_type/action: 稳定事件与动作码。
workflow_id/workflow_item_id/workflow_item_version_id/version_no: Workflow 软引用。
before/after: 必须已是白名单可投影的状态摘要。
error_code: 拒绝/失败时的稳定业务错误码。
sensitivity_level: 可选敏感分级(如 sensitive),透传审计表。
strict: True 时审计失败阻断调用方;False 时仅记日志(仅限显式降级场景)。
"""
request_id = _request_id()
client_ip, user_agent = _client_request_context()
try:
append_shipping_audit_event(
event_type=event_type,
aggregate_type=aggregate_type,
aggregate_id=str(aggregate_id),
action=action,
actor_type=actor_type,
actor_id=actor_id,
request_id=request_id,
operation_id=request_id,
run_no=run_no,
task_no=task_no,
document_id=document_id,
review_case_no=review_case_no,
conversation_id=conversation_id,
workflow_id=workflow_id,
workflow_item_id=workflow_item_id,
workflow_item_version_id=workflow_item_version_id,
version_no=version_no,
owner_user_id=owner_user_id,
client_ip=client_ip,
user_agent=user_agent,
reason_code=reason_code,
reason=reason,
result=result,
error_code=error_code,
before=before,
after=after,
metadata=metadata or {},
source=source,
sensitivity_level=sensitivity_level,
)
except Exception as exc:
_LOGGER.exception('fulfillment audit append failed event_type=%s aggregate_id=%s', event_type, aggregate_id)
if strict:
raise ServiceUnavailableError(
'Shipping audit persistence failed',
code='SHIPPING_NOTICE.AUDIT_PERSIST_FAILED',
details={'event_type': event_type, 'aggregate_id': str(aggregate_id)},
) from exc
def record_access_audit(
*,
action: str,
aggregate_type: str,
aggregate_id: str,
actor_id: str | int | None,
actor_type: str = 'user',
run_no: str | None = None,
task_no: str | None = None,
document_id: str | int | None = None,
review_case_no: str | None = None,
conversation_id: str | None = None,
workflow_id: str | None = None,
workflow_item_id: str | None = None,
workflow_item_version_id: str | None = None,
version_no: int | None = None,
owner_user_id: str | int | None = None,
reason_code: str | None = None,
metadata: dict[str, Any] | None = None,
strict: bool = True,
) -> bool:
"""
记录敏感读取/导出访问审计(无业务正文);每次调用均落库。
核心逻辑:自行提交;失败时回滚并按 strict 抛错,禁止静默丢审计;附带客户端哈希;
可选 reason_code 供审计中心按可解释性码筛选(如 Excel 下载)。
Args:
reason_code: 可选稳定原因/动作码(访问类事件通常为业务动作标识)。
Returns:
True 表示本次写入了新事件。
"""
from app import db
request_id = _request_id()
client_ip, user_agent = _client_request_context()
resolved_reason = str(reason_code or '').strip() or None
meta = dict(metadata or {'access': True})
if resolved_reason:
meta.setdefault('reason_code', resolved_reason)
try:
append_shipping_audit_event(
event_type='shipping_resource_accessed',
aggregate_type=str(aggregate_type)[:64],
aggregate_id=str(aggregate_id)[:128],
action=str(action)[:64],
actor_type=actor_type,
actor_id=actor_id,
request_id=request_id,
operation_id=request_id,
run_no=run_no,
task_no=task_no,
document_id=document_id,
review_case_no=review_case_no,
conversation_id=conversation_id,
workflow_id=workflow_id,
workflow_item_id=workflow_item_id,
workflow_item_version_id=workflow_item_version_id,
version_no=version_no,
owner_user_id=owner_user_id,
client_ip=client_ip,
user_agent=user_agent,
reason_code=resolved_reason,
result='success',
metadata=meta,
source='api',
persist_snapshots=False,
sensitivity_level='sensitive',
)
db.session.commit()
return True
except Exception as exc:
db.session.rollback()
_LOGGER.exception('access audit append failed action=%s aggregate_id=%s', action, aggregate_id)
if strict:
raise ServiceUnavailableError(
'Shipping access audit persistence failed',
code='SHIPPING_NOTICE.AUDIT_PERSIST_FAILED',
details={'action': action, 'aggregate_id': str(aggregate_id)},
) from exc
return False