Merge branch 'dev' into branch-statement-button
# Conflicts: # docs/funclist.md
This commit is contained in:
commit
97c46625e4
986 files changed
+96142
-38961
No files matched your search
@@ -2,7 +2,7 @@
|
||||
backend/app/services/admin/faq_service.py
|
||||
|
||||
用途:全局常用问题(QuickQuestion)与热点 FAQ 候选管理。
|
||||
依赖:models、faq_kb_invalidation、hot_faq_* services。
|
||||
依赖:models、faq_kb_invalidation、hot_faq_* services、faq_text_utils(模糊阈值钳制)。
|
||||
逻辑:由 api/admin/quick_questions.py、faq_candidates.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
@@ -13,6 +13,7 @@ from typing import Any
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Agent, KbDocument, QuickQuestion
|
||||
from app.services.faq_text_utils import clamp_fuzzy_threshold
|
||||
|
||||
|
||||
def parse_aliases(raw_aliases) -> list[str]:
|
||||
@@ -61,6 +62,8 @@ def serialize_quick_question(
|
||||
'aliases': q.aliases if isinstance(q.aliases, list) else [],
|
||||
'cache_enabled': bool(q.cache_enabled),
|
||||
'is_enabled': bool(q.is_enabled),
|
||||
'fuzzy_enabled': bool(getattr(q, 'fuzzy_enabled', False)),
|
||||
'fuzzy_threshold': clamp_fuzzy_threshold(getattr(q, 'fuzzy_threshold', None)),
|
||||
'hit_count': q.hit_count or 0,
|
||||
'agent_id': q.agent_id,
|
||||
'agent_name': agent_name,
|
||||
@@ -93,6 +96,12 @@ def apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answe
|
||||
qq.cache_enabled = bool(data['cache_enabled'])
|
||||
if 'is_enabled' in data:
|
||||
qq.is_enabled = bool(data['is_enabled'])
|
||||
if 'fuzzy_enabled' in data:
|
||||
qq.fuzzy_enabled = bool(data['fuzzy_enabled'])
|
||||
if 'fuzzy_threshold' in data:
|
||||
qq.fuzzy_threshold = clamp_fuzzy_threshold(data['fuzzy_threshold'])
|
||||
else:
|
||||
qq.fuzzy_threshold = clamp_fuzzy_threshold(qq.fuzzy_threshold)
|
||||
if 'expires_at' in data:
|
||||
qq.expires_at = parse_expires_at(data['expires_at'])
|
||||
if 'retriever_resources' in data and isinstance(data.get('retriever_resources'), list):
|
||||
@@ -106,6 +115,8 @@ def apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answe
|
||||
|
||||
if qq.cache_enabled and not str(qq.answer or '').strip():
|
||||
raise ValidationError('启用 FAQ 缓存时必须填写标准答案')
|
||||
if qq.fuzzy_enabled and not qq.cache_enabled:
|
||||
raise ValidationError('启用模糊匹配前需先启用 FAQ 缓存')
|
||||
if require_answer and (not qq.title or not qq.question or not qq.agent_id):
|
||||
raise ValidationError('Missing required fields')
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
services/admin/freight_rpa_form_utils.py
|
||||
|
||||
用途:货代 RPA 管理端表单校验共用件(JSON 对象、报表路径、查询条件、时间序列化)。
|
||||
依赖:app.core.errors.ValidationError。
|
||||
逻辑:freight_rpa_source_admin_service(站点/连接)与 freight_rpa_report_config_service
|
||||
(入站/出站报表配置)共用;错误码沿用历史 SHIPPING.ONHAND_SOURCE_CONFIG_INVALID,
|
||||
调用方可按域 remap。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
|
||||
def json_object(data: dict[str, Any], field: str) -> dict[str, Any]:
|
||||
"""读取并复制对象型 JSON 配置。
|
||||
|
||||
Args:
|
||||
data: 管理 API 的请求载荷。
|
||||
field: 只允许 JSON object 的字段名。
|
||||
|
||||
Returns:
|
||||
空值规范化为空对象后的可写入配置。
|
||||
|
||||
Raises:
|
||||
ValidationError: 字段不是 JSON object。
|
||||
"""
|
||||
value = data.get(field, {})
|
||||
if not isinstance(value, dict):
|
||||
raise ValidationError(f'{field} must be an object', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
return dict(value)
|
||||
|
||||
|
||||
def validate_report_path(connector_type: str, report_path: dict[str, Any]) -> dict[str, str]:
|
||||
"""校验 DBS 四级报表路径,防止技术选择器混入业务配置。"""
|
||||
allowed = {'program_group', 'program_label', 'report_group', 'report_name'}
|
||||
if set(report_path) - allowed:
|
||||
raise ValidationError('report_path_json contains unsupported fields', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
normalized = {key: str(value or '').strip() for key, value in report_path.items()}
|
||||
if connector_type == 'dbs':
|
||||
missing = [key for key in allowed if not normalized.get(key)]
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
'DBS inventory source requires a complete report path',
|
||||
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'missing': sorted(missing)},
|
||||
)
|
||||
elif normalized:
|
||||
raise ValidationError(
|
||||
'Only DBS inventory sources can define report_path_json',
|
||||
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID',
|
||||
)
|
||||
return {key: normalized[key] for key in allowed if normalized.get(key)}
|
||||
|
||||
|
||||
def validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""校验 Source 的可视化查询参数列表,禁止保存 selector 等 Driver 实现细节。"""
|
||||
raw = data.get('query_parameters_json', [])
|
||||
if not isinstance(raw, list):
|
||||
raise ValidationError('query_parameters_json must be a list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
result: list[dict[str, Any]] = []
|
||||
seen_names: set[str] = set()
|
||||
allowed = {'name', 'mode', 'values', 'required', 'select_all', 'joiner'}
|
||||
for index, item in enumerate(raw):
|
||||
if not isinstance(item, dict) or set(item) - allowed:
|
||||
raise ValidationError(
|
||||
'query parameter contains unsupported fields',
|
||||
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID', details={'index': index},
|
||||
)
|
||||
name = str(item.get('name') or '').strip()
|
||||
mode = str(item.get('mode') or 'single').strip().lower()
|
||||
values = item.get('values', [])
|
||||
required = item.get('required', False)
|
||||
select_all = item.get('select_all', False)
|
||||
if not name or name.lower() in seen_names or mode not in {'single', 'multi_text', 'multi_select'}:
|
||||
raise ValidationError('query parameter name or mode is invalid', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
if not isinstance(values, list) or any(not isinstance(value, str) for value in values):
|
||||
raise ValidationError('query parameter values must be a string list', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
if not isinstance(required, bool) or not isinstance(select_all, bool):
|
||||
raise ValidationError('query parameter flags must be boolean', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
normalized_values = [value.strip() for value in values if value.strip()]
|
||||
if required and not normalized_values and not select_all:
|
||||
raise ValidationError('required query parameter needs values or select_all', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
if select_all and mode != 'multi_select':
|
||||
raise ValidationError('select_all only applies to multi_select', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
parameter: dict[str, Any] = {
|
||||
'name': name, 'mode': mode, 'values': normalized_values,
|
||||
'required': required, 'select_all': select_all,
|
||||
}
|
||||
if mode == 'multi_text':
|
||||
joiner = str(item.get('joiner') or ',').strip()
|
||||
if not joiner:
|
||||
raise ValidationError('multi_text query parameter needs joiner', code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID')
|
||||
parameter['joiner'] = joiner
|
||||
seen_names.add(name.lower())
|
||||
result.append(parameter)
|
||||
return result
|
||||
|
||||
|
||||
def iso(value: datetime | None) -> str | None:
|
||||
"""datetime → ISO 字符串;None 保持 None。"""
|
||||
return value.isoformat() if value else None
|
||||
@@ -0,0 +1,224 @@
|
||||
"""
|
||||
services/admin/freight_rpa_report_config_service.py
|
||||
|
||||
用途:货代 RPA 入站 / 出站报表配置管理(GET/PUT),与在手配置解耦。
|
||||
依赖:db、FreightRpaSource / FreightRpaInboundReportConfig / FreightRpaOutboundReportConfig /
|
||||
FreightRpaParsingProfile、freight_rpa_form_utils、shipping_notice.audit_service。
|
||||
逻辑:admin_freight_rpa 蓝图委托本服务;不进入来源站点启用硬门槛;
|
||||
解析绑定须 published 且 purpose 匹配 inbound/outbound。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FreightRpaInboundReportConfig,
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaParsingProfile,
|
||||
FreightRpaSource,
|
||||
)
|
||||
from app.services.admin.freight_rpa_form_utils import iso, json_object, validate_query_parameters, validate_report_path
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def _inbound_report_config_payload(config: FreightRpaInboundReportConfig) -> dict[str, Any]:
|
||||
"""序列化独立入站配置,禁止把库存路径或凭据透传至管理端。"""
|
||||
profile = config.parsing_profile
|
||||
return {
|
||||
'id': config.id, 'source_id': config.source_id,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
'parsing_profile_id': config.parsing_profile_id,
|
||||
'parsing_profile': ({
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'version': profile.version, 'status': profile.status,
|
||||
} if profile else None),
|
||||
'config_version': config.config_version,
|
||||
'created_at': iso(config.created_at), 'updated_at': iso(config.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _outbound_report_config_payload(config: FreightRpaOutboundReportConfig) -> dict[str, Any]:
|
||||
"""序列化独立出站配置,禁止把库存/入站路径或凭据透传至管理端。"""
|
||||
profile = config.parsing_profile
|
||||
return {
|
||||
'id': config.id, 'source_id': config.source_id,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
'parsing_profile_id': config.parsing_profile_id,
|
||||
'parsing_profile': ({
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'version': profile.version, 'status': profile.status,
|
||||
} if profile else None),
|
||||
'config_version': config.config_version,
|
||||
'created_at': iso(config.created_at), 'updated_at': iso(config.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _validate_inbound_profile_binding(profile_id: Any) -> int | None:
|
||||
"""校验入站配置绑定的解析规则:必须已发布且 purpose='inbound';空值表示解绑。"""
|
||||
if profile_id is None or str(profile_id).strip() == '':
|
||||
return None
|
||||
profile = db.session.get(FreightRpaParsingProfile, int(profile_id))
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
|
||||
raise ValidationError(
|
||||
'Inbound parsing profile must be published with purpose inbound',
|
||||
code='SHIPPING.INBOUND_PROFILE_INVALID',
|
||||
)
|
||||
return profile.id
|
||||
|
||||
|
||||
def _validate_outbound_profile_binding(profile_id: Any) -> int | None:
|
||||
"""校验出站配置绑定的解析规则:必须已发布且 purpose='outbound';空值表示解绑。"""
|
||||
if profile_id is None or str(profile_id).strip() == '':
|
||||
return None
|
||||
profile = db.session.get(FreightRpaParsingProfile, int(profile_id))
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'outbound':
|
||||
raise ValidationError(
|
||||
'Outbound parsing profile must be published with purpose outbound',
|
||||
code='SHIPPING.OUTBOUND_PROFILE_INVALID',
|
||||
)
|
||||
return profile.id
|
||||
|
||||
|
||||
def _validate_inbound_report_config(
|
||||
source: FreightRpaSource, data: dict[str, Any],
|
||||
) -> tuple[dict[str, str], list[dict[str, Any]]]:
|
||||
"""规范入站配置:路径+查询条件;日期禁填。"""
|
||||
try:
|
||||
parameters = validate_query_parameters(data)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') from exc
|
||||
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
|
||||
raise ValidationError('Inbound report date filtering is not supported', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID')
|
||||
raw_path = json_object(data, 'report_path_json')
|
||||
if source.connector_type == 'dbs':
|
||||
try:
|
||||
path = validate_report_path('dbs', raw_path)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID') from exc
|
||||
return path, parameters
|
||||
if source.connector_type == 'crane':
|
||||
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
|
||||
raise ValidationError('Crane inbound report is fixed to Inbound Details', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID')
|
||||
if parameters:
|
||||
raise ValidationError(
|
||||
'Crane inbound report does not support query parameters',
|
||||
code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID',
|
||||
)
|
||||
return {'report_name': 'Inbound Details'}, []
|
||||
raise ValidationError('Unsupported inbound connector type', code='SHIPPING.INBOUND_REPORT_CONFIG_INVALID')
|
||||
|
||||
|
||||
def _validate_outbound_report_config(
|
||||
source: FreightRpaSource, data: dict[str, Any],
|
||||
) -> tuple[dict[str, str], list[dict[str, Any]]]:
|
||||
"""规范出站配置:路径+查询条件;日期禁填;Crane 固定 Outbound Details。"""
|
||||
try:
|
||||
parameters = validate_query_parameters(data)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') from exc
|
||||
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
|
||||
raise ValidationError('Outbound report date filtering is not supported', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID')
|
||||
raw_path = json_object(data, 'report_path_json')
|
||||
if source.connector_type == 'dbs':
|
||||
try:
|
||||
path = validate_report_path('dbs', raw_path)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID') from exc
|
||||
return path, parameters
|
||||
if source.connector_type == 'crane':
|
||||
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Outbound Details'):
|
||||
raise ValidationError('Crane outbound report is fixed to Outbound Details', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID')
|
||||
if parameters:
|
||||
raise ValidationError(
|
||||
'Crane outbound report does not support query parameters',
|
||||
code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID',
|
||||
)
|
||||
return {'report_name': 'Outbound Details'}, []
|
||||
raise ValidationError('Unsupported outbound connector type', code='SHIPPING.OUTBOUND_REPORT_CONFIG_INVALID')
|
||||
|
||||
|
||||
def get_inbound_report_config(source_id: int) -> dict[str, Any] | None:
|
||||
"""读取站点的入站配置;不存在时返回空。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
|
||||
return _inbound_report_config_payload(config) if config else None
|
||||
|
||||
|
||||
def save_inbound_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""保存站点内独立入站配置并追加配置前后快照审计。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
path, parameters = _validate_inbound_report_config(source, data)
|
||||
config = FreightRpaInboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
|
||||
before = _inbound_report_config_payload(config) if config else None
|
||||
is_new = config is None
|
||||
if config is None:
|
||||
config = FreightRpaInboundReportConfig(source_id=source.id)
|
||||
config.created_by = actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.report_path_json = path
|
||||
config.query_parameters_json = parameters
|
||||
config.parsing_profile_id = _validate_inbound_profile_binding(data.get('parsing_profile_id'))
|
||||
config.updated_by = actor_id
|
||||
db.session.flush()
|
||||
after = _inbound_report_config_payload(config)
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_inbound_report_config_saved', aggregate_type='shipping_inbound_report_config',
|
||||
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
|
||||
result='success', before=before, after=after,
|
||||
metadata={'source_id': source.id, 'connector_type': source.connector_type,
|
||||
'parsing_profile_id': config.parsing_profile_id},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
|
||||
|
||||
def get_outbound_report_config(source_id: int) -> dict[str, Any] | None:
|
||||
"""读取站点的出站配置;不存在时返回空。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
config = FreightRpaOutboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
|
||||
return _outbound_report_config_payload(config) if config else None
|
||||
|
||||
|
||||
def save_outbound_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""保存站点内独立出站配置并追加配置前后快照审计。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
path, parameters = _validate_outbound_report_config(source, data)
|
||||
config = FreightRpaOutboundReportConfig.query.filter_by(source_id=source.id).one_or_none()
|
||||
before = _outbound_report_config_payload(config) if config else None
|
||||
is_new = config is None
|
||||
if config is None:
|
||||
config = FreightRpaOutboundReportConfig(source_id=source.id)
|
||||
config.created_by = actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.report_path_json = path
|
||||
config.query_parameters_json = parameters
|
||||
config.parsing_profile_id = _validate_outbound_profile_binding(data.get('parsing_profile_id'))
|
||||
config.updated_by = actor_id
|
||||
db.session.flush()
|
||||
after = _outbound_report_config_payload(config)
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_outbound_report_config_saved', aggregate_type='shipping_outbound_report_config',
|
||||
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
|
||||
result='success', before=before, after=after,
|
||||
metadata={'source_id': source.id, 'connector_type': source.connector_type,
|
||||
'parsing_profile_id': config.parsing_profile_id},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
@@ -0,0 +1,733 @@
|
||||
"""
|
||||
services/admin/freight_rpa_source_admin_service.py
|
||||
|
||||
用途:货代 RPA 共用主数据管理——登录连接(FreightRpaProfile)与来源站点(FreightRpaSource),
|
||||
含站点启用门禁、在手配置行写入、解析绑定审计。
|
||||
依赖:db、FreightRpaProfile / FreightRpaSource / FreightRpaOnhandReportConfig、
|
||||
freight_rpa_form_utils、credential_crypto、parsing_profile、upload_config_validation、
|
||||
onhand_source_repository.validate_source_profile、audit_service。
|
||||
逻辑:admin_freight_rpa 蓝图的 rpa-profiles / sources / bind-parsing / activate 委托本服务;
|
||||
Profile 列表与保存回执返回用户名明文,密码与密文不返回;
|
||||
在手快照/路由规则/外部映射仍见 shipping_onhand_admin_service。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ServiceUnavailableError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FreightRpaOnhandExternalMapping,
|
||||
FreightRpaOnhandReportConfig,
|
||||
FreightRpaOnhandReportFile,
|
||||
FreightRpaOnhandRoutingRule,
|
||||
FreightRpaParsingProfile,
|
||||
FreightRpaProfile,
|
||||
FreightRpaSource,
|
||||
FreightRpaSourceParsingBindingAudit,
|
||||
ScheduleRun,
|
||||
ShippingExcelTemplate,
|
||||
ShippingNoticeLine,
|
||||
ShippingNoticeLineOnhandMatch,
|
||||
)
|
||||
from app.services.admin.freight_rpa_form_utils import (
|
||||
iso as _iso,
|
||||
json_object as _json_object,
|
||||
validate_query_parameters as _validate_query_parameters,
|
||||
validate_report_path as _validate_report_path,
|
||||
)
|
||||
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
|
||||
from app.services.freight_rpa.common.credential_crypto import decrypt_credential, encrypt_credential
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.onhand_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.upload_config_validation import validate_upload_config
|
||||
|
||||
|
||||
def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None:
|
||||
"""读取并清洗字符串表单字段。"""
|
||||
value = str(data.get(field) or '').strip()
|
||||
if required and not value:
|
||||
raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field})
|
||||
return value or None
|
||||
|
||||
|
||||
def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool:
|
||||
"""读取布尔表单字段。"""
|
||||
value = data.get(field, default)
|
||||
if not isinstance(value, bool):
|
||||
raise ValidationError(f'{field} must be a boolean', details={'field': field})
|
||||
return value
|
||||
|
||||
|
||||
|
||||
def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
|
||||
"""校验连接级登录配置,不接收页面选择器或报表操作字段。"""
|
||||
value = data.get('login_config_json', {})
|
||||
if not isinstance(value, dict) or set(value) - {'auth_mode'}:
|
||||
raise ValidationError('login_config_json is invalid', code='SHIPPING.RPA_PROFILE_CONFIG_INVALID')
|
||||
auth_mode = str(value.get('auth_mode') or 'password').strip().lower()
|
||||
if auth_mode != 'password':
|
||||
raise ValidationError(
|
||||
'Only password authentication is currently supported',
|
||||
code='SHIPPING.RPA_PROFILE_CONFIG_INVALID',
|
||||
)
|
||||
return {'auth_mode': auth_mode}
|
||||
|
||||
|
||||
|
||||
|
||||
def _stored_username(profile: FreightRpaProfile) -> str | None:
|
||||
"""解密已保存的用户名,供管理端辨认账号。
|
||||
|
||||
核心逻辑:用户名是账号标识,库内仍只存密文;解密失败时返回 None,避免坏密文拖垮连接列表。
|
||||
密码不走本函数。
|
||||
|
||||
Args:
|
||||
profile: 已持久化的货代登录连接。
|
||||
|
||||
Returns:
|
||||
str | None: 用户名明文;未配置或无法解密时为 None。
|
||||
"""
|
||||
if not profile.username_ciphertext:
|
||||
return None
|
||||
try:
|
||||
return decrypt_credential(profile.username_ciphertext)
|
||||
except (ServiceUnavailableError, ValidationError):
|
||||
return None
|
||||
|
||||
|
||||
def _profile_payload(profile: FreightRpaProfile) -> dict[str, Any]:
|
||||
"""序列化系统连接。用户名明文回传,密码与密文不出现在响应中。"""
|
||||
return {
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'connector_type': profile.connector_type, 'login_url': profile.login_url,
|
||||
'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled),
|
||||
'upload_config_json': profile.upload_config_json,
|
||||
'config_version': profile.config_version,
|
||||
'username': _stored_username(profile),
|
||||
'username_masked': _mask(profile.username_ciphertext),
|
||||
'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at),
|
||||
'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _mask(ciphertext: str | None) -> str | None:
|
||||
"""密码等不可回显凭据只报告是否已配置。"""
|
||||
return 'configured' if ciphertext else None
|
||||
|
||||
|
||||
|
||||
|
||||
def list_profiles() -> list[dict[str, Any]]:
|
||||
"""列出 Profile。响应含用户名明文,不含密码与密文。"""
|
||||
return [_profile_payload(item) for item in FreightRpaProfile.query.order_by(FreightRpaProfile.profile_code).all()]
|
||||
|
||||
|
||||
def delete_profile(profile_id: int) -> None:
|
||||
"""删除未绑定库存源的错误连接配置,保留已使用连接的可追溯性。"""
|
||||
profile = db.session.get(FreightRpaProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
if FreightRpaSource.query.filter_by(rpa_profile_id=profile.id).count():
|
||||
raise ConflictError('RPA Profile is referenced by inventory sources', code='SHIPPING.RPA_PROFILE_DELETE_BLOCKED')
|
||||
db.session.delete(profile)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建或更新货代登录连接。
|
||||
|
||||
核心逻辑:用户名留空,或与已存明文相同,不重写用户名密文;密码留空则保留既有密码密文。
|
||||
只有用户名实际变更或提交了新密码时才刷新 credential_updated_at。
|
||||
"""
|
||||
profile = db.session.get(FreightRpaProfile, profile_id) if profile_id else None
|
||||
if profile_id and profile is None:
|
||||
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
profile = profile or FreightRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={})
|
||||
# 记录“非 upload_config”的既有运行时配置快照:仅当这些字段变化才递增 config_version,
|
||||
# upload_config_json 属于连接上传配置,变更不得误判库存 RPA 配置测试过期。
|
||||
prev_non_upload = (
|
||||
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
|
||||
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
|
||||
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
|
||||
) if profile_id else None
|
||||
profile.profile_code = str(_text(data, 'profile_code', required=True)).upper()
|
||||
profile.display_name = str(_text(data, 'display_name', required=True))
|
||||
profile.connector_type = str(_text(data, 'connector_type', required=True)).lower()
|
||||
profile.login_url = str(_text(data, 'login_url', required=True))
|
||||
profile.login_config_json = _validate_profile_login_config(data)
|
||||
profile.enabled = _bool(data, 'enabled', bool(profile.enabled) if profile_id else True)
|
||||
if not profile.enabled and any(source.enabled for source in profile.sources):
|
||||
raise ConflictError(
|
||||
'Disable inventory sources before disabling their RPA Profile',
|
||||
code='SHIPPING.RPA_PROFILE_DISABLE_BLOCKED',
|
||||
)
|
||||
username = _text(data, 'username')
|
||||
password = _text(data, 'password')
|
||||
# [STEP] 管理端回显的用户名会随保存再次提交;与库内明文相同则不轮换 Fernet 密文。
|
||||
username_changed = False
|
||||
if username is not None and _stored_username(profile) != username:
|
||||
profile.username_ciphertext = encrypt_credential(username)
|
||||
username_changed = True
|
||||
if password is not None:
|
||||
profile.password_ciphertext = encrypt_credential(password)
|
||||
if username_changed or password is not None:
|
||||
profile.credential_updated_at = datetime.utcnow()
|
||||
# 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。
|
||||
if 'upload_config_json' in data:
|
||||
profile.upload_config_json = validate_upload_config(profile.connector_type, data.get('upload_config_json'))
|
||||
profile.updated_by = actor_id
|
||||
if profile_id:
|
||||
now_non_upload = (
|
||||
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
|
||||
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
|
||||
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
|
||||
)
|
||||
if now_non_upload != prev_non_upload:
|
||||
profile.config_version += 1
|
||||
if not profile_id:
|
||||
profile.created_by = actor_id
|
||||
db.session.add(profile)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('RPA Profile code already exists', code='SHIPPING.RPA_PROFILE_CONFLICT') from exc
|
||||
return _profile_payload(profile)
|
||||
|
||||
|
||||
def _onhand_report_config_payload(config: FreightRpaOnhandReportConfig) -> dict[str, Any]:
|
||||
"""序列化站点一对一在手报表配置行,不透传解析方案定义。"""
|
||||
return {
|
||||
'id': config.id,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
'parsing_profile_id': config.parsing_profile_id,
|
||||
}
|
||||
|
||||
|
||||
def _source_payload(source: FreightRpaSource) -> dict[str, Any]:
|
||||
"""序列化库存站点及其是否满足正式启用前置条件。
|
||||
|
||||
s18 起报表路径/查询条件/解析方案绑定不再随站点 DTO 平铺,
|
||||
改挂在 ``onhand_report_config`` 嵌套对象(配置行不存在时为 null)。
|
||||
"""
|
||||
return {
|
||||
'id': source.id, 'source_code': source.source_code, 'display_name': source.display_name,
|
||||
'connector_type': source.connector_type, 'rpa_profile_id': source.rpa_profile_id,
|
||||
'excel_template_id': source.excel_template_id,
|
||||
'warehouse_resolution_mode': source.warehouse_resolution_mode, 'fixed_warehouse_id': source.fixed_warehouse_id,
|
||||
'onhand_report_config': (
|
||||
_onhand_report_config_payload(source.onhand_report_config)
|
||||
if source.onhand_report_config is not None else None
|
||||
),
|
||||
'snapshot_ttl_seconds': source.snapshot_ttl_seconds, 'enabled': bool(source.enabled),
|
||||
'config_version': source.config_version, 'created_at': _iso(source.created_at), 'updated_at': _iso(source.updated_at),
|
||||
'activation': get_source_activation_status(source),
|
||||
}
|
||||
|
||||
|
||||
def _validate_onhand_profile_binding(profile_id: Any) -> int | None:
|
||||
"""校验在手配置绑定的解析方案:必须已发布且 purpose='onhand';空值/0 表示解绑。
|
||||
|
||||
Args:
|
||||
profile_id: 请求载荷中的 parsing_profile_id;None/空串/0 视为解绑(与旧站点保存语义一致)。
|
||||
|
||||
Returns:
|
||||
int | None: 规整后的方案 id 或 None。
|
||||
|
||||
Raises:
|
||||
ValidationError: 方案 id 非法、不存在、未发布或用途不是 onhand
|
||||
(fail-closed,防误绑入站/出站方案,统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。
|
||||
"""
|
||||
raw = str(profile_id).strip() if profile_id is not None else ''
|
||||
if raw in {'', '0'}:
|
||||
return None
|
||||
if not raw.isdigit():
|
||||
raise ValidationError(
|
||||
'Onhand parsing profile must be published with purpose onhand',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
|
||||
)
|
||||
profile = db.session.get(FreightRpaParsingProfile, int(raw))
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'onhand':
|
||||
raise ValidationError(
|
||||
'Onhand parsing profile must be published with purpose onhand',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
|
||||
)
|
||||
return profile.id
|
||||
|
||||
|
||||
def _apply_onhand_report_config(
|
||||
source: FreightRpaSource, data: dict[str, Any], *, actor_id: int | None,
|
||||
) -> FreightRpaOnhandReportConfig:
|
||||
"""把手报表三字段写入手配置行(无则插入),不触碰站点行已删除的三列。
|
||||
|
||||
核心逻辑:先全量校验路径对象/查询条件/解析绑定,失败时不留脏会话;
|
||||
校验通过后无配置行则插入(created_by=actor),有则更新并递增 config_version。
|
||||
报表路径按原样 JSON object 存取(Driver selector 等实现细节归 Worker/模板域,
|
||||
管理端 DBS 四段路径由前端 normaliseInventoryReportPath 规整后提交)。
|
||||
|
||||
Args:
|
||||
source: 已存在的库存站点(新配置行经 inventory_source 关系级联挂载)。
|
||||
data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。
|
||||
actor_id: 当前管理员主键,仅写审计字段。
|
||||
|
||||
Returns:
|
||||
FreightRpaOnhandReportConfig: 已写入(尚未提交)的配置行。
|
||||
"""
|
||||
# [STEP 1] 全量校验先行,任何失败都不会留下半写的配置行。
|
||||
report_path = _json_object(data, 'report_path_json')
|
||||
# DBS 四段路径按原样 JSON object 存取(前端 normaliseInventoryReportPath 规整);
|
||||
# 非 DBS(Crane)站点不得误填 DBS 报表路径(fail-closed,与列搬迁前契约一致)。
|
||||
if source.connector_type != 'dbs' and report_path:
|
||||
raise ValidationError(
|
||||
'Only DBS inventory sources can define report_path_json',
|
||||
code='SHIPPING.ONHAND_SOURCE_CONFIG_INVALID',
|
||||
)
|
||||
parameters = _validate_query_parameters(data)
|
||||
parsing_profile_id = _validate_onhand_profile_binding(data.get('parsing_profile_id'))
|
||||
# [STEP 2] 校验通过后写配置行:无则插入,有则更新并递增 config_version。
|
||||
config = source.onhand_report_config
|
||||
if config is None:
|
||||
config = FreightRpaOnhandReportConfig(source=source)
|
||||
config.created_by = actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.report_path_json = report_path
|
||||
config.query_parameters_json = parameters
|
||||
config.parsing_profile_id = parsing_profile_id
|
||||
config.updated_by = actor_id
|
||||
return config
|
||||
|
||||
|
||||
def save_onhand_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""保存站点一对一在手报表配置:没有配置行时插入,有则更新并递增该行 config_version。
|
||||
|
||||
核心逻辑:委托 _apply_onhand_report_config 校验并写行;启用中的站点借保存拆掉
|
||||
启用门禁(缺解析绑定/模板)时由 assert_onhand_source_can_enable fail-closed 拒绝。
|
||||
|
||||
Args:
|
||||
source_id: 库存站点主键,必须已存在。
|
||||
data: 含 report_path_json / query_parameters_json / parsing_profile_id 的载荷。
|
||||
actor_id: 当前管理员主键,仅写审计字段。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: 配置行 DTO(id / report_path_json / query_parameters_json / parsing_profile_id)。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 站点不存在。
|
||||
ValidationError: 解析方案不存在/未发布/purpose 不是 onhand,或启用中站点门禁被拆。
|
||||
"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
config = _apply_onhand_report_config(source, data, actor_id=actor_id)
|
||||
# 启用中的站点不得借配置保存解绑解析方案(excel_template 缺失同样拒绝)。
|
||||
assert_onhand_source_can_enable(source)
|
||||
db.session.commit()
|
||||
return _onhand_report_config_payload(config)
|
||||
|
||||
|
||||
def assert_onhand_source_can_enable(source: FreightRpaSource) -> None:
|
||||
"""启用中的库存站点必须已有在手配置行(含解析方案绑定)与发货模板。
|
||||
|
||||
【AI 触发时机】:保存站点(save_source 载荷含 enabled=true 或保留启用态)、
|
||||
保存在手配置(save_onhand_report_config 拆绑定前)时调用;
|
||||
PostgreSQL CHECK 不能跨表,解析方案存在性只能由服务层执行。
|
||||
|
||||
Args:
|
||||
source: 站点对象(可为未提交的暂态行,配置行经 onhand_report_config 关系读取)。
|
||||
|
||||
Returns:
|
||||
None: 门禁通过(站点未启用时恒通过)。
|
||||
|
||||
Raises:
|
||||
ValidationError: enabled 为真但缺配置行、配置行未绑解析方案或站点未绑模板,
|
||||
统一 code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED'。
|
||||
"""
|
||||
if not source.enabled:
|
||||
return
|
||||
config = source.onhand_report_config
|
||||
if config is None or not config.parsing_profile_id or not source.excel_template_id:
|
||||
raise ValidationError(
|
||||
'Enabled inventory source requires onhand report config, parsing profile and excel template',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
|
||||
)
|
||||
|
||||
|
||||
def _binding_snapshot(source: FreightRpaSource) -> dict[str, Any]:
|
||||
"""冻结解析绑定变更的最小站点上下文,避免审计依赖后续可变主数据。
|
||||
|
||||
s18 起解析绑定挂在 onhand_report_config 配置行上,快照同样取自配置行。
|
||||
"""
|
||||
config = source.onhand_report_config
|
||||
return {
|
||||
'source_id': source.id,
|
||||
'source_code': source.source_code,
|
||||
'enabled': bool(source.enabled),
|
||||
'parsing_profile_id': config.parsing_profile_id if config is not None else None,
|
||||
'parsing_profile_checksum': (
|
||||
config.parsing_profile.checksum
|
||||
if config is not None and config.parsing_profile is not None else None
|
||||
),
|
||||
'excel_template_id': source.excel_template_id,
|
||||
'config_version': source.config_version,
|
||||
}
|
||||
|
||||
|
||||
def _validate_source_parsing_binding(source: FreightRpaSource, profile: FreightRpaParsingProfile) -> None:
|
||||
"""校验站点可直接采用的已发布方案与当前发货模板字段契约;启用中的站点同样允许更换解析绑定。"""
|
||||
if profile.status != 'published':
|
||||
raise ValidationError('Published parsing profile is required', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {}
|
||||
if not mapping:
|
||||
raise ValidationError('Published parsing profile is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
|
||||
template = source.excel_template
|
||||
if template is None:
|
||||
return
|
||||
if template.status != 'published':
|
||||
raise ValidationError('Published excel template is required', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
|
||||
template_definition = template.definition_json if isinstance(template.definition_json, dict) else {}
|
||||
template_mappings = template_definition.get('mappings') if isinstance(template_definition.get('mappings'), list) else []
|
||||
missing_fields = sorted({
|
||||
str(item.get('source_key') or '')
|
||||
for item in template_mappings
|
||||
if isinstance(item, dict)
|
||||
and item.get('source_kind') == 'inventory_field'
|
||||
and str(item.get('source_key') or '') not in mapping
|
||||
})
|
||||
if missing_fields:
|
||||
raise ValidationError(
|
||||
'Parsing profile does not provide all inventory fields required by the excel template',
|
||||
code='SHIPPING.ONHAND_SOURCE_BINDING_TEMPLATE_INVALID', details={'inventory_field_ids': missing_fields},
|
||||
)
|
||||
|
||||
|
||||
def bind_source_parsing_profile(
|
||||
source_ids: list[int], profile_id: int, *, actor_id: int | None, reason: str | None = None, operation: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""为一个或多个库存站点原子绑定已发布解析方案并写入追加式审计(含已启用站点)。
|
||||
|
||||
Args:
|
||||
source_ids: 待绑定的库存站点主键,不能为空且不得重复。
|
||||
profile_id: 必须为已发布解析方案主键。
|
||||
actor_id: 当前管理员主键,仅写入审计。
|
||||
reason: 可选的补充说明;未填写时由系统记录本次直接或批量绑定动作。
|
||||
operation: 审计操作类型,仅允许 ``direct`` 或 ``bulk``。
|
||||
|
||||
Returns:
|
||||
list[dict[str, Any]]: 已更新站点的管理端 DTO。
|
||||
|
||||
Raises:
|
||||
ValidationError: 任一站点、方案或模板字段契约不合法;批量请求不会部分写入。
|
||||
ConflictError: 试图变更已启用站点的正式解析方案。
|
||||
"""
|
||||
try:
|
||||
normalized_ids = sorted({int(item) for item in source_ids if int(item) > 0})
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM') from exc
|
||||
if not normalized_ids or len(normalized_ids) != len(source_ids):
|
||||
raise ValidationError('source_ids must be a non-empty unique integer list', code='VALIDATION.INVALID_PARAM')
|
||||
if operation not in {'direct', 'bulk'}:
|
||||
raise ValidationError('Binding operation is invalid', code='VALIDATION.INVALID_PARAM')
|
||||
normalized_reason = str(reason or '').strip()
|
||||
if len(normalized_reason) > 500:
|
||||
raise ValidationError('Binding note must not exceed 500 characters', code='VALIDATION.INVALID_PARAM')
|
||||
# 审计必须保留可读动作,但不应把技术审计字段变成管理员的额外填写负担。
|
||||
if not normalized_reason:
|
||||
normalized_reason = '管理员直接绑定已发布解析方案' if operation == 'direct' else '管理员批量绑定已发布解析方案'
|
||||
try:
|
||||
normalized_profile_id = int(profile_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('parsing_profile_id is required', code='VALIDATION.INVALID_PARAM') from exc
|
||||
profile = db.session.get(FreightRpaParsingProfile, normalized_profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
sources = [db.session.get(FreightRpaSource, source_id) for source_id in normalized_ids]
|
||||
if any(source is None for source in sources):
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
typed_sources = [source for source in sources if source is not None]
|
||||
# [STEP 1] 全量预检后才变更,避免多站点操作出现部分绑定。
|
||||
for source in typed_sources:
|
||||
_validate_source_parsing_binding(source, profile)
|
||||
for source in typed_sources:
|
||||
before = _binding_snapshot(source)
|
||||
# s18 起解析绑定写 onhand_report_config 配置行(无则插入),站点行不再承载该外键。
|
||||
config = source.onhand_report_config
|
||||
previous_profile_id = config.parsing_profile_id if config is not None else None
|
||||
if config is None:
|
||||
config = FreightRpaOnhandReportConfig(source=source)
|
||||
config.created_by = actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.parsing_profile_id = profile.id
|
||||
config.updated_by = actor_id
|
||||
source.updated_by = actor_id
|
||||
# 站点 config_version 仍随绑定递增:配置测试锁定版本与运行期失效判断依赖它。
|
||||
source.config_version += 1
|
||||
db.session.flush()
|
||||
db.session.add(FreightRpaSourceParsingBindingAudit(
|
||||
source_id=source.id, previous_parsing_profile_id=previous_profile_id,
|
||||
parsing_profile_id=config.parsing_profile_id, operation=operation, reason=normalized_reason, actor_id=actor_id,
|
||||
source_config_version_before=before['config_version'], source_config_version_after=source.config_version,
|
||||
before_snapshot_json=before, after_snapshot_json=_binding_snapshot(source),
|
||||
))
|
||||
db.session.commit()
|
||||
return [_source_payload(source) for source in typed_sources]
|
||||
|
||||
|
||||
def get_source_parsing_binding_audits(source_id: int) -> list[dict[str, Any]]:
|
||||
"""读取库存站点解析绑定审计,仅返回配置快照和操作者标识。"""
|
||||
if db.session.get(FreightRpaSource, source_id) is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
rows = FreightRpaSourceParsingBindingAudit.query.filter_by(
|
||||
source_id=source_id,
|
||||
).order_by(FreightRpaSourceParsingBindingAudit.id.desc()).all()
|
||||
return [{
|
||||
'id': row.id, 'operation': row.operation, 'reason': row.reason, 'actor_id': row.actor_id,
|
||||
'previous_parsing_profile_id': row.previous_parsing_profile_id, 'parsing_profile_id': row.parsing_profile_id,
|
||||
'source_config_version_before': row.source_config_version_before,
|
||||
'source_config_version_after': row.source_config_version_after,
|
||||
'before': row.before_snapshot_json, 'after': row.after_snapshot_json,
|
||||
'created_at': row.created_at.isoformat() if row.created_at else None,
|
||||
} for row in rows]
|
||||
|
||||
|
||||
def list_sources() -> list[dict[str, Any]]:
|
||||
"""列出库存源及其稳定业务配置。"""
|
||||
return [_source_payload(item) for item in FreightRpaSource.query.order_by(FreightRpaSource.source_code).all()]
|
||||
|
||||
|
||||
def delete_source(source_id: int) -> None:
|
||||
"""删除未参与映射、快照或规则的错误库存源,避免破坏历史路由身份。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
source_code = str(source.source_code or '').strip().upper()
|
||||
has_mapping = FreightRpaOnhandExternalMapping.query.filter_by(source_id=source.id).count() > 0
|
||||
has_snapshot = FreightRpaOnhandReportFile.query.filter_by(source_code=source_code).count() > 0
|
||||
has_rule = any(
|
||||
source_code in {str(code).strip().upper() for code in candidates}
|
||||
for rule in FreightRpaOnhandRoutingRule.query.all()
|
||||
for candidates in [(rule.action_payload_json or {}).get('source_codes', [])]
|
||||
if isinstance(candidates, list)
|
||||
)
|
||||
has_task = db.session.query(ShippingNoticeLine.id).filter(
|
||||
ShippingNoticeLine.inventory_source_code == source_code,
|
||||
).first() is not None or db.session.query(ShippingNoticeLineOnhandMatch.id).filter(
|
||||
ShippingNoticeLineOnhandMatch.source_code == source_code,
|
||||
).first() is not None
|
||||
has_export_run = any(
|
||||
source_code in {str(code).strip().upper() for code in source_codes}
|
||||
for run in ScheduleRun.query.all()
|
||||
for source_codes in [(run.api_request_json or {}).get('source_codes', [])]
|
||||
if isinstance(source_codes, list)
|
||||
)
|
||||
if has_mapping or has_snapshot or has_rule or has_task or has_export_run:
|
||||
raise ConflictError('Inventory Source has operational references', code='SHIPPING.ONHAND_SOURCE_DELETE_BLOCKED')
|
||||
db.session.delete(source)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _template_validation_missing(source: FreightRpaSource) -> list[str]:
|
||||
"""确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。"""
|
||||
template = source.excel_template
|
||||
# s18 起解析方案绑定取自 onhand_report_config 配置行。
|
||||
config = source.onhand_report_config
|
||||
profile = config.parsing_profile if config is not None else None
|
||||
if template is None or profile is None:
|
||||
return []
|
||||
definition = template.definition_json if isinstance(template.definition_json, dict) else {}
|
||||
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
|
||||
profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
inventory_fields = {str(field_id) for field_id in (profile_definition.get('field_mapping') or {}).keys()}
|
||||
invalid = any(
|
||||
isinstance(item, dict)
|
||||
and item.get('source_kind') == 'inventory_field'
|
||||
and str(item.get('source_key') or '') not in inventory_fields
|
||||
for item in mappings
|
||||
)
|
||||
return ['template_validation'] if not mappings or invalid else []
|
||||
|
||||
|
||||
def _activation_check(
|
||||
code: str, *, passed: bool, action: str, evidence: dict[str, Any], status: str | None = None,
|
||||
blocking: bool | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""构造单项启用门禁结果,确保管理端只展示服务端已判定的业务事实。"""
|
||||
return {
|
||||
'code': code,
|
||||
'status': status or ('passed' if passed else 'pending'),
|
||||
'blocking': not passed if blocking is None else blocking,
|
||||
'action': action,
|
||||
'evidence': evidence,
|
||||
}
|
||||
|
||||
|
||||
def _source_activation_checks(source: FreightRpaSource) -> list[dict[str, Any]]:
|
||||
"""构建库存站点启用硬门槛:可用连接、已发布解析方案、已绑定已发布发货模板及字段契约。
|
||||
|
||||
测试导出不再参与启用门禁;启停由管理员显式开关完成。
|
||||
"""
|
||||
profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled)
|
||||
# s18 起解析方案绑定取自 onhand_report_config 配置行;配置行缺失即解析门禁未就绪。
|
||||
config = source.onhand_report_config
|
||||
parsing_profile = config.parsing_profile if config is not None else None
|
||||
parsing_ready = parsing_profile is not None and parsing_profile.status == 'published'
|
||||
template_ready = source.excel_template is not None and source.excel_template.status == 'published'
|
||||
template_invalid = bool(_template_validation_missing(source)) if template_ready and parsing_ready else False
|
||||
return [
|
||||
_activation_check(
|
||||
'rpa_profile', passed=profile_ready, action='configure_connection',
|
||||
evidence={'profile_id': source.rpa_profile_id, 'enabled': profile_ready},
|
||||
),
|
||||
_activation_check(
|
||||
'parsing_profile', passed=parsing_ready, action='configure_parsing_profile',
|
||||
evidence={'profile_id': parsing_profile.id if parsing_profile is not None else None, 'published': parsing_ready},
|
||||
),
|
||||
_activation_check(
|
||||
'excel_template', passed=template_ready, action='configure_excel_template',
|
||||
evidence={'template_id': source.excel_template_id, 'published': template_ready},
|
||||
),
|
||||
_activation_check(
|
||||
'template_validation', passed=not template_invalid,
|
||||
action='configure_excel_template', evidence={}, blocking=template_invalid,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def get_source_activation_status(source: FreightRpaSource) -> dict[str, Any]:
|
||||
"""返回库存站点启用硬门槛的结构化结果。
|
||||
|
||||
Args:
|
||||
source: 已持久化的库存站点,关联配置由当前数据库事务提供。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: ``checks`` 为前端唯一的检查真相;``ready`` 为启用结论;
|
||||
``missing_requirements`` 是由 checks 派生的紧凑摘要,供现有调用方读取。
|
||||
"""
|
||||
checks = _source_activation_checks(source)
|
||||
missing = [item['code'] for item in checks if item['blocking']]
|
||||
return {
|
||||
'ready': not missing,
|
||||
'checks': checks,
|
||||
'missing_requirements': missing,
|
||||
}
|
||||
|
||||
|
||||
def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""启用已满足硬门槛的库存站点;未通过任一前置条件时保持停用。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
status = get_source_activation_status(source)
|
||||
if not status['ready']:
|
||||
raise ConflictError(
|
||||
'Inventory Source is not ready for activation',
|
||||
code='SHIPPING.ONHAND_SOURCE_ACTIVATION_BLOCKED',
|
||||
details=status,
|
||||
)
|
||||
source.enabled = True
|
||||
source.updated_by = actor_id
|
||||
db.session.commit()
|
||||
return _source_payload(source)
|
||||
|
||||
|
||||
def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""停用库存站点,保留其解析方案和历史运行审计。"""
|
||||
source = db.session.get(FreightRpaSource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
source.enabled = False
|
||||
source.updated_by = actor_id
|
||||
db.session.commit()
|
||||
return _source_payload(source)
|
||||
|
||||
|
||||
def save_source(
|
||||
data: dict[str, Any], *, actor_id: int | None, source_id: int | None = None,
|
||||
allow_enable_transition: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""保存库存站点基础配置;管理 API 不允许通过普通保存直接启用站点。
|
||||
|
||||
s18 起站点头部仅编辑 source_code / display_name / connector_type / rpa_profile_id /
|
||||
excel_template_id / 仓库模式 / snapshot_ttl_seconds;报表路径、查询条件与解析方案
|
||||
绑定经载荷内嵌的 ``onhand_report_config`` 对象写入配置行(与独立保存同一校验路径)。
|
||||
"""
|
||||
source = db.session.get(FreightRpaSource, source_id) if source_id else None
|
||||
if source_id and source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
try:
|
||||
profile_id = int(data.get('rpa_profile_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('rpa_profile_id is required') from exc
|
||||
profile = db.session.get(FreightRpaProfile, profile_id)
|
||||
if profile is None:
|
||||
raise ValidationError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
requested_enabled = _bool(data, 'enabled', bool(source.enabled) if source_id else False)
|
||||
if not allow_enable_transition:
|
||||
# 普通保存不承担状态切换:首次一律停用,已启用站点保留当前状态。
|
||||
enabled = bool(source.enabled) if source is not None else False
|
||||
else:
|
||||
enabled = requested_enabled
|
||||
if enabled and not profile.enabled:
|
||||
raise ValidationError(
|
||||
'Enabled Inventory Source requires an enabled RPA Profile',
|
||||
code='SHIPPING.RPA_PROFILE_DISABLED',
|
||||
)
|
||||
excel_template_id = data.get('excel_template_id')
|
||||
excel_template = db.session.get(ShippingExcelTemplate, int(excel_template_id)) if str(excel_template_id or '').isdigit() else None
|
||||
if excel_template_id not in (None, '', 0, '0') and (excel_template is None or excel_template.status != 'published'):
|
||||
raise ValidationError('excel_template_id must reference a published template', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
|
||||
is_new = source is None
|
||||
source = source or FreightRpaSource(
|
||||
source_code='', display_name='', connector_type='', warehouse_resolution_mode='fixed',
|
||||
)
|
||||
source.source_code = str(_text(data, 'source_code', required=True)).upper()
|
||||
source.display_name = str(_text(data, 'display_name', required=True))
|
||||
source.connector_type = str(_text(data, 'connector_type', required=True)).lower()
|
||||
source.rpa_profile = profile
|
||||
source.excel_template = excel_template
|
||||
source.warehouse_resolution_mode = str(_text(data, 'warehouse_resolution_mode', required=True)).lower()
|
||||
source.fixed_warehouse_id = _text(data, 'fixed_warehouse_id')
|
||||
source.snapshot_ttl_seconds = int(data.get('snapshot_ttl_seconds') or 86400)
|
||||
source.enabled = enabled
|
||||
source.updated_by = actor_id
|
||||
if source_id:
|
||||
source.config_version += 1
|
||||
if is_new:
|
||||
source.created_by = actor_id
|
||||
db.session.add(source)
|
||||
# [STEP 1] 启用门禁先行:缺模板在写库前给出可解释错误,避免撞站点行 CHECK 的 IntegrityError
|
||||
# (模板缺失复用 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED,不新造码)。
|
||||
if enabled and excel_template is None:
|
||||
raise ValidationError(
|
||||
'published excel_template_id is required',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED',
|
||||
)
|
||||
try:
|
||||
# flush 让 excel_template_id / 新行主键先行落位,后续门禁读取规整后的外键。
|
||||
db.session.flush()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc
|
||||
# [STEP 2] 载荷内嵌 onhand_report_config 时与独立保存走同一校验/写行路径(无则插入配置行)。
|
||||
config_data = data.get('onhand_report_config')
|
||||
if isinstance(config_data, dict):
|
||||
_apply_onhand_report_config(source, config_data, actor_id=actor_id)
|
||||
# [STEP 3] 启用门禁复核(缺配置行/解析绑定/模板统一 SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED)。
|
||||
if enabled:
|
||||
assert_onhand_source_can_enable(source)
|
||||
validate_source_profile(source, profile)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.ONHAND_SOURCE_INVALID') from exc
|
||||
return _source_payload(source)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,391 @@
|
||||
"""
|
||||
services/admin/shipping_onhand_admin_service.py
|
||||
|
||||
用途:在手域管理——库存快照只读、导出运行记录、路由规则、外部仓库映射。
|
||||
依赖:db、FreightRpaOnhandReportFile / FreightRpaOnhandRoutingRule /
|
||||
FreightRpaOnhandExternalMapping、order_schema、routing_operators、ALLOWED_ACTIONS。
|
||||
逻辑:admin_freight_rpa 的 snapshots / export-records / rules / external-mappings 委托本服务;
|
||||
登录连接与来源站点见 freight_rpa_source_admin_service。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FreightRpaOnhandExternalMapping,
|
||||
FreightRpaOnhandReportFile,
|
||||
FreightRpaOnhandRoutingRule,
|
||||
FreightRpaOnhandRoutingRuleCondition,
|
||||
FreightRpaOnhandRoutingRuleVersion,
|
||||
FreightRpaSource,
|
||||
ScheduleRun,
|
||||
ScheduleTask,
|
||||
ShippingOrderField,
|
||||
)
|
||||
from app.services.admin.freight_rpa_form_utils import iso as _iso
|
||||
from app.services.shipping_notice.onhand_routing_engine import ALLOWED_ACTIONS
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS
|
||||
|
||||
|
||||
def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None:
|
||||
"""读取并清洗字符串表单字段。"""
|
||||
value = str(data.get(field) or '').strip()
|
||||
if required and not value:
|
||||
raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field})
|
||||
return value or None
|
||||
|
||||
|
||||
def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool:
|
||||
"""读取布尔表单字段。"""
|
||||
value = data.get(field, default)
|
||||
if not isinstance(value, bool):
|
||||
raise ValidationError(f'{field} must be a boolean', details={'field': field})
|
||||
return value
|
||||
|
||||
|
||||
def _snapshot_payload(snapshot: FreightRpaOnhandReportFile) -> dict[str, Any]:
|
||||
"""投影库存快照的管理端只读行,不暴露存储路径或库存明细。"""
|
||||
return {
|
||||
'id': snapshot.id, 'inventory_file_no': snapshot.onhand_file_no,
|
||||
'source_code': snapshot.source_code, 'warehouse_id': snapshot.warehouse_id,
|
||||
'snapshot_status': snapshot.snapshot_status, 'identity_status': snapshot.identity_status,
|
||||
'line_count': snapshot.line_count, 'share_mode': snapshot.share_mode,
|
||||
'exported_at': _iso(snapshot.exported_at), 'expires_at': _iso(snapshot.expires_at),
|
||||
'rpa_run_no': snapshot.rpa_run_no, 'schedule_run_id': snapshot.schedule_run_id,
|
||||
'source_file_name': snapshot.source_file_name, 'created_at': _iso(snapshot.created_at),
|
||||
'download_available': bool(snapshot.storage_path and not str(snapshot.storage_path).startswith('failed://')),
|
||||
'error_message': (snapshot.schema_preview_json or {}).get('error') if snapshot.snapshot_status == 'failed' else None,
|
||||
}
|
||||
|
||||
|
||||
def list_snapshots(*, limit: int = 100) -> list[dict[str, Any]]:
|
||||
"""列出最新库存快照,供管理员确认当前可用的库存文件。"""
|
||||
rows = FreightRpaOnhandReportFile.query.order_by(
|
||||
FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc(),
|
||||
).limit(max(1, min(limit, 200))).all()
|
||||
return [_snapshot_payload(row) for row in rows]
|
||||
|
||||
|
||||
def get_snapshot_download(snapshot_id: int) -> tuple[str, str]:
|
||||
"""返回管理员可下载的库存快照路径及安全文件名。
|
||||
|
||||
Args:
|
||||
snapshot_id: 库存快照主键。
|
||||
|
||||
Returns:
|
||||
本地托管文件绝对路径和面向下载的文件名。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 快照不存在或托管文件已不存在。
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
snapshot = db.session.get(FreightRpaOnhandReportFile, snapshot_id)
|
||||
if snapshot is None:
|
||||
raise NotFoundError('Inventory snapshot not found', code='SHIPPING.ONHAND_SNAPSHOT_NOT_FOUND')
|
||||
path = Path(str(snapshot.storage_path or '')).resolve()
|
||||
if not str(snapshot.storage_path or '') or str(snapshot.storage_path).startswith('failed://') or not path.is_file():
|
||||
raise NotFoundError('Inventory snapshot file not found', code='SHIPPING.ONHAND_SNAPSHOT_FILE_NOT_FOUND')
|
||||
filename = str(snapshot.source_file_name or f'{snapshot.onhand_file_no}{path.suffix or ".xlsx"}')
|
||||
return str(path), filename
|
||||
|
||||
|
||||
def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]:
|
||||
"""列出 RPA 导出记录,合并已归档文件与排程失败/跳过结果。"""
|
||||
file_rows = FreightRpaOnhandReportFile.query.filter(
|
||||
FreightRpaOnhandReportFile.rpa_run_no.is_not(None),
|
||||
).order_by(
|
||||
FreightRpaOnhandReportFile.exported_at.desc(), FreightRpaOnhandReportFile.id.desc(),
|
||||
).limit(max(1, min(limit, 200))).all()
|
||||
records = [_snapshot_payload(row) for row in file_rows]
|
||||
known_identities = {
|
||||
(str(item.get('rpa_run_no') or ''), str(item.get('source_code') or ''), str(item.get('warehouse_id') or ''))
|
||||
for item in records
|
||||
}
|
||||
|
||||
# 失败或跳过的 RPA 执行不会生成库存文件,必须从 ScheduleRun 补齐审计记录。
|
||||
schedule_runs = ScheduleRun.query.join(ScheduleTask).filter(
|
||||
ScheduleTask.platform_api_path == 'freight-rpa-onhand',
|
||||
).order_by(ScheduleRun.created_at.desc()).limit(max(1, min(limit, 200))).all()
|
||||
for run in schedule_runs:
|
||||
response = run.api_response_json if isinstance(run.api_response_json, dict) else {}
|
||||
request_data = run.api_request_json if isinstance(run.api_request_json, dict) else {}
|
||||
run_no = str(response.get('run_no') or request_data.get('run_no') or run.run_no or '').strip()
|
||||
items: list[tuple[str, dict[str, Any]]] = []
|
||||
for status, key in (('skipped', 'skipped'), ('failed', 'failed')):
|
||||
for item in response.get(key) if isinstance(response.get(key), list) else []:
|
||||
if isinstance(item, dict):
|
||||
items.append((status, item))
|
||||
if not items and run.status in {'queued', 'running'}:
|
||||
pending = (run.response_summary_json or {}).get('pending_details', [])
|
||||
for item in pending if isinstance(pending, list) else []:
|
||||
if isinstance(item, dict):
|
||||
items.append(('awaiting_rpa', item))
|
||||
if not items and run.status in {'failed', 'partial_failed'}:
|
||||
for source_code in request_data.get('source_codes') if isinstance(request_data.get('source_codes'), list) else []:
|
||||
items.append(('failed', {'source_code': source_code, 'error_message': run.error_message}))
|
||||
for status, item in items:
|
||||
source_code = str(item.get('source_code') or '').strip()
|
||||
warehouse_id = str(item.get('warehouse_id') or '').strip()
|
||||
identity = (run_no, source_code, warehouse_id)
|
||||
if identity in known_identities:
|
||||
continue
|
||||
known_identities.add(identity)
|
||||
records.append({
|
||||
'id': f'schedule-{run.id}-{status}-{source_code}-{warehouse_id}',
|
||||
'inventory_file_no': None,
|
||||
'source_code': source_code or None,
|
||||
'warehouse_id': warehouse_id or None,
|
||||
'snapshot_status': status,
|
||||
'export_status': status,
|
||||
'identity_status': None,
|
||||
'line_count': 0,
|
||||
'share_mode': None,
|
||||
'exported_at': _iso(run.finished_at or run.created_at),
|
||||
'expires_at': None,
|
||||
'rpa_run_no': run_no or None,
|
||||
'schedule_run_id': run.id,
|
||||
'source_file_name': None,
|
||||
'created_at': _iso(run.created_at),
|
||||
'error_message': str(item.get('error_message') or item.get('error') or run.error_message or '')[:500] or None,
|
||||
})
|
||||
records.sort(key=lambda item: str(item.get('exported_at') or item.get('created_at') or ''), reverse=True)
|
||||
return records[:max(1, min(limit, 200))]
|
||||
|
||||
|
||||
def _rule_payload(rule: FreightRpaOnhandRoutingRule) -> dict[str, Any]:
|
||||
return {
|
||||
'id': rule.id, 'rule_code': rule.rule_code, 'rule_name': rule.rule_name, 'scope': rule.scope,
|
||||
'priority': rule.priority, 'match_mode': rule.match_mode, 'status': rule.status,
|
||||
'action_type': rule.action_type, 'action_payload_json': rule.action_payload_json or {}, 'version': rule.version,
|
||||
'conditions': [{'source_kind': c.source_kind, 'order_field_id': c.order_field_id,
|
||||
'operator': c.operator, 'expected_value_json': c.expected_value_json,
|
||||
'condition_group': c.condition_group, 'sequence': c.sequence} for c in rule.conditions],
|
||||
}
|
||||
|
||||
|
||||
def _validate_rule_condition_expected(operator: str, value: Any) -> Any:
|
||||
"""按匹配符号规范化期望值,避免自由 JSON 在运行期才暴露配置错误。"""
|
||||
if operator in {'is_empty', 'is_not_empty'}:
|
||||
return None
|
||||
if operator in {'in', 'not_in'}:
|
||||
if not isinstance(value, list):
|
||||
raise ValidationError('List operator requires a string list', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
normalized = [str(item).strip() for item in value if str(item).strip()]
|
||||
if not normalized:
|
||||
raise ValidationError('List operator requires at least one value', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
return normalized
|
||||
if operator in {'numeric_length', 'string_length'}:
|
||||
try:
|
||||
length = int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Length operator requires an integer', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID') from exc
|
||||
if length < 0:
|
||||
raise ValidationError('Length must not be negative', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
return length
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise ValidationError('Routing condition requires an expected value', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
return value.strip()
|
||||
|
||||
|
||||
def list_rules() -> list[dict[str, Any]]:
|
||||
"""列出规则及条件,用于草稿编辑和已发布规则查看。"""
|
||||
return [_rule_payload(item) for item in FreightRpaOnhandRoutingRule.query.order_by(FreightRpaOnhandRoutingRule.priority.desc()).all()]
|
||||
|
||||
|
||||
def delete_draft_rule(rule_id: int) -> None:
|
||||
"""删除从未发布的草稿规则;发布过的规则必须归档以保留审计定义。"""
|
||||
rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
|
||||
if rule is None:
|
||||
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
|
||||
if rule.status != 'draft':
|
||||
raise ConflictError('Only draft routing rules can be deleted', code='SHIPPING.ONHAND_RULE_DELETE_BLOCKED')
|
||||
db.session.delete(rule)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def retire_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""归档已发布规则,使其不再参与新路由,同时保留已发布版本。"""
|
||||
rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
|
||||
if rule is None:
|
||||
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
|
||||
if rule.status != 'published':
|
||||
raise ConflictError('Only published routing rules can be retired', code='SHIPPING.ONHAND_RULE_RETIRE_INVALID')
|
||||
rule.status = 'retired'
|
||||
rule.updated_by = actor_id
|
||||
db.session.commit()
|
||||
return _rule_payload(rule)
|
||||
|
||||
|
||||
def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None = None) -> dict[str, Any]:
|
||||
"""保存草稿规则;发布规则必须以新版本创建,避免篡改历史定义。"""
|
||||
if rule_id:
|
||||
current = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
|
||||
if current is None:
|
||||
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
|
||||
if current.status != 'draft':
|
||||
raise ConflictError('Only draft routing rules can be updated', code='SHIPPING.ONHAND_RULE_IMMUTABLE')
|
||||
rule = current if rule_id else FreightRpaOnhandRoutingRule(
|
||||
rule_code='', rule_name='', scope='', action_type='', action_payload_json={}
|
||||
)
|
||||
rule.rule_code = str(_text(data, 'rule_code', required=True)).upper()
|
||||
rule.rule_name = str(_text(data, 'rule_name', required=True))
|
||||
rule.scope = str(_text(data, 'scope', required=True)).lower()
|
||||
rule.priority = int(data.get('priority') or 0)
|
||||
rule.match_mode = str(data.get('match_mode') or 'all').lower()
|
||||
rule.status = 'draft'
|
||||
rule.action_type = str(_text(data, 'action_type', required=True)).lower()
|
||||
rule.action_payload_json = data.get('action_payload_json') if isinstance(data.get('action_payload_json'), dict) else {}
|
||||
rule.version = int(data.get('version') or 1)
|
||||
if not rule_id:
|
||||
rule.created_by = actor_id
|
||||
rule.updated_by = actor_id
|
||||
if rule.action_type not in ALLOWED_ACTIONS or rule.scope not in {'task', 'line'} or rule.match_mode not in {'all', 'any'}:
|
||||
raise ValidationError('Invalid routing rule metadata', code='SHIPPING.ONHAND_RULE_INVALID')
|
||||
conditions = data.get('conditions')
|
||||
if not isinstance(conditions, list) or not conditions:
|
||||
raise ValidationError('Routing rule requires conditions', code='SHIPPING.ONHAND_RULE_CONDITIONS_REQUIRED')
|
||||
# 草稿更新在同一版本内替换条件;发布后不可原地修改。
|
||||
if rule_id:
|
||||
db.session.query(FreightRpaOnhandRoutingRuleCondition).filter_by(rule_id=rule.id).delete(
|
||||
synchronize_session=False
|
||||
)
|
||||
db.session.flush()
|
||||
db.session.expire(rule, ['conditions'])
|
||||
for index, item in enumerate(conditions, start=1):
|
||||
if not isinstance(item, dict) or item.get('operator') not in ALLOWED_OPERATORS:
|
||||
raise ValidationError('Routing rule condition is not allowed', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
source_kind = str(item.get('source_kind') or 'order_field')
|
||||
order_field_id = str(item.get('order_field_id') or '') or None
|
||||
field = db.session.get(ShippingOrderField, order_field_id) if order_field_id else None
|
||||
if source_kind == 'order_field':
|
||||
if field is None or field.status != 'active' or field.scope != rule.scope.replace('task', 'header'):
|
||||
raise ValidationError('Routing order field is invalid for rule scope', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
published_fields = {
|
||||
str(config.get('field_id'))
|
||||
for config in order_schema_service.get_published_contract()['fields']
|
||||
if config.get('scope') == field.scope
|
||||
}
|
||||
if field.id not in published_fields:
|
||||
raise ValidationError('Routing order field is not published', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
else:
|
||||
raise ValidationError('Routing conditions must use a published order field', code='SHIPPING.ONHAND_RULE_CONDITION_INVALID')
|
||||
operator = str(item['operator'])
|
||||
rule.conditions.append(FreightRpaOnhandRoutingRuleCondition(
|
||||
condition_group=int(item.get('condition_group') or 1), source_kind=source_kind,
|
||||
order_field_id=order_field_id,
|
||||
operator=operator, expected_value_json=_validate_rule_condition_expected(
|
||||
operator, item.get('expected_value_json'),
|
||||
), sequence=index,
|
||||
))
|
||||
if not rule_id:
|
||||
db.session.add(rule)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Routing rule code and version already exist', code='SHIPPING.ONHAND_RULE_CONFLICT') from exc
|
||||
return _rule_payload(rule)
|
||||
|
||||
|
||||
def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""发布草稿并写入不可变规则定义快照。
|
||||
|
||||
路由规则只声明库存源候选,允许引用已配置但暂时停用的 Source;实际
|
||||
库存 RPA 运行时仍由库存源门禁拒绝停用 Source,避免发布配置误触发 RPA。
|
||||
"""
|
||||
rule = db.session.get(FreightRpaOnhandRoutingRule, rule_id)
|
||||
if rule is None:
|
||||
raise NotFoundError('Routing rule not found', code='SHIPPING.ONHAND_RULE_NOT_FOUND')
|
||||
if rule.status != 'draft':
|
||||
raise ConflictError('Only draft routing rules can be published', code='SHIPPING.ONHAND_RULE_PUBLISH_INVALID')
|
||||
if rule.action_type in {'add_source_candidates', 'exclude_source_candidates'}:
|
||||
payload = rule.action_payload_json if isinstance(rule.action_payload_json, dict) else {}
|
||||
source_codes = {
|
||||
str(code or '').strip().upper()
|
||||
for code in payload.get('source_codes', [])
|
||||
if str(code or '').strip()
|
||||
}
|
||||
existing_codes = {
|
||||
str(code).strip().upper()
|
||||
for (code,) in db.session.query(FreightRpaSource.source_code).all()
|
||||
}
|
||||
missing_codes = sorted(source_codes - existing_codes)
|
||||
if missing_codes:
|
||||
raise ValidationError(
|
||||
'Routing rule references unavailable inventory sources',
|
||||
code='SHIPPING.ONHAND_RULE_SOURCE_INVALID',
|
||||
details={'source_codes': missing_codes},
|
||||
)
|
||||
rule.status = 'published'
|
||||
rule.updated_by = actor_id
|
||||
db.session.add(FreightRpaOnhandRoutingRuleVersion(
|
||||
rule_id=rule.id, version=rule.version, definition_json=_rule_payload(rule), published_by=actor_id,
|
||||
))
|
||||
db.session.commit()
|
||||
return _rule_payload(rule)
|
||||
|
||||
|
||||
def _external_payload(mapping: FreightRpaOnhandExternalMapping) -> dict[str, Any]:
|
||||
return {
|
||||
'id': mapping.id, 'source_id': mapping.source_id,
|
||||
'freight_warehouse_id': mapping.freight_warehouse_id, 'external_system_code': mapping.external_system_code,
|
||||
'external_organization_code': mapping.external_organization_code, 'external_site_code': mapping.external_site_code,
|
||||
'external_warehouse_code': mapping.external_warehouse_code, 'external_warehouse_name': mapping.external_warehouse_name,
|
||||
'in_transit_warehouse_code': mapping.in_transit_warehouse_code,
|
||||
'enabled': bool(mapping.enabled), 'version': mapping.version,
|
||||
}
|
||||
|
||||
|
||||
def list_external_mappings() -> list[dict[str, Any]]:
|
||||
"""列出库存源到外部系统仓库的映射,不执行调拨判断。"""
|
||||
return [_external_payload(item) for item in FreightRpaOnhandExternalMapping.query.order_by(FreightRpaOnhandExternalMapping.id).all()]
|
||||
|
||||
|
||||
def delete_external_mapping(mapping_id: int) -> None:
|
||||
"""删除错误的外部仓库映射;历史文件和任务不回写此实时配置。"""
|
||||
record = db.session.get(FreightRpaOnhandExternalMapping, mapping_id)
|
||||
if record is None:
|
||||
raise NotFoundError('External mapping not found', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_NOT_FOUND')
|
||||
db.session.delete(record)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建或更新精确/默认外部系统映射。"""
|
||||
record = db.session.get(FreightRpaOnhandExternalMapping, mapping_id) if mapping_id else None
|
||||
if mapping_id and record is None:
|
||||
raise NotFoundError('External mapping not found', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_NOT_FOUND')
|
||||
try:
|
||||
source_id = int(data.get('source_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('source_id is required') from exc
|
||||
if db.session.get(FreightRpaSource, source_id) is None:
|
||||
raise ValidationError('Inventory Source not found', code='SHIPPING.ONHAND_SOURCE_NOT_FOUND')
|
||||
record = record or FreightRpaOnhandExternalMapping(source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='')
|
||||
record.source_id = source_id
|
||||
# 货代仓库改为可选维度:inventory_match 源按「收料文件仓库 == 货代仓库」匹配映射行,
|
||||
# 空值即「空库位」默认映射行;归一化为大写以与收料仓库值精确比对。
|
||||
record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id') or '').upper() or None
|
||||
# 在途仓编码是在途调拨拨出库位来源(DefaultRouteResolver),保存端必填并大写归一。
|
||||
record.in_transit_warehouse_code = str(_text(data, 'in_transit_warehouse_code', required=True)).upper()
|
||||
record.external_system_code = str(_text(data, 'external_system_code', required=True)).upper()
|
||||
record.external_organization_code = _text(data, 'external_organization_code')
|
||||
record.external_site_code = _text(data, 'external_site_code')
|
||||
record.external_warehouse_code = str(_text(data, 'external_warehouse_code', required=True)).upper()
|
||||
record.external_warehouse_name = str(_text(data, 'external_warehouse_name', required=True))
|
||||
record.enabled = _bool(data, 'enabled', bool(record.enabled) if mapping_id else True)
|
||||
record.updated_by = actor_id
|
||||
if not mapping_id:
|
||||
record.created_by = actor_id
|
||||
db.session.add(record)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Active external mapping already exists for this freight identity', code='SHIPPING.ONHAND_EXTERNAL_MAPPING_CONFLICT') from exc
|
||||
return _external_payload(record)
|
||||
@@ -3,19 +3,22 @@ backend/app/services/admin/user_service.py
|
||||
|
||||
用途:管理端用户 CRUD、审批与批量删除;创建/改密时同步 Casdoor。
|
||||
依赖:models、user_admin.delete_admin_users、services/auth/casdoor_service、permission_roles。
|
||||
逻辑:由 api/admin/users.py 调用;权限组启用后创建/改角色只同步角色包,不再按人勾应用。
|
||||
逻辑:由 api/admin/users.py 调用;权限组启用后创建/改角色按角色集合重算并集,不再按人勾应用。
|
||||
提交 roles 时替换该用户的全部业务角色;只提交 role 时改成这一个角色。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.models.permission_role import PermissionRole, user_permission_roles
|
||||
from app.services.auth import casdoor_service
|
||||
from app.services.permission_roles import service as role_service
|
||||
from app.services.user_admin import delete_admin_users
|
||||
@@ -69,15 +72,22 @@ def assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None)
|
||||
raise ConflictError(message, code=code, details={'field': field})
|
||||
|
||||
|
||||
def serialize_admin_user(user: User, role_names: dict[str, str] | None = None) -> dict:
|
||||
def serialize_admin_user(
|
||||
user: User,
|
||||
role_names: dict[str, str] | None = None,
|
||||
assigned: list | None = None,
|
||||
) -> dict:
|
||||
"""管理端用户行。role 是主角色,role_name / role_codes 覆盖全部已挂角色。"""
|
||||
names = role_names if role_names is not None else role_service.list_role_name_map()
|
||||
described = role_service.describe_user_roles(user, assigned=assigned, role_names=names)
|
||||
return {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'email': user.email,
|
||||
'department': user.department,
|
||||
'role': user.role,
|
||||
'role_name': names.get(user.role) or user.role,
|
||||
'role': described['role'],
|
||||
'role_name': described['role_name'],
|
||||
'role_codes': described['role_codes'],
|
||||
'is_platform_admin': user.is_platform_admin(),
|
||||
'status': user.status,
|
||||
'real_name': user.real_name,
|
||||
@@ -95,12 +105,23 @@ def apply_users_filters(query, query_params: dict[str, str]):
|
||||
'username': User.username,
|
||||
'email': User.email,
|
||||
'department': User.department,
|
||||
'role': User.role,
|
||||
'status': User.status,
|
||||
'real_name': User.real_name,
|
||||
'employee_id': User.employee_id,
|
||||
'phone_number': User.phone_number,
|
||||
}
|
||||
role_value = (query_params.get('role') or '').strip()
|
||||
if role_value:
|
||||
# [STEP 1] 角色筛选同时命中主角色和成员表里的其他角色
|
||||
if role_service.roles_configured():
|
||||
member_ids = (
|
||||
db.session.query(user_permission_roles.c.user_id)
|
||||
.join(PermissionRole, PermissionRole.id == user_permission_roles.c.role_id)
|
||||
.filter(PermissionRole.code.ilike(f'%{role_value}%'))
|
||||
)
|
||||
query = query.filter(or_(User.role.ilike(f'%{role_value}%'), User.id.in_(member_ids)))
|
||||
else:
|
||||
query = query.filter(User.role.ilike(f'%{role_value}%'))
|
||||
for key, column in filter_columns.items():
|
||||
value = (query_params.get(key) or '').strip()
|
||||
if value:
|
||||
@@ -142,7 +163,8 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
||||
if 'page' not in query_params:
|
||||
users = query.options(joinedload(User.agents)).order_by(*order_by).all()
|
||||
names = role_service.list_role_name_map()
|
||||
return [serialize_admin_user(u, names) for u in users]
|
||||
assigned = role_service.roles_by_user_ids([user.id for user in users])
|
||||
return [serialize_admin_user(user, names, assigned.get(user.id)) for user in users]
|
||||
|
||||
try:
|
||||
page = int(query_params.get('page') or 1)
|
||||
@@ -168,8 +190,9 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
||||
.all()
|
||||
)
|
||||
names = role_service.list_role_name_map()
|
||||
assigned = role_service.roles_by_user_ids([user.id for user in users])
|
||||
return {
|
||||
'items': [serialize_admin_user(u, names) for u in users],
|
||||
'items': [serialize_admin_user(user, names, assigned.get(user.id)) for user in users],
|
||||
'total': int(total),
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
@@ -200,10 +223,17 @@ def create_user(data: dict[str, Any]) -> dict:
|
||||
employee_id=empty_to_none(data.get('employee_id')),
|
||||
phone_number=empty_to_none(data.get('phone_number')),
|
||||
)
|
||||
role_code = role_service.assert_role_assignable(
|
||||
data.get('role') or role_service.default_role_code(),
|
||||
allow_admin=True,
|
||||
)
|
||||
if isinstance(data.get('roles'), list) and data.get('roles'):
|
||||
role_codes = [
|
||||
role_service.assert_role_assignable(code, allow_admin=True)
|
||||
for code in data.get('roles') or []
|
||||
]
|
||||
else:
|
||||
role_codes = [role_service.assert_role_assignable(
|
||||
data.get('role') or role_service.default_role_code(),
|
||||
allow_admin=True,
|
||||
)]
|
||||
role_code = role_codes[0]
|
||||
user = User(
|
||||
username=data['username'],
|
||||
email=email,
|
||||
@@ -220,7 +250,7 @@ def create_user(data: dict[str, Any]) -> dict:
|
||||
db.session.add(user)
|
||||
try:
|
||||
if role_service.roles_configured():
|
||||
role_service.sync_user_grants_from_role(user)
|
||||
role_service.assign_role_codes(user, role_codes)
|
||||
elif data.get('agent_ids'):
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
@@ -279,20 +309,25 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
|
||||
assert_user_unique_fields(user_id, **unique_updates)
|
||||
new_password = empty_to_none(data.get('password'))
|
||||
try:
|
||||
for key in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||
for key in ['email', 'department', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||
if key in data:
|
||||
if key == 'role':
|
||||
next_role = role_service.assert_role_assignable(data.get('role'), allow_admin=True)
|
||||
role_service.ensure_not_last_admin(user, next_role)
|
||||
user.role = next_role
|
||||
elif key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
if key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
setattr(user, key, empty_to_none(data[key]))
|
||||
else:
|
||||
setattr(user, key, data[key])
|
||||
if role_service.roles_configured():
|
||||
if role_service.roles_configured() and ('role' in data or 'roles' in data):
|
||||
if isinstance(data.get('roles'), list):
|
||||
codes = [
|
||||
role_service.assert_role_assignable(code, allow_admin=True)
|
||||
for code in data.get('roles') or []
|
||||
]
|
||||
else:
|
||||
codes = [role_service.assert_role_assignable(data.get('role'), allow_admin=True)]
|
||||
role_service.ensure_role_codes_keep_admin(user, codes)
|
||||
role_service.assign_role_codes(user, codes)
|
||||
elif not role_service.roles_configured():
|
||||
if 'role' in data:
|
||||
role_service.sync_user_grants_from_role(user)
|
||||
else:
|
||||
user.role = role_service.assert_role_assignable(data.get('role'), allow_admin=True)
|
||||
if 'feature_permissions' in data or 'role' in data:
|
||||
permissions_payload = data.get('feature_permissions', user.feature_permissions)
|
||||
user.set_feature_permissions(permissions_payload)
|
||||
@@ -340,8 +375,11 @@ def batch_update_users(user_ids: list[Any], data: dict[str, Any]) -> dict:
|
||||
user.status = payload.get('status')
|
||||
if next_role:
|
||||
role_service.ensure_not_last_admin(user, next_role)
|
||||
user.role = next_role
|
||||
role_service.sync_user_grants_from_role(user)
|
||||
if role_service.roles_configured():
|
||||
role_service.assign_role_codes(user, [next_role])
|
||||
else:
|
||||
user.role = next_role
|
||||
role_service.sync_user_grants_from_role(user)
|
||||
db.session.commit()
|
||||
return {'status': 'ok', 'updated_count': len(users)}
|
||||
|
||||
|
||||
@@ -162,6 +162,8 @@ agent_types:
|
||||
handler_config_schema: {}
|
||||
in_transit_transfer:
|
||||
label: 在途仓自动调拨
|
||||
# 调拨类型来自平台配置(管理端「在途调拨类型」维护,GET /transfer-types 下发),
|
||||
# 本清单与提示词不硬编码类型列表;Dify 平台侧如有副本需人工同步。
|
||||
conversation_mode_default: task_chat
|
||||
runtime_provider_default: hybrid
|
||||
models:
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
输出结构化 message.completed 卡片,并经 Run API 恢复;本 Handler 负责 hybrid
|
||||
运行时的上下文钩子与领域 UI State 扩展位(transfer_ui_state),暂不注入
|
||||
Dify Chatflow 生命周期。
|
||||
【调拨类型语义 2026-10-14】调拨类型来自平台配置(管理端「在途调拨类型」
|
||||
维护,`GET /api/in-transit-transfer/transfer-types` 下发);提示词与本
|
||||
Handler 一律不硬编码类型列表,Dify 平台侧如有副本需人工同步。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -77,12 +77,13 @@ def try_fast_route(
|
||||
_log_fast_route('faq_cache', agent_code=agent_code, agent_id=agent_id, session_id=session_id)
|
||||
return FastRouteResult(
|
||||
generator=FaqCacheService.stream_chat(
|
||||
faq_hit,
|
||||
faq_hit.entry,
|
||||
query,
|
||||
user,
|
||||
agent,
|
||||
external_conversation_id,
|
||||
session_id=session_id,
|
||||
match=faq_hit,
|
||||
),
|
||||
route_name='faq_cache',
|
||||
)
|
||||
|
||||
@@ -3,7 +3,7 @@ services/contract_payment/alert_service.py
|
||||
|
||||
用途:按付款阶段生成待发送预警,在每周五按收件人汇总发送企业微信和 Excel 明细,并提供工作台待发送摘要。
|
||||
依赖:合同付款模型、用户目录、openpyxl、企业微信通知服务、OA 上级矩阵、排程时区工具。
|
||||
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;发送失败时把原因写入批次审计。摘要接口与周五发送使用同一 pending 口径。预付款、出货款可手动标为已付,并关闭该节点尚未发送的预警。
|
||||
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;发送失败时把原因写入批次审计。摘要接口与周五发送使用同一 pending 口径。预付款、出货款、验收款、质保款都可手动标为已付,并关闭该节点尚未发送的预警。金额和比例都为 0 的阶段关闭未发送预警,不再新建。
|
||||
第一轮按台账申请人 `real_name` 唯一匹配系统用户;第二、三轮查 OA HrmResource + Matrixtable_3,用 zz/jfl 作为企微 userid,不向第一轮兜底。
|
||||
"""
|
||||
|
||||
@@ -40,6 +40,7 @@ from app.services.contract_payment.erp_payment_service import (
|
||||
normalize_purchase_order_no,
|
||||
resolve_paid_node_dates,
|
||||
)
|
||||
from app.services.contract_payment.ledger_focus import stage_has_nothing_to_pay
|
||||
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrixCache
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
@@ -52,6 +53,7 @@ class _AlertRecipient:
|
||||
oa_wecom_userid: str | None = None
|
||||
|
||||
|
||||
_ERP_PAID_STAGE_TYPES = {"prepayment", "shipment", "acceptance", "warranty"}
|
||||
_ALERT_RULES: dict[str, tuple[tuple[int, str], ...]] = {
|
||||
"prepayment": ((7, "owner"), (14, "department_head"), (21, "procurement_leader")),
|
||||
"shipment": ((-7, "owner"), (0, "department_head"), (14, "procurement_leader")),
|
||||
@@ -65,7 +67,7 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
||||
|
||||
AI 触发时机:每日排程或管理员手动执行扫描时调用。
|
||||
核心逻辑:按阶段计算已到期的三轮提醒,按节点、轮次、收件人幂等;第二、三轮收件人来自 OA 部门矩阵;
|
||||
ERP `apa_file` 的合格付款记录只停止尚未发送的后续轮次。
|
||||
ERP `apa_file` 的合格付款记录按金额匹配四个阶段,并停止已付款阶段尚未发送的后续轮次。金额和比例都为 0 的阶段关闭未发送预警,不再新建。
|
||||
Args:
|
||||
today: 业务日期,未传时使用服务器日期。
|
||||
send: 保留旧调用兼容参数;最新方案下始终不发送消息。
|
||||
@@ -85,14 +87,20 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
||||
payable_orders = [
|
||||
(normalize_purchase_order_no(contract.purchase_order_no), contract.company_name)
|
||||
for node, contract in rows
|
||||
if node.node_type in {"prepayment", "shipment"} and normalize_purchase_order_no(contract.purchase_order_no)
|
||||
if node.node_type in _ERP_PAID_STAGE_TYPES
|
||||
and normalize_purchase_order_no(contract.purchase_order_no)
|
||||
and not stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount)
|
||||
]
|
||||
paid_records = fetch_paid_records(payable_orders)
|
||||
paid_node_dates: dict[int, str | None] = {}
|
||||
nodes_by_ledger: dict[tuple[str, str], list[ContractPaymentNode]] = defaultdict(list)
|
||||
for node, contract in rows:
|
||||
purchase_order_no = normalize_purchase_order_no(contract.purchase_order_no)
|
||||
if node.node_type in {"prepayment", "shipment"} and purchase_order_no:
|
||||
if (
|
||||
node.node_type in _ERP_PAID_STAGE_TYPES
|
||||
and purchase_order_no
|
||||
and not stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount)
|
||||
):
|
||||
nodes_by_ledger[(erp_schema_for_company(contract.company_name), purchase_order_no)].append(node)
|
||||
for ledger_key, payment_nodes in nodes_by_ledger.items():
|
||||
paid_node_dates.update(resolve_paid_node_dates(
|
||||
@@ -100,6 +108,11 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
||||
paid_records.get(ledger_key, []),
|
||||
))
|
||||
for node, contract in rows:
|
||||
if stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount):
|
||||
# 金额和比例都为 0 时没有应付金额,关掉尚未发送的预警,不再按日期升级。
|
||||
resolved += _resolve_pending_alerts(node_id=node.id, reason="nothing_to_pay")
|
||||
skipped += 1
|
||||
continue
|
||||
anchor = _anchor_date(contract=contract, node=node)
|
||||
if anchor is None:
|
||||
skipped += 1
|
||||
@@ -113,7 +126,7 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
||||
scheduled_date = anchor + timedelta(days=offset_days)
|
||||
if today < scheduled_date:
|
||||
continue
|
||||
# ERP 合格付款先按金额匹配阶段;同金额时预付款优先于出货款。
|
||||
# ERP 合格付款按金额匹配四个阶段;同金额时按预付款、出货款、验收款、质保款的顺序占用。
|
||||
# 节点被匹配为已付款后,保留历史 sent,仅关闭尚未发送轮次。
|
||||
if erp_paid:
|
||||
resolved += _resolve_pending_alerts(node_id=node.id)
|
||||
@@ -160,10 +173,10 @@ def _resolve_pending_alerts(*, node_id: int, reason: str = "erp_paid") -> int:
|
||||
|
||||
def mark_payment_node_paid(contract_id: int, node_id: int, payload: dict, *, operator_id: int | None = None) -> ContractPaymentContract:
|
||||
"""
|
||||
把一个未付的预付款或出货款手动标为已付。
|
||||
把一个未付阶段手动标为已付。
|
||||
|
||||
核心逻辑:只改这一阶段。写入付款日期和手动来源,并关闭该节点尚未发送的预警;已发送记录保留。
|
||||
验收款、质保款和已经付款的阶段不能标记。
|
||||
核心逻辑:预付款、出货款、验收款、质保款都可以标记。只改这一阶段,写入付款日期和手动来源,并关闭该节点尚未发送的预警;已发送记录保留。
|
||||
金额和比例都为 0、已经付款、或不是进行中的阶段不能标记。
|
||||
|
||||
Args:
|
||||
contract_id: 合同台账主键。
|
||||
@@ -186,8 +199,10 @@ def mark_payment_node_paid(contract_id: int, node_id: int, payload: dict, *, ope
|
||||
node = db.session.get(ContractPaymentNode, node_id)
|
||||
if node is None or node.contract_id != contract.id:
|
||||
raise NotFoundError("付款节点不存在")
|
||||
if node.node_type not in {"prepayment", "shipment"}:
|
||||
raise ValidationError("只有预付款和出货款可以手动标为已付")
|
||||
if node.node_type not in _ERP_PAID_STAGE_TYPES:
|
||||
raise ValidationError("该阶段不能标为已付")
|
||||
if stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount):
|
||||
raise ValidationError("该阶段没有应付金额,不能标为已付")
|
||||
if node.status == "paid":
|
||||
raise ValidationError("该阶段已是已付")
|
||||
if node.status != "active":
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/services/contract_payment/erp_payment_service.py
|
||||
|
||||
用途:从 ERP Oracle `apa_file` 读取采购单付款记录,作为预付款和出货款的付款完成事实来源。
|
||||
用途:从 ERP Oracle `apa_file` 读取采购单付款记录,作为预付款、出货款、验收款和质保款的付款完成事实来源。
|
||||
依赖:oracledb、Text2SQLService 的 Oracle 客户端初始化能力及 Flask 配置。
|
||||
逻辑:按 OA「公司」选择账套后只读查询 `{账套}.apa_file`;只接受 `apa00='15'`(厂商预付款作业)且 `apa41='Y'`、`apa63=1` 的记录,并按采购单收集 `apa34f` 供明细和阶段匹配使用。
|
||||
"""
|
||||
@@ -17,7 +17,7 @@ from typing import Iterable
|
||||
from flask import current_app
|
||||
|
||||
|
||||
_PAYMENT_STAGE_ORDER = {"prepayment": 1, "shipment": 2}
|
||||
_PAYMENT_STAGE_ORDER = {"prepayment": 1, "shipment": 2, "acceptance": 3, "warranty": 4}
|
||||
# OA 合同申请单「公司」到 ERP 账套。未列出的公司默认 HXJM。标识符只允许来自这个白名单。
|
||||
_SCHEMA_BY_COMPANY = {
|
||||
"无锡和宏智散热科技有限公司": "WZHHZ",
|
||||
@@ -100,7 +100,7 @@ def fetch_paid_records(orders: Iterable[tuple[str, str | None]]) -> dict[tuple[s
|
||||
"""
|
||||
按公司对应的 ERP 账套查询采购单已完成付款记录(含付款日期)。
|
||||
|
||||
AI 触发时机:合同付款预警每日扫描前,需要判断预付款/出货款是否已经完成付款。
|
||||
AI 触发时机:合同付款预警每日扫描前,需要判断预付款、出货款、验收款、质保款是否已经完成付款。
|
||||
核心逻辑:公司映射到 HXJM / WZHHZ / HTT 后,分别查询该账套的 `apa_file`;
|
||||
先按 `apa00='15'` 限定为「厂商预付款作业」,再过滤 `apa41='Y'` 和 `apa63=1`,按 `apaud03` 收集 `apa34f` 与 `apa02`。
|
||||
某一账套查询失败只影响该账套,其它账套继续。
|
||||
@@ -234,14 +234,13 @@ def resolve_paid_node_dates(
|
||||
paid_rows: Iterable[ErpPaidRow],
|
||||
) -> dict[int, str | None]:
|
||||
"""
|
||||
将同一采购单的 ERP 付款记录匹配到预付款、出货款节点,并返回节点 ID 到付款日期的映射。
|
||||
将同一采购单的 ERP 付款记录匹配到预付款、出货款、验收款、质保款节点,并返回节点 ID 到付款日期的映射。
|
||||
|
||||
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按金额与节点匹配;
|
||||
金额相同则按预付款、出货款的业务顺序匹配最前面仍未付款的节点;若单节点无匹配但
|
||||
「预付款+出货款」金额之和与该笔付款一致,说明预付款与出货款在同一笔请款中一并请款,
|
||||
则把两者同时标记为已付款,并携带该笔付款日期。
|
||||
金额相同则按预付款、出货款、验收款、质保款的业务顺序匹配最前面仍未付款的节点;若单节点无匹配但
|
||||
若干阶段金额之和与该笔付款一致,则把这些阶段同时标记为已付款,并携带该笔付款日期。
|
||||
Args:
|
||||
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
|
||||
nodes: 同一采购单仍需付款的 `(node_id, node_type, amount)` 节点;金额为 0 的阶段不要传入。
|
||||
paid_rows: 该采购单的合格 ERP 付款记录。
|
||||
Returns:
|
||||
已匹配节点的付款日期映射(节点 ID -> 付款日期,日期可能为空)。
|
||||
@@ -268,14 +267,13 @@ def resolve_paid_node_ids(
|
||||
paid_amounts: Iterable[Decimal],
|
||||
) -> set[int]:
|
||||
"""
|
||||
将同一采购单的 ERP 付款金额匹配到预付款、出货款节点。
|
||||
将同一采购单的 ERP 付款金额匹配到预付款、出货款、验收款、质保款节点。
|
||||
|
||||
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按 `apa34f` 与节点金额匹配;
|
||||
金额不同则自然对应相应节点,金额相同时按预付款、出货款的业务顺序匹配最前面仍未付款的节点;
|
||||
若单节点无匹配但「预付款+出货款」金额之和与该笔付款一致,则一并标记两者为已付款
|
||||
(预付款、出货款在同一笔请款中一并请款的场景)。
|
||||
金额不同则自然对应相应节点,金额相同时按预付款、出货款、验收款、质保款的业务顺序匹配最前面仍未付款的节点;
|
||||
若单节点无匹配但若干阶段金额之和与该笔付款一致,则一并标记这些阶段为已付款。
|
||||
Args:
|
||||
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
|
||||
nodes: 同一采购单仍需付款的 `(node_id, node_type, amount)` 节点;金额为 0 的阶段不要传入。
|
||||
paid_amounts: 该采购单的合格 ERP 每笔付款金额。
|
||||
Returns:
|
||||
已付款节点 ID 集合。
|
||||
|
||||
@@ -4,11 +4,13 @@ backend/app/services/contract_payment/ledger_focus.py
|
||||
用途:合同台账汇总卡口径——即将到期、逾期未付、未到期(7日外)、本月应付,均按合同计数。
|
||||
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
|
||||
逻辑:由 list/summary API 调用;即将到期/逾期/未到期互斥,本月应付可与这三项重叠。行级「待补充」不进汇总卡。
|
||||
金额和比例都为 0 的阶段不参与逾期、即将到期和本月应付。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from datetime import date, datetime
|
||||
from typing import Any, Iterable
|
||||
from zoneinfo import ZoneInfo
|
||||
@@ -58,6 +60,37 @@ def node_due_reference(due_date: date | None, anchor_date: date | None) -> date
|
||||
return due_date or anchor_date
|
||||
|
||||
|
||||
def stage_has_nothing_to_pay(*, status: str | None, percentage: object, amount: object) -> bool:
|
||||
"""
|
||||
判断付款阶段是否没有应付金额。
|
||||
|
||||
核心逻辑:无此阶段,或比例与金额都是 0(空值按 0)。已付阶段不按 0 处理。
|
||||
与前台 isNothingToPay 一致,避免 0 元验收款、质保款把合同标成已逾期。
|
||||
Args:
|
||||
status: 节点状态。
|
||||
percentage: 付款比例,可为 Decimal、数字或字符串。
|
||||
amount: 应付金额,空值视为 0。
|
||||
Returns:
|
||||
无需付款时为 True。
|
||||
"""
|
||||
normalized = str(status or "").strip().lower()
|
||||
if normalized == "not_applicable":
|
||||
return True
|
||||
if normalized == "paid":
|
||||
return False
|
||||
return _is_zero(percentage) and _is_zero(amount)
|
||||
|
||||
|
||||
def _is_zero(value: object) -> bool:
|
||||
"""空值和 0 都视为没有金额或比例;无法解析的值不当成 0。"""
|
||||
if value is None or value == "":
|
||||
return True
|
||||
try:
|
||||
return Decimal(str(value)) == 0
|
||||
except (InvalidOperation, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def classify_ledger_status(
|
||||
*,
|
||||
contract_status: str | None,
|
||||
@@ -69,11 +102,11 @@ def classify_ledger_status(
|
||||
按合同聚合出台账状态,与列表「状态」列一致。
|
||||
|
||||
核心逻辑:非激活或待确认 → 待补充(仅行状态,不进汇总卡);无进行中节点则按是否已付分为已完成/待补充;
|
||||
进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
|
||||
金额和比例都为 0 的阶段不参与判断。其余进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
|
||||
Args:
|
||||
contract_status: 合同主状态。
|
||||
parse_status: 解析状态。
|
||||
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at。
|
||||
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at / percentage / amount。
|
||||
today: 业务日。
|
||||
Returns:
|
||||
overdue / due / active / completed / needs_completion。
|
||||
@@ -83,7 +116,14 @@ def classify_ledger_status(
|
||||
return "needs_completion"
|
||||
if not node_list:
|
||||
return "needs_completion"
|
||||
active = [node for node in node_list if str(node.get("status") or "").strip().lower() == "active"]
|
||||
active = [
|
||||
node for node in node_list
|
||||
if str(node.get("status") or "").strip().lower() == "active" and not stage_has_nothing_to_pay(
|
||||
status=node.get("status"),
|
||||
percentage=node.get("percentage"),
|
||||
amount=node.get("amount"),
|
||||
)
|
||||
]
|
||||
if not active:
|
||||
has_paid = any(
|
||||
str(node.get("status") or "").strip().lower() == "paid" or bool(node.get("paid_at"))
|
||||
@@ -106,7 +146,7 @@ def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> b
|
||||
"""
|
||||
合同是否有未付节点的到期日落在本自然月。
|
||||
|
||||
核心逻辑:只看 status=active 的节点;月份按 today 所在自然月(含 today 所在月的逾期节点)。
|
||||
核心逻辑:只看 status=active 且仍有应付金额的节点;月份按 today 所在自然月(含 today 所在月的逾期节点)。
|
||||
Args:
|
||||
nodes: 轻量节点 dict。
|
||||
today: 业务日,用于确定自然月。
|
||||
@@ -118,6 +158,8 @@ def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> b
|
||||
for node in nodes:
|
||||
if str(node.get("status") or "").strip().lower() != "active":
|
||||
continue
|
||||
if stage_has_nothing_to_pay(status=node.get("status"), percentage=node.get("percentage"), amount=node.get("amount")):
|
||||
continue
|
||||
ref = node_due_reference(node.get("due_date"), node.get("anchor_date"))
|
||||
if ref and month_start <= ref < month_end:
|
||||
return True
|
||||
@@ -131,6 +173,8 @@ def _node_payload(node: ContractPaymentNode) -> dict[str, Any]:
|
||||
"due_date": node.due_date,
|
||||
"anchor_date": node.anchor_date,
|
||||
"paid_at": (node.evidence_json or {}).get("paid_at"),
|
||||
"percentage": node.percentage,
|
||||
"amount": node.amount,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -136,6 +136,47 @@ def resolve_account(
|
||||
)
|
||||
|
||||
|
||||
def resolve_direct_wecom(
|
||||
*,
|
||||
slot: str,
|
||||
label: str,
|
||||
name: str | None,
|
||||
wecom_userid: str | None,
|
||||
user: Any = None,
|
||||
oa_employee_id: int | None = None,
|
||||
missing_error: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
把已经是企业微信 userid 的人员收成收件人。
|
||||
|
||||
核心逻辑:E8 矩阵的 zz、jfl 本身就是企微 userid,不再用工号对用户。
|
||||
系统里能对上这个 userid 时带上用户主键。对不上仍按该 userid 发送。
|
||||
Args:
|
||||
slot: to 或 cc。
|
||||
label: 直接主管或经副理。
|
||||
name: 展示姓名。
|
||||
wecom_userid: 企业微信 userid。
|
||||
user: 已按 wecom_userid 找到的系统用户。可空。
|
||||
oa_employee_id: HrmResource.id。
|
||||
missing_error: 没有 userid 时的失败原因。
|
||||
Returns:
|
||||
一名收件人。
|
||||
"""
|
||||
wecom = str(wecom_userid or "").strip()
|
||||
if not wecom:
|
||||
return make_person(slot=slot, label=label, name=name, oa_employee_id=oa_employee_id, error=missing_error)
|
||||
display = _user_name(user) or name
|
||||
bound = str(getattr(user, "wecom_userid", None) or "").strip() if user is not None else ""
|
||||
return make_person(
|
||||
slot=slot,
|
||||
label=label,
|
||||
name=display,
|
||||
user_id=getattr(user, "id", None) if user is not None else None,
|
||||
wecom_userid=bound or wecom,
|
||||
oa_employee_id=oa_employee_id,
|
||||
)
|
||||
|
||||
|
||||
def resolve_configured_user(*, slot: str, label: str, user: Any, missing_error: str) -> dict[str, Any]:
|
||||
"""
|
||||
把预警配置里的固定岗位收成收件人。
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/services/equipment_acceptance/alert_service.py
|
||||
|
||||
用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。
|
||||
依赖:同步服务、OA 人员目录、alert_plan、alert_notice、发送记录模型、企微通知。
|
||||
逻辑:扫描先同步 E10,再按停留天数跨档。第 4 轮关闭时不生成、也不发送总经理那一轮。
|
||||
依赖:同步服务、E10 人员目录、E8 人员矩阵、alert_plan、alert_notice、发送记录模型、企微通知。
|
||||
逻辑:扫描先同步 E10 和 E8,再按停留天数跨档。第 1 档主送使用部门担当,不按当前未办人。
|
||||
第 4 轮关闭时不生成、也不发送总经理那一轮。
|
||||
周五按收件人发一条汇总卡片,紧跟着一份 Excel。卡片和文件都成功才算已发送。停表取消未发送记录。已发送的不重发、不改收件人。
|
||||
"""
|
||||
|
||||
@@ -35,6 +36,7 @@ from app.services.equipment_acceptance.alert_plan import (
|
||||
make_person,
|
||||
resolve_account,
|
||||
resolve_configured_user,
|
||||
resolve_direct_wecom,
|
||||
)
|
||||
from app.services.equipment_acceptance.config_service import is_round_4_enabled, reminder_days
|
||||
from app.services.equipment_acceptance.snapshot_rules import WATCHING
|
||||
@@ -47,9 +49,9 @@ _UNSENT = ("pending", "failed")
|
||||
|
||||
def generate_alerts() -> dict[str, Any]:
|
||||
"""
|
||||
同步 E10 后生成或更新待发送记录。
|
||||
同步两个来源后生成或更新待发送记录。
|
||||
|
||||
核心逻辑:先拉最新节点和停表状态,再按当前处理人解析收件人。本函数不发企业微信。
|
||||
核心逻辑:先拉最新快照,再按使用部门担当解析收件人。本函数不发企业微信。
|
||||
Returns:
|
||||
sync 摘要,以及 created、updated、cancelled 条数。
|
||||
"""
|
||||
@@ -78,9 +80,9 @@ def refresh_pending_alerts(
|
||||
created、updated、cancelled。
|
||||
"""
|
||||
orders = db.session.query(EquipmentAcceptanceOrder).all()
|
||||
operators = _operators_by_order([order.id for order in orders])
|
||||
people, deputies = directory if directory is not None else _load_directory(orders, operators)
|
||||
users_by_job = _users_by_job(_job_numbers(orders, operators, people, deputies))
|
||||
e10_people, e10_deputies, e8_people, e8_matrix, e8_ok = _directories(orders, directory)
|
||||
users_by_job = _users_by_job(_job_numbers(orders, e10_people, e10_deputies, e8_people))
|
||||
users_by_wecom = _users_by_wecom(_wecom_ids(e8_matrix))
|
||||
roles = _configured_users()
|
||||
thresholds = reminder_days()
|
||||
max_tier = 4 if is_round_4_enabled() else 3
|
||||
@@ -96,12 +98,16 @@ def refresh_pending_alerts(
|
||||
if order.monitor_status != WATCHING:
|
||||
cancelled += cancel_unsent(order.id)
|
||||
continue
|
||||
if (order.oa_system or "e10") == "e8" and not e8_ok:
|
||||
continue
|
||||
for draft in _drafts(
|
||||
order,
|
||||
operators.get(order.id, []),
|
||||
people,
|
||||
deputies,
|
||||
e10_people,
|
||||
e10_deputies,
|
||||
e8_people,
|
||||
e8_matrix,
|
||||
users_by_job,
|
||||
users_by_wecom,
|
||||
roles,
|
||||
thresholds,
|
||||
max_tier=max_tier,
|
||||
@@ -282,82 +288,31 @@ def send_pending_alerts() -> dict[str, Any]:
|
||||
|
||||
def _drafts(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
operators: list[EquipmentAcceptanceOperator],
|
||||
people: dict[int, dict[str, Any]],
|
||||
deputies: dict[str, list[dict[str, Any]]],
|
||||
e10_people: dict[int, dict[str, Any]],
|
||||
e10_deputies: dict[str, list[dict[str, Any]]],
|
||||
e8_people: dict[int, dict[str, Any]],
|
||||
e8_matrix: dict[str, dict[str, Any]],
|
||||
users_by_job: dict[str, User],
|
||||
users_by_wecom: dict[str, User],
|
||||
roles: dict[str, User | None],
|
||||
thresholds: tuple[int, int, int, int],
|
||||
*,
|
||||
max_tier: int = 4,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""按当前处理人展开已经跨过、且配置允许的档。第 4 轮关闭时最高到第 3 档。"""
|
||||
"""按使用部门担当展开已经跨过、且配置允许的档。第 4 轮关闭时最高到第 3 档。"""
|
||||
due = due_tiers(order.dwell_days, thresholds, max_tier=max_tier)
|
||||
if not due:
|
||||
return []
|
||||
handlers: list[dict[str, Any]] = []
|
||||
supervisors: list[dict[str, Any]] = []
|
||||
deputy_people: list[dict[str, Any]] = []
|
||||
if not operators:
|
||||
handlers.append(make_person(slot="to", label="当前处理人", error="没有当前处理人"))
|
||||
deputy_people.append(make_person(slot="to", label="经副理", error="没有当前处理人,查不到经副理"))
|
||||
for operator in operators:
|
||||
fact = people.get(operator.user_id) or {}
|
||||
name = fact.get("name") or operator.handler_name
|
||||
job_num = fact.get("job_num") or operator.handler_job_num
|
||||
shown = name or "处理人"
|
||||
handlers.append(resolve_account(
|
||||
slot="to",
|
||||
label="当前处理人",
|
||||
name=name,
|
||||
job_num=job_num,
|
||||
user=users_by_job.get(str(job_num or "")),
|
||||
missing_job_error=f"{shown}没有工号",
|
||||
oa_employee_id=operator.user_id,
|
||||
))
|
||||
superior_id = fact.get("superior_id")
|
||||
if superior_id is None:
|
||||
supervisors.append(make_person(slot="cc", label="直接主管", name=name, error=f"{shown}没有直接主管"))
|
||||
else:
|
||||
supervisors.append(resolve_account(
|
||||
slot="cc",
|
||||
label="直接主管",
|
||||
name=fact.get("superior_name"),
|
||||
job_num=fact.get("superior_job_num"),
|
||||
user=users_by_job.get(str(fact.get("superior_job_num") or "")),
|
||||
missing_job_error=f"{shown}的直接主管没有工号",
|
||||
oa_employee_id=superior_id,
|
||||
))
|
||||
found = deputies.get(str(fact.get("department_id") or ""), [])
|
||||
if not found:
|
||||
deputy_people.append(make_person(slot="to", label="经副理", name=name, error=f"{shown}没有经副理"))
|
||||
else:
|
||||
for item in found:
|
||||
deputy_people.append(resolve_account(
|
||||
slot="to",
|
||||
label="经副理",
|
||||
name=item.get("name"),
|
||||
job_num=item.get("job_num"),
|
||||
user=users_by_job.get(str(item.get("job_num") or "")),
|
||||
missing_job_error=f"{shown}的经副理没有工号",
|
||||
oa_employee_id=item.get("oa_id"),
|
||||
))
|
||||
applicant_fact = people.get(order.applicant_oa_id) if order.applicant_oa_id else None
|
||||
applicant = resolve_account(
|
||||
slot="cc",
|
||||
label="采购担当",
|
||||
name=(applicant_fact or {}).get("name") or order.applicant_name,
|
||||
job_num=(applicant_fact or {}).get("job_num") or order.applicant_job_num,
|
||||
user=users_by_job.get(str(((applicant_fact or {}).get("job_num") or order.applicant_job_num) or "")),
|
||||
missing_job_error="没有申请人工号",
|
||||
oa_employee_id=order.applicant_oa_id,
|
||||
owner, supervisors, deputy_people = _owner_seats(
|
||||
order, e10_people, e10_deputies, e8_people, e8_matrix, users_by_job, users_by_wecom
|
||||
)
|
||||
applicant = _applicant(order, e10_people if (order.oa_system or "e10") != "e8" else e8_people, users_by_job)
|
||||
drafts: list[dict[str, Any]] = []
|
||||
if 1 in due:
|
||||
drafts.append(assemble_tier(
|
||||
tier=1,
|
||||
threshold_days=thresholds[0],
|
||||
to_people=handlers,
|
||||
to_people=[owner],
|
||||
cc_people=[*supervisors, applicant],
|
||||
))
|
||||
if 2 in due:
|
||||
@@ -390,6 +345,159 @@ def _drafts(
|
||||
return drafts
|
||||
|
||||
|
||||
def _owner_seats(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
e10_people: dict[int, dict[str, Any]],
|
||||
e10_deputies: dict[str, list[dict[str, Any]]],
|
||||
e8_people: dict[int, dict[str, Any]],
|
||||
e8_matrix: dict[str, dict[str, Any]],
|
||||
users_by_job: dict[str, User],
|
||||
users_by_wecom: dict[str, User],
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""第 1 档主送和其上级。E8 的上级来自部门矩阵,E10 来自 employee 和审批矩阵。"""
|
||||
if (order.oa_system or "e10") == "e8":
|
||||
return _e8_owner_seats(order, e8_people, e8_matrix, users_by_job, users_by_wecom)
|
||||
return _e10_owner_seats(order, e10_people, e10_deputies, users_by_job)
|
||||
|
||||
|
||||
def _e10_owner_seats(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
people: dict[int, dict[str, Any]],
|
||||
deputies: dict[str, list[dict[str, Any]]],
|
||||
users_by_job: dict[str, User],
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""E10 只取 sybmdd 这一名使用部门担当,不展开当前节点上的其他人。"""
|
||||
if not order.owner_oa_id:
|
||||
return (
|
||||
make_person(slot="to", label="使用部门担当", error="没有使用部门担当"),
|
||||
[make_person(slot="cc", label="直接主管", error="没有使用部门担当,查不到直接主管")],
|
||||
[make_person(slot="to", label="经副理", error="没有使用部门担当,查不到经副理")],
|
||||
)
|
||||
fact = people.get(order.owner_oa_id) or {}
|
||||
name = fact.get("name") or order.owner_name
|
||||
job_num = fact.get("job_num") or order.owner_job_num
|
||||
shown = name or "使用部门担当"
|
||||
owner = resolve_account(
|
||||
slot="to",
|
||||
label="使用部门担当",
|
||||
name=name,
|
||||
job_num=job_num,
|
||||
user=users_by_job.get(str(job_num or "")),
|
||||
missing_job_error=f"{shown}没有工号",
|
||||
oa_employee_id=order.owner_oa_id,
|
||||
)
|
||||
superior_id = fact.get("superior_id")
|
||||
if superior_id is None:
|
||||
supervisors = [make_person(slot="cc", label="直接主管", name=name, error=f"{shown}没有直接主管")]
|
||||
else:
|
||||
supervisors = [resolve_account(
|
||||
slot="cc",
|
||||
label="直接主管",
|
||||
name=fact.get("superior_name"),
|
||||
job_num=fact.get("superior_job_num"),
|
||||
user=users_by_job.get(str(fact.get("superior_job_num") or "")),
|
||||
missing_job_error=f"{shown}的直接主管没有工号",
|
||||
oa_employee_id=superior_id,
|
||||
)]
|
||||
found = deputies.get(str(fact.get("department_id") or ""), [])
|
||||
if not found:
|
||||
deputy_people = [make_person(slot="to", label="经副理", name=name, error=f"{shown}没有经副理")]
|
||||
else:
|
||||
deputy_people = [
|
||||
resolve_account(
|
||||
slot="to",
|
||||
label="经副理",
|
||||
name=item.get("name"),
|
||||
job_num=item.get("job_num"),
|
||||
user=users_by_job.get(str(item.get("job_num") or "")),
|
||||
missing_job_error=f"{shown}的经副理没有工号",
|
||||
oa_employee_id=item.get("oa_id"),
|
||||
)
|
||||
for item in found
|
||||
]
|
||||
return owner, supervisors, deputy_people
|
||||
|
||||
|
||||
def _e8_owner_seats(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
people: dict[int, dict[str, Any]],
|
||||
matrix: dict[str, dict[str, Any]],
|
||||
users_by_job: dict[str, User],
|
||||
users_by_wecom: dict[str, User],
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""E8 的直接主管是矩阵 zz,经副理是 jfl。不是一行就不发这两个席位。"""
|
||||
if not order.owner_oa_id:
|
||||
return (
|
||||
make_person(slot="to", label="使用部门担当", error="没有使用部门担当"),
|
||||
[make_person(slot="cc", label="直接主管", error="没有使用部门担当,查不到直接主管")],
|
||||
[make_person(slot="to", label="经副理", error="没有使用部门担当,查不到经副理")],
|
||||
)
|
||||
fact = people.get(order.owner_oa_id) or {}
|
||||
name = fact.get("name") or order.owner_name
|
||||
job_num = fact.get("job_num") or order.owner_job_num
|
||||
shown = name or "使用部门担当"
|
||||
owner = resolve_account(
|
||||
slot="to",
|
||||
label="使用部门担当",
|
||||
name=name,
|
||||
job_num=job_num,
|
||||
user=users_by_job.get(str(job_num or "")),
|
||||
missing_job_error=f"{shown}没有工号",
|
||||
oa_employee_id=order.owner_oa_id,
|
||||
)
|
||||
seat = matrix.get(str(fact.get("department_id") or ""))
|
||||
if not seat or not seat.get("ok"):
|
||||
return (
|
||||
owner,
|
||||
[make_person(slot="cc", label="直接主管", name=name, error=f"{shown}的部门矩阵不是一行")],
|
||||
[make_person(slot="to", label="经副理", name=name, error=f"{shown}的部门矩阵不是一行")],
|
||||
)
|
||||
return owner, [_matrix_seat(seat.get("zz"), "cc", "直接主管", shown, users_by_wecom)], [
|
||||
_matrix_seat(seat.get("jfl"), "to", "经副理", shown, users_by_wecom)
|
||||
]
|
||||
|
||||
|
||||
def _matrix_seat(
|
||||
seat: dict[str, Any] | None,
|
||||
slot: str,
|
||||
label: str,
|
||||
owner_name: str,
|
||||
users_by_wecom: dict[str, User],
|
||||
) -> dict[str, Any]:
|
||||
"""矩阵人员按企微 userid 发送。空席位记失败。"""
|
||||
if not seat:
|
||||
return make_person(slot=slot, label=label, name=owner_name, error=f"{owner_name}没有{label}")
|
||||
wecom = str(seat.get("wecom_userid") or "")
|
||||
return resolve_direct_wecom(
|
||||
slot=slot,
|
||||
label=label,
|
||||
name=seat.get("name"),
|
||||
wecom_userid=wecom,
|
||||
user=users_by_wecom.get(wecom),
|
||||
oa_employee_id=seat.get("oa_id"),
|
||||
missing_error=f"{owner_name}没有{label}",
|
||||
)
|
||||
|
||||
|
||||
def _applicant(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
people: dict[int, dict[str, Any]],
|
||||
users_by_job: dict[str, User],
|
||||
) -> dict[str, Any]:
|
||||
"""采购担当是申请人。E8 用工号 workcode,E10 用工号 JOB_NUM,都对系统用户。"""
|
||||
fact = people.get(order.applicant_oa_id) if order.applicant_oa_id else None
|
||||
job_num = (fact or {}).get("job_num") or order.applicant_job_num
|
||||
return resolve_account(
|
||||
slot="cc",
|
||||
label="采购担当",
|
||||
name=(fact or {}).get("name") or order.applicant_name,
|
||||
job_num=job_num,
|
||||
user=users_by_job.get(str(job_num or "")),
|
||||
missing_job_error="没有申请人工号",
|
||||
oa_employee_id=order.applicant_oa_id,
|
||||
)
|
||||
|
||||
|
||||
def _apply_draft(row: EquipmentAcceptanceSendRecord, order: EquipmentAcceptanceOrder, draft: dict[str, Any]) -> None:
|
||||
"""把草稿写进未发送的记录。不改创建时间,也不填发送时间。"""
|
||||
row.acceptance_no = order.acceptance_no
|
||||
@@ -402,51 +510,103 @@ def _apply_draft(row: EquipmentAcceptanceSendRecord, order: EquipmentAcceptanceO
|
||||
row.error_message = draft["error_message"]
|
||||
|
||||
|
||||
def _load_directory(
|
||||
def _directories(
|
||||
orders: list[EquipmentAcceptanceOrder],
|
||||
directory: tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]] | None,
|
||||
) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]], dict[int, dict[str, Any]], dict[str, dict[str, Any]], bool]:
|
||||
"""分开取 E10 和 E8 的人员。E8 查询失败时本轮不改写 E8 待发送。"""
|
||||
if directory is not None:
|
||||
return directory[0], directory[1], {}, {}, True
|
||||
e10_people, e10_deputies = _load_e10_directory(orders)
|
||||
try:
|
||||
e8_people, e8_matrix = _load_e8_directory(orders)
|
||||
return e10_people, e10_deputies, e8_people, e8_matrix, True
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance e8 directory skipped error=%s", type(exc).__name__)
|
||||
return e10_people, e10_deputies, {}, {}, False
|
||||
|
||||
|
||||
def _load_e10_directory(
|
||||
orders: list[EquipmentAcceptanceOrder],
|
||||
operators: dict[int, list[EquipmentAcceptanceOperator]],
|
||||
) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
||||
"""向 E10 要当前处理人和申请人的主管、部门、经副理。"""
|
||||
"""向 E10 要使用部门担当和申请人的主管、部门、经副理。不传入 E8 人员 ID。"""
|
||||
from app.services.equipment_acceptance.oa_repository import fetch_alert_directory
|
||||
|
||||
ids: set[int] = set()
|
||||
for group in operators.values():
|
||||
for operator in group:
|
||||
if operator.user_id:
|
||||
ids.add(operator.user_id)
|
||||
for order in orders:
|
||||
if order.monitor_status == WATCHING and order.applicant_oa_id:
|
||||
if (order.oa_system or "e10") == "e8" or order.monitor_status != WATCHING:
|
||||
continue
|
||||
if order.owner_oa_id:
|
||||
ids.add(order.owner_oa_id)
|
||||
if order.applicant_oa_id:
|
||||
ids.add(order.applicant_oa_id)
|
||||
return fetch_alert_directory(sorted(ids))
|
||||
|
||||
|
||||
def _load_e8_directory(
|
||||
orders: list[EquipmentAcceptanceOrder],
|
||||
) -> tuple[dict[int, dict[str, Any]], dict[str, dict[str, Any]]]:
|
||||
"""向 E8 要使用部门担当和申请人。人员 ID 只进 HrmResource。"""
|
||||
from app.services.equipment_acceptance.e8_repository import fetch_e8_alert_directory
|
||||
|
||||
ids: set[int] = set()
|
||||
for order in orders:
|
||||
if (order.oa_system or "e10") != "e8" or order.monitor_status != WATCHING:
|
||||
continue
|
||||
if order.owner_oa_id:
|
||||
ids.add(order.owner_oa_id)
|
||||
if order.applicant_oa_id:
|
||||
ids.add(order.applicant_oa_id)
|
||||
return fetch_e8_alert_directory(sorted(ids))
|
||||
|
||||
|
||||
def _job_numbers(
|
||||
orders: list[EquipmentAcceptanceOrder],
|
||||
operators: dict[int, list[EquipmentAcceptanceOperator]],
|
||||
people: dict[int, dict[str, Any]],
|
||||
deputies: dict[str, list[dict[str, Any]]],
|
||||
e10_people: dict[int, dict[str, Any]],
|
||||
e10_deputies: dict[str, list[dict[str, Any]]],
|
||||
e8_people: dict[int, dict[str, Any]],
|
||||
) -> set[str]:
|
||||
"""收集要对系统用户的工号。"""
|
||||
"""收集要对系统用户的工号。E8 矩阵人员不走工号。"""
|
||||
found: set[str] = set()
|
||||
for order in orders:
|
||||
if order.owner_job_num:
|
||||
found.add(order.owner_job_num)
|
||||
if order.applicant_job_num:
|
||||
found.add(order.applicant_job_num)
|
||||
for group in operators.values():
|
||||
for operator in group:
|
||||
if operator.handler_job_num:
|
||||
found.add(operator.handler_job_num)
|
||||
for fact in people.values():
|
||||
for fact in (*e10_people.values(), *e8_people.values()):
|
||||
if fact.get("job_num"):
|
||||
found.add(str(fact["job_num"]))
|
||||
if fact.get("superior_job_num"):
|
||||
found.add(str(fact["superior_job_num"]))
|
||||
for group in deputies.values():
|
||||
for group in e10_deputies.values():
|
||||
for item in group:
|
||||
if item.get("job_num"):
|
||||
found.add(str(item["job_num"]))
|
||||
return found
|
||||
|
||||
|
||||
def _wecom_ids(matrix: dict[str, dict[str, Any]]) -> set[str]:
|
||||
"""收集 E8 矩阵上的企业微信 userid,用来补系统用户主键。"""
|
||||
found: set[str] = set()
|
||||
for item in matrix.values():
|
||||
if not item.get("ok"):
|
||||
continue
|
||||
for key in ("zz", "jfl"):
|
||||
seat = item.get(key) or {}
|
||||
wecom = str(seat.get("wecom_userid") or "").strip()
|
||||
if wecom:
|
||||
found.add(wecom)
|
||||
return found
|
||||
|
||||
|
||||
def _users_by_wecom(wecom_ids: set[str]) -> dict[str, User]:
|
||||
"""按企业微信 userid 索引系统用户。"""
|
||||
if not wecom_ids:
|
||||
return {}
|
||||
rows = db.session.query(User).filter(User.wecom_userid.in_(wecom_ids)).all()
|
||||
return {str(row.wecom_userid): row for row in rows if row.wecom_userid}
|
||||
|
||||
|
||||
def _users_by_job(job_nums: set[str]) -> dict[str, User]:
|
||||
"""用工号索引系统用户。"""
|
||||
if not job_nums:
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/e8_group.py
|
||||
|
||||
用途:把 E8 验收单联表行收成与 E10 相同的快照草稿。
|
||||
依赖:e8_status、snapshot_rules、source_group。
|
||||
逻辑:同步服务在写库前调用。流程状态先翻译。人员 ID 仍是 E8 的 HrmResource.id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.services.equipment_acceptance.e8_status import e8_flow_status
|
||||
from app.services.equipment_acceptance.snapshot_rules import (
|
||||
as_datetime,
|
||||
as_int,
|
||||
can_accept_from_oa,
|
||||
is_returned_from_oa,
|
||||
)
|
||||
from app.services.equipment_acceptance.source_group import (
|
||||
AcceptanceDraft,
|
||||
NodeDraft,
|
||||
OperatorDraft,
|
||||
)
|
||||
|
||||
_TERMINAL_FLOW = {3, 7}
|
||||
|
||||
|
||||
def group_e8_rows(rows: list[dict[str, Any]]) -> tuple[list[AcceptanceDraft], int]:
|
||||
"""
|
||||
按 requestid 合并 E8 联表行。
|
||||
|
||||
核心逻辑:没有 requestid 的行跳过。同一请求的未办人收成一张单。
|
||||
计时起点读 syddjssj。可以验收读 sfkys。来源标记为 e8。
|
||||
Args:
|
||||
rows: 查询别名组成的字典行。
|
||||
Returns:
|
||||
(草稿列表, 因缺少 requestid 而跳过的行数)。
|
||||
"""
|
||||
skipped = 0
|
||||
buckets: dict[int, list[dict[str, Any]]] = {}
|
||||
for row in rows:
|
||||
request_id = as_int(row.get("requestid"))
|
||||
if request_id is None:
|
||||
skipped += 1
|
||||
continue
|
||||
buckets.setdefault(request_id, []).append(row)
|
||||
return [_draft_from_rows(request_id, items) for request_id, items in buckets.items()], skipped
|
||||
|
||||
|
||||
def _draft_from_rows(request_id: int, items: list[dict[str, Any]]) -> AcceptanceDraft:
|
||||
"""同一流程的多行收成一条 E8 草稿。"""
|
||||
header = items[0]
|
||||
flow_status = e8_flow_status(header.get("currentnodetype"), header.get("currentstatus"))
|
||||
return AcceptanceDraft(
|
||||
oa_system="e8",
|
||||
request_id=request_id,
|
||||
acceptance_no=_text(header.get("ysddh")),
|
||||
purchase_order_no=_text(header.get("cgdh")),
|
||||
contract_no=_text(header.get("htbh")),
|
||||
flow_no=_text(header.get("flow_no")),
|
||||
request_title=_text(header.get("request_title")),
|
||||
request_created_at=_e8_created_at(header),
|
||||
timer_started_at=as_datetime(header.get("syddjssj")),
|
||||
can_accept=can_accept_from_oa(as_int(header.get("sfkys"))),
|
||||
cannot_accept_note=_text(header.get("ycsm")),
|
||||
is_returned=is_returned_from_oa(as_int(header.get("sfzfth"))),
|
||||
flow_status_raw=flow_status,
|
||||
finished_at=_finished_at(header, flow_status),
|
||||
request_match_count=1,
|
||||
nodes=_nodes(items),
|
||||
operators=_operators(items),
|
||||
owner_oa_id=as_int(header.get("sybmdd")),
|
||||
owner_name=_text(header.get("owner_name")),
|
||||
owner_job_num=_text(header.get("owner_job_num")),
|
||||
equip_oa_id=None,
|
||||
equip_name=None,
|
||||
equip_job_num=None,
|
||||
applicant_oa_id=as_int(header.get("creater")),
|
||||
applicant_name=_text(header.get("applicant_name")),
|
||||
applicant_job_num=_text(header.get("applicant_job_num")),
|
||||
)
|
||||
|
||||
|
||||
def _e8_created_at(header: dict[str, Any]) -> datetime | None:
|
||||
"""
|
||||
拼出 E8 流程创建时间。
|
||||
|
||||
核心逻辑:createdate 是日期,createtime 是时分秒,两边分开存。
|
||||
只有日期时按当天 0 点。都空则没有创建时间。
|
||||
"""
|
||||
day = _text(header.get("createdate"))
|
||||
clock = _text(header.get("createtime"))
|
||||
if day is None:
|
||||
return None
|
||||
if clock is None:
|
||||
return as_datetime(day)
|
||||
return as_datetime(f"{day} {clock}")
|
||||
|
||||
|
||||
def _finished_at(header: dict[str, Any], flow_status: int | None) -> datetime | None:
|
||||
"""归档或撤销时,用最后操作时间作为结束时间。进行中不写。"""
|
||||
if flow_status not in _TERMINAL_FLOW:
|
||||
return None
|
||||
parsed = as_datetime(header.get("lastoperatedate"))
|
||||
if parsed is not None:
|
||||
return parsed
|
||||
return None
|
||||
|
||||
|
||||
def _nodes(rows: list[dict[str, Any]]) -> list[NodeDraft]:
|
||||
"""当前节点只取 currentnodeid。没有节点 ID 时不造一行。"""
|
||||
found: dict[int, NodeDraft] = {}
|
||||
for row in rows:
|
||||
node_id = as_int(row.get("currentnodeid"))
|
||||
if node_id is None or node_id in found:
|
||||
continue
|
||||
found[node_id] = NodeDraft(
|
||||
node_id=node_id,
|
||||
node_name=_text(row.get("nodename")),
|
||||
node_type=None,
|
||||
)
|
||||
return list(found.values())
|
||||
|
||||
|
||||
def _operators(rows: list[dict[str, Any]]) -> list[OperatorDraft]:
|
||||
"""当前未办人。查询已限定 isremark=0,这里只按人和节点去重。"""
|
||||
found: dict[tuple[int, int], OperatorDraft] = {}
|
||||
for row in rows:
|
||||
node_id = as_int(row.get("currentnodeid"))
|
||||
user_id = as_int(row.get("userid"))
|
||||
if node_id is None or user_id is None:
|
||||
continue
|
||||
key = (node_id, user_id)
|
||||
if key in found:
|
||||
continue
|
||||
found[key] = OperatorDraft(
|
||||
node_id=node_id,
|
||||
user_id=user_id,
|
||||
handler_name=_text(row.get("handler_name")),
|
||||
handler_job_num=_text(row.get("handler_job_num")),
|
||||
)
|
||||
return list(found.values())
|
||||
|
||||
|
||||
def _text(value: Any) -> str | None:
|
||||
"""去空白;空串视为没有值。"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
@@ -0,0 +1,71 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/e8_query.py
|
||||
|
||||
用途:组装 E8 验收单只读 SQL。
|
||||
依赖:无。不连接数据库。
|
||||
逻辑:e8_repository 执行本文件的语句。表名固定,不拼接外部字符串。
|
||||
不复用合同付款只取归档日的查询。不取 currentnodetype=3 的归档单,空节点类型仍取。
|
||||
流程编号取 lcbh,标题取 requestname。创建时间取 createdate 加 createtime。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def build_e8_acceptance_sql() -> str:
|
||||
"""
|
||||
组装未归档的 E8 验收单查询。
|
||||
|
||||
核心逻辑:formtable_main_324.requestId 对 workflow_requestbase.requestid。
|
||||
当前节点用 currentnodeid,不用 lastnodeid。当前未办人是 isremark=0。
|
||||
currentnodetype=3 的归档单不取,空值仍取。申请人读 creater,不是 creator。
|
||||
流程编号读 lcbh,标题读 requestname。创建时间由 createdate 与 createtime 拼成。
|
||||
Returns:
|
||||
一条 SELECT。
|
||||
"""
|
||||
return """
|
||||
SELECT
|
||||
f.ysddh AS ysddh,
|
||||
f.cgdh AS cgdh,
|
||||
f.htbh AS htbh,
|
||||
f.lcbh AS flow_no,
|
||||
f.syddjssj AS syddjssj,
|
||||
f.sfzfth AS sfzfth,
|
||||
f.sfkys AS sfkys,
|
||||
f.ycsm AS ycsm,
|
||||
f.sybmdd AS sybmdd,
|
||||
w.requestid AS requestid,
|
||||
w.requestname AS request_title,
|
||||
w.createdate AS createdate,
|
||||
w.createtime AS createtime,
|
||||
LTRIM(RTRIM(CAST(w.currentnodetype AS nvarchar(10)))) AS currentnodetype,
|
||||
w.currentstatus AS currentstatus,
|
||||
w.currentnodeid AS currentnodeid,
|
||||
w.creater AS creater,
|
||||
w.lastoperatedate AS lastoperatedate,
|
||||
w.lastoperatetime AS lastoperatetime,
|
||||
n.nodename AS nodename,
|
||||
op.userid AS userid,
|
||||
owner.lastname AS owner_name,
|
||||
owner.workcode AS owner_job_num,
|
||||
applicant.lastname AS applicant_name,
|
||||
applicant.workcode AS applicant_job_num,
|
||||
handler.lastname AS handler_name,
|
||||
handler.workcode AS handler_job_num
|
||||
FROM formtable_main_324 AS f
|
||||
INNER JOIN workflow_requestbase AS w
|
||||
ON w.requestid = f.requestId
|
||||
LEFT JOIN workflow_nodebase AS n
|
||||
ON n.id = w.currentnodeid
|
||||
LEFT JOIN workflow_currentoperator AS op
|
||||
ON op.requestid = w.requestid
|
||||
AND op.nodeid = w.currentnodeid
|
||||
AND LTRIM(RTRIM(CAST(op.isremark AS nvarchar(10)))) = N'0'
|
||||
LEFT JOIN HrmResource AS owner
|
||||
ON owner.id = f.sybmdd
|
||||
LEFT JOIN HrmResource AS applicant
|
||||
ON applicant.id = w.creater
|
||||
LEFT JOIN HrmResource AS handler
|
||||
ON handler.id = op.userid
|
||||
WHERE w.currentnodetype IS NULL
|
||||
OR LTRIM(RTRIM(CAST(w.currentnodetype AS nvarchar(10)))) <> N'3'
|
||||
""".strip()
|
||||
@@ -0,0 +1,213 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/e8_repository.py
|
||||
|
||||
用途:只读拉取 E8 验收单,以及使用部门担当的直接主管和经副理。
|
||||
依赖:OASQLServerService、e8_query。不连接 E10,不把人员 ID 送进 eteams。
|
||||
逻辑:验收单一次联表。收件人再按 HrmResource.id 查部门和 Matrixtable_3。
|
||||
zz、jfl 就是企业微信 userid。矩阵不是一行时该部门失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.equipment_acceptance.e8_query import build_e8_acceptance_sql
|
||||
from app.services.equipment_acceptance.snapshot_rules import as_int
|
||||
from app.services.integrations.oa.sqlserver import OASQLServerService
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def fetch_e8_acceptance_rows() -> list[dict[str, Any]]:
|
||||
"""
|
||||
从 E8 拉验收单联表结果。
|
||||
|
||||
核心逻辑:复用 OA_SQLSERVER_* 只读连接。失败不改走 E10。
|
||||
Returns:
|
||||
字段名为小写别名的字典行。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 连接或查询失败。
|
||||
"""
|
||||
connection = _open()
|
||||
try:
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(build_e8_acceptance_sql())
|
||||
columns = [str(col[0]).lower() for col in cursor.description]
|
||||
return [
|
||||
{columns[index]: raw[index] for index in range(len(columns))}
|
||||
for raw in cursor.fetchall()
|
||||
]
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance e8 sql failed error=%s", type(exc).__name__)
|
||||
raise ServiceUnavailableError(
|
||||
"查询 E8 设备验收数据失败",
|
||||
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||
) from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def fetch_e8_alert_directory(
|
||||
person_ids: list[int],
|
||||
) -> tuple[dict[int, dict[str, Any]], dict[str, dict[str, Any]]]:
|
||||
"""
|
||||
按使用部门担当和申请人的 HrmResource.id 取工号,并按部门取直接主管、经副理。
|
||||
|
||||
核心逻辑:工号是 workcode。Matrixtable_3.bm 必须只命中一行,zz 是直接主管,jfl 是经副理。
|
||||
这两个 ID 同时是企业微信 userid。没有人员时不连库。
|
||||
Args:
|
||||
person_ids: HrmResource.id。禁止传入 E10 的 employee.ID。
|
||||
Returns:
|
||||
(人员字典, 部门 ID 到矩阵结果)。矩阵结果含 ok、zz、jfl。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 连接或查询失败。
|
||||
"""
|
||||
ids = sorted({int(item) for item in person_ids if item is not None})
|
||||
if not ids:
|
||||
return {}, {}
|
||||
connection = _open()
|
||||
try:
|
||||
cursor = connection.cursor()
|
||||
people = _load_people(cursor, ids)
|
||||
departments = sorted({item["department_id"] for item in people.values() if item.get("department_id")})
|
||||
matrix = _load_matrix(cursor, departments)
|
||||
_fill_matrix_names(cursor, matrix)
|
||||
return people, matrix
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance e8 directory failed error=%s", type(exc).__name__)
|
||||
raise ServiceUnavailableError(
|
||||
"查询 E8 直接主管和经副理失败",
|
||||
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||
) from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def _open():
|
||||
"""打开 E8 ecology 连接。异常收成业务错误,不把连接串写进日志。"""
|
||||
try:
|
||||
return OASQLServerService._connect()
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance e8 connect failed error=%s", type(exc).__name__)
|
||||
raise ServiceUnavailableError(
|
||||
"连接 E8 SQL Server 失败",
|
||||
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||
) from exc
|
||||
|
||||
|
||||
def _load_people(cursor: Any, person_ids: list[int]) -> dict[int, dict[str, Any]]:
|
||||
"""取出姓名、工号和部门。"""
|
||||
found: dict[int, dict[str, Any]] = {}
|
||||
for chunk in _chunks(person_ids):
|
||||
marks = ",".join("?" for _ in chunk)
|
||||
cursor.execute(
|
||||
f"""
|
||||
SELECT id, lastname, workcode, departmentid
|
||||
FROM HrmResource
|
||||
WHERE id IN ({marks})
|
||||
""",
|
||||
chunk,
|
||||
)
|
||||
for raw in cursor.fetchall():
|
||||
person_id = as_int(raw[0])
|
||||
if person_id is None:
|
||||
continue
|
||||
found[person_id] = {
|
||||
"oa_id": person_id,
|
||||
"name": _clean(raw[1]),
|
||||
"job_num": _clean(raw[2]),
|
||||
"department_id": _clean(raw[3]),
|
||||
}
|
||||
return found
|
||||
|
||||
|
||||
def _load_matrix(cursor: Any, department_ids: list[str]) -> dict[str, dict[str, Any]]:
|
||||
"""按部门取矩阵。不是正好一行就记失败,不挑其中一行。"""
|
||||
grouped: dict[str, list[tuple[Any, Any]]] = {}
|
||||
if not department_ids:
|
||||
return {}
|
||||
for chunk in _chunks(department_ids):
|
||||
marks = ",".join("?" for _ in chunk)
|
||||
params = [int(item) if str(item).isdigit() else item for item in chunk]
|
||||
cursor.execute(
|
||||
f"""
|
||||
SELECT bm, zz, jfl
|
||||
FROM Matrixtable_3
|
||||
WHERE bm IN ({marks})
|
||||
""",
|
||||
params,
|
||||
)
|
||||
for raw in cursor.fetchall():
|
||||
department_id = _clean(raw[0])
|
||||
if not department_id:
|
||||
continue
|
||||
grouped.setdefault(department_id, []).append((raw[1], raw[2]))
|
||||
found: dict[str, dict[str, Any]] = {}
|
||||
for department_id, rows in grouped.items():
|
||||
if len(rows) != 1:
|
||||
found[department_id] = {"ok": False, "zz": None, "jfl": None}
|
||||
continue
|
||||
zz_id = as_int(rows[0][0])
|
||||
jfl_id = as_int(rows[0][1])
|
||||
found[department_id] = {
|
||||
"ok": True,
|
||||
"zz": _seat(zz_id),
|
||||
"jfl": _seat(jfl_id),
|
||||
}
|
||||
return found
|
||||
|
||||
|
||||
def _fill_matrix_names(cursor: Any, matrix: dict[str, dict[str, Any]]) -> None:
|
||||
"""给直接主管和经副理补姓名。查不到姓名仍保留企微 userid。"""
|
||||
ids = sorted({
|
||||
seat["oa_id"]
|
||||
for item in matrix.values()
|
||||
if item.get("ok")
|
||||
for seat in (item.get("zz"), item.get("jfl"))
|
||||
if seat and seat.get("oa_id") is not None
|
||||
})
|
||||
if not ids:
|
||||
return
|
||||
names = _load_people(cursor, ids)
|
||||
for item in matrix.values():
|
||||
if not item.get("ok"):
|
||||
continue
|
||||
for key in ("zz", "jfl"):
|
||||
seat = item.get(key)
|
||||
if not seat:
|
||||
continue
|
||||
fact = names.get(seat["oa_id"]) or {}
|
||||
if fact.get("name"):
|
||||
seat["name"] = fact["name"]
|
||||
|
||||
|
||||
def _seat(person_id: int | None) -> dict[str, Any] | None:
|
||||
"""矩阵里的人员 ID 直接作为企业微信 userid。"""
|
||||
if person_id is None:
|
||||
return None
|
||||
return {
|
||||
"oa_id": person_id,
|
||||
"name": None,
|
||||
"wecom_userid": str(person_id),
|
||||
}
|
||||
|
||||
|
||||
def _chunks(values: list[Any], size: int = 400) -> list[list[Any]]:
|
||||
"""把 IN 列表拆开。"""
|
||||
return [values[index:index + size] for index in range(0, len(values), size)]
|
||||
|
||||
|
||||
def _clean(value: Any) -> str | None:
|
||||
"""去掉空白。"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/e8_status.py
|
||||
|
||||
用途:把 E8 流程状态收成与 E10 相同的 flow_status_raw。
|
||||
依赖:无。不读数据库。
|
||||
逻辑:同步分组在落库前调用。currentstatus 优先于 currentnodetype。
|
||||
E8 没有作废和强制结束,不写成 5 或 4。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
# 与 E10 的审批中、归档、撤销对齐。暂停按 E10 的 flowstatus=7,同样停表。
|
||||
_APPROVING = 1
|
||||
_ARCHIVED = 3
|
||||
_REVOKED = 7
|
||||
_APPROVING_NODE_TYPES = {"0", "1", "2"}
|
||||
_PAUSE_OR_REVOKE = {0, 1}
|
||||
|
||||
|
||||
def e8_flow_status(currentnodetype: Any, currentstatus: Any) -> int | None:
|
||||
"""
|
||||
把 E8 的节点类型和暂停/撤销收成本地流程状态。
|
||||
|
||||
核心逻辑:currentstatus 为空才看 currentnodetype。0 暂停、1 撤销都写成 7。
|
||||
空、0、1 以外不写成审批中,返回空,调用方不把这张单放进进行中。
|
||||
Args:
|
||||
currentnodetype: workflow_requestbase.currentnodetype。0/1/2 审批中,3 归档。
|
||||
currentstatus: workflow_requestbase.currentstatus。空是正常,0 暂停,1 撤销。
|
||||
Returns:
|
||||
1、3 或 7。无法识别时为 None。
|
||||
"""
|
||||
status = _blank_to_none(currentstatus)
|
||||
if status is not None:
|
||||
code = _as_int(status)
|
||||
if code in _PAUSE_OR_REVOKE:
|
||||
return _REVOKED
|
||||
return None
|
||||
node_type = _blank_to_none(currentnodetype)
|
||||
if node_type in _APPROVING_NODE_TYPES:
|
||||
return _APPROVING
|
||||
if node_type == "3":
|
||||
return _ARCHIVED
|
||||
return None
|
||||
|
||||
|
||||
def _blank_to_none(value: Any) -> str | None:
|
||||
"""空白当成没有值。数字也收成去掉空白的文本。"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _as_int(value: str) -> int | None:
|
||||
"""整数字符串收成 int。带小数或字母的不猜。"""
|
||||
try:
|
||||
if "." in value:
|
||||
return None
|
||||
return int(value)
|
||||
except ValueError:
|
||||
return None
|
||||
@@ -126,12 +126,12 @@ def _open_connection(settings: EquipmentAcceptanceSqlSettings):
|
||||
|
||||
def fetch_alert_directory(employee_ids: list[int]) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
||||
"""
|
||||
读取处理人的直接主管,并按部门查出经副理。
|
||||
读取使用部门担当的直接主管,并按部门查出经副理。
|
||||
|
||||
核心逻辑:主管在 employee.SUPERIOR。经副理不在这一列,按部门 ID 走 eteams 矩阵条件表。
|
||||
人员 ID 必须是整数。没有人员时不连库。
|
||||
人员 ID 必须是 E10 的 employee.ID。没有人员时不连库。
|
||||
Args:
|
||||
employee_ids: 当前处理人和申请人的 employee.ID。
|
||||
employee_ids: 使用部门担当和申请人的 employee.ID。禁止传入 E8 的 HrmResource.id。
|
||||
Returns:
|
||||
(人员字典, 部门 ID 到经副理列表)。人员字典的键是 employee.ID。
|
||||
|
||||
|
||||
@@ -4,7 +4,8 @@ backend/app/services/equipment_acceptance/query_sql.py
|
||||
用途:决定 E10 各表所在库,并组装只读联表 SQL。
|
||||
依赖:无 Flask。库名只允许字母、数字和下划线。
|
||||
逻辑:同步仓库调用。验收单用 FORM_DATA_ID 经 wfc_form_data 挂到流程实例。
|
||||
不读流程编号、第二合同编号、验收日期、optgroupid、batch_number、operate_log_id、isremark。无法验收说明读取 ycsm。字典库看不到时,流程表回退到 ecology10。
|
||||
不取 flowstatus=3 的归档单。flowstatus 为空仍取。
|
||||
流程编号读 requestmark,标题读 requestname,创建时间读 createdatetime。不读第二合同编号、验收日期、optgroupid、batch_number、operate_log_id、isremark。无法验收说明读取 ycsm。字典库看不到时,流程表回退到 ecology10。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -68,8 +69,8 @@ def build_acceptance_sql(catalogs: AcceptanceCatalogs) -> str:
|
||||
组装验收单、人员、流程实例、当前节点、节点定义、操作人的只读 SQL。
|
||||
|
||||
核心逻辑:用 FORM_DATA_ID 对齐 wfc_form_data.dataid,再按 requestid 挂到流程实例。
|
||||
不查询流程编号、第二合同编号、验收日期和 isremark。当前节点和操作人按 requestid + nodeid 对齐,
|
||||
delete_type 只取 0。当前处理人就是这些 userid。
|
||||
流程编号取 requestmark,标题取 requestname,创建时间取 createdatetime。不查询第二合同编号、验收日期和 isremark。当前节点和操作人按 requestid + nodeid 对齐,
|
||||
delete_type 只取 0。当前处理人就是这些 userid。归档(flowstatus=3)不取,空状态仍取。
|
||||
Args:
|
||||
catalogs: 已解析的库名。
|
||||
Returns:
|
||||
@@ -104,6 +105,9 @@ SELECT
|
||||
applicant.USERNAME AS applicant_name,
|
||||
applicant.JOB_NUM AS applicant_job_num,
|
||||
r.requestid,
|
||||
r.requestmark AS flow_no,
|
||||
r.requestname AS request_title,
|
||||
r.createdatetime,
|
||||
r.flowstatus,
|
||||
r.finishdatetime,
|
||||
c.nodeid,
|
||||
@@ -135,6 +139,7 @@ LEFT JOIN {operate} AS op
|
||||
LEFT JOIN {employee} AS handler ON handler.ID = op.userid
|
||||
WHERE ISNULL(f.delete_type, 0) = 0
|
||||
AND r.requestid IS NOT NULL
|
||||
AND (r.flowstatus IS NULL OR r.flowstatus <> 3)
|
||||
""".strip()
|
||||
|
||||
|
||||
|
||||
@@ -179,7 +179,7 @@ def classify_monitor_status(
|
||||
按已确认规则给出监控状态。入参已是标准 0=否、1=是。
|
||||
|
||||
核心逻辑:退回、无法验收、作废、归档、强制结束、撤销优先于未开始。
|
||||
审批中、可以验收、未退回、已有计时起点才是计时中。
|
||||
审批中、未退回、已有计时起点,且可以验收不是明确为否时计时。空和是都监控。
|
||||
flowstatus 为 7、8、99、-99 时记为已撤销,有没有计时起点都不再提醒。
|
||||
Args:
|
||||
can_accept: 本地是否可以正常验收。0 否,1 是,空为未标明。
|
||||
@@ -204,8 +204,8 @@ def classify_monitor_status(
|
||||
return STOPPED_REVOKED
|
||||
if not timer_started:
|
||||
return NOT_STARTED
|
||||
# [STEP 2] 只有审批中、可以验收、未退回时继续计时
|
||||
if can_accept == 1 and flow_status == _FLOW_APPROVING and is_returned == 0:
|
||||
# [STEP 2] 可以验收只有明确为否才停表,空和是都继续计时。0、1、空以外不猜。
|
||||
if can_accept in (1, None) and flow_status == _FLOW_APPROVING and is_returned == 0:
|
||||
return WATCHING
|
||||
return EXCLUDED
|
||||
|
||||
|
||||
@@ -42,12 +42,16 @@ class NodeDraft:
|
||||
|
||||
@dataclass
|
||||
class AcceptanceDraft:
|
||||
"""一张验收单在一次同步中的快照草稿。不包含流程编号、第二合同编号和验收日期。"""
|
||||
"""一张验收单在一次同步中的快照草稿。含流程编号、标题和创建时间。不含第二合同编号和验收日期。"""
|
||||
|
||||
oa_system: str
|
||||
request_id: int
|
||||
acceptance_no: str | None
|
||||
purchase_order_no: str | None
|
||||
contract_no: str | None
|
||||
flow_no: str | None
|
||||
request_title: str | None
|
||||
request_created_at: datetime | None
|
||||
timer_started_at: datetime | None
|
||||
can_accept: int | None
|
||||
cannot_accept_note: str | None
|
||||
@@ -73,7 +77,7 @@ def group_acceptance_rows(rows: list[dict[str, Any]]) -> tuple[list[AcceptanceDr
|
||||
按流程实例 requestid 合并联表结果。
|
||||
|
||||
核心逻辑:没有 requestid 的行跳过。同一请求上的节点和操作人收成一张单。
|
||||
不读取流程编号、第二合同编号和验收日期。
|
||||
流程编号和标题随行写入。不读取第二合同编号和验收日期。
|
||||
Args:
|
||||
rows: 查询别名组成的字典行。
|
||||
Returns:
|
||||
@@ -94,10 +98,14 @@ def _draft_from_rows(request_id: int, items: list[dict[str, Any]]) -> Acceptance
|
||||
"""同一流程实例的多行收成一条草稿。"""
|
||||
header = items[0]
|
||||
return AcceptanceDraft(
|
||||
oa_system="e10",
|
||||
request_id=request_id,
|
||||
acceptance_no=_text(header.get("ysddh")),
|
||||
purchase_order_no=_text(header.get("cgdh")),
|
||||
contract_no=_text(header.get("htbh")),
|
||||
flow_no=_text(header.get("flow_no")),
|
||||
request_title=_text(header.get("request_title")),
|
||||
request_created_at=as_datetime(header.get("createdatetime")),
|
||||
timer_started_at=as_datetime(header.get("sbsyrjssj")),
|
||||
can_accept=can_accept_from_oa(as_int(header.get("sfkyzcys"))),
|
||||
cannot_accept_note=_text(header.get("ycsm")),
|
||||
|
||||
@@ -1,19 +1,24 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/sync_service.py
|
||||
|
||||
用途:把 E10 验收单快照写入本地表,并提供管理员查询。
|
||||
依赖:extensions.db、equipment_acceptance 模型、snapshot_rules、source_group、oa_repository。
|
||||
逻辑:手动同步 upsert 主表并替换子表。列表按原型分组过滤,并附带全部单据的汇总。
|
||||
停表时取消该单未发送的预警。操作人不保存 isremark。
|
||||
用途:把 E10 和 E8 验收单快照写入本地表,并提供管理员查询。
|
||||
依赖:extensions.db、sqlalchemy.or_、equipment_acceptance 模型、snapshot_rules、source_group、e8_group、oa_repository、e8_repository。
|
||||
逻辑:两个来源分开拉取。一边失败不改另一边的快照,也不把失败来源标成消失。
|
||||
只保留未归档单据。归档单不写入;该来源本次结果里没有的本地单删除,并取消未发送预警。
|
||||
主表按 oa_system + request_id 更新,并写入流程编号和标题。子表整批替换。停表时取消未发送预警。
|
||||
列表查询由 api/equipment_acceptance 调用。单号关键字同时匹配流程编号、验收单号和采购单号,再与申请人取交集。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections import Counter
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.core.response import utc_iso
|
||||
from app.extensions import db
|
||||
@@ -25,12 +30,15 @@ from app.models.equipment_acceptance import (
|
||||
from app.services.equipment_acceptance.config_service import first_reminder_day
|
||||
from app.services.equipment_acceptance.snapshot_rules import (
|
||||
MONITOR_STATUSES,
|
||||
STOPPED_ARCHIVED,
|
||||
classify_monitor_status,
|
||||
dwell_days,
|
||||
)
|
||||
from app.services.equipment_acceptance.source_group import AcceptanceDraft, group_acceptance_rows
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
_SHANGHAI = ZoneInfo("Asia/Shanghai")
|
||||
_ARCHIVED_FLOW = 3
|
||||
_LEDGER_FOCUSES = ("watching", "overdue", "stopped", "not_started")
|
||||
_STOPPED_STATUSES = (
|
||||
"stopped_returned",
|
||||
@@ -42,34 +50,107 @@ _STOPPED_STATUSES = (
|
||||
)
|
||||
|
||||
|
||||
def sync_acceptance_snapshots(rows: list[dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||
def sync_acceptance_snapshots(
|
||||
rows: list[dict[str, Any]] | None = None,
|
||||
*,
|
||||
e8_rows: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
同步验收单快照。
|
||||
同步 E10 和 E8 验收单快照。
|
||||
|
||||
核心逻辑:未传入行时自己读 E10。按流程实例 request_id 更新主表,子表整批替换。
|
||||
本次查询里消失的单据保留上次内容,只把 present_in_source 标成否。
|
||||
核心逻辑:未传入行时分别读两个来源。一边查询失败只跳过这一边,不把已有快照标成消失。
|
||||
只保留未归档单据。该来源本次没返回的本地单删掉。只传入 rows 时只同步 E10,方便既有测试注入联表行。
|
||||
Args:
|
||||
rows: 测试或调用方已经取好的联表行。None 时访问 E10。
|
||||
rows: 已取好的 E10 联表行。None 时访问 E10。
|
||||
e8_rows: 已取好的 E8 联表行。与 rows 同时为 None 时才访问 E8。
|
||||
Returns:
|
||||
本次写入条数、跳过条数、停表取消的未发送条数,以及各监控状态计数。
|
||||
两边合计的写入、跳过、消失和取消条数,以及 e10、e8 各自的结果。
|
||||
"""
|
||||
if rows is None:
|
||||
from app.services.equipment_acceptance.oa_repository import fetch_acceptance_rows
|
||||
|
||||
rows = fetch_acceptance_rows()
|
||||
drafts, skipped = group_acceptance_rows(rows)
|
||||
fetch_live = rows is None and e8_rows is None
|
||||
e10_rows, e10_ok, e10_error = _source_rows("e10", rows, fetch_live)
|
||||
e8_input, e8_ok, e8_error = _source_rows("e8", e8_rows, fetch_live)
|
||||
as_of = datetime.now(_SHANGHAI).date()
|
||||
e10_result = _apply_source("e10", e10_rows, e10_ok, e10_error, as_of, group_acceptance_rows)
|
||||
from app.services.equipment_acceptance.e8_group import group_e8_rows
|
||||
|
||||
e8_result = _apply_source("e8", e8_input, e8_ok, e8_error, as_of, group_e8_rows)
|
||||
db.session.commit()
|
||||
cancelled = e10_result["cancelled"] + e8_result["cancelled"]
|
||||
counts: Counter[str] = Counter(e10_result["by_status"])
|
||||
counts.update(e8_result["by_status"])
|
||||
return {
|
||||
"upserted": e10_result["upserted"] + e8_result["upserted"],
|
||||
"skipped_without_request_id": (
|
||||
e10_result["skipped_without_request_id"] + e8_result["skipped_without_request_id"]
|
||||
),
|
||||
"absent": e10_result["absent"] + e8_result["absent"],
|
||||
"cancelled": cancelled,
|
||||
"by_status": dict(counts),
|
||||
"e10": e10_result,
|
||||
"e8": e8_result,
|
||||
}
|
||||
|
||||
|
||||
def _source_rows(
|
||||
source: str,
|
||||
injected: list[dict[str, Any]] | None,
|
||||
fetch_live: bool,
|
||||
) -> tuple[list[dict[str, Any]] | None, bool, str | None]:
|
||||
"""取一个来源的行。注入的行视为成功。实时查询失败时不标消失。"""
|
||||
if injected is not None:
|
||||
return injected, True, None
|
||||
if not fetch_live:
|
||||
return None, False, None
|
||||
try:
|
||||
if source == "e10":
|
||||
from app.services.equipment_acceptance.oa_repository import fetch_acceptance_rows
|
||||
|
||||
return fetch_acceptance_rows(), True, None
|
||||
from app.services.equipment_acceptance.e8_repository import fetch_e8_acceptance_rows
|
||||
|
||||
return fetch_e8_acceptance_rows(), True, None
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance %s sync skipped error=%s", source, type(exc).__name__)
|
||||
return None, False, type(exc).__name__
|
||||
|
||||
|
||||
def _apply_source(
|
||||
source: str,
|
||||
rows: list[dict[str, Any]] | None,
|
||||
ok: bool,
|
||||
error: str | None,
|
||||
as_of,
|
||||
grouper,
|
||||
) -> dict[str, Any]:
|
||||
"""把一个来源的未归档草稿写入。该来源这次没返回的本地单删除。"""
|
||||
if not ok or rows is None:
|
||||
return {
|
||||
"ok": False,
|
||||
"error": error,
|
||||
"upserted": 0,
|
||||
"skipped_without_request_id": 0,
|
||||
"absent": 0,
|
||||
"cancelled": 0,
|
||||
"by_status": {},
|
||||
}
|
||||
drafts, skipped = grouper(rows)
|
||||
counts: Counter[str] = Counter()
|
||||
request_ids: list[int] = []
|
||||
cancelled = 0
|
||||
for draft in drafts:
|
||||
# [STEP] 归档单不落本地。查询已排除;这里再挡一层,避免注入行把归档单写回来。
|
||||
if draft.flow_status_raw == _ARCHIVED_FLOW:
|
||||
continue
|
||||
draft.oa_system = source
|
||||
order, cancelled_now = _upsert_order(draft, as_of=as_of)
|
||||
request_ids.append(order.request_id)
|
||||
counts[order.monitor_status] += 1
|
||||
cancelled += cancelled_now
|
||||
absent = _mark_absent(request_ids)
|
||||
db.session.commit()
|
||||
absent, cancelled_missing = _drop_missing(request_ids, source)
|
||||
cancelled += cancelled_missing
|
||||
return {
|
||||
"ok": True,
|
||||
"error": None,
|
||||
"upserted": len(drafts),
|
||||
"skipped_without_request_id": skipped,
|
||||
"absent": absent,
|
||||
@@ -84,17 +165,23 @@ def list_acceptance_orders(
|
||||
focus: str | None,
|
||||
page: int,
|
||||
page_size: int,
|
||||
keyword: str | None = None,
|
||||
applicant: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
分页列出本地快照。
|
||||
|
||||
核心逻辑:focus 按原型的全部、进行中、已逾期、不再提醒、未开始过滤。
|
||||
已逾期是计时中且签核天数超过第 1 档。汇总数字始终看全部单据。
|
||||
核心逻辑:focus 按全部、进行中、已逾期、不再提醒、未开始过滤。
|
||||
keyword 在流程编号、验收单号、采购单号里任一包含即命中,再与申请人姓名取交集。
|
||||
已归档不列出。已逾期是计时中且签核天数超过第 1 档。
|
||||
汇总不看当前状态分组,但跟着单号关键字和申请人走,也不计归档。
|
||||
Args:
|
||||
monitor_status: 可选的单个监控状态代码。与 focus 同时传时以 focus 为准。
|
||||
focus: watching、overdue、stopped、not_started 或空。
|
||||
page: 从 1 开始。
|
||||
page_size: 每页条数,上限 100。
|
||||
keyword: 流程编号、验收单号或采购单号的包含匹配。空白表示不筛。
|
||||
applicant: 申请人姓名的包含匹配。空白表示不筛。
|
||||
Returns:
|
||||
items、total、page、page_size、summary。
|
||||
|
||||
@@ -106,7 +193,11 @@ def list_acceptance_orders(
|
||||
reminder_day = first_reminder_day()
|
||||
page = max(1, page)
|
||||
page_size = min(100, max(1, page_size))
|
||||
query = db.session.query(EquipmentAcceptanceOrder)
|
||||
query = _apply_search(
|
||||
_without_archived(db.session.query(EquipmentAcceptanceOrder)),
|
||||
keyword=keyword,
|
||||
applicant=applicant,
|
||||
)
|
||||
if ledger_focus:
|
||||
query = _apply_focus(query, ledger_focus, reminder_day)
|
||||
elif status:
|
||||
@@ -131,7 +222,7 @@ def list_acceptance_orders(
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"pages": pages,
|
||||
"summary": _ledger_summary(reminder_day),
|
||||
"summary": _ledger_summary(reminder_day, keyword=keyword, applicant=applicant),
|
||||
}
|
||||
|
||||
|
||||
@@ -160,20 +251,25 @@ def get_acceptance_order(order_id: int) -> dict[str, Any]:
|
||||
|
||||
def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptanceOrder, int]:
|
||||
"""
|
||||
按流程实例 request_id 更新主表,并替换该单的节点和操作人。
|
||||
按来源和流程实例更新主表,并替换该单的节点和操作人。
|
||||
|
||||
核心逻辑:不再计时的单据顺手取消未发送预警。已发送的记录不动。
|
||||
E10 与 E8 的 request_id 可以相同,必须连 oa_system 一起查。
|
||||
Returns:
|
||||
更新后的验收单,以及本次改成已取消的发送记录条数。
|
||||
"""
|
||||
order = (
|
||||
db.session.query(EquipmentAcceptanceOrder)
|
||||
.filter(EquipmentAcceptanceOrder.request_id == draft.request_id)
|
||||
.filter(
|
||||
EquipmentAcceptanceOrder.oa_system == draft.oa_system,
|
||||
EquipmentAcceptanceOrder.request_id == draft.request_id,
|
||||
)
|
||||
.one_or_none()
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
if order is None:
|
||||
order = EquipmentAcceptanceOrder(
|
||||
oa_system=draft.oa_system,
|
||||
request_id=draft.request_id,
|
||||
monitor_status="excluded",
|
||||
synced_at=now,
|
||||
@@ -185,6 +281,9 @@ def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptance
|
||||
order.acceptance_no = draft.acceptance_no
|
||||
order.purchase_order_no = draft.purchase_order_no
|
||||
order.contract_no = draft.contract_no
|
||||
order.flow_no = draft.flow_no
|
||||
order.request_title = draft.request_title
|
||||
order.request_created_at = draft.request_created_at
|
||||
order.timer_started_at = draft.timer_started_at
|
||||
order.can_accept = draft.can_accept
|
||||
order.cannot_accept_note = draft.cannot_accept_note
|
||||
@@ -254,12 +353,45 @@ def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptance
|
||||
return order, cancelled
|
||||
|
||||
|
||||
def _mark_absent(request_ids: list[int]) -> int:
|
||||
"""把这次没拉到的单据标成源里不存在。"""
|
||||
query = db.session.query(EquipmentAcceptanceOrder).filter(EquipmentAcceptanceOrder.present_in_source.is_(True))
|
||||
def _drop_missing(request_ids: list[int], oa_system: str) -> tuple[int, int]:
|
||||
"""
|
||||
删除这个来源里本次未归档结果没有的本地单。
|
||||
|
||||
核心逻辑:查询已不含归档。本地还在、结果里没有的单,视为已归档或已从 OA 消失。
|
||||
先取消未发送预警,再删主表。节点和操作人随外键级联删除。已发送记录保留,只解开验收单外键。
|
||||
不改另一个来源。查询失败的来源不会进到这里。
|
||||
Returns:
|
||||
删除张数,以及取消的未发送条数。
|
||||
"""
|
||||
query = db.session.query(EquipmentAcceptanceOrder).filter(EquipmentAcceptanceOrder.oa_system == oa_system)
|
||||
if request_ids:
|
||||
query = query.filter(EquipmentAcceptanceOrder.request_id.notin_(request_ids))
|
||||
return query.update({EquipmentAcceptanceOrder.present_in_source: False}, synchronize_session=False)
|
||||
gone = query.all()
|
||||
if not gone:
|
||||
return 0, 0
|
||||
from app.services.equipment_acceptance.alert_service import cancel_unsent
|
||||
|
||||
cancelled = 0
|
||||
for order in gone:
|
||||
cancelled += cancel_unsent(order.id)
|
||||
db.session.delete(order)
|
||||
return len(gone), cancelled
|
||||
|
||||
|
||||
def _without_archived(query):
|
||||
"""
|
||||
列表和汇总都不展示已归档。
|
||||
|
||||
核心逻辑:状态已是归档的不显示。流程原值已是 3 的也不显示,
|
||||
避免退回或无法验收优先落成别的状态后,归档单仍留在列表里。
|
||||
"""
|
||||
return query.filter(
|
||||
EquipmentAcceptanceOrder.monitor_status != STOPPED_ARCHIVED,
|
||||
or_(
|
||||
EquipmentAcceptanceOrder.flow_status_raw.is_(None),
|
||||
EquipmentAcceptanceOrder.flow_status_raw != _ARCHIVED_FLOW,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _clean_focus(focus: str | None) -> str | None:
|
||||
@@ -290,9 +422,65 @@ def _apply_focus(query, focus: str, reminder_day: int):
|
||||
)
|
||||
|
||||
|
||||
def _ledger_summary(reminder_day: int) -> dict[str, int]:
|
||||
"""统计全部单据的进行中、已逾期、不再提醒、未开始,不受当前筛选影响。"""
|
||||
base = db.session.query(EquipmentAcceptanceOrder)
|
||||
def _clean_search(value: str | None) -> str | None:
|
||||
"""去掉首尾空白。空白视为不筛选。过长时只保留前 100 字,避免把整段说明送进 LIKE。"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
return text[:100]
|
||||
|
||||
|
||||
def _contains_pattern(text: str) -> str:
|
||||
"""
|
||||
把用户输入收成包含匹配,并把 LIKE 通配符当成普通字符。
|
||||
|
||||
核心逻辑:% 和 _ 要能搜出单号里的原字符,不能变成任意匹配。
|
||||
|
||||
Args:
|
||||
text: 已经去掉空白的搜索词。
|
||||
|
||||
Returns:
|
||||
带前后百分号、且转义过的模式。
|
||||
"""
|
||||
escaped = text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
return f"%{escaped}%"
|
||||
|
||||
|
||||
def _apply_search(query, *, keyword: str | None, applicant: str | None):
|
||||
"""
|
||||
按单号关键字和申请人收窄查询。
|
||||
|
||||
核心逻辑:关键字在流程编号、验收单号、采购单号三者取并集;申请人再与这个结果取交集。
|
||||
比较不区分大小写。空值不加入条件。
|
||||
"""
|
||||
number = _clean_search(keyword)
|
||||
if number:
|
||||
pattern = _contains_pattern(number)
|
||||
query = query.filter(or_(
|
||||
EquipmentAcceptanceOrder.flow_no.ilike(pattern, escape="\\"),
|
||||
EquipmentAcceptanceOrder.acceptance_no.ilike(pattern, escape="\\"),
|
||||
EquipmentAcceptanceOrder.purchase_order_no.ilike(pattern, escape="\\"),
|
||||
))
|
||||
person = _clean_search(applicant)
|
||||
if person:
|
||||
query = query.filter(
|
||||
EquipmentAcceptanceOrder.applicant_name.ilike(_contains_pattern(person), escape="\\"),
|
||||
)
|
||||
return query
|
||||
|
||||
|
||||
def _ledger_summary(
|
||||
reminder_day: int,
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
applicant: str | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""统计未归档单据的进行中、已逾期、不再提醒、未开始。不看状态分组,但跟着单号和申请人走。"""
|
||||
base = _apply_search(
|
||||
_without_archived(db.session.query(EquipmentAcceptanceOrder)),
|
||||
keyword=keyword,
|
||||
applicant=applicant,
|
||||
)
|
||||
return {
|
||||
"watching": base.filter(EquipmentAcceptanceOrder.monitor_status == "watching").count(),
|
||||
"overdue": base.filter(
|
||||
@@ -359,9 +547,13 @@ def _order_payload(
|
||||
"""把快照收成 API 数据。人员主键用字符串,避免长整型在前端丢精度。overdue 只标记计时中且超过第 1 档的单据。"""
|
||||
payload: dict[str, Any] = {
|
||||
"id": order.id,
|
||||
"oa_system": order.oa_system,
|
||||
"acceptance_no": order.acceptance_no,
|
||||
"purchase_order_no": order.purchase_order_no,
|
||||
"contract_no": order.contract_no,
|
||||
"flow_no": order.flow_no,
|
||||
"request_title": order.request_title,
|
||||
"request_created_at": utc_iso(order.request_created_at),
|
||||
"timer_started_at": utc_iso(order.timer_started_at),
|
||||
"dwell_days": order.dwell_days,
|
||||
"can_accept": order.can_accept,
|
||||
|
||||
@@ -2,11 +2,14 @@
|
||||
backend/app/services/faq_cache.py
|
||||
|
||||
用途:全局常用问题 FAQ 缓存匹配与 SSE 直答,避免重复调用 Dify。
|
||||
依赖:models.QuickQuestion、ChatLog、SQLAlchemy db。
|
||||
逻辑:chat.py 在调用 DifyService 前委托本模块 try_match(只看 cache_enabled,不看首页展示 is_enabled);命中则 stream_chat 返回预置答案。
|
||||
依赖:models.QuickQuestion、ChatLog、SQLAlchemy db、faq_text_utils(归一化与模糊评分)。
|
||||
逻辑:chat router 在调用 DifyService 前委托本模块 try_match(只看 cache_enabled,不看首页展示 is_enabled)。
|
||||
匹配分两阶段:[STEP 1] 归一化精确命中(所有启用缓存的条目);[STEP 2] 模糊兜底
|
||||
(仅 fuzzy_enabled 条目,得分达该条目阈值才命中),命中后 stream_chat 返回预置答案。
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
@@ -14,7 +17,26 @@ from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ChatLog, QuickQuestion
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.faq_text_utils import (
|
||||
FUZZY_MIN_LENGTH,
|
||||
clamp_fuzzy_threshold,
|
||||
fuzzy_match_score,
|
||||
normalize_faq_query,
|
||||
)
|
||||
|
||||
# 命中类型(写入 ChatLog payload 与 SSE metadata,供审计与排障)
|
||||
MATCH_TYPE_EXACT = 'exact'
|
||||
MATCH_TYPE_FUZZY = 'fuzzy'
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FaqCacheMatch:
|
||||
"""FAQ 缓存命中结果:条目本体 + 命中方式审计信息。"""
|
||||
|
||||
entry: QuickQuestion
|
||||
match_type: str # 'exact' 归一化全等;'fuzzy' 模糊兜底
|
||||
match_score: Optional[float] = None
|
||||
matched_text: Optional[str] = None
|
||||
|
||||
|
||||
class FaqCacheService:
|
||||
@@ -43,33 +65,48 @@ class FaqCacheService:
|
||||
return expires_at <= datetime.utcnow()
|
||||
|
||||
@staticmethod
|
||||
def _candidate_texts(entry: QuickQuestion) -> list[str]:
|
||||
def _candidate_pairs(entry: QuickQuestion) -> list[tuple[str, str]]:
|
||||
"""
|
||||
收集条目可用于匹配的标准化文本集合。
|
||||
收集条目可用于匹配的 (原文, 归一化文本) 对。
|
||||
核心逻辑:候选来源为 question、title 与 aliases;原文用于审计展示,归一化文本用于比对。
|
||||
@param entry - QuickQuestion 实例
|
||||
@returns 归一化后的候选文本列表
|
||||
@returns (原文, 归一化文本) 列表
|
||||
"""
|
||||
texts: list[str] = []
|
||||
pairs: list[tuple[str, str]] = []
|
||||
for raw in (entry.question, entry.title):
|
||||
normalized = FaqCacheService._normalize_text(raw)
|
||||
if normalized:
|
||||
texts.append(normalized)
|
||||
pairs.append((str(raw), normalized))
|
||||
aliases = entry.aliases if isinstance(entry.aliases, list) else []
|
||||
for alias in aliases:
|
||||
normalized = FaqCacheService._normalize_text(str(alias))
|
||||
if normalized:
|
||||
texts.append(normalized)
|
||||
return texts
|
||||
pairs.append((str(alias), normalized))
|
||||
return pairs
|
||||
|
||||
@staticmethod
|
||||
def try_match(query: str, agent_id: int) -> Optional[QuickQuestion]:
|
||||
def _candidate_texts(entry: QuickQuestion) -> list[str]:
|
||||
"""
|
||||
尝试为指定 Agent 命中全局 FAQ 缓存条目。
|
||||
核心逻辑:加载 cache_enabled 的全局条目,对 question/title/aliases 做归一化精确匹配。
|
||||
收集条目可用于匹配的标准化文本集合。
|
||||
核心逻辑:委托 _candidate_pairs 取归一化列;热点聚合(hot_faq_aggregator)依赖本方法做去重比对。
|
||||
@param entry - QuickQuestion 实例
|
||||
@returns 归一化后的候选文本列表
|
||||
"""
|
||||
return [normalized for _, normalized in FaqCacheService._candidate_pairs(entry)]
|
||||
|
||||
@staticmethod
|
||||
def try_match(query: str, agent_id: int) -> Optional[FaqCacheMatch]:
|
||||
"""
|
||||
尝试为指定 Agent 命中全局 FAQ 缓存条目(两阶段)。
|
||||
核心逻辑:
|
||||
[STEP 1] 精确阶段——所有 cache_enabled 条目的 question/title/aliases 归一化后与输入全等比对;
|
||||
[STEP 2] 模糊兜底——精确未命中且输入长度达 FUZZY_MIN_LENGTH 时,仅对 fuzzy_enabled 条目
|
||||
计算 fuzzy_match_score,最高分达到该条目阈值(钳制在 0.5~1.0)才命中;
|
||||
同分时先出现的条目(sort_order 靠前)胜出。
|
||||
is_enabled 只控制工作台首页是否展示快捷入口,不影响本方法是否直答。
|
||||
@param query - 用户提问
|
||||
@param agent_id - 当前 Agent 主键
|
||||
@returns 命中的 QuickQuestion;未命中返回 None
|
||||
@returns FaqCacheMatch;未命中返回 None
|
||||
"""
|
||||
normalized_query = FaqCacheService._normalize_text(query)
|
||||
if not normalized_query or not agent_id:
|
||||
@@ -89,12 +126,50 @@ class FaqCacheService:
|
||||
.all()
|
||||
)
|
||||
|
||||
# [STEP 1] 精确命中:归一化后全等,任何启用缓存的条目参与
|
||||
for entry in entries:
|
||||
if FaqCacheService._is_expired(entry):
|
||||
continue
|
||||
if normalized_query in FaqCacheService._candidate_texts(entry):
|
||||
return entry
|
||||
return None
|
||||
for raw, normalized in FaqCacheService._candidate_pairs(entry):
|
||||
if normalized_query == normalized:
|
||||
return FaqCacheMatch(
|
||||
entry=entry, match_type=MATCH_TYPE_EXACT, match_score=1.0, matched_text=raw
|
||||
)
|
||||
|
||||
# [STEP 2] 模糊兜底:仅参与模糊开关打开的条目,取最高分;短问句不参与
|
||||
if len(normalized_query) < FUZZY_MIN_LENGTH:
|
||||
return None
|
||||
best: Optional[FaqCacheMatch] = None
|
||||
for entry in entries:
|
||||
if not entry.fuzzy_enabled:
|
||||
continue
|
||||
if FaqCacheService._is_expired(entry):
|
||||
continue
|
||||
threshold = clamp_fuzzy_threshold(entry.fuzzy_threshold)
|
||||
for raw, normalized in FaqCacheService._candidate_pairs(entry):
|
||||
if len(normalized) < FUZZY_MIN_LENGTH:
|
||||
continue
|
||||
score = fuzzy_match_score(normalized_query, normalized)
|
||||
if score >= threshold and (best is None or score > (best.match_score or 0.0)):
|
||||
best = FaqCacheMatch(
|
||||
entry=entry, match_type=MATCH_TYPE_FUZZY, match_score=score, matched_text=raw
|
||||
)
|
||||
return best
|
||||
|
||||
@staticmethod
|
||||
def _match_audit_fields(match: Optional[FaqCacheMatch]) -> dict[str, Any]:
|
||||
"""
|
||||
构造命中方式的审计字段,写入 ChatLog payload 与 SSE metadata。
|
||||
@param match - try_match 的命中结果;可为 None(历史调用方未传)
|
||||
@returns 含 match_type / match_score / matched_text 的字典
|
||||
"""
|
||||
if match is None:
|
||||
return {}
|
||||
return {
|
||||
'match_type': match.match_type,
|
||||
'match_score': round(match.match_score, 4) if match.match_score is not None else None,
|
||||
'matched_text': match.matched_text,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _increment_hit_count(entry_id: int) -> None:
|
||||
@@ -124,28 +199,38 @@ class FaqCacheService:
|
||||
agent,
|
||||
conversation_id: str | None = None,
|
||||
session_id: str | None = None,
|
||||
match: Optional[FaqCacheMatch] = None,
|
||||
):
|
||||
"""
|
||||
以 SSE 形式返回 FAQ 预置答案,并写入 ChatLog。
|
||||
核心逻辑:产出 message + message_end 事件,标记 payload.source=faq_cache。
|
||||
核心逻辑:产出 message + message_end 事件,标记 payload.source=faq_cache;
|
||||
match 非空时附带 match_type / match_score / matched_text 供审计与排障。
|
||||
@param entry - 命中的 QuickQuestion
|
||||
@param query - 用户原始提问
|
||||
@param user - 当前用户代理对象(需含 id)
|
||||
@param agent - 当前 Agent 代理对象(需含 id)
|
||||
@param conversation_id - Dify/外部会话 ID
|
||||
@param session_id - 本地会话 ID
|
||||
@param match - try_match 的命中结果;历史调用方可不传
|
||||
@yields SSE 格式字符串
|
||||
"""
|
||||
start_time = time.time()
|
||||
final_conversation_id = conversation_id or f"faq_{int(time.time())}"
|
||||
answer = str(entry.answer or "").strip()
|
||||
retriever_resources = entry.retriever_resources if isinstance(entry.retriever_resources, list) else []
|
||||
audit_fields = FaqCacheService._match_audit_fields(match)
|
||||
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': answer}, ensure_ascii=False)}\n\n"
|
||||
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
chat_log_id = None
|
||||
try:
|
||||
payload: dict[str, Any] = {
|
||||
'source': 'faq_cache',
|
||||
'faq_id': entry.id,
|
||||
'faq_title': entry.title,
|
||||
}
|
||||
payload.update(audit_fields)
|
||||
chat_log = ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
@@ -156,11 +241,7 @@ class FaqCacheService:
|
||||
tokens_used=0,
|
||||
latency=latency,
|
||||
retriever_resources=retriever_resources,
|
||||
payload={
|
||||
"source": "faq_cache",
|
||||
"faq_id": entry.id,
|
||||
"faq_title": entry.title,
|
||||
},
|
||||
payload=payload,
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
@@ -173,15 +254,16 @@ class FaqCacheService:
|
||||
FaqCacheService._increment_hit_count(entry.id)
|
||||
|
||||
end_data: dict[str, Any] = {
|
||||
"event": "message_end",
|
||||
"answer": answer,
|
||||
"replace_answer": True,
|
||||
"chat_log_id": chat_log_id,
|
||||
"conversation_id": final_conversation_id,
|
||||
"metadata": {
|
||||
"retriever_resources": retriever_resources,
|
||||
"source": "faq_cache",
|
||||
"faq_id": entry.id,
|
||||
'event': 'message_end',
|
||||
'answer': answer,
|
||||
'replace_answer': True,
|
||||
'chat_log_id': chat_log_id,
|
||||
'conversation_id': final_conversation_id,
|
||||
'metadata': {
|
||||
'retriever_resources': retriever_resources,
|
||||
'source': 'faq_cache',
|
||||
'faq_id': entry.id,
|
||||
**audit_fields,
|
||||
},
|
||||
}
|
||||
if retriever_resources:
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
"""
|
||||
backend/app/services/faq_text_utils.py
|
||||
|
||||
用途:FAQ / 热点问句归一化等纯文本工具,供 faq_cache 与 hot_faq_aggregator 共用。
|
||||
依赖:无外部业务模块。
|
||||
逻辑:保证离线聚合与在线命中使用同一 normalize 规则。
|
||||
用途:FAQ / 热点问句归一化、模糊相似度评分等纯文本工具,供 faq_cache 与 hot_faq_aggregator 共用。
|
||||
依赖:difflib(Python 标准库,无第三方依赖)。
|
||||
逻辑:保证离线聚合与在线命中使用同一 normalize 规则;模糊评分供 FAQ 兜底直答使用。
|
||||
"""
|
||||
import re
|
||||
from difflib import SequenceMatcher
|
||||
|
||||
# 模糊兜底参与的最低归一化长度:过短问句(如「帮助」)误命中代价高,只走精确匹配。
|
||||
FUZZY_MIN_LENGTH = 4
|
||||
# 模糊阈值的安全钳制区间与默认值:下限防止管理员设得过低导致大面积误直答。
|
||||
FUZZY_THRESHOLD_MIN = 0.5
|
||||
FUZZY_THRESHOLD_MAX = 1.0
|
||||
FUZZY_THRESHOLD_DEFAULT = 0.8
|
||||
|
||||
|
||||
def normalize_faq_query(text: str) -> str:
|
||||
@@ -16,5 +24,38 @@ def normalize_faq_query(text: str) -> str:
|
||||
@returns 归一化后的字符串;空输入返回空串
|
||||
"""
|
||||
value = str(text or "").strip().lower()
|
||||
value = re.sub(r"[\s\u3000,。!?、;:""''()()\[\]【】\-—·,.!?;:'\"]+", "", value)
|
||||
value = re.sub(r"[\s\u3000,。!?、;:“”‘’()()\[\]【】\-—·,.!?;:'\"]+", "", value)
|
||||
return value
|
||||
|
||||
|
||||
def clamp_fuzzy_threshold(value) -> float:
|
||||
"""
|
||||
将模糊匹配阈值钳制到安全区间 [0.5, 1.0]。
|
||||
核心逻辑:空值/非法值回退默认 0.8,越界值收敛到边界,保证在线匹配不会因配置异常失真。
|
||||
@param value - 数据库或请求体中的阈值原始值
|
||||
@returns 钳制后的浮点阈值
|
||||
"""
|
||||
try:
|
||||
threshold = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return FUZZY_THRESHOLD_DEFAULT
|
||||
return min(FUZZY_THRESHOLD_MAX, max(FUZZY_THRESHOLD_MIN, threshold))
|
||||
|
||||
|
||||
def fuzzy_match_score(query: str, candidate: str) -> float:
|
||||
"""
|
||||
计算两段归一化问句的模糊相似度得分(0~1),供 FAQ 模糊兜底匹配使用。
|
||||
核心逻辑:取编辑距离类相似度(SequenceMatcher.ratio)与包含覆盖率的最大值——
|
||||
前者容忍换字/错字(能→可以),后者容忍加前后缀(我还能问什么 vs 还能问什么);
|
||||
真问题偶含候选短语时(如「怎么用你查MES服务器」vs「怎么用你」)覆盖率很低,不会误命中。
|
||||
@param query - 归一化后的用户问句
|
||||
@param candidate - 归一化后的候选问句(标题/标准问句/同义问法)
|
||||
@returns 0~1 之间的相似度得分
|
||||
"""
|
||||
if not query or not candidate:
|
||||
return 0.0
|
||||
score = SequenceMatcher(None, query, candidate).ratio()
|
||||
if query in candidate or candidate in query:
|
||||
coverage = min(len(query), len(candidate)) / max(len(query), len(candidate))
|
||||
score = max(score, coverage)
|
||||
return score
|
||||
@@ -3,7 +3,10 @@ backend/app/services/file_assets/storage.py
|
||||
|
||||
用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。
|
||||
依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。
|
||||
逻辑:由 file_assets.service 调用;禁止 public-read policy 与本地静默回退;读写删失败统一抛 503。
|
||||
逻辑:由 file_assets.service 与调拨证据清单调用;禁止 public-read policy 与本地静默回退;
|
||||
读写删走 MINIO_ENDPOINT(容器内网)。浏览器预签走 MINIO_PUBLIC_BASE_URL,
|
||||
因为签名包含 Host,不能把 host.docker.internal 交给浏览器后再替换。
|
||||
读写删失败统一抛 503。预签下载可附带 response-content-disposition,避免保存名落成对象键。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,6 +15,7 @@ import io
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
from typing import BinaryIO
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
@@ -23,16 +27,75 @@ _LOGGER = logging.getLogger(__name__)
|
||||
_cfg = config[ACTIVE_ENV_NAME]
|
||||
|
||||
|
||||
def resolve_presign_endpoint(
|
||||
public_base: str,
|
||||
fallback_endpoint: str,
|
||||
fallback_secure: bool,
|
||||
) -> tuple[str, bool]:
|
||||
"""把浏览器可访问的 MinIO 基址收成预签名客户端的 endpoint 与 secure。
|
||||
|
||||
核心逻辑:SigV4 把 Host 写进签名。正式环境容器用 host.docker.internal:9000
|
||||
读写,浏览器必须打开 MINIO_PUBLIC_BASE_URL(如 http://ai.well-trust.com:9000)。
|
||||
基址为空或解析不出主机时退回内网端点。80/443 省略端口,交给 Minio 客户端按协议补。
|
||||
|
||||
Args:
|
||||
public_base: MINIO_PUBLIC_BASE_URL,可带或不带协议。
|
||||
fallback_endpoint: 容器内访问用的 host:port。
|
||||
fallback_secure: 内网端点是否走 HTTPS。
|
||||
|
||||
Returns:
|
||||
(endpoint, secure)。endpoint 形如 ai.well-trust.com:9000。
|
||||
"""
|
||||
raw = (public_base or "").strip()
|
||||
if not raw:
|
||||
return fallback_endpoint, fallback_secure
|
||||
parsed = urlparse(raw if "://" in raw else f"http://{raw}")
|
||||
host = parsed.hostname
|
||||
if not host:
|
||||
return fallback_endpoint, fallback_secure
|
||||
if ":" in host:
|
||||
host = f"[{host}]"
|
||||
secure = parsed.scheme.lower() == "https"
|
||||
port = parsed.port
|
||||
if port and not ((secure and port == 443) or (not secure and port == 80)):
|
||||
return f"{host}:{port}", secure
|
||||
return host, secure
|
||||
|
||||
|
||||
class FileAssetStorage:
|
||||
"""私有业务文件 MinIO 存储客户端。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""分别建立内网读写客户端与浏览器预签名客户端。
|
||||
|
||||
核心逻辑:两端点主机与协议相同时共用一个客户端。预签名客户端只在
|
||||
生成 URL 时做本地签名,不靠它访问内网 MinIO。
|
||||
"""
|
||||
endpoint = str(_cfg.MINIO_ENDPOINT or "").strip()
|
||||
access_key = _cfg.MINIO_ACCESS_KEY
|
||||
secret_key = _cfg.MINIO_SECRET_KEY
|
||||
secure = bool(_cfg.MINIO_SECURE)
|
||||
self.client = Minio(
|
||||
_cfg.MINIO_ENDPOINT,
|
||||
access_key=_cfg.MINIO_ACCESS_KEY,
|
||||
secret_key=_cfg.MINIO_SECRET_KEY,
|
||||
secure=_cfg.MINIO_SECURE,
|
||||
endpoint,
|
||||
access_key=access_key,
|
||||
secret_key=secret_key,
|
||||
secure=secure,
|
||||
)
|
||||
# [STEP 1] 预签名单独用浏览器主机。只改 URL 字符串会使签名失效。
|
||||
presign_endpoint, presign_secure = resolve_presign_endpoint(
|
||||
str(_cfg.MINIO_PUBLIC_BASE_URL or ""),
|
||||
endpoint,
|
||||
secure,
|
||||
)
|
||||
if presign_endpoint == endpoint and presign_secure == secure:
|
||||
self.presign_client = self.client
|
||||
else:
|
||||
self.presign_client = Minio(
|
||||
presign_endpoint,
|
||||
access_key=access_key,
|
||||
secret_key=secret_key,
|
||||
secure=presign_secure,
|
||||
)
|
||||
self.bucket_name = str(_cfg.MINIO_FILE_ASSETS_BUCKET or 'hxops-file-assets').strip()
|
||||
|
||||
def _ensure_bucket_exists(self) -> None:
|
||||
@@ -119,13 +182,55 @@ class FileAssetStorage:
|
||||
except S3Error:
|
||||
return False
|
||||
|
||||
def presigned_get_url(self, storage_key: str, *, expires_seconds: int) -> str:
|
||||
"""生成短期受控下载 URL。"""
|
||||
def _bind_presign_region(self) -> None:
|
||||
"""把内网客户端已探到的 region 抄给预签名客户端。
|
||||
|
||||
核心逻辑:minio-py 在签名前会请求 GetBucketLocation。若用公网客户端发这次请求,
|
||||
容器里可能访问不到浏览器入口,或每次下载多一次公网探测。
|
||||
bucket 检查已经通过内网客户端写入 _region_map;这里只复用该结果。
|
||||
尚未探测到时用 MinIO 默认 us-east-1。
|
||||
"""
|
||||
if self.presign_client is self.client:
|
||||
return
|
||||
region = self.client._region_map.get(self.bucket_name) or "us-east-1"
|
||||
self.presign_client._region_map[self.bucket_name] = region
|
||||
|
||||
def presigned_get_url(
|
||||
self,
|
||||
storage_key: str,
|
||||
*,
|
||||
expires_seconds: int,
|
||||
download_name: str | None = None,
|
||||
) -> str:
|
||||
"""生成短期受控下载 URL。
|
||||
|
||||
核心逻辑:先把内网探到的 region 绑到 presign_client,再用它签名。
|
||||
主机来自 MINIO_PUBLIC_BASE_URL。签名在本地完成,不再向公网探测 bucket 区域。
|
||||
对象键常为内容哈希,浏览器会把它当成保存名。
|
||||
download_name 非空时把 response-content-disposition 签进 URL,
|
||||
让保存对话框使用业务文件名。预览地址不要传这个参数。
|
||||
|
||||
Args:
|
||||
storage_key: MinIO 对象键。
|
||||
expires_seconds: 链接有效秒数,短于 60 秒时抬到 60。
|
||||
download_name: 附件保存名;只接受调用方已洗净的文件名。
|
||||
|
||||
Returns:
|
||||
带过期签名的 GET URL,主机是浏览器可访问的 MinIO 地址。
|
||||
"""
|
||||
self._ensure_bucket_exists()
|
||||
return self.client.presigned_get_object(
|
||||
self._bind_presign_region()
|
||||
response_headers = None
|
||||
if download_name:
|
||||
safe = download_name.replace('"', '').replace('\\', '').replace('\r', '').replace('\n', '')
|
||||
response_headers = {
|
||||
'response-content-disposition': f'attachment; filename="{safe}"',
|
||||
}
|
||||
return self.presign_client.presigned_get_object(
|
||||
self.bucket_name,
|
||||
storage_key,
|
||||
expires=timedelta(seconds=max(int(expires_seconds or 60), 60)),
|
||||
response_headers=response_headers,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""货代 RPA 模块根:承载 freight_rpa 域代码(common/onhand/inbound/upload)。"""
|
||||
@@ -0,0 +1 @@
|
||||
"""common:域中立件(跨 RPA Worker 共用、不依赖具体业务域)。"""
|
||||
@@ -0,0 +1,58 @@
|
||||
"""
|
||||
services/freight_rpa/common/callback_sinks.py
|
||||
|
||||
用途:RPA 回调「进度类」sink 注册表——freight_rpa 侧的回调分发缝(批次 B Task 6 起
|
||||
与文件事实分发分工:文件/报表就绪类回调走 freight_rpa.reports.dispatch.
|
||||
dispatch_report_fact——归档入口先 db.session.commit() 再投递 ReportFact,
|
||||
kind 未注册同样 404 FREIGHT_RPA.SINK_NOT_REGISTERED;进度类 kind
|
||||
(inbound-unit-progress / inbound-batch-progress / onhand-batch-claimed 等)
|
||||
仍走本模块的 register_sink / dispatch_sink,不改 envelope)。
|
||||
依赖:app.core.errors.AppError。
|
||||
逻辑:Worker 回调进入 /api/freight-rpa/* 蓝图后,进度类端点按 kind 分发到
|
||||
组合根(create_app / api 层)注册的业务处理器;未注册的 kind 显式 404,
|
||||
绝不静默吞回调。Task 9/10 落地 workflow_protocol / report_archive 时由
|
||||
组合根调用 register_sink 注入真实业务持久化处理器。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.core.errors import AppError
|
||||
|
||||
_SINKS: dict[str, Callable[..., Any]] = {}
|
||||
|
||||
|
||||
def register_sink(kind: str, handler: Callable[..., Any]) -> None:
|
||||
"""
|
||||
注册一个回调 sink 处理器(由组合根在应用启动时调用)。
|
||||
|
||||
Args:
|
||||
kind: 回调种类,命名 = 回调路由名去前缀(如 "onhand-ready"、
|
||||
"onhand-configuration-test-complete");同一 kind 重复注册为覆盖。
|
||||
handler: 业务处理器;契约:接收回调载荷的关键字参数并返回可 jsonify 的业务结果。
|
||||
"""
|
||||
_SINKS[kind] = handler
|
||||
|
||||
|
||||
def dispatch_sink(kind: str, **payload: Any) -> Any:
|
||||
"""
|
||||
按 kind 分发回调载荷到已注册 sink。
|
||||
|
||||
Args:
|
||||
kind: register_sink 注册过的回调种类。
|
||||
payload: 回调载荷键值对;键必须为合法 Python 标识符(回调 schema 均为 snake_case)。
|
||||
Returns:
|
||||
handler 的返回值(业务结果 dict,由蓝图 jsonify)。
|
||||
Raises:
|
||||
AppError: code=FREIGHT_RPA.SINK_NOT_REGISTERED、http_status=404——kind 未注册时
|
||||
显式失败(Task 9/10 注册真实 sink 前的既定语义)。
|
||||
"""
|
||||
handler = _SINKS.get(kind)
|
||||
if handler is None:
|
||||
raise AppError(
|
||||
code='FREIGHT_RPA.SINK_NOT_REGISTERED',
|
||||
message=f'No callback sink registered for kind: {kind}',
|
||||
http_status=404,
|
||||
)
|
||||
return handler(**payload)
|
||||
+5
-4
@@ -1,10 +1,11 @@
|
||||
"""
|
||||
services/shipping_notice/credential_crypto.py
|
||||
services/freight_rpa/common/credential_crypto.py
|
||||
|
||||
用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。
|
||||
依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。
|
||||
逻辑:管理服务写入 Profile 前调用 encrypt_credential;RPA 配置读取服务在受控内存中调用
|
||||
decrypt_credential。主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。
|
||||
逻辑:管理服务写入 Profile 前调用 encrypt_credential;管理端读取 Profile 时只解密用户名用于展示;
|
||||
密码仅在 RPA 执行内存中调用 decrypt_credential。密码与密文不得进入 API 响应或日志。
|
||||
主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -48,7 +49,7 @@ def decrypt_credential(ciphertext: str) -> str:
|
||||
ciphertext: 数据库中保存的 Fernet 密文。
|
||||
|
||||
Returns:
|
||||
str: 仅供 RPA 执行内存使用的明文。
|
||||
str: 明文。密码只留在 RPA 执行内存;用户名可由管理端 Profile 接口返回。禁止写入日志。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 未配置或配置了无效的主密钥。
|
||||
@@ -0,0 +1,384 @@
|
||||
"""freight_rpa/common/report_audit.py
|
||||
|
||||
用途:货代 RPA 域(inbound 回调归档、保留期清理、通知投递)写入
|
||||
ShippingAuditEvent 统一审计账本的唯一入口(批次 B Task 6)。
|
||||
依赖:app.models.ShippingAuditEvent(允许 import 模型)、app.core.errors.
|
||||
ValidationError、SQLAlchemy 会话(app.db)。
|
||||
逻辑:替代此前对 app.services.shipping_notice.audit_service 的依赖——freight_rpa
|
||||
包禁止 import app.services.shipping_notice.*(import 边界由 tests/services/
|
||||
freight_rpa/test_import_boundary.py 的空白名单锁定),故本模块以与
|
||||
append_shipping_audit_event 相同的关键字面直接写同一个 ShippingAuditEvent
|
||||
模型,事件名(shipping_inbound_rpa_callback_received /
|
||||
shipping_inbound_report_archived 等)与聚合键保持不变,避免审计查询断档。
|
||||
与 audit_service 的有意差异(均为本域受控场景):
|
||||
(1)before/after 快照不做白名单投影——本域快照键均为受控诊断键
|
||||
(status/error_code/sha256/file_size 等),原样入 snapshot 列;
|
||||
(2)不做 XFA 加密完整快照(本域无敏感完整载荷);
|
||||
(3)保留期恒为 None(货代统一审计账本永久保留);
|
||||
(4)event_hash 以本地稳定哈希对核心字段集合计算,previous_event_hash
|
||||
取同聚合最新一条已 flush 事件的 event_hash(链结构与 audit_service 同构)。
|
||||
本模块不提交事务,由调用方与业务写入同一事务提交;写入失败时业务不得 commit。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ShippingAuditEvent
|
||||
|
||||
# 与 audit_service 同源的 actor/result 白名单(模型 CHECK 约束同集)。
|
||||
_ALLOWED_ACTOR_TYPES = frozenset({'user', 'system', 'rpa', 'chatflow', 'admin', 'worker'})
|
||||
_ALLOWED_RESULTS = frozenset({'success', 'failure', 'rejected', 'ignored'})
|
||||
|
||||
# 审计元数据/快照禁止键本地冻结子集(凭据 / 正文 / URL 类;自
|
||||
# shipping_notice.progress_audit_contract.AUDIT_FORBIDDEN_KEYS 裁剪,仅供本域防呆)。
|
||||
_FORBIDDEN_AUDIT_KEYS = frozenset({
|
||||
'api_key',
|
||||
'api_base_url',
|
||||
'authorization',
|
||||
'body',
|
||||
'content',
|
||||
'document_text',
|
||||
'email_body',
|
||||
'minio',
|
||||
'object_key',
|
||||
'object_url',
|
||||
'password',
|
||||
'prompt',
|
||||
'provider_config',
|
||||
'quote',
|
||||
'raw_content',
|
||||
'raw_output',
|
||||
'secret',
|
||||
'token',
|
||||
'url',
|
||||
'user_agent',
|
||||
})
|
||||
|
||||
|
||||
def _is_forbidden_audit_key(key: str) -> bool:
|
||||
"""键名大小写不敏感命中本地禁止键集合(与 audit_service 判定同构)。"""
|
||||
return str(key or '').strip().lower() in _FORBIDDEN_AUDIT_KEYS
|
||||
|
||||
|
||||
def _collect_forbidden_keys(payload: Any, *, path: str = '') -> list[str]:
|
||||
"""
|
||||
递归收集命中敏感黑名单的键路径(dict/list 均遍历,嵌套路径稳定拼接)。
|
||||
|
||||
Returns:
|
||||
命中键路径列表(调用方排序后入 ValidationError.details)。
|
||||
"""
|
||||
found: list[str] = []
|
||||
if isinstance(payload, dict):
|
||||
for key, child in payload.items():
|
||||
key_text = str(key)
|
||||
child_path = f'{path}.{key_text}' if path else key_text
|
||||
if _is_forbidden_audit_key(key_text):
|
||||
found.append(child_path)
|
||||
found.extend(_collect_forbidden_keys(child, path=child_path))
|
||||
elif isinstance(payload, list):
|
||||
for index, child in enumerate(payload):
|
||||
found.extend(_collect_forbidden_keys(child, path=f'{path}[{index}]'))
|
||||
return found
|
||||
|
||||
|
||||
def _sanitize_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""验证元数据仅含脱敏诊断事实,阻断凭据、正文与 URL 进入审计账本。"""
|
||||
safe = dict(metadata or {})
|
||||
forbidden = _collect_forbidden_keys(safe)
|
||||
if forbidden:
|
||||
raise ValidationError(
|
||||
'RPA report audit metadata contains forbidden keys',
|
||||
code='SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN',
|
||||
details={'forbidden_keys': sorted(set(forbidden))},
|
||||
)
|
||||
return safe
|
||||
|
||||
|
||||
def _sanitize_refs(refs: list[dict[str, Any]] | None, *, field_name: str) -> list[dict[str, Any]] | None:
|
||||
"""校验证据/产物引用仅含标识类字段,拒绝 URL 与正文。"""
|
||||
if refs is None:
|
||||
return None
|
||||
if not isinstance(refs, list):
|
||||
raise ValidationError(
|
||||
f'RPA report audit {field_name} must be a list',
|
||||
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
|
||||
)
|
||||
forbidden = _collect_forbidden_keys(refs)
|
||||
if forbidden:
|
||||
raise ValidationError(
|
||||
f'RPA report audit {field_name} contains forbidden keys',
|
||||
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
|
||||
details={'forbidden_keys': sorted(set(forbidden))},
|
||||
)
|
||||
return refs
|
||||
|
||||
|
||||
def _stable_hash(value: Any) -> str:
|
||||
"""对受控状态对象生成 SHA-256(排序键 + 紧凑分隔符,与 audit_service 同构)。"""
|
||||
encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str)
|
||||
return hashlib.sha256(encoded.encode('ascii')).hexdigest()
|
||||
|
||||
|
||||
def _snapshot_diff(before: Any, after: Any) -> dict[str, Any] | None:
|
||||
"""
|
||||
计算前后快照顶层差异(changed/added/removed 三段;无变化返回 None)。
|
||||
|
||||
核心逻辑:值均为受控诊断键原样比较(本域快照不做白名单投影,见模块 docstring)。
|
||||
"""
|
||||
left = before if isinstance(before, dict) else {}
|
||||
right = after if isinstance(after, dict) else {}
|
||||
changed: dict[str, Any] = {}
|
||||
added: dict[str, Any] = {}
|
||||
removed: dict[str, Any] = {}
|
||||
for key in sorted(set(left) | set(right)):
|
||||
if key in left and key in right:
|
||||
if left[key] != right[key]:
|
||||
changed[key] = {'from': left[key], 'to': right[key]}
|
||||
elif key in right:
|
||||
added[key] = right[key]
|
||||
else:
|
||||
removed[key] = left[key]
|
||||
if not changed and not added and not removed:
|
||||
return None
|
||||
return {'changed': changed, 'added': added, 'removed': removed}
|
||||
|
||||
|
||||
def _resolve_previous_event_hash(*, aggregate_type: str, aggregate_id: str) -> str | None:
|
||||
"""
|
||||
读取同聚合最新一条事件的 event_hash 作为哈希链前驱。
|
||||
|
||||
核心逻辑:按 id 倒序取一条;缺失或旧数据无 hash 时返回 None(链从本条起锚)。
|
||||
调用方须先 flush 保证同事务先前事件可查(与 audit_service 顺序一致)。
|
||||
"""
|
||||
previous = (
|
||||
ShippingAuditEvent.query
|
||||
.filter_by(aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128])
|
||||
.order_by(ShippingAuditEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
if previous is None:
|
||||
return None
|
||||
return str(previous.event_hash) if previous.event_hash else None
|
||||
|
||||
|
||||
def _event_hash_payload(
|
||||
*,
|
||||
event_type: str,
|
||||
aggregate_type: str,
|
||||
aggregate_id: str,
|
||||
action: str | None,
|
||||
result: str | None,
|
||||
reason_code: str | None,
|
||||
run_no: str | None,
|
||||
task_no: str | None,
|
||||
operation_id: str | None,
|
||||
request_id: str | None,
|
||||
actor_type: str,
|
||||
actor_id: str | None,
|
||||
before_snapshot: dict[str, Any] | None,
|
||||
after_snapshot: dict[str, Any] | None,
|
||||
diff_json: dict[str, Any] | None,
|
||||
previous_event_hash: str | None,
|
||||
sensitivity_level: str | None,
|
||||
) -> dict[str, Any]:
|
||||
"""组装参与 event_hash 计算的稳定字段集合(字段集与 audit_snapshot_service 同构)。"""
|
||||
return {
|
||||
'event_type': event_type,
|
||||
'aggregate_type': aggregate_type,
|
||||
'aggregate_id': aggregate_id,
|
||||
'action': action,
|
||||
'result': result,
|
||||
'reason_code': reason_code,
|
||||
'workflow_id': None,
|
||||
'workflow_item_id': None,
|
||||
'workflow_item_version_id': None,
|
||||
'version_no': None,
|
||||
'run_no': run_no,
|
||||
'document_id': None,
|
||||
'review_case_no': None,
|
||||
'task_no': task_no,
|
||||
'operation_id': operation_id,
|
||||
'request_id': request_id,
|
||||
'actor_type': actor_type,
|
||||
'actor_id': actor_id,
|
||||
'before_snapshot': before_snapshot,
|
||||
'after_snapshot': after_snapshot,
|
||||
'diff': diff_json,
|
||||
'previous_event_hash': previous_event_hash,
|
||||
'sensitivity_level': sensitivity_level,
|
||||
}
|
||||
|
||||
|
||||
def append_rpa_report_event(
|
||||
*,
|
||||
event_type: str,
|
||||
aggregate_type: str,
|
||||
aggregate_id: str,
|
||||
run_no: str | None = None,
|
||||
task_no: str | None = None,
|
||||
intake_no: str | None = None,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
actor_role: str | None = None,
|
||||
actor_display: str | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
correlation_id: str | None = None,
|
||||
source: str | None = None,
|
||||
result: str | None = None,
|
||||
error_code: str | None = None,
|
||||
conversation_id: str | None = None,
|
||||
unit_id: str | int | None = None,
|
||||
document_id: str | int | None = None,
|
||||
review_case_no: str | None = None,
|
||||
owner_user_id: str | int | None = None,
|
||||
attempt_no: int | None = None,
|
||||
action: str | None = None,
|
||||
reason_code: str | None = None,
|
||||
reason: str | None = None,
|
||||
before: Any = None,
|
||||
after: Any = None,
|
||||
evidence_refs: list[dict[str, Any]] | None = None,
|
||||
artifact_refs: list[dict[str, Any]] | None = None,
|
||||
context_refs: dict[str, Any] | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
sensitivity_level: str | None = None,
|
||||
) -> ShippingAuditEvent:
|
||||
"""
|
||||
追加一条货代 RPA 审计事实(freight_rpa 域唯一审计写入口)。
|
||||
|
||||
用途:与 shipping_notice.audit_service.append_shipping_audit_event 关键字兼容的
|
||||
RPA 域替代品——调用方(report_archive 等)自 audit_service 迁移时仅改函数名,
|
||||
事件名与聚合键原样保持,避免审计查询断档(见模块 docstring 的四处有意差异)。
|
||||
核心逻辑:[STEP 1] 校验 actor_type/result 白名单 + 元数据/引用脱敏;
|
||||
[STEP 2] 计算 before/after 稳定哈希与顶层 diff;
|
||||
[STEP 3] flush 后取同聚合前驱 event_hash,对核心字段集合计算 event_hash;
|
||||
[STEP 4] 写入 ShippingAuditEvent(保留期恒 None=永久)并 flush,不 commit。
|
||||
Args:
|
||||
event_type: 稳定业务事件名(如 shipping_inbound_rpa_callback_received);
|
||||
禁止传入用户自由文本。
|
||||
aggregate_type/aggregate_id: 业务聚合类型与稳定编号(软引用,不使用外键)。
|
||||
run_no/task_no: 排程 run / task 软引用(截断 64)。
|
||||
actor_type/actor_id/actor_role/actor_display: 操作主体四元组
|
||||
(actor_type 必须在 user/system/rpa/chatflow/admin/worker 内)。
|
||||
result: success / failure / rejected / ignored(白名单外抛 ValidationError)。
|
||||
before/after: 受控状态快照(本域不做白名单投影,键须为诊断类,禁敏感键)。
|
||||
evidence_refs/artifact_refs: FileAsset ID、SHA-256 等标识引用;禁止 URL/正文。
|
||||
metadata: 仅允许原因码、计数等脱敏诊断事实(禁止键见 _FORBIDDEN_AUDIT_KEYS)。
|
||||
unit_id/document_id/review_case_no/owner_user_id/attempt_no: 业务关联软引用。
|
||||
action/reason_code/reason/error_code/conversation_id/correlation_id/source/
|
||||
request_id/operation_id/intake_no/sensitivity_level: 追溯与分级补充字段。
|
||||
Returns:
|
||||
尚未提交的 ShippingAuditEvent,由调用方与业务写入在同一事务提交。
|
||||
Raises:
|
||||
ValidationError: actor/result 非法,或元数据/快照引用包含正文、凭据等敏感键。
|
||||
"""
|
||||
# [STEP 1] 校验与脱敏(错误码与 audit_service 共用,避免同义分裂)。
|
||||
if actor_type not in _ALLOWED_ACTOR_TYPES:
|
||||
raise ValidationError('Invalid shipping audit actor type', code='SHIPPING_NOTICE.AUDIT_ACTOR_INVALID')
|
||||
if result is not None and result not in _ALLOWED_RESULTS:
|
||||
raise ValidationError('Invalid shipping audit result', code='SHIPPING_NOTICE.AUDIT_RESULT_INVALID')
|
||||
safe_metadata = _sanitize_metadata(metadata)
|
||||
if before is not None and _collect_forbidden_keys(before):
|
||||
raise ValidationError(
|
||||
'RPA report audit snapshot contains forbidden keys',
|
||||
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
|
||||
details={'forbidden_keys': sorted(set(_collect_forbidden_keys(before)))},
|
||||
)
|
||||
if after is not None and _collect_forbidden_keys(after):
|
||||
raise ValidationError(
|
||||
'RPA report audit snapshot contains forbidden keys',
|
||||
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
|
||||
details={'forbidden_keys': sorted(set(_collect_forbidden_keys(after)))},
|
||||
)
|
||||
|
||||
# [STEP 2] 快照哈希与顶层差异。
|
||||
before_snapshot = before if isinstance(before, dict) else None
|
||||
after_snapshot = after if isinstance(after, dict) else None
|
||||
diff_json = _snapshot_diff(before, after)
|
||||
|
||||
# [STEP 3] 哈希链:flush 保证同事务先前事件可查,再取前驱并计算本条 event_hash。
|
||||
db.session.flush()
|
||||
previous_event_hash = _resolve_previous_event_hash(
|
||||
aggregate_type=str(aggregate_type)[:64], aggregate_id=str(aggregate_id)[:128],
|
||||
)
|
||||
resolved_run_no = str(run_no)[:64] if run_no else None
|
||||
resolved_task_no = str(task_no)[:64] if task_no else None
|
||||
resolved_actor_id = str(actor_id)[:128] if actor_id is not None else None
|
||||
resolved_operation_id = str(operation_id)[:64] if operation_id else None
|
||||
resolved_request_id = str(request_id)[:64] if request_id else None
|
||||
resolved_sensitivity = str(sensitivity_level)[:16] if sensitivity_level else None
|
||||
event_hash = _stable_hash(_event_hash_payload(
|
||||
event_type=str(event_type)[:64],
|
||||
aggregate_type=str(aggregate_type)[:64],
|
||||
aggregate_id=str(aggregate_id)[:128],
|
||||
action=str(action)[:64] if action else None,
|
||||
result=result,
|
||||
reason_code=str(reason_code)[:128] if reason_code else None,
|
||||
run_no=resolved_run_no,
|
||||
task_no=resolved_task_no,
|
||||
operation_id=resolved_operation_id,
|
||||
request_id=resolved_request_id,
|
||||
actor_type=actor_type,
|
||||
actor_id=resolved_actor_id,
|
||||
before_snapshot=before_snapshot,
|
||||
after_snapshot=after_snapshot,
|
||||
diff_json=diff_json,
|
||||
previous_event_hash=previous_event_hash,
|
||||
sensitivity_level=resolved_sensitivity,
|
||||
))
|
||||
|
||||
# [STEP 4] 写入事件(保留期恒 None=永久保留;不 commit,由调用方保证原子性)。
|
||||
event = ShippingAuditEvent(
|
||||
event_type=str(event_type)[:64],
|
||||
aggregate_type=str(aggregate_type)[:64],
|
||||
aggregate_id=str(aggregate_id)[:128],
|
||||
run_no=resolved_run_no,
|
||||
task_no=resolved_task_no,
|
||||
intake_no=str(intake_no)[:64] if intake_no else None,
|
||||
actor_type=actor_type,
|
||||
actor_id=resolved_actor_id,
|
||||
actor_role=str(actor_role)[:64] if actor_role else None,
|
||||
actor_display=str(actor_display)[:128] if actor_display else None,
|
||||
request_id=resolved_request_id,
|
||||
operation_id=resolved_operation_id,
|
||||
correlation_id=str(correlation_id)[:64] if correlation_id else None,
|
||||
source=str(source)[:32] if source else None,
|
||||
result=result,
|
||||
error_code=str(error_code)[:64] if error_code else None,
|
||||
conversation_id=str(conversation_id)[:100] if conversation_id else None,
|
||||
unit_id=str(unit_id)[:64] if unit_id is not None else None,
|
||||
document_id=str(document_id)[:64] if document_id is not None else None,
|
||||
review_case_no=str(review_case_no)[:64] if review_case_no else None,
|
||||
owner_user_id=str(owner_user_id)[:64] if owner_user_id is not None else None,
|
||||
attempt_no=int(attempt_no) if attempt_no is not None else None,
|
||||
action=str(action)[:64] if action else None,
|
||||
reason_code=str(reason_code)[:128] if reason_code else None,
|
||||
reason=str(reason)[:2000] if reason else None,
|
||||
before_hash=_stable_hash(before_snapshot) if before_snapshot is not None else None,
|
||||
after_hash=_stable_hash(after_snapshot) if after_snapshot is not None else None,
|
||||
before_snapshot_json=before_snapshot,
|
||||
after_snapshot_json=after_snapshot,
|
||||
diff_json=diff_json,
|
||||
previous_event_hash=previous_event_hash,
|
||||
event_hash=event_hash,
|
||||
sensitivity_level=resolved_sensitivity,
|
||||
evidence_refs_json=_sanitize_refs(evidence_refs, field_name='evidence_refs'),
|
||||
artifact_refs_json=_sanitize_refs(artifact_refs, field_name='artifact_refs'),
|
||||
context_refs_json=dict(context_refs or {}) if context_refs else None,
|
||||
metadata_json=safe_metadata,
|
||||
retention_expires_at=None,
|
||||
)
|
||||
db.session.add(event)
|
||||
db.session.flush()
|
||||
return event
|
||||
|
||||
|
||||
# 供测试与契约引用的冻结黑名单导出(与 audit_service.FORBIDDEN_AUDIT_METADATA_KEYS 对应的本地子集)。
|
||||
RPA_FORBIDDEN_AUDIT_KEYS = _FORBIDDEN_AUDIT_KEYS
|
||||
@@ -0,0 +1,36 @@
|
||||
"""
|
||||
services/freight_rpa/common/rpa_runtime.py
|
||||
|
||||
用途:RPA 运行模式(browser/mock)的展示助手——把任务回调记录或后端配置规范化为前端安全摘要。
|
||||
依赖:Flask current_app 配置(FREIGHT_RPA_WORKER_MOCK);不依赖目录 IO 与 Worker 文件契约。
|
||||
逻辑:由 shipping_notice.query_service(任务序列化注入 rpa_runtime 摘要)、
|
||||
同包 worker_heartbeat(mock 模式下跳过真实 Worker 在线探测)消费;
|
||||
仅做展示归一,不承载触发/回调逻辑。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
|
||||
def _runtime_summary(mode: str) -> dict[str, str | bool]:
|
||||
"""将 browser/mock 规范化为前端安全展示摘要。"""
|
||||
normalized = "mock" if str(mode or "").strip().lower() == "mock" else "browser"
|
||||
mock_enabled = normalized == "mock"
|
||||
return {
|
||||
"mode": normalized,
|
||||
"label": "Mock RPA" if mock_enabled else "真实 RPA",
|
||||
"mock": mock_enabled,
|
||||
}
|
||||
|
||||
|
||||
def rpa_runtime_mode(runtime: dict[str, Any] | None = None) -> dict[str, str | bool]:
|
||||
"""返回 RPA 运行模式摘要;优先使用任务最近一次回调实际模式,兜底读取当前后端配置。"""
|
||||
if isinstance(runtime, dict):
|
||||
mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower()
|
||||
if mode in {"browser", "mock"}:
|
||||
return _runtime_summary(mode)
|
||||
raw = str(current_app.config.get("FREIGHT_RPA_WORKER_MOCK", "false") or "false").strip().lower()
|
||||
return _runtime_summary("mock" if raw in {"1", "true", "yes", "on"} else "browser")
|
||||
+161
-67
@@ -1,11 +1,14 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_worker_heartbeat.py
|
||||
services/freight_rpa/common/worker_heartbeat.py
|
||||
|
||||
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/收料就绪检查与状态查询。
|
||||
依赖:Flask current_app、redis_client、shipping_notice.rpa(库存与上传目录、mock 模式)、
|
||||
shipping_notice.receipt_rpa(收料 trigger 目录)。
|
||||
逻辑:freight_rpa_worker 调 POST /rpa/heartbeat;写 inventory/upload/receipt trigger 前强制就绪检查;
|
||||
管理端 /rpa-workers/status?scope=inventory|receipt 展示对应 Worker 心跳徽标。
|
||||
用途:货代 RPA Worker 心跳存储、共享目录校验、库存/上传/入站/出站就绪检查与状态查询。
|
||||
依赖:Flask current_app、redis_client、同包 rpa_runtime(mock 模式)、
|
||||
freight_rpa.onhand.trigger_io(onhand trigger 目录)、
|
||||
freight_rpa.upload.trigger_io(上传目录)、
|
||||
freight_rpa.inbound.trigger_io(inbound trigger 目录)、
|
||||
freight_rpa.outbound.trigger_io(outbound trigger 目录)。
|
||||
逻辑:Windows Worker 调 POST /api/freight-rpa/heartbeat;写 onhand/upload/inbound/outbound trigger 前强制就绪检查;
|
||||
管理端 /rpa-workers/status?scope=onhand|inbound|outbound 展示对应 Worker 心跳徽标。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -24,18 +27,25 @@ from flask import current_app
|
||||
|
||||
from app.core.config.settings import _normalize_env_name
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.shipping_notice.rpa import inventory_trigger_dir, rpa_runtime_mode
|
||||
from app.services.freight_rpa.onhand.trigger_io import onhand_trigger_dir
|
||||
from .rpa_runtime import rpa_runtime_mode
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
RPA_WORKER_OFFLINE_MESSAGE = "RPA Worker 未在线,请启动 Windows RPA 服务后重试"
|
||||
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE = "RPA Worker 心跳存储不可用,请检查 Redis 连接"
|
||||
RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE = "货代上传 RPA 未就绪,请检查 Worker、凭据与共享目录后重试"
|
||||
INVENTORY_EXPORT_CAPABILITY = "inventory_export"
|
||||
FREIGHT_UPLOAD_CAPABILITY = "freight_upload"
|
||||
RECEIPT_EXPORT_CAPABILITY = "receipt_export"
|
||||
# 收料 Worker 由 start_receipt_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-receipt。
|
||||
RECEIPT_WORKER_ID_SUFFIX = "-receipt"
|
||||
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:能力串随 Worker 侧(Task 12)切换——
|
||||
# inventory_export→onhand_export、receipt_export→inbound_export;上传能力为 freight_rpa_upload;
|
||||
# worker_id 后缀判定 -receipt→-inbound(ps1 注入值随发布窗口改配,见 cutover runbook)。
|
||||
ONHAND_EXPORT_CAPABILITY = "onhand_export"
|
||||
FREIGHT_RPA_UPLOAD_CAPABILITY = "freight_rpa_upload"
|
||||
INBOUND_EXPORT_CAPABILITY = "inbound_export"
|
||||
OUTBOUND_EXPORT_CAPABILITY = "outbound_export"
|
||||
# inbound Worker 由 start_inbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-inbound。
|
||||
INBOUND_WORKER_ID_SUFFIX = "-inbound"
|
||||
# outbound Worker 由 start_outbound_worker.ps1 注入 FREIGHT_RPA_WORKER_ID=<主机名>-outbound。
|
||||
OUTBOUND_WORKER_ID_SUFFIX = "-outbound"
|
||||
_REDIS_INDEX_KEY = "shipping:rpa:heartbeat:index"
|
||||
_REDIS_WORKER_KEY_PREFIX = "shipping:rpa:heartbeat:worker:"
|
||||
_MEMORY_STORE: dict[str, dict[str, Any]] = {}
|
||||
@@ -51,8 +61,10 @@ _REASON_USER_HINTS: dict[str, str] = {
|
||||
"shared_scope_mismatch": "共享目录 scope 与后端配置不一致",
|
||||
"trigger_dir_not_writable": "trigger 目录不可写",
|
||||
"environment_mismatch": "Worker 环境与后端环境不一致",
|
||||
"missing_inventory_export_capability": "Worker 未声明 inventory_export 能力",
|
||||
"missing_freight_upload_capability": "Worker 未声明 freight_upload 能力",
|
||||
"missing_onhand_export_capability": "Worker 未声明 onhand_export 能力",
|
||||
"missing_inbound_export_capability": "Worker 未声明 inbound_export 能力",
|
||||
"missing_outbound_export_capability": "Worker 未声明 outbound_export 能力",
|
||||
"missing_freight_rpa_upload_capability": "Worker 未声明 freight_rpa_upload 能力",
|
||||
"credential_key_missing": "未配置 FREIGHT_RPA_CREDENTIAL_KEY",
|
||||
"upload_queue_dir_not_configured": "未配置货代上传队列目录",
|
||||
"upload_queue_dir_not_accessible": "货代上传队列目录不可访问",
|
||||
@@ -139,7 +151,7 @@ def shared_scope_id() -> str:
|
||||
explicit = _config_str("FREIGHT_RPA_SHARED_SCOPE_ID", "")
|
||||
if explicit:
|
||||
return explicit
|
||||
trigger_dir = inventory_trigger_dir()
|
||||
trigger_dir = onhand_trigger_dir()
|
||||
if not trigger_dir:
|
||||
return ""
|
||||
for part in Path(trigger_dir).parts:
|
||||
@@ -362,7 +374,7 @@ def _verify_shared_trigger_mount(
|
||||
trigger_dir: Path | None, *, require_sentinel: bool = True,
|
||||
) -> tuple[bool, list[str]]:
|
||||
"""
|
||||
校验 trigger 目录可写;默认要求共享哨兵(库存与收料同口径)。
|
||||
校验 trigger 目录可写;默认要求共享哨兵(库存与入站同口径)。
|
||||
|
||||
Args:
|
||||
trigger_dir: 共享 trigger 目录。
|
||||
@@ -400,18 +412,39 @@ def _verify_shared_trigger_mount(
|
||||
return not reasons, reasons
|
||||
|
||||
|
||||
def is_receipt_rpa_worker(worker: dict[str, Any]) -> bool:
|
||||
def is_inbound_rpa_worker(worker: dict[str, Any]) -> bool:
|
||||
"""
|
||||
判断心跳是否来自收料 Worker。
|
||||
判断心跳是否来自 inbound(原收料)Worker。
|
||||
|
||||
优先认 <主机名>-receipt(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
|
||||
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与收料目录对齐判定。
|
||||
优先认 <主机名>-inbound(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
|
||||
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与 inbound 目录对齐判定。
|
||||
"""
|
||||
if str(worker.get("worker_id") or "").strip().lower().endswith(RECEIPT_WORKER_ID_SUFFIX):
|
||||
if str(worker.get("worker_id") or "").strip().lower().endswith(INBOUND_WORKER_ID_SUFFIX):
|
||||
return True
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
|
||||
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
|
||||
|
||||
expected = receipt_trigger_dir()
|
||||
expected = inbound_trigger_dir()
|
||||
actual = str(worker.get("trigger_dir") or "").strip()
|
||||
if expected is None or not actual:
|
||||
return False
|
||||
try:
|
||||
return Path(actual).resolve() == expected.resolve()
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def is_outbound_rpa_worker(worker: dict[str, Any]) -> bool:
|
||||
"""
|
||||
判断心跳是否来自 outbound Worker。
|
||||
|
||||
优先认 <主机名>-outbound(ps1 注入);兼容未注入 FREIGHT_RPA_WORKER_ID、
|
||||
回退为 <主机名>-<pid> 的进程——用心跳 trigger_dir 与 outbound 目录对齐判定。
|
||||
"""
|
||||
if str(worker.get("worker_id") or "").strip().lower().endswith(OUTBOUND_WORKER_ID_SUFFIX):
|
||||
return True
|
||||
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
|
||||
|
||||
expected = outbound_trigger_dir()
|
||||
actual = str(worker.get("trigger_dir") or "").strip()
|
||||
if expected is None or not actual:
|
||||
return False
|
||||
@@ -437,7 +470,7 @@ def _worker_is_eligible(
|
||||
backend_env: str,
|
||||
ttl_seconds: int,
|
||||
now: float,
|
||||
required_capability: str = INVENTORY_EXPORT_CAPABILITY,
|
||||
required_capability: str = ONHAND_EXPORT_CAPABILITY,
|
||||
) -> tuple[bool, list[str]]:
|
||||
"""
|
||||
判断单 Worker 是否满足心跳新鲜度、能力声明与环境/scope 隔离。
|
||||
@@ -447,7 +480,7 @@ def _worker_is_eligible(
|
||||
backend_env: 后端归一环境(dev/test/prod)。
|
||||
ttl_seconds: 心跳 TTL。
|
||||
now: 当前 epoch 秒。
|
||||
required_capability: 必选能力(inventory_export / freight_upload)。
|
||||
required_capability: 必选能力(onhand_export / inbound_export / outbound_export / freight_rpa_upload)。
|
||||
|
||||
Returns:
|
||||
(是否合格, 不合格原因列表)。
|
||||
@@ -461,10 +494,7 @@ def _worker_is_eligible(
|
||||
|
||||
capabilities = _parse_capabilities(worker.get("capabilities"))
|
||||
if required_capability and required_capability not in capabilities:
|
||||
if required_capability == FREIGHT_UPLOAD_CAPABILITY:
|
||||
reasons.append("missing_freight_upload_capability")
|
||||
else:
|
||||
reasons.append("missing_inventory_export_capability")
|
||||
reasons.append(_missing_capability_reason(required_capability))
|
||||
|
||||
worker_env = str(worker.get("environment") or "").strip().lower()
|
||||
if worker_env and worker_env != backend_env:
|
||||
@@ -477,6 +507,11 @@ def _worker_is_eligible(
|
||||
return not reasons, reasons
|
||||
|
||||
|
||||
def _missing_capability_reason(required_capability: str) -> str:
|
||||
"""按必选能力生成缺失原因码(onhand_export / inbound_export / outbound_export / freight_rpa_upload)。"""
|
||||
return f"missing_{required_capability}_capability"
|
||||
|
||||
|
||||
def _summarize_reasons(reasons: list[str]) -> str:
|
||||
hints: list[str] = []
|
||||
for reason in reasons:
|
||||
@@ -512,8 +547,8 @@ def _check_rpa_worker_ready_for_capability(
|
||||
trigger_dir: 待校验的共享 trigger 目录。
|
||||
required_capability: 必选 Worker 能力;空字符串表示不校验能力。
|
||||
extra_reasons: 调用方预检附加原因(凭据/队列等)。
|
||||
worker_predicate: 可选过滤(如仅收料 Worker);不匹配的心跳不进入列表。
|
||||
require_sentinel: 是否要求共享哨兵(库存/收料同口径均 True)。
|
||||
worker_predicate: 可选过滤(如仅入站 Worker);不匹配的心跳不进入列表。
|
||||
require_sentinel: 是否要求共享哨兵(库存/入站同口径均 True)。
|
||||
|
||||
Returns:
|
||||
RpaWorkerReadiness。
|
||||
@@ -601,7 +636,7 @@ def _check_rpa_worker_ready_for_capability(
|
||||
message, detail_message = "ready", "ready"
|
||||
else:
|
||||
failure = RpaWorkerReadiness(ready=False, message="", reasons=sorted(set(reasons)))
|
||||
if required_capability == FREIGHT_UPLOAD_CAPABILITY:
|
||||
if required_capability == FREIGHT_RPA_UPLOAD_CAPABILITY:
|
||||
detail = _summarize_reasons(failure.reasons)
|
||||
message = RPA_FREIGHT_UPLOAD_NOT_READY_MESSAGE
|
||||
detail_message = f"{message}({detail})" if detail else message
|
||||
@@ -623,41 +658,41 @@ def check_inventory_rpa_worker_ready() -> RpaWorkerReadiness:
|
||||
核心逻辑:Redis 可用、共享哨兵有效、最近心跳在 TTL 内、环境/scope 匹配。
|
||||
"""
|
||||
return _check_rpa_worker_ready_for_capability(
|
||||
trigger_dir=inventory_trigger_dir(),
|
||||
required_capability=INVENTORY_EXPORT_CAPABILITY,
|
||||
trigger_dir=onhand_trigger_dir(),
|
||||
required_capability=ONHAND_EXPORT_CAPABILITY,
|
||||
)
|
||||
|
||||
|
||||
def check_receipt_rpa_worker_ready() -> RpaWorkerReadiness:
|
||||
def check_inbound_rpa_worker_ready() -> RpaWorkerReadiness:
|
||||
"""
|
||||
检查收料 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。
|
||||
检查入站 RPA Worker 是否在线(管理端徽标 + 写 trigger 前 fail-fast)。
|
||||
|
||||
核心逻辑:仅看收料 Worker 心跳(*-receipt 或 trigger_dir 对齐);要求
|
||||
receipt_export 能力;校验收料 trigger 目录可写;与库存同口径要求共享哨兵。
|
||||
核心逻辑:仅看 inbound Worker 心跳(*-inbound 或 trigger_dir 对齐);要求
|
||||
inbound_export 能力;校验 inbound trigger 目录可写;与 onhand 同口径要求共享哨兵。
|
||||
"""
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
|
||||
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
|
||||
|
||||
return _check_rpa_worker_ready_for_capability(
|
||||
trigger_dir=receipt_trigger_dir(),
|
||||
required_capability=RECEIPT_EXPORT_CAPABILITY,
|
||||
worker_predicate=is_receipt_rpa_worker,
|
||||
trigger_dir=inbound_trigger_dir(),
|
||||
required_capability=INBOUND_EXPORT_CAPABILITY,
|
||||
worker_predicate=is_inbound_rpa_worker,
|
||||
require_sentinel=True,
|
||||
)
|
||||
|
||||
|
||||
def assert_receipt_rpa_worker_ready() -> None:
|
||||
def assert_inbound_rpa_worker_ready() -> None:
|
||||
"""
|
||||
写收料 trigger 前的强制就绪检查。
|
||||
写入站 trigger 前的强制就绪检查。
|
||||
|
||||
核心逻辑:镜像 assert_inventory_rpa_worker_ready;离线则抛 ServiceUnavailableError,
|
||||
排程不得进入 awaiting_receipt_rpa。
|
||||
排程不得进入 awaiting_inbound_rpa。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
|
||||
"""
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
|
||||
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
|
||||
|
||||
result = check_receipt_rpa_worker_ready()
|
||||
result = check_inbound_rpa_worker_ready()
|
||||
if result.ready:
|
||||
return
|
||||
code = 'RPA.WORKER_OFFLINE'
|
||||
@@ -677,7 +712,61 @@ def assert_receipt_rpa_worker_ready() -> None:
|
||||
'detail_message': result.detail_message,
|
||||
'checked_at': result.checked_at,
|
||||
'shared_scope_id': shared_scope_id(),
|
||||
'trigger_dir': str(receipt_trigger_dir() or ''),
|
||||
'trigger_dir': str(inbound_trigger_dir() or ''),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def check_outbound_rpa_worker_ready() -> RpaWorkerReadiness:
|
||||
"""
|
||||
检查出站 RPA Worker 是否在线(写 trigger 前 fail-fast)。
|
||||
|
||||
核心逻辑:仅看 outbound Worker 心跳(*-outbound 或 trigger_dir 对齐);要求
|
||||
outbound_export 能力;校验 outbound trigger 目录可写;与 onhand/inbound 同口径要求共享哨兵。
|
||||
"""
|
||||
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
|
||||
|
||||
return _check_rpa_worker_ready_for_capability(
|
||||
trigger_dir=outbound_trigger_dir(),
|
||||
required_capability=OUTBOUND_EXPORT_CAPABILITY,
|
||||
worker_predicate=is_outbound_rpa_worker,
|
||||
require_sentinel=True,
|
||||
)
|
||||
|
||||
|
||||
def assert_outbound_rpa_worker_ready() -> None:
|
||||
"""
|
||||
写出站 trigger 前的强制就绪检查。
|
||||
|
||||
核心逻辑:镜像 assert_inbound_rpa_worker_ready;离线则抛 ServiceUnavailableError,
|
||||
排程不得进入 awaiting_outbound_rpa_callback。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: worker 未就绪、共享目录无效或心跳存储不可用。
|
||||
"""
|
||||
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
|
||||
|
||||
result = check_outbound_rpa_worker_ready()
|
||||
if result.ready:
|
||||
return
|
||||
code = 'RPA.WORKER_OFFLINE'
|
||||
if 'heartbeat_storage_unavailable' in result.reasons:
|
||||
code = 'RPA.HEARTBEAT_STORAGE_UNAVAILABLE'
|
||||
logger.warning(
|
||||
'[rpa-heartbeat] outbound readiness blocked code=%s reasons=%s detail=%s',
|
||||
code,
|
||||
result.reasons,
|
||||
result.detail_message,
|
||||
)
|
||||
raise ServiceUnavailableError(
|
||||
result.message,
|
||||
code=code,
|
||||
details={
|
||||
'reasons': result.reasons,
|
||||
'detail_message': result.detail_message,
|
||||
'checked_at': result.checked_at,
|
||||
'shared_scope_id': shared_scope_id(),
|
||||
'trigger_dir': str(outbound_trigger_dir() or ''),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -689,7 +778,7 @@ def _freight_upload_config_reasons() -> list[str]:
|
||||
Returns:
|
||||
不合规原因码列表(空表示静态配置通过)。
|
||||
"""
|
||||
from app.services.shipping_notice.rpa import upload_queue_dir, upload_trigger_dir
|
||||
from app.services.freight_rpa.upload.trigger_io import upload_queue_dir, upload_trigger_dir
|
||||
|
||||
reasons: list[str] = []
|
||||
credential_key = _config_str("FREIGHT_RPA_CREDENTIAL_KEY", "")
|
||||
@@ -722,16 +811,16 @@ def check_freight_upload_rpa_ready() -> RpaWorkerReadiness:
|
||||
检查货代上传 RPA 是否可安全自动触发。
|
||||
|
||||
核心逻辑:凭据/队列/回调基址预检 + 上传 trigger 共享挂载 + Worker 心跳与
|
||||
freight_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。
|
||||
freight_rpa_upload 能力 + 环境/scope 隔离。Mock 模式跳过心跳。
|
||||
|
||||
Returns:
|
||||
RpaWorkerReadiness(含 reasons 供建单前/启动日志展示)。
|
||||
"""
|
||||
from app.services.shipping_notice.rpa import upload_trigger_dir
|
||||
from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
|
||||
|
||||
return _check_rpa_worker_ready_for_capability(
|
||||
trigger_dir=upload_trigger_dir(),
|
||||
required_capability=FREIGHT_UPLOAD_CAPABILITY,
|
||||
required_capability=FREIGHT_RPA_UPLOAD_CAPABILITY,
|
||||
extra_reasons=_freight_upload_config_reasons(),
|
||||
)
|
||||
|
||||
@@ -757,7 +846,7 @@ def assert_freight_upload_rpa_ready() -> None:
|
||||
result.reasons,
|
||||
result.detail_message,
|
||||
)
|
||||
from app.services.shipping_notice.rpa import upload_trigger_dir
|
||||
from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
|
||||
|
||||
raise ServiceUnavailableError(
|
||||
result.message,
|
||||
@@ -768,7 +857,7 @@ def assert_freight_upload_rpa_ready() -> None:
|
||||
"checked_at": result.checked_at,
|
||||
"shared_scope_id": shared_scope_id(),
|
||||
"trigger_dir": str(upload_trigger_dir() or ""),
|
||||
"capability": FREIGHT_UPLOAD_CAPABILITY,
|
||||
"capability": FREIGHT_RPA_UPLOAD_CAPABILITY,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -836,29 +925,34 @@ def assert_inventory_rpa_worker_ready() -> None:
|
||||
"detail_message": result.detail_message,
|
||||
"checked_at": result.checked_at,
|
||||
"shared_scope_id": shared_scope_id(),
|
||||
"trigger_dir": str(inventory_trigger_dir() or ""),
|
||||
"trigger_dir": str(onhand_trigger_dir() or ""),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def serialize_rpa_worker_status(*, scope: str = "inventory") -> dict[str, Any]:
|
||||
def serialize_rpa_worker_status(*, scope: str = "onhand") -> dict[str, Any]:
|
||||
"""
|
||||
管理端展示:按 scope 返回库存或收料 Worker 心跳摘要。
|
||||
管理端展示:按 scope 返回在手(onhand)、入站(inbound)或出站(outbound)Worker 心跳摘要。
|
||||
|
||||
Args:
|
||||
scope: inventory(默认)或 receipt。
|
||||
scope: onhand(默认,库存 RPA 工作台)、inbound(入站)或 outbound(出站);
|
||||
取值为后端内部与前端查询参数约定,与 Worker 上报能力标识无关。
|
||||
"""
|
||||
from app.services.shipping_notice.rpa import upload_trigger_dir
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_trigger_dir
|
||||
from app.services.freight_rpa.upload.trigger_io import upload_trigger_dir
|
||||
from app.services.freight_rpa.inbound.trigger_io import inbound_trigger_dir
|
||||
from app.services.freight_rpa.outbound.trigger_io import outbound_trigger_dir
|
||||
|
||||
normalized = str(scope or "inventory").strip().lower()
|
||||
if normalized == "receipt":
|
||||
readiness = check_receipt_rpa_worker_ready()
|
||||
trigger_path = str(receipt_trigger_dir() or "")
|
||||
normalized = str(scope or "onhand").strip().lower()
|
||||
if normalized == "inbound":
|
||||
readiness = check_inbound_rpa_worker_ready()
|
||||
trigger_path = str(inbound_trigger_dir() or "")
|
||||
elif normalized == "outbound":
|
||||
readiness = check_outbound_rpa_worker_ready()
|
||||
trigger_path = str(outbound_trigger_dir() or "")
|
||||
else:
|
||||
readiness = check_inventory_rpa_worker_ready()
|
||||
trigger_path = str(inventory_trigger_dir() or "")
|
||||
normalized = "inventory"
|
||||
trigger_path = str(onhand_trigger_dir() or "")
|
||||
normalized = "onhand"
|
||||
|
||||
freight_readiness = check_freight_upload_rpa_ready()
|
||||
ttl_seconds = _heartbeat_ttl_seconds()
|
||||
@@ -896,7 +990,7 @@ def serialize_rpa_worker_status(*, scope: str = "inventory") -> dict[str, Any]:
|
||||
"upload_trigger_dir": str(upload_trigger_dir() or ""),
|
||||
"reasons": readiness.reasons,
|
||||
"workers": workers,
|
||||
"freight_upload": {
|
||||
"freight_rpa_upload": {
|
||||
"ready": freight_readiness.ready,
|
||||
"message": freight_readiness.message,
|
||||
"detail_message": freight_readiness.detail_message,
|
||||
+3
-3
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_worker_heartbeat_alert.py
|
||||
services/freight_rpa/common/worker_heartbeat_alert.py
|
||||
|
||||
用途:库存 RPA Worker 离线/恢复主动告警(企微 textcard + 冷却去重)。
|
||||
依赖:rpa_worker_heartbeat、redis_client、wecom_notify、models.User、models.AppSetting。
|
||||
依赖:同包 worker_heartbeat、redis_client、wecom_notify、models.User、models.AppSetting。
|
||||
逻辑:由 schedule worker 每轮循环调用;默认 ALERT_ENABLED=false 不发送;DB 为告警状态权威源,Redis 仅作缓存同步。
|
||||
"""
|
||||
|
||||
@@ -21,7 +21,7 @@ from sqlalchemy.exc import IntegrityError
|
||||
from app import db
|
||||
from app.models import AppSetting, User
|
||||
from app.services.permission_roles.service import list_platform_admin_users
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
from .worker_heartbeat import (
|
||||
RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE,
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
_heartbeat_check_required,
|
||||
@@ -0,0 +1 @@
|
||||
"""inbound:入站 RPA。"""
|
||||
@@ -0,0 +1,219 @@
|
||||
"""
|
||||
services/freight_rpa/inbound/report_archive.py
|
||||
|
||||
用途:inbound(入站,原收料)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、
|
||||
三年保留期、不写库存快照表)与到期对象清理(retention)。per-file 企微投递与 resend
|
||||
已拆除(Task 2);排程终态通知仍走 freight_rpa_inbound_finalize 统一出口。
|
||||
依赖:models(FreightRpaInboundReportFile / FreightRpaInboundUnitRun、ScheduleRun 经行对象访问)、
|
||||
file_assets.storage、freight_rpa.inbound.trigger_io(回调 SCHEMA 与 drop 根)、
|
||||
freight_rpa.common.report_audit(本域唯一审计写入口,批次 B Task 6 起替代
|
||||
shipping_notice.audit_service——freight_rpa 禁止 import shipping_notice 业务模块,
|
||||
边界由 tests/services/freight_rpa/test_import_boundary.py 空白名单锁定)、
|
||||
freight_rpa.reports.facts / reports.dispatch(ReportFact 事实投递,Task 6)。
|
||||
逻辑:Worker 回调进入 /api/freight-rpa/inbound-batch-ready 后由组合根注册的业务 sink
|
||||
(in_transit_transfer.rpa_sinks.register_inbound_sinks)调 ingest_inbound_callback 完成原样归档,
|
||||
empty/success/failed 三个终态分支各自「先 db.session.commit() 再投递事实」——
|
||||
commit 后构造 ReportFact(report_kind='inbound', ...) 调 dispatch_report_fact;
|
||||
处理函数异常原样外抛(不吞、不回滚已提交终态),kind 未注册时 404
|
||||
FREIGHT_RPA.SINK_NOT_REGISTERED;同一 unit_run_id + sha256 已有文件时不插第二行、
|
||||
仍投递 ok=True 的事实供处理函数重试。业务收尾(推进在途调拨来源任务、调拨证据
|
||||
同步、排程终态归集)改由 Task 7 的处理函数(handle_inbound_report 等)承担,
|
||||
本模块不 import 任何桥与 finalize——依赖方向保持 shipping_notice → freight_rpa。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
)
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.freight_rpa.common.report_audit import append_rpa_report_event
|
||||
from app.services.freight_rpa.inbound.trigger_io import SCHEMA as INBOUND_TRIGGER_SCHEMA, inbound_drop_dir
|
||||
from app.services.freight_rpa.reports.dispatch import dispatch_report_fact
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
def _read_inbound_callback_file(file_path: str) -> bytes:
|
||||
"""只读取 inbound 专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。
|
||||
|
||||
路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属
|
||||
两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...),
|
||||
Worker 只上报文件名,后端用自身挂载的 drop 根拼接定位;携带本机绝对路径的历史
|
||||
载荷亦按末段文件名解析(2026-10-08 修复跨机成功回调全程 400 的事故)。
|
||||
"""
|
||||
configured_root = str(inbound_drop_dir() or '').strip()
|
||||
if not configured_root:
|
||||
raise ValidationError('inbound callback file root is unavailable', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID')
|
||||
root = Path(configured_root).resolve()
|
||||
# 容忍历史载荷携带 Windows 绝对路径:先归一分隔符再取末段文件名(防遍历,单一分段)。
|
||||
name = Path(str(file_path).replace('\\', '/')).name
|
||||
path = (root / name).resolve()
|
||||
try:
|
||||
path.relative_to(root)
|
||||
except ValueError as exc:
|
||||
raise ValidationError('inbound callback file is outside inbound drop root', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID') from exc
|
||||
if path.suffix.lower() != '.xlsx' or not path.is_file():
|
||||
raise ValidationError('inbound callback file must be an existing xlsx', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID')
|
||||
max_size = max(int(current_app.config.get('FILE_ASSET_MAX_SIZE_MB', 30) or 30), 1) * 1024 * 1024
|
||||
if path.stat().st_size > max_size:
|
||||
raise ValidationError('inbound callback file exceeds configured size limit', code='SHIPPING.INBOUND_CALLBACK_FILE_INVALID')
|
||||
return path.read_bytes()
|
||||
|
||||
|
||||
def ingest_inbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""幂等接收单个 inbound 单元回调,原样归档三年且不写库存快照表。
|
||||
|
||||
Args:
|
||||
payload: Worker 回调载荷(schema_version/callback_id/status/file_path/...)。
|
||||
Returns:
|
||||
dict: unit_run_id/status[/file_id/idempotent],与拆分前逐键一致(API envelope 契约)。
|
||||
Raises:
|
||||
ValidationError: 载荷非法(schema/callback_id/sha256/文件路径)——commit 之前抛出,不投递事实。
|
||||
NotFoundError: callback_id 无匹配单元——commit 之前抛出,不投递事实。
|
||||
AppError: 终态已 commit 后 kind 未注册处理函数(FREIGHT_RPA.SINK_NOT_REGISTERED, 404)。
|
||||
业务顺序(Task 6 契约):每个终态分支先 db.session.commit() 再构造
|
||||
ReportFact(report_kind='inbound', source_code=unit.source_code, ...) 调
|
||||
dispatch_report_fact;事实恒带 unit_run_id=unit.id(Task 7 修复轮 2——
|
||||
含 failure/empty 与幂等重放,处理函数据此精确定位本单元的排程 run);
|
||||
处理函数异常原样外抛(不吞、不回滚已提交终态);
|
||||
同一 unit_run_id + sha256 已有文件时不插第二行,仍投递 ok=True 的事实
|
||||
(供处理函数重试)。落 MinIO / 插行失败时事务回滚,同样不投递。
|
||||
"""
|
||||
if payload.get('schema_version') != INBOUND_TRIGGER_SCHEMA:
|
||||
raise ValidationError('inbound callback schema_version is invalid', code='SHIPPING.INBOUND_CALLBACK_INVALID')
|
||||
callback_id = str(payload.get('callback_id') or '').strip()
|
||||
unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
|
||||
if unit is None:
|
||||
raise NotFoundError('Inbound RPA unit not found', code='SHIPPING.INBOUND_UNIT_NOT_FOUND')
|
||||
status = str(payload.get('status') or '').strip().lower()
|
||||
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
|
||||
if status in {'empty', 'no_data'}:
|
||||
# [STEP] 与库存 no_inventory_data 对齐:empty 是合法业务结果,落 error_code=no_inbound_data。
|
||||
unit.status = 'empty'
|
||||
unit.error_code = str(payload.get('error_code') or 'no_inbound_data')[:64]
|
||||
unit.error_message = str(payload.get('error_message') or 'no_inbound_data')[:2000]
|
||||
unit.finished_at = datetime.utcnow()
|
||||
append_rpa_report_event(
|
||||
event_type='shipping_inbound_rpa_callback_received', aggregate_type='shipping_inbound_unit',
|
||||
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
|
||||
actor_type='rpa', actor_id='inbound-worker', unit_id=unit.id, result='success',
|
||||
before=before,
|
||||
after={
|
||||
'status': 'empty',
|
||||
'callback_id': unit.callback_id,
|
||||
'error_code': unit.error_code,
|
||||
'error_message': unit.error_message,
|
||||
},
|
||||
metadata={'callback_status': status, 'skip_reason': unit.error_code},
|
||||
)
|
||||
# [STEP] 先 commit 终态,再投递 ok=False 事实(Task 6 顺序契约);unit_run_id
|
||||
# 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。
|
||||
db.session.commit()
|
||||
dispatch_report_fact(ReportFact(
|
||||
report_kind='inbound', source_code=unit.source_code, file_id=None, sha256=None, ok=False,
|
||||
error_code=unit.error_code or 'no_inbound_data',
|
||||
error_message=unit.error_message or 'no_inbound_data',
|
||||
unit_run_id=unit.id,
|
||||
))
|
||||
return {'unit_run_id': unit.id, 'status': 'empty'}
|
||||
if status != 'success':
|
||||
unit.status = 'failed'; unit.error_code = str(payload.get('error_code') or 'RPA.INBOUND_EXPORT_FAILED')[:64]; unit.error_message = str(payload.get('error_message') or 'inbound export failed')[:2000]; unit.finished_at = datetime.utcnow()
|
||||
append_rpa_report_event(
|
||||
event_type='shipping_inbound_rpa_callback_received', aggregate_type='shipping_inbound_unit',
|
||||
aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None,
|
||||
actor_type='rpa', actor_id='inbound-worker', unit_id=unit.id, result='failure',
|
||||
before=before, after={'status': 'failed', 'error_code': unit.error_code, 'error_message': unit.error_message},
|
||||
metadata={'callback_status': status},
|
||||
)
|
||||
# [STEP] 先 commit 终态,再投递 ok=False 事实(Task 6 顺序契约);unit_run_id
|
||||
# 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。
|
||||
db.session.commit()
|
||||
dispatch_report_fact(ReportFact(
|
||||
report_kind='inbound', source_code=unit.source_code, file_id=None, sha256=None, ok=False,
|
||||
error_code=unit.error_code, error_message=unit.error_message,
|
||||
unit_run_id=unit.id,
|
||||
))
|
||||
return {'unit_run_id': unit.id, 'status': 'failed'}
|
||||
data = _read_inbound_callback_file(str(payload.get('file_path') or ''))
|
||||
sha256 = hashlib.sha256(data).hexdigest()
|
||||
claimed = str(payload.get('sha256') or '').lower()
|
||||
if claimed and claimed != sha256:
|
||||
raise ValidationError('inbound callback sha256 mismatch', code='SHIPPING.INBOUND_CALLBACK_SHA_MISMATCH')
|
||||
existing = FreightRpaInboundReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none()
|
||||
if existing:
|
||||
# [STEP] 幂等重放:不插第二行,仍投递 ok=True 事实(同一 file_id),供处理函数重试;
|
||||
# unit_run_id 自单元行回填(Task 7 修复轮 2)。
|
||||
dispatch_report_fact(ReportFact(
|
||||
report_kind='inbound', source_code=unit.source_code, file_id=existing.id, sha256=sha256, ok=True,
|
||||
unit_run_id=unit.id,
|
||||
))
|
||||
return {'unit_run_id': unit.id, 'status': unit.status, 'file_id': existing.id, 'idempotent': True}
|
||||
filename = Path(str(payload.get('original_filename') or payload.get('file_path') or 'receipt.xlsx')).name
|
||||
storage_key = f'shipping/receipt-reports/{datetime.utcnow():%Y/%m}/{unit.id}/{sha256}.xlsx'
|
||||
file_asset_storage.upload_bytes(storage_key=storage_key, data=data, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
record = FreightRpaInboundReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key, original_filename=filename, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', file_size=len(data), sha256=sha256, archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3))
|
||||
db.session.add(record)
|
||||
unit.status = 'success'; unit.finished_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
append_rpa_report_event(event_type='shipping_inbound_report_archived', aggregate_type='shipping_inbound_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='inbound-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'inbound_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
|
||||
# [STEP] 先 commit 归档,再投递 ok=True 事实(Task 6 顺序契约);unit_run_id
|
||||
# 自单元行回填(Task 7 修复轮 2——处理函数据此精确收口本单元的排程 run)。
|
||||
db.session.commit()
|
||||
dispatch_report_fact(ReportFact(
|
||||
report_kind='inbound', source_code=unit.source_code, file_id=record.id, sha256=sha256, ok=True,
|
||||
unit_run_id=unit.id,
|
||||
))
|
||||
return {'unit_run_id': unit.id, 'status': 'success', 'file_id': record.id, 'idempotent': False}
|
||||
|
||||
|
||||
def run_freight_rpa_inbound_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
|
||||
"""仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。
|
||||
|
||||
Args:
|
||||
task: 排程任务行(job_params.limit 提供单批上限,1..1000)。
|
||||
run: 排程执行记录(本函数不改写 run,仅按排程协议返回计数/明细/日志)。
|
||||
Returns:
|
||||
排程平台 Job 协议七元组(总查得数、成功、失败、跳过 0、明细、错误、step_logs)。
|
||||
"""
|
||||
limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000))
|
||||
now = datetime.utcnow()
|
||||
rows = FreightRpaInboundReportFile.query.filter(
|
||||
FreightRpaInboundReportFile.archive_expires_at.is_not(None),
|
||||
FreightRpaInboundReportFile.archive_expires_at <= now,
|
||||
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
|
||||
).order_by(FreightRpaInboundReportFile.id).limit(limit).all()
|
||||
success = failed = 0
|
||||
errors: list[str] = []
|
||||
for report_file in rows:
|
||||
try:
|
||||
file_asset_storage.delete_object(report_file.storage_key)
|
||||
report_file.archive_deleted_at = now
|
||||
report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()}
|
||||
append_rpa_report_event(
|
||||
event_type='shipping_inbound_report_archive_deleted', aggregate_type='shipping_inbound_file',
|
||||
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
|
||||
unit_id=report_file.unit_run_id, result='success',
|
||||
before={'status': 'archived'}, after={'status': 'archive_deleted'},
|
||||
artifact_refs=[{'kind': 'inbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
success += 1
|
||||
except Exception as exc:
|
||||
errors.append(f'{report_file.id}: {exc}')
|
||||
append_rpa_report_event(
|
||||
event_type='shipping_inbound_report_archive_delete_attempted', aggregate_type='shipping_inbound_file',
|
||||
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
|
||||
unit_id=report_file.unit_run_id, result='failure',
|
||||
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
|
||||
artifact_refs=[{'kind': 'inbound_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
failed += 1
|
||||
db.session.commit()
|
||||
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'inbound_retention', 'status': 'completed'}]
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
services/freight_rpa/inbound/trigger_io.py
|
||||
|
||||
用途:inbound(入站,原收料)RPA 的纯文件 IO——trigger/落盘目录解析、批量 trigger JSON
|
||||
原子写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。
|
||||
依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块
|
||||
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
|
||||
逻辑:由 schedule.freight_rpa_inbound_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、
|
||||
in_transit_transfer.inbound_trigger_service(调拨按需/批量触发)、
|
||||
freight_rpa.common.worker_heartbeat(inbound trigger 目录探测/就绪检查)、
|
||||
freight_rpa.inbound.report_archive(drop 目录定位与回调 SCHEMA 校验,Task 10 下沉)等调用,
|
||||
与外部 RPA Worker 的文件投递目录交互;schema/action 新值以本文件常量为单一真相
|
||||
(Worker 侧 Task 12 对表:freight_rpa.inbound.v1 / inbound_export_batch)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
# Worker 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。
|
||||
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:schema/action 切换为下述新值
|
||||
# (旧 receipt 时代字面量已从 backend/app 与 Worker 双侧清零,历史对照见 cutover runbook),
|
||||
# 旧字符串已在 backend/app 内清零;Worker 侧由 Task 12 对齐。
|
||||
SCHEMA = "freight_rpa.inbound.v1"
|
||||
ACTION_INBOUND_EXPORT_BATCH = "inbound_export_batch"
|
||||
|
||||
|
||||
def _path(key: str) -> Path | None:
|
||||
value = str(current_app.config.get(key) or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
return Path(value)
|
||||
|
||||
|
||||
def inbound_trigger_dir() -> Path | None:
|
||||
"""RPA inbound 批量导出触发 JSON 目录(FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR);
|
||||
绝不回落到 onhand trigger 目录。"""
|
||||
return _path("FREIGHT_RPA_SHARED_INBOUND_TRIGGER_DIR")
|
||||
|
||||
|
||||
def inbound_drop_dir() -> Path | None:
|
||||
"""RPA inbound 导出文件落盘目录(FREIGHT_RPA_SHARED_INBOUND_DROP_DIR)。"""
|
||||
return _path("FREIGHT_RPA_SHARED_INBOUND_DROP_DIR")
|
||||
|
||||
|
||||
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
|
||||
"""原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。"""
|
||||
temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
|
||||
try:
|
||||
with open(temp_path, 'w', encoding='utf-8') as handle:
|
||||
json.dump(body, handle, ensure_ascii=False, indent=2)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temp_path, path)
|
||||
finally:
|
||||
if temp_path.exists():
|
||||
temp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def write_inbound_export_batch_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None:
|
||||
"""
|
||||
写入 inbound 批量 trigger 文件 inbound_export_batch_{run_no}.json
|
||||
([PROMPT_UPDATE] 2026-10-16 批次 R:文件名前缀随 Worker 侧 Task 12 一起由
|
||||
receipt_export_batch_* 切换为 inbound_export_batch_*;Worker 轮询 <root>/*.json
|
||||
按内容消费,schema/action 取本文件常量新值)。
|
||||
|
||||
Args:
|
||||
run_no: 批次运行号;进 body.batch_run_no 并参与文件名(安全化仅保留字母数字-_)。
|
||||
units: 触发单元载荷列表;业务约束——空列表直接返回 None(无单元不落盘)。
|
||||
payload: 调用方附加字段,合并覆盖 body 顶层键(schema_version/action 缺省取常量)。
|
||||
|
||||
Returns:
|
||||
str | None: 触发文件绝对路径;目录未配置或 units 为空时返回 None。
|
||||
"""
|
||||
trigger_dir = inbound_trigger_dir()
|
||||
if not trigger_dir or not units:
|
||||
return None
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
safe_run_no = ''.join(char for char in run_no if char.isalnum() or char in {'-', '_'}) or 'inbound'
|
||||
body = {
|
||||
'schema_version': SCHEMA, 'action': ACTION_INBOUND_EXPORT_BATCH,
|
||||
'batch_run_no': run_no, 'requested_at': datetime.utcnow().isoformat(), 'units': units,
|
||||
**(payload or {}),
|
||||
}
|
||||
path = trigger_dir / f'inbound_export_batch_{safe_run_no}.json'
|
||||
_write_trigger_json_atomic(path, body)
|
||||
return str(path)
|
||||
@@ -0,0 +1 @@
|
||||
"""onhand:在手库存 RPA。"""
|
||||
+14
-12
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
services/shipping_notice/rpa_attempts.py
|
||||
services/freight_rpa/onhand/attempts.py
|
||||
|
||||
用途:统计任务的 RPA 库存导出与货代上传重试次数,并返回统一上限。
|
||||
依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑。
|
||||
逻辑:由 inventory_rpa_workflow、fulfillment_workflow 等模块调用本文件,决定是否还能继续触发 RPA 重试。
|
||||
用途:统计任务的 onhand(库存)RPA 导出与货代上传重试次数,并返回统一上限。
|
||||
依赖:ShippingNotice、ShippingTaskEvent 模型与事件查询逻辑(仅 models,无业务编排 import)。
|
||||
逻辑:由 shipping_notice 的 onhand_rpa_workflow、fulfillment_workflow 等模块调用本文件,
|
||||
决定是否还能继续触发 RPA 重试;事件类型字符串(onhand_rpa_* 等)是落库数据值,
|
||||
随 models 命名一并留待批次 S 处理,本模块只改包归属与标识符词根。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,15 +17,15 @@ from app.models import ShippingNotice, ShippingTaskEvent
|
||||
|
||||
DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
|
||||
|
||||
_INVENTORY_SUCCESS_EVENTS = {
|
||||
_ONHAND_SUCCESS_EVENTS = {
|
||||
"inventory_uploaded",
|
||||
"inventory_parsed",
|
||||
"inventory_rpa_drop_ingested",
|
||||
"inventory_rpa_ready",
|
||||
"onhand_rpa_drop_ingested",
|
||||
"onhand_rpa_ready",
|
||||
"inventory_template_mapping_used",
|
||||
}
|
||||
|
||||
_INVENTORY_ATTEMPT_RESET_EVENTS = _INVENTORY_SUCCESS_EVENTS | {
|
||||
_ONHAND_ATTEMPT_RESET_EVENTS = _ONHAND_SUCCESS_EVENTS | {
|
||||
"decision_retry_rpa",
|
||||
}
|
||||
|
||||
@@ -33,24 +35,24 @@ _UPLOAD_SUCCESS_EVENTS = {
|
||||
}
|
||||
|
||||
|
||||
def inventory_rpa_attempts(task: ShippingNotice | None) -> int:
|
||||
def onhand_rpa_attempts(task: ShippingNotice | None) -> int:
|
||||
"""统计自上次库存成功事件以来的 RPA 库存导出触发/失败次数。"""
|
||||
if not task or task.id is None:
|
||||
return 0
|
||||
|
||||
last_reset = (
|
||||
ShippingTaskEvent.query.filter_by(task_id=task.id)
|
||||
.filter(ShippingTaskEvent.event_type.in_(_INVENTORY_ATTEMPT_RESET_EVENTS))
|
||||
.filter(ShippingTaskEvent.event_type.in_(_ONHAND_ATTEMPT_RESET_EVENTS))
|
||||
.order_by(ShippingTaskEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
since: datetime | None = last_reset.created_at if last_reset else None
|
||||
|
||||
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
|
||||
ShippingTaskEvent.event_type == "inventory_rpa_triggered"
|
||||
ShippingTaskEvent.event_type == "onhand_rpa_triggered"
|
||||
)
|
||||
failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
|
||||
ShippingTaskEvent.event_type == "inventory_rpa_failed"
|
||||
ShippingTaskEvent.event_type == "onhand_rpa_failed"
|
||||
)
|
||||
if since:
|
||||
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
|
||||
+11
-9
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_rpa_callback_cleanup.py
|
||||
services/freight_rpa/onhand/callback_cleanup.py
|
||||
|
||||
用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记。
|
||||
依赖:rpa.inventory_drop_dir / inventory_processed_dir、json、uuid、Flask current_app。
|
||||
逻辑:commit 后尝试归档;失败则移入 .hxops_quarantine 并入队;scheduler/worker 启动时定期消费队列。
|
||||
用途:RPA callback drop 区文件归档失败后的持久化重试队列、隔离与消费标记
|
||||
(Task 9 自 shipping_notice.onhand_rpa_callback_cleanup 整体平移,纯协议文件 IO、零业务落盘)。
|
||||
依赖:freight_rpa.onhand.trigger_io(onhand_drop_dir / onhand_processed_dir)、json、uuid、Flask current_app。
|
||||
逻辑:commit 后由 shipping_notice 业务 sink 调用尝试归档;失败则移入 .hxops_quarantine 并入队;
|
||||
scheduler/worker 启动时定期消费队列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,7 +20,7 @@ from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.services.shipping_notice.rpa import inventory_drop_dir, inventory_processed_dir
|
||||
from app.services.freight_rpa.onhand.trigger_io import onhand_drop_dir, onhand_processed_dir
|
||||
|
||||
_CALLBACK_CONSUMED_SUFFIX = ".hxops_consumed"
|
||||
_CLEANUP_QUEUE_DIRNAME = ".cleanup_queue"
|
||||
@@ -30,7 +32,7 @@ _LOGGER = logging.getLogger(__name__)
|
||||
|
||||
def callback_cleanup_queue_dir() -> Path | None:
|
||||
"""drop 目录下 callback 归档重试队列路径。"""
|
||||
drop = inventory_drop_dir()
|
||||
drop = onhand_drop_dir()
|
||||
if not drop:
|
||||
return None
|
||||
return drop / _CLEANUP_QUEUE_DIRNAME
|
||||
@@ -38,7 +40,7 @@ def callback_cleanup_queue_dir() -> Path | None:
|
||||
|
||||
def callback_cleanup_failed_dir() -> Path | None:
|
||||
"""超过最大重试次数的 cleanup job 隔离目录。"""
|
||||
drop = inventory_drop_dir()
|
||||
drop = onhand_drop_dir()
|
||||
if not drop:
|
||||
return None
|
||||
return drop / _CLEANUP_FAILED_DIRNAME
|
||||
@@ -49,7 +51,7 @@ def callback_quarantine_dir() -> Path | None:
|
||||
Worker 不应扫描的 callback 隔离目录(drop 根目录外的子目录)。
|
||||
归档失败时 HXOPS 将文件原子移入此处,避免重复上报。
|
||||
"""
|
||||
drop = inventory_drop_dir()
|
||||
drop = onhand_drop_dir()
|
||||
if not drop:
|
||||
return None
|
||||
return drop / _QUARANTINE_DIRNAME
|
||||
@@ -243,7 +245,7 @@ def flush_callback_cleanup_queue(*, max_jobs: int = 32) -> list[str]:
|
||||
callback_raw = str(payload.get("callback_path") or "").strip()
|
||||
processed_raw = str(payload.get("processed_dir") or "").strip()
|
||||
callback_path = Path(callback_raw) if callback_raw else None
|
||||
processed_dir = Path(processed_raw) if processed_raw else inventory_processed_dir()
|
||||
processed_dir = Path(processed_raw) if processed_raw else onhand_processed_dir()
|
||||
if callback_path is None or processed_dir is None:
|
||||
try:
|
||||
job_path.unlink()
|
||||
@@ -0,0 +1,84 @@
|
||||
"""freight_rpa/onhand/report_store.py
|
||||
|
||||
用途:freight_rpa_onhand_report_files 的写入唯一入口(阶段 B Task 5)——发货域
|
||||
(shipping_notice)与调度等其他消费方不得自行构造 FreightRpaOnhandReportFile 行,
|
||||
插入/按主键更新统一经本模块收敛,保证报表事实写入只发生在货代 RPA 域。
|
||||
依赖:app.db、app.models.FreightRpaOnhandReportFile、app.core.errors.NotFoundError。
|
||||
逻辑:insert_onhand_report 接收与 FreightRpaOnhandReportFile 列同名的关键字参数
|
||||
(storage_path、file_sha256、onhand_lines_json、field_mapping_json、
|
||||
snapshot_status、warehouse_id、source_code、rpa_run_no 等),flush 后
|
||||
返回 file_id;update_onhand_report 按主键更新给定列。两者都【只 flush 不
|
||||
commit】——事务提交时机归属调用方;两者都【不创建任务关联】——
|
||||
shipping_task_onhand_links 等 link 表归发货域,由调用方自行维护。
|
||||
【禁止】import app.services.shipping_notice / in_transit_transfer(import
|
||||
方向只能反过来,边界由 tests/services/shipping_notice/
|
||||
test_report_model_boundary.py 锁定)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import FreightRpaOnhandReportFile
|
||||
|
||||
|
||||
def insert_onhand_report(**columns: Any) -> int:
|
||||
"""插入 freight_rpa_onhand_report_files 一行并 flush。返回 file_id。不创建任务关联,不 commit。
|
||||
|
||||
【AI 触发时机】:任何需要新增在手/库存快照文件记录的场景
|
||||
(RPA 回调入快照、人工上传保存、空快照记录)须调用本函数,禁止在
|
||||
shipping_notice 域内直接构造 FreightRpaOnhandReportFile 行。
|
||||
|
||||
核心逻辑:[STEP 1] 以与模型列同名的关键字参数构造行;
|
||||
[STEP 2] db.session.add + flush(拿到自增主键且同事务内可见);
|
||||
[STEP 3] 返回 int 主键,供调用方按需经 db.session.get 取回 ORM 对象。
|
||||
|
||||
Args:
|
||||
**columns: FreightRpaOnhandReportFile 的任意合法列关键字(禁止传入不存在的
|
||||
列名,非法列名会在构造时抛 TypeError)。无默认值语义变化——
|
||||
列默认值仍由模型定义(default=)承担。
|
||||
|
||||
Returns:
|
||||
新插入行的 file_id(int)。
|
||||
|
||||
Raises:
|
||||
TypeError: 传入了模型不存在的列关键字。
|
||||
sqlalchemy.exc.IntegrityError: 唯一约束(如 onhand_file_no / RPA 幂等索引)
|
||||
冲突,由调用方决定 savepoint 回滚或复用既有行。
|
||||
"""
|
||||
row = FreightRpaOnhandReportFile(**columns)
|
||||
db.session.add(row)
|
||||
db.session.flush()
|
||||
return int(row.id)
|
||||
|
||||
|
||||
def update_onhand_report(file_id: int, **columns: Any) -> None:
|
||||
"""按 file_id 更新该行的给定列并 flush。不 commit。
|
||||
|
||||
【AI 触发时机】:快照过期(snapshot_status→expired)、批次同身份改写
|
||||
share_mode、identity_status 回填等针对既有在手报表行的列更新场景。
|
||||
|
||||
核心逻辑:[STEP 1] 按主键取行(命中身份缓存即为同一 ORM 对象,调用方
|
||||
持有的引用会同步可见更新),缺失抛 NotFoundError(fail-closed,禁止静默
|
||||
吞掉错配);[STEP 2] 逐列 setattr;[STEP 3] flush。【不 commit】——
|
||||
事务归属调用方;【不动任务关联】——link 表更新归发货域。
|
||||
|
||||
Args:
|
||||
file_id: freight_rpa_onhand_report_files 主键(int;禁止传入非整数 ID)。
|
||||
**columns: 要更新的列名与取值(禁止传入模型不存在的列名)。
|
||||
|
||||
Raises:
|
||||
NotFoundError: file_id 对应的行不存在。
|
||||
TypeError: 传入了模型不存在的列关键字。
|
||||
"""
|
||||
row = db.session.get(FreightRpaOnhandReportFile, file_id)
|
||||
if row is None:
|
||||
raise NotFoundError(
|
||||
f"Onhand report file not found: {file_id}",
|
||||
details={'file_id': file_id},
|
||||
)
|
||||
for key, value in columns.items():
|
||||
setattr(row, key, value)
|
||||
db.session.flush()
|
||||
@@ -0,0 +1,108 @@
|
||||
"""
|
||||
services/freight_rpa/onhand/trigger_io.py
|
||||
|
||||
用途:onhand(在手库存)RPA 的纯文件 IO——trigger/落盘目录解析、trigger JSON 原子写、
|
||||
单任务导出 trigger 写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。
|
||||
依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块
|
||||
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
|
||||
逻辑:由 shipping_notice.onhand_trigger_batch(批量/按需编排)、onhand_rpa_workflow(回调 schema 校验)、
|
||||
per_source_rpa_service(回调 schema 校验)、freight_rpa.common.worker_heartbeat(目录探测)等调用,
|
||||
与外部 RPA Worker 的文件投递目录交互;schema/action 新值以本文件常量为单一真相
|
||||
(Worker 侧 Task 12 对表:freight_rpa.onhand.v1 / onhand_export / onhand_export_batch)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
# Worker 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。
|
||||
# [PROMPT_UPDATE] 2026-10-16 freight_rpa 解耦批次 R:schema/action 切换为下述新值
|
||||
# (旧 inventory 时代字面量已从 backend/app 与 Worker 双侧清零,历史对照见 cutover runbook),
|
||||
# 旧字符串已在 backend/app 内清零;Worker 侧由 Task 12 对齐。
|
||||
SCHEMA = "freight_rpa.onhand.v1"
|
||||
ACTION_ONHAND_EXPORT = "onhand_export"
|
||||
ACTION_ONHAND_EXPORT_BATCH = "onhand_export_batch"
|
||||
|
||||
|
||||
def _path(key: str) -> Path | None:
|
||||
value = str(current_app.config.get(key) or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
return Path(value)
|
||||
|
||||
|
||||
def onhand_drop_dir() -> Path | None:
|
||||
"""RPA onhand 库存 Excel 落盘目录(FREIGHT_RPA_SHARED_ONHAND_DROP_DIR)。"""
|
||||
return _path("FREIGHT_RPA_SHARED_ONHAND_DROP_DIR")
|
||||
|
||||
|
||||
def onhand_processed_dir() -> Path | None:
|
||||
"""已处理 onhand 文件归档子目录(drop_dir/processed)。"""
|
||||
base = onhand_drop_dir()
|
||||
if not base:
|
||||
return None
|
||||
return base / "processed"
|
||||
|
||||
|
||||
def onhand_trigger_dir() -> Path | None:
|
||||
"""RPA onhand 导出触发 JSON 目录(FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR)。"""
|
||||
return _path("FREIGHT_RPA_SHARED_ONHAND_TRIGGER_DIR")
|
||||
|
||||
|
||||
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
|
||||
"""原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。"""
|
||||
temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
|
||||
try:
|
||||
with open(temp_path, 'w', encoding='utf-8') as handle:
|
||||
json.dump(body, handle, ensure_ascii=False, indent=2)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temp_path, path)
|
||||
finally:
|
||||
if temp_path.exists():
|
||||
temp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def write_onhand_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None:
|
||||
"""
|
||||
写入 RPA onhand 导出触发文件 inventory_export_{task_no}.json
|
||||
(文件名沿用既有 Worker 契约,仅 action 取新值 ACTION_ONHAND_EXPORT)。
|
||||
|
||||
Returns:
|
||||
str | None: 触发文件绝对路径;目录未配置时返回 None。
|
||||
"""
|
||||
trigger_dir = onhand_trigger_dir()
|
||||
if not trigger_dir:
|
||||
return None
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
body = {
|
||||
"action": ACTION_ONHAND_EXPORT,
|
||||
"task_no": task_no,
|
||||
"run_no": f"LEGACY-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}",
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
**(payload or {}),
|
||||
}
|
||||
path = trigger_dir / f"inventory_export_{task_no}.json"
|
||||
_write_trigger_json_atomic(path, body)
|
||||
return str(path)
|
||||
|
||||
|
||||
# TODO(批次S): 全仓零调用,死代码候选,收敛时删除
|
||||
def find_latest_inventory_file() -> Path | None:
|
||||
"""在 drop 目录中查找最新修改的 xlsx/xls/csv 库存文件。"""
|
||||
drop = onhand_drop_dir()
|
||||
if not drop or not drop.is_dir():
|
||||
return None
|
||||
candidates = [
|
||||
p for p in drop.iterdir()
|
||||
if p.is_file() and p.suffix.lower() in {".xlsx", ".xls", ".csv"}
|
||||
]
|
||||
if not candidates:
|
||||
return None
|
||||
return max(candidates, key=lambda p: p.stat().st_mtime)
|
||||
@@ -0,0 +1,349 @@
|
||||
"""
|
||||
services/freight_rpa/onhand/workflow_protocol.py
|
||||
|
||||
用途:onhand(在手库存)RPA 回调协议态——attempt 行记账、run_no 幂等键、轮次校验、
|
||||
排程进度记账与超时窗口判定的纯协议层。
|
||||
依赖:app.models(ShippingTaskEvent / FreightRpaOnhandTaskAttempt / ScheduleRun)、
|
||||
app.extensions.db、freight_rpa.onhand 包内模块;**禁止 import 任何
|
||||
shipping_notice 业务模块**(import 边界由 tests/services/freight_rpa/test_import_boundary.py
|
||||
AST 全包扫描锁死,含函数内延迟 import)。
|
||||
逻辑:Task 9 拆分自 shipping_notice.onhand_rpa_workflow——回调进入
|
||||
/api/freight-rpa/* 蓝图后,业务 sink(shipping_notice.rpa_sinks 注册)在原事务内
|
||||
调用本模块完成协议记账(不改变 commit 时机),再由域内业务函数做快照落盘/
|
||||
门禁推进/审计投影;快照、Gate、状态机等业务终态一律留在 shipping_notice。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ScheduleRun, ShippingTaskEvent, FreightRpaOnhandTaskAttempt
|
||||
|
||||
|
||||
def latest_task_event(task: Any, event_type: str) -> ShippingTaskEvent | None:
|
||||
"""返回任务最近一条指定类型的 ShippingTaskEvent(RPA 超时/重试/轮次校验用)。"""
|
||||
if task.id is None:
|
||||
return None
|
||||
return (
|
||||
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type=event_type)
|
||||
.order_by(ShippingTaskEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def extract_run_no_from_trigger(trigger_path: str | None) -> str:
|
||||
"""从 trigger 文件路径或 JSON 内容提取 run_no(batch / legacy 单票均支持)。"""
|
||||
path = Path(str(trigger_path or ""))
|
||||
name = path.name
|
||||
prefix = "inventory_export_batch_"
|
||||
if name.startswith(prefix) and name.endswith(".json"):
|
||||
return name[len(prefix) : -len(".json")]
|
||||
if name.startswith("inventory_export_") and name.endswith(".json") and path.is_file():
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
if isinstance(payload, dict):
|
||||
run_no = str(payload.get("run_no") or "").strip()
|
||||
if run_no:
|
||||
return run_no
|
||||
except (OSError, json.JSONDecodeError, TypeError, ValueError):
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def is_legacy_trigger_run_no(run_no: str) -> bool:
|
||||
"""判断 run_no 是否来自 legacy 单任务 trigger(worker 可能不回传 run_no)。"""
|
||||
return str(run_no or "").strip().upper().startswith("LEGACY-")
|
||||
|
||||
|
||||
def expected_rpa_callback_run_no(task: Any) -> str:
|
||||
"""读取任务最近一次 RPA 触发记录的 run_no(事件 detail 优先,缺失回退 trigger 文件)。"""
|
||||
last_trigger = latest_task_event(task, "onhand_rpa_triggered")
|
||||
if not last_trigger:
|
||||
return ""
|
||||
detail = last_trigger.detail_json if isinstance(last_trigger.detail_json, dict) else {}
|
||||
run_no = str(detail.get("run_no") or "").strip()
|
||||
if run_no:
|
||||
return run_no
|
||||
return extract_run_no_from_trigger(str(detail.get("trigger") or ""))
|
||||
|
||||
|
||||
def validate_rpa_callback_run_no(task: Any, callback_run_no: str) -> str | None:
|
||||
"""校验回调 run_no 属于当前任务最近一次有效触发轮次。
|
||||
|
||||
Returns:
|
||||
None 校验通过;否则返回拒绝原因码(no_active_trigger / run_no_missing / run_no_mismatch)。
|
||||
"""
|
||||
provided = str(callback_run_no or "").strip()
|
||||
expected = expected_rpa_callback_run_no(task)
|
||||
if not expected:
|
||||
return "no_active_trigger"
|
||||
if not provided:
|
||||
if is_legacy_trigger_run_no(expected):
|
||||
return None
|
||||
return "run_no_missing"
|
||||
if provided != expected:
|
||||
return "run_no_mismatch"
|
||||
return None
|
||||
|
||||
|
||||
def resolve_effective_callback_run_no(task: Any, payload: dict[str, Any]) -> str:
|
||||
"""解析回调实际归属的 run_no(显式传入优先,否则回退当前触发轮次)。"""
|
||||
provided = str(payload.get("run_no") or "").strip()
|
||||
if provided:
|
||||
return provided
|
||||
return expected_rpa_callback_run_no(task)
|
||||
|
||||
|
||||
def get_consumed_inventory_rpa_run_no(task: Any) -> str:
|
||||
"""读取已消费(处理完成)的 RPA 轮次 run_no。"""
|
||||
attempt = (
|
||||
FreightRpaOnhandTaskAttempt.query
|
||||
.filter_by(task_no=str(task.task_no or ''), status='consumed')
|
||||
.order_by(FreightRpaOnhandTaskAttempt.consumed_at.desc(), FreightRpaOnhandTaskAttempt.id.desc())
|
||||
.first()
|
||||
)
|
||||
return str(getattr(attempt, 'source_run_no', '') or '').strip()
|
||||
|
||||
|
||||
def mark_inventory_rpa_run_no_consumed(task: Any, run_no: str) -> None:
|
||||
"""[协议记账] 标记当前 RPA 轮次已被回调消费,防止同一 run_no 重放重复入库。
|
||||
|
||||
核心逻辑:只改 Attempt 行(status/consumed_at),不 commit——commit 时机由调用方
|
||||
业务事务决定,与拆分前行为一致。
|
||||
"""
|
||||
effective = str(run_no or "").strip()
|
||||
if not effective:
|
||||
return
|
||||
attempt = (
|
||||
FreightRpaOnhandTaskAttempt.query
|
||||
.filter_by(task_no=str(task.task_no or ''), source_run_no=effective)
|
||||
.one_or_none()
|
||||
)
|
||||
if attempt is not None:
|
||||
attempt.status = 'consumed'
|
||||
attempt.consumed_at = datetime.utcnow()
|
||||
|
||||
|
||||
def validate_rpa_callback_not_replayed(task: Any, run_no: str) -> str | None:
|
||||
"""拒绝同一 run_no 的重复成功/失败/跳过回调。
|
||||
|
||||
Returns:
|
||||
None 允许处理;"run_no_already_consumed" 表示重放,应拒绝。
|
||||
"""
|
||||
effective = str(run_no or "").strip()
|
||||
consumed = get_consumed_inventory_rpa_run_no(task)
|
||||
if effective and consumed and effective == consumed:
|
||||
return "run_no_already_consumed"
|
||||
return None
|
||||
|
||||
|
||||
def validate_schedule_batch_callback_run_no(
|
||||
schedule_run_id: int | None,
|
||||
callback_run_no: str,
|
||||
*,
|
||||
require_awaiting: bool = True,
|
||||
) -> str | None:
|
||||
"""校验定时 batch 回调 run_no 与排程 run 记录一致,防止错绑终态。
|
||||
|
||||
Args:
|
||||
schedule_run_id: 排程 run 主键;None 表示非排程回调,直接通过。
|
||||
callback_run_no: Worker 上报的 batch_run_no / run_no。
|
||||
require_awaiting: True(进度/收件终态)要求仍处于 awaiting_rpa;
|
||||
False(解析 Job)只校验身份,允许排程已按「文件返回」终态化。
|
||||
|
||||
Returns:
|
||||
None 校验通过;否则返回拒绝原因码(schedule_run_not_found / schedule_run_no_missing /
|
||||
schedule_run_no_mismatch / schedule_run_not_awaiting)。
|
||||
"""
|
||||
if schedule_run_id is None:
|
||||
return None
|
||||
run = db.session.get(ScheduleRun, schedule_run_id)
|
||||
if not run:
|
||||
return "schedule_run_not_found"
|
||||
expected = str(run.run_no or "").strip()
|
||||
provided = str(callback_run_no or "").strip()
|
||||
if not expected:
|
||||
return "schedule_run_no_missing"
|
||||
if provided != expected:
|
||||
return "schedule_run_no_mismatch"
|
||||
if not require_awaiting:
|
||||
return None
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
if run.status != "running" or not summary.get("awaiting_rpa"):
|
||||
return "schedule_run_not_awaiting"
|
||||
return None
|
||||
|
||||
|
||||
def record_onhand_batch_progress(
|
||||
run: ScheduleRun,
|
||||
run_no: str,
|
||||
*,
|
||||
success_count: int,
|
||||
skipped_count: int,
|
||||
failed_count: int,
|
||||
) -> dict[str, Any]:
|
||||
"""[协议记账] 排程批量导出进度回写:max(现有, 上报) 防乱序回退,写后即 commit。
|
||||
|
||||
【AI 触发时机】:onhand-batch-progress 业务 sink 已完成 schema/run 校验后调用;
|
||||
非终态记账(不修改 status/started_at/finished_at,终态仍以 batch-ready 为准)。
|
||||
|
||||
Args:
|
||||
run: 已确认存在且处于 awaiting_rpa 的 ScheduleRun 行。
|
||||
run_no: 批次 run_no,写入 response_summary_json.progress 供审计。
|
||||
success_count / skipped_count / failed_count: 已按 max(0, int(x)) 归一的非负计数。
|
||||
|
||||
Returns:
|
||||
dict: 提交后的最终计数 {'success_count','skipped_count','failed_count','run_no'};
|
||||
供业务层拼装响应,键值与拆分前响应逐字一致。
|
||||
"""
|
||||
run.success_count = max(int(run.success_count or 0), success_count)
|
||||
run.skipped_count = max(int(run.skipped_count or 0), skipped_count)
|
||||
run.failed_count = max(int(run.failed_count or 0), failed_count)
|
||||
summary = dict(run.response_summary_json or {})
|
||||
summary['progress'] = {
|
||||
'success_count': int(run.success_count or 0),
|
||||
'skipped_count': int(run.skipped_count or 0),
|
||||
'failed_count': int(run.failed_count or 0),
|
||||
'batch_run_no': run_no,
|
||||
'updated_at': datetime.utcnow().isoformat(),
|
||||
}
|
||||
run.response_summary_json = summary
|
||||
# commit 时机与拆分前 onhand_rpa_workflow.report_inventory_batch_progress 完全一致:
|
||||
# 校验通过、计数写完后立即提交,再由业务层构造响应。
|
||||
db.session.commit()
|
||||
return {
|
||||
'run_no': run_no,
|
||||
'success_count': int(run.success_count or 0),
|
||||
'skipped_count': int(run.skipped_count or 0),
|
||||
'failed_count': int(run.failed_count or 0),
|
||||
}
|
||||
|
||||
|
||||
def compute_rpa_wait_window(
|
||||
triggered_at: datetime,
|
||||
timeout_seconds: int,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> tuple[int, int, int]:
|
||||
"""计算库存 RPA 等待窗口(elapsed / timeout / remaining 秒)。
|
||||
|
||||
【AI 触发时机】:业务层已确认任务处于 RPA 等待态、需要判断是否超时或调度复查时调用。
|
||||
|
||||
Args:
|
||||
triggered_at: 最近一次 onhand_rpa_triggered 事件的 created_at。
|
||||
timeout_seconds: 超时阈值秒数(由业务层 tool_common 读取配置)。
|
||||
now: 可注入当前时间(测试用);缺省 utcnow。
|
||||
|
||||
Returns:
|
||||
tuple[int, int, int]: (elapsed_seconds, timeout_seconds, remaining_seconds);
|
||||
elapsed 向下取整且不为负,remaining 不为负。
|
||||
"""
|
||||
current = now or datetime.utcnow()
|
||||
elapsed = max(int((current - triggered_at).total_seconds()), 0)
|
||||
remaining = max(int(timeout_seconds) - elapsed, 0)
|
||||
return elapsed, int(timeout_seconds), remaining
|
||||
|
||||
|
||||
def resolve_shared_inventory_drop_file(raw_path: str, *, allowed_root: Path) -> Path | None:
|
||||
"""将 Worker 回调中的 file_path 解析为 Linux 侧共享 drop 内的真实文件。
|
||||
|
||||
Windows Worker 上报 ``C:\\HxopsRpaTest\\data\\inventory_drop\\file.xlsx``,
|
||||
Ubuntu 后端通过 ``/mnt/hxops-rpa-*-data/inventory_drop/file.xlsx`` 读同一 SMB 文件。
|
||||
安全约束:仅允许 ``allowed_root`` 下按文件名映射,拒绝路径穿越。
|
||||
|
||||
Returns:
|
||||
Path | None: 解析成功且确为 allowed_root 下存在文件时返回绝对路径;否则 None。
|
||||
"""
|
||||
text = str(raw_path or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
root = allowed_root.resolve()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
candidate = Path(text)
|
||||
try:
|
||||
resolved = candidate.resolve()
|
||||
if resolved.is_file():
|
||||
resolved.relative_to(root)
|
||||
return resolved
|
||||
except (OSError, ValueError, RuntimeError):
|
||||
pass
|
||||
|
||||
name = Path(text.replace('\\', '/')).name.strip()
|
||||
if not name or name in {'.', '..'} or '/' in name or '\\' in name:
|
||||
return None
|
||||
mapped = (root / name).resolve()
|
||||
try:
|
||||
mapped.relative_to(root)
|
||||
except ValueError:
|
||||
return None
|
||||
if mapped.is_file():
|
||||
return mapped
|
||||
return None
|
||||
|
||||
|
||||
def normalize_inventory_result_status(payload: dict[str, Any]) -> str:
|
||||
"""归一化单任务 RPA 库存回调结果。
|
||||
|
||||
核心逻辑:优先读取 worker 上报的 status;兼容旧回调仅含 success/skipped 布尔字段;
|
||||
缺省 success 视为 true(历史单任务回调兼容)。
|
||||
|
||||
Returns:
|
||||
str: success | skipped | failed
|
||||
"""
|
||||
raw_status = str(payload.get("status") or "").strip().lower()
|
||||
if raw_status in {"success", "skipped", "failed"}:
|
||||
return raw_status
|
||||
if payload.get("skipped"):
|
||||
return "skipped"
|
||||
if bool(payload.get("success", True)):
|
||||
return "success"
|
||||
return "failed"
|
||||
|
||||
|
||||
def normalize_inventory_batch_item_status(item: dict[str, Any]) -> str:
|
||||
"""归一化 batch results 单条明细(比单任务更严格:缺字段不算 success)。
|
||||
|
||||
核心逻辑:与 worker `_normalize_inventory_batch_item_status` 对齐;空 dict 或
|
||||
缺 status/success/skipped 直接归为 failed,避免误走 success→file_missing 分支。
|
||||
|
||||
Returns:
|
||||
str: success | skipped | failed
|
||||
"""
|
||||
raw_status = str(item.get("status") or "").strip().lower()
|
||||
if raw_status in {"success", "skipped", "failed"}:
|
||||
return raw_status
|
||||
if item.get("skipped"):
|
||||
return "skipped"
|
||||
if item.get("success") is True:
|
||||
return "success"
|
||||
return "failed"
|
||||
|
||||
|
||||
def merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]:
|
||||
"""合并 batch 顶层契约字段到 result item。
|
||||
|
||||
核心逻辑:合并 batch 已认证的 schema_version / run_no / task_no;其余身份字段必须由
|
||||
Worker item 显式返回,禁止后端从任务或数据库补齐。
|
||||
|
||||
Returns:
|
||||
dict: 合并后的 item 副本(不修改入参)。
|
||||
"""
|
||||
merged = dict(item)
|
||||
top_schema_version = str(payload.get('schema_version') or '').strip()
|
||||
if top_schema_version and not str(merged.get('schema_version') or '').strip():
|
||||
merged['schema_version'] = top_schema_version
|
||||
top_run_no = str(payload.get("run_no") or "").strip()
|
||||
if top_run_no and not str(merged.get("run_no") or "").strip():
|
||||
merged["run_no"] = top_run_no
|
||||
|
||||
task_no = str(merged.get("task_no") or payload.get("task_no") or "").strip()
|
||||
if task_no and not str(merged.get("task_no") or "").strip():
|
||||
merged["task_no"] = task_no
|
||||
return merged
|
||||
@@ -0,0 +1 @@
|
||||
"""outbound:出站 RPA。"""
|
||||
@@ -0,0 +1,246 @@
|
||||
"""
|
||||
services/freight_rpa/outbound/report_archive.py
|
||||
|
||||
用途:outbound(出站)RPA 产物事实能力——Worker 回调的原样归档(xlsx 落 MinIO、
|
||||
三年保留期、不写库存快照表)。
|
||||
依赖:models(FreightRpaOutboundReportFile / FreightRpaOutboundUnitRun)、
|
||||
file_assets.storage、freight_rpa.outbound.trigger_io(回调 SCHEMA 与 drop 根)、
|
||||
freight_rpa.common.report_audit(本域唯一审计写入口)、
|
||||
freight_rpa.reports.facts / reports.dispatch(ReportFact 事实投递)。
|
||||
逻辑:Worker 回调进入 /api/freight-rpa/outbound-batch-ready 后由组合根(Task 10)
|
||||
或测内临时 register 的 sink 调 ingest_outbound_callback 完成原样归档;
|
||||
empty/success/failed 三个终态分支各自「先 db.session.commit() 再投递事实」——
|
||||
commit 后构造 ReportFact(report_kind='outbound', ...) 调 dispatch_report_fact;
|
||||
处理函数异常原样外抛(不吞、不回滚已提交终态);同一 unit_run_id + sha256
|
||||
已有文件时不插第二行、仍投递 ok=True 的事实供处理函数重试。
|
||||
跨机路径:file_path 只认 outbound drop 根内文件名,禁止把 Worker Windows
|
||||
绝对路径当 Linux 路径打开(对照 inbound._read_inbound_callback_file)。
|
||||
本模块不 import shipping_notice / in_transit_transfer,不移植入站逐文件企微投递。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
)
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.freight_rpa.common.report_audit import append_rpa_report_event
|
||||
from app.services.freight_rpa.outbound.trigger_io import SCHEMA as OUTBOUND_TRIGGER_SCHEMA, outbound_drop_dir
|
||||
from app.services.freight_rpa.reports.dispatch import dispatch_report_fact
|
||||
from app.services.freight_rpa.reports.facts import ReportFact
|
||||
|
||||
|
||||
def _read_outbound_callback_file(file_path: str) -> bytes:
|
||||
"""只读取 outbound 专用 drop 根内的 xlsx,拒绝 callback 任意本机文件读取。
|
||||
|
||||
路径契约为「drop 根内文件名」:Worker(Windows RPA 主机)与后端(Linux 容器)分属
|
||||
两机,各自看到的根路径不同(C:\\HxopsRpaTest\\... vs /mnt/hxops-rpa-*-data/...)。
|
||||
一律 replace('\\','/') 后取 .name,再拼本机 FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR,
|
||||
relative_to(root) 防穿越。禁止把回调串当 Linux 路径直接 open。
|
||||
"""
|
||||
configured_root = str(outbound_drop_dir() or "").strip()
|
||||
if not configured_root:
|
||||
raise ValidationError(
|
||||
"outbound callback file root is unavailable",
|
||||
code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID",
|
||||
)
|
||||
root = Path(configured_root).resolve()
|
||||
# [STEP] 跨机:先归一分隔符再取末段文件名,绝不 Path(file_path).read_bytes()。
|
||||
name = Path(str(file_path).replace("\\", "/")).name
|
||||
path = (root / name).resolve()
|
||||
try:
|
||||
path.relative_to(root)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(
|
||||
"outbound callback file is outside outbound drop root",
|
||||
code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID",
|
||||
) from exc
|
||||
if path.suffix.lower() != ".xlsx" or not path.is_file():
|
||||
raise ValidationError(
|
||||
"outbound callback file must be an existing xlsx",
|
||||
code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID",
|
||||
)
|
||||
max_size = max(int(current_app.config.get("FILE_ASSET_MAX_SIZE_MB", 30) or 30), 1) * 1024 * 1024
|
||||
if path.stat().st_size > max_size:
|
||||
raise ValidationError(
|
||||
"outbound callback file exceeds configured size limit",
|
||||
code="SHIPPING.OUTBOUND_CALLBACK_FILE_INVALID",
|
||||
)
|
||||
return path.read_bytes()
|
||||
|
||||
|
||||
def ingest_outbound_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""幂等接收单个 outbound 单元回调,原样归档三年且不写库存快照表。
|
||||
|
||||
Args:
|
||||
payload: Worker 回调载荷(schema_version/callback_id/status/file_path/...)。
|
||||
Returns:
|
||||
dict: unit_run_id/status[/file_id/idempotent],供 HTTP envelope 的 data 使用。
|
||||
(brief 曾写 -> None;与入站 API envelope 对齐仍返回 dict。)
|
||||
Raises:
|
||||
ValidationError: 载荷非法(schema/callback_id/sha256/文件路径)——commit 之前抛出,不投递事实。
|
||||
NotFoundError: callback_id 无匹配单元——commit 之前抛出,不投递事实。
|
||||
AppError: 终态已 commit 后 kind 未注册处理函数(FREIGHT_RPA.SINK_NOT_REGISTERED, 404)。
|
||||
业务顺序:每个终态分支先 db.session.commit() 再构造
|
||||
ReportFact(report_kind='outbound', source_code=unit.source_code, ...) 调
|
||||
dispatch_report_fact;事实恒带 unit_run_id=unit.id;处理函数异常原样外抛;
|
||||
同一 unit_run_id + sha256 已有文件时不插第二行,仍投递 ok=True 的事实。
|
||||
"""
|
||||
if payload.get("schema_version") != OUTBOUND_TRIGGER_SCHEMA:
|
||||
raise ValidationError(
|
||||
"outbound callback schema_version is invalid",
|
||||
code="SHIPPING.OUTBOUND_CALLBACK_INVALID",
|
||||
)
|
||||
callback_id = str(payload.get("callback_id") or "").strip()
|
||||
unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
|
||||
if unit is None:
|
||||
raise NotFoundError("Outbound RPA unit not found", code="SHIPPING.OUTBOUND_UNIT_NOT_FOUND")
|
||||
status = str(payload.get("status") or "").strip().lower()
|
||||
before = {"status": unit.status, "error_code": unit.error_code, "error_message": unit.error_message}
|
||||
if status in {"empty", "no_data"}:
|
||||
# [STEP] 与入站 empty / 库存 no_inventory_data 对齐:empty 是合法业务结果。
|
||||
unit.status = "empty"
|
||||
unit.error_code = str(payload.get("error_code") or "no_outbound_data")[:64]
|
||||
unit.error_message = str(payload.get("error_message") or "no_outbound_data")[:2000]
|
||||
unit.finished_at = datetime.utcnow()
|
||||
append_rpa_report_event(
|
||||
event_type="shipping_outbound_rpa_callback_received",
|
||||
aggregate_type="shipping_outbound_unit",
|
||||
aggregate_id=str(unit.id),
|
||||
run_no=unit.schedule_run.run_no if unit.schedule_run else None,
|
||||
actor_type="rpa",
|
||||
actor_id="outbound-worker",
|
||||
unit_id=unit.id,
|
||||
result="success",
|
||||
before=before,
|
||||
after={
|
||||
"status": "empty",
|
||||
"callback_id": unit.callback_id,
|
||||
"error_code": unit.error_code,
|
||||
"error_message": unit.error_message,
|
||||
},
|
||||
metadata={"callback_status": status, "skip_reason": unit.error_code},
|
||||
)
|
||||
db.session.commit()
|
||||
dispatch_report_fact(ReportFact(
|
||||
report_kind="outbound",
|
||||
source_code=unit.source_code,
|
||||
file_id=None,
|
||||
sha256=None,
|
||||
ok=False,
|
||||
error_code=unit.error_code or "no_outbound_data",
|
||||
error_message=unit.error_message or "no_outbound_data",
|
||||
unit_run_id=unit.id,
|
||||
))
|
||||
return {"unit_run_id": unit.id, "status": "empty"}
|
||||
if status != "success":
|
||||
unit.status = "failed"
|
||||
unit.error_code = str(payload.get("error_code") or "RPA.OUTBOUND_EXPORT_FAILED")[:64]
|
||||
unit.error_message = str(payload.get("error_message") or "outbound export failed")[:2000]
|
||||
unit.finished_at = datetime.utcnow()
|
||||
append_rpa_report_event(
|
||||
event_type="shipping_outbound_rpa_callback_received",
|
||||
aggregate_type="shipping_outbound_unit",
|
||||
aggregate_id=str(unit.id),
|
||||
run_no=unit.schedule_run.run_no if unit.schedule_run else None,
|
||||
actor_type="rpa",
|
||||
actor_id="outbound-worker",
|
||||
unit_id=unit.id,
|
||||
result="failure",
|
||||
before=before,
|
||||
after={"status": "failed", "error_code": unit.error_code, "error_message": unit.error_message},
|
||||
metadata={"callback_status": status},
|
||||
)
|
||||
db.session.commit()
|
||||
dispatch_report_fact(ReportFact(
|
||||
report_kind="outbound",
|
||||
source_code=unit.source_code,
|
||||
file_id=None,
|
||||
sha256=None,
|
||||
ok=False,
|
||||
error_code=unit.error_code,
|
||||
error_message=unit.error_message,
|
||||
unit_run_id=unit.id,
|
||||
))
|
||||
return {"unit_run_id": unit.id, "status": "failed"}
|
||||
data = _read_outbound_callback_file(str(payload.get("file_path") or ""))
|
||||
sha256 = hashlib.sha256(data).hexdigest()
|
||||
claimed = str(payload.get("sha256") or "").lower()
|
||||
if claimed and claimed != sha256:
|
||||
raise ValidationError(
|
||||
"outbound callback sha256 mismatch",
|
||||
code="SHIPPING.OUTBOUND_CALLBACK_SHA_MISMATCH",
|
||||
)
|
||||
existing = FreightRpaOutboundReportFile.query.filter_by(unit_run_id=unit.id, sha256=sha256).one_or_none()
|
||||
if existing:
|
||||
dispatch_report_fact(ReportFact(
|
||||
report_kind="outbound",
|
||||
source_code=unit.source_code,
|
||||
file_id=existing.id,
|
||||
sha256=sha256,
|
||||
ok=True,
|
||||
unit_run_id=unit.id,
|
||||
))
|
||||
return {"unit_run_id": unit.id, "status": unit.status, "file_id": existing.id, "idempotent": True}
|
||||
filename = Path(str(payload.get("original_filename") or payload.get("file_path") or "outbound.xlsx")).name
|
||||
storage_key = f"shipping/outbound-reports/{datetime.utcnow():%Y/%m}/{unit.id}/{sha256}.xlsx"
|
||||
file_asset_storage.upload_bytes(
|
||||
storage_key=storage_key,
|
||||
data=data,
|
||||
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
record = FreightRpaOutboundReportFile(
|
||||
unit_run_id=unit.id,
|
||||
storage_provider="minio",
|
||||
storage_bucket=file_asset_storage.bucket_name,
|
||||
storage_key=storage_key,
|
||||
original_filename=filename,
|
||||
content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
file_size=len(data),
|
||||
sha256=sha256,
|
||||
archive_expires_at=datetime.utcnow() + timedelta(days=365 * 3),
|
||||
)
|
||||
db.session.add(record)
|
||||
unit.status = "success"
|
||||
unit.finished_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
append_rpa_report_event(
|
||||
event_type="shipping_outbound_report_archived",
|
||||
aggregate_type="shipping_outbound_unit",
|
||||
aggregate_id=str(unit.id),
|
||||
run_no=unit.schedule_run.run_no if unit.schedule_run else None,
|
||||
actor_type="rpa",
|
||||
actor_id="outbound-worker",
|
||||
unit_id=unit.id,
|
||||
result="success",
|
||||
before=before,
|
||||
after={
|
||||
"status": "success",
|
||||
"source_run_no": unit.callback_id,
|
||||
"file_id": record.id,
|
||||
"sha256": sha256,
|
||||
"file_size": len(data),
|
||||
},
|
||||
artifact_refs=[{"kind": "outbound_report", "id": str(record.id), "sha256": sha256}],
|
||||
metadata={"file_size": len(data), "retention_days": 365 * 3},
|
||||
)
|
||||
db.session.commit()
|
||||
dispatch_report_fact(ReportFact(
|
||||
report_kind="outbound",
|
||||
source_code=unit.source_code,
|
||||
file_id=record.id,
|
||||
sha256=sha256,
|
||||
ok=True,
|
||||
unit_run_id=unit.id,
|
||||
))
|
||||
return {"unit_run_id": unit.id, "status": "success", "file_id": record.id, "idempotent": False}
|
||||
@@ -0,0 +1,92 @@
|
||||
"""
|
||||
services/freight_rpa/outbound/trigger_io.py
|
||||
|
||||
用途:outbound(出站)RPA 的纯文件 IO——trigger/落盘目录解析、批量 trigger JSON
|
||||
原子写入,以及 Worker 触发/回调契约常量(SCHEMA/ACTION_*)。
|
||||
依赖:Flask current_app 配置、Path/JSON/文件系统工具;不 import 任何业务编排模块
|
||||
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
|
||||
逻辑:由 schedule.freight_rpa_outbound_job(排程写 trigger)、api.schedule.runs(admin 单元重试)、
|
||||
in_transit_transfer.outbound_trigger_service(调拨按需/批量触发)、
|
||||
freight_rpa.common.worker_heartbeat(outbound trigger 目录探测/就绪检查)、
|
||||
freight_rpa.outbound.report_archive(drop 目录定位与回调 SCHEMA 校验,后续任务)等调用,
|
||||
与外部 RPA Worker 的文件投递目录交互;schema/action 以本文件常量为单一真相
|
||||
(Worker 侧对表:freight_rpa.outbound.v1 / outbound_export_batch)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
# Worker 触发/回调契约常量:后端写入侧与校验侧共用单一真相,禁止再写字面量。
|
||||
SCHEMA = "freight_rpa.outbound.v1"
|
||||
ACTION_OUTBOUND_EXPORT_BATCH = "outbound_export_batch"
|
||||
|
||||
|
||||
def _path(key: str) -> Path | None:
|
||||
value = str(current_app.config.get(key) or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
return Path(value)
|
||||
|
||||
|
||||
def outbound_trigger_dir() -> Path | None:
|
||||
"""RPA outbound 批量导出触发 JSON 目录(FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR);
|
||||
绝不回落到 onhand/inbound trigger 目录。"""
|
||||
return _path("FREIGHT_RPA_SHARED_OUTBOUND_TRIGGER_DIR")
|
||||
|
||||
|
||||
def outbound_drop_dir() -> Path | None:
|
||||
"""RPA outbound 导出文件落盘目录(FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR)。"""
|
||||
return _path("FREIGHT_RPA_SHARED_OUTBOUND_DROP_DIR")
|
||||
|
||||
|
||||
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
|
||||
"""原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。"""
|
||||
temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
|
||||
try:
|
||||
with open(temp_path, 'w', encoding='utf-8') as handle:
|
||||
json.dump(body, handle, ensure_ascii=False, indent=2)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temp_path, path)
|
||||
finally:
|
||||
if temp_path.exists():
|
||||
temp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def write_outbound_export_batch_trigger(
|
||||
run_no: str,
|
||||
units: list[dict[str, Any]],
|
||||
meta: dict[str, Any] | None = None,
|
||||
) -> str | None:
|
||||
"""
|
||||
写入 outbound 批量 trigger 文件 outbound_export_batch_{run_no}.json
|
||||
(Worker 轮询 <root>/*.json 按内容消费,schema/action 取本文件常量)。
|
||||
|
||||
Args:
|
||||
run_no: 批次运行号;进 body.batch_run_no 并参与文件名(安全化仅保留字母数字-_)。
|
||||
units: 触发单元载荷列表;业务约束——空列表直接返回 None(无单元不落盘)。
|
||||
meta: 调用方附加字段,合并覆盖 body 顶层键(schema_version/action 缺省取常量)。
|
||||
|
||||
Returns:
|
||||
str | None: 触发文件绝对路径;目录未配置或 units 为空时返回 None。
|
||||
"""
|
||||
trigger_dir = outbound_trigger_dir()
|
||||
if not trigger_dir or not units:
|
||||
return None
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
safe_run_no = ''.join(char for char in run_no if char.isalnum() or char in {'-', '_'}) or 'outbound'
|
||||
body = {
|
||||
'schema_version': SCHEMA, 'action': ACTION_OUTBOUND_EXPORT_BATCH,
|
||||
'batch_run_no': run_no, 'requested_at': datetime.utcnow().isoformat(), 'units': units,
|
||||
**(meta or {}),
|
||||
}
|
||||
path = trigger_dir / f'outbound_export_batch_{safe_run_no}.json'
|
||||
_write_trigger_json_atomic(path, body)
|
||||
return str(path)
|
||||
+90
-73
@@ -1,9 +1,16 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/inventory_parsing_profile.py
|
||||
services/freight_rpa/parsing_profile.py
|
||||
|
||||
用途:管理可跨库存源复用的版本化库存解析 Profile,并为运行期提供确定性解析定义。
|
||||
依赖:ShippingInventoryParsingProfile、ShippingInventorySource、ShippingOrderField、inventory_mapping。
|
||||
逻辑:管理员保存草稿并发布不可变版本;库存源仅绑定 published Profile,解析链直接使用定义中的列映射与订单字段匹配键。
|
||||
用途:管理货代「报表规则」(FreightRpaParsingProfile)的草稿/发布与运行期定义读取。
|
||||
purpose=onhand 走库存字段目录 + match_keys;purpose=inbound/outbound 走调拨
|
||||
MOVEMENT_FIELDS 契约(与在途异动对齐)。
|
||||
依赖:FreightRpaParsingProfile、FreightRpaOnhandReportConfig、FreightRpaInboundReportConfig、
|
||||
FreightRpaOutboundReportConfig、ShippingOrderField、
|
||||
in_transit_transfer.movement_contract.MOVEMENT_FIELDS、
|
||||
shipping_notice.order_schema(仅 onhand 发布时校验订单字段)。
|
||||
逻辑:管理员保存草稿并发布不可变版本;来源站点 / 入站·出站报表配置只绑定 published
|
||||
Profile;退役前检查 onhand/inbound/outbound 配置引用。管理端入口
|
||||
/api/admin/freight-rpa/.../parsing-profiles。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,47 +25,49 @@ from sqlalchemy import func
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventorySource,
|
||||
ShippingInventoryStructureAnalysis,
|
||||
FreightRpaOnhandField,
|
||||
FreightRpaOnhandReportConfig,
|
||||
FreightRpaParsingProfile,
|
||||
FreightRpaOnhandStructureAnalysis,
|
||||
ShippingOrderField,
|
||||
FreightRpaInboundReportConfig,
|
||||
FreightRpaOutboundReportConfig,
|
||||
)
|
||||
|
||||
|
||||
def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]:
|
||||
def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, FreightRpaOnhandField]:
|
||||
"""解析字段目录 ID 并确认均为可用于新方案的启用库存业务字段。"""
|
||||
field_ids: list[int] = []
|
||||
for raw_id in field_mapping:
|
||||
try:
|
||||
field_id = int(raw_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') from exc
|
||||
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID') from exc
|
||||
if field_id <= 0:
|
||||
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
field_ids.append(field_id)
|
||||
rows = ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(set(field_ids))).all() if field_ids else []
|
||||
rows = FreightRpaOnhandField.query.filter(FreightRpaOnhandField.id.in_(set(field_ids))).all() if field_ids else []
|
||||
fields = {str(row.id): row for row in rows if row.status == 'active'}
|
||||
if len(fields) != len(set(str(item) for item in field_ids)):
|
||||
raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
return fields
|
||||
|
||||
|
||||
def _required_catalog_field_ids(fields: dict[str, ShippingInventoryField]) -> set[str]:
|
||||
def _required_catalog_field_ids(fields: dict[str, FreightRpaOnhandField]) -> set[str]:
|
||||
"""校验解析方案具备匹配与库存数量能力,不限定字段名称。"""
|
||||
match_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'match_identity'}
|
||||
quantity_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'inventory_quantity'}
|
||||
if not match_ids or len(quantity_ids) != 1:
|
||||
raise ValidationError(
|
||||
'Parsing profile requires at least one match field and exactly one inventory quantity field',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
return match_ids | quantity_ids
|
||||
|
||||
|
||||
# 异动(movement)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。
|
||||
# 入站(inbound)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。
|
||||
def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]:
|
||||
"""校验 movement 用途的解析定义只引用定死领域字段,且必需字段齐全。"""
|
||||
"""校验 inbound/outbound 用途的解析定义只引用定死领域字段,且必需字段齐全。"""
|
||||
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
|
||||
|
||||
movement_codes = {field.code for field in MOVEMENT_FIELDS}
|
||||
@@ -68,37 +77,37 @@ def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]:
|
||||
if unknown:
|
||||
raise ValidationError(
|
||||
f'Movement parsing profile references unknown field: {sorted(unknown)}',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
missing = {code for code in ('doc_no', 'material_code', 'quantity', 'movement_date') if code not in mapped_codes}
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
f'Movement parsing profile requires doc_no/material_code/quantity/movement_date: {sorted(missing)}',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
return mapped_codes
|
||||
|
||||
|
||||
def _validate_definition(raw: Any, *, purpose: str = 'inventory') -> dict[str, Any]:
|
||||
def _validate_definition(raw: Any, *, purpose: str = 'onhand') -> dict[str, Any]:
|
||||
"""校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。
|
||||
|
||||
Args:
|
||||
raw: 解析定义对象。
|
||||
purpose: 'inventory'(沿用库存字段目录与 match_keys)或
|
||||
'movement'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。
|
||||
purpose: 'onhand'(库存字段目录 + match_keys)或
|
||||
'inbound'/'outbound'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。
|
||||
"""
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
field_mapping = raw.get('field_mapping')
|
||||
if not isinstance(field_mapping, dict) or not field_mapping:
|
||||
raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
if any(not str(value or '').strip() for value in field_mapping.values()):
|
||||
raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
header_row_index = raw.get('header_row_index')
|
||||
if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1):
|
||||
raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('header_row_index is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
|
||||
if purpose == 'movement':
|
||||
if purpose in {'inbound', 'outbound'}:
|
||||
_required_movement_field_ids(raw)
|
||||
return {
|
||||
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
|
||||
@@ -111,7 +120,7 @@ def _validate_definition(raw: Any, *, purpose: str = 'inventory') -> dict[str, A
|
||||
_required_catalog_field_ids(catalog_fields)
|
||||
match_keys = raw.get('match_keys')
|
||||
if not isinstance(match_keys, list) or not match_keys:
|
||||
raise ValidationError('Parsing profile requires match keys', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile requires match keys', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
normalized_keys: list[dict[str, str]] = []
|
||||
seen_order_fields: set[str] = set()
|
||||
seen_inventory_fields: set[str] = set()
|
||||
@@ -123,9 +132,9 @@ def _validate_definition(raw: Any, *, purpose: str = 'inventory') -> dict[str, A
|
||||
field is None or field.status != 'active' or field.scope != 'line'
|
||||
or inventory is None or inventory.usage_type != 'match_identity'
|
||||
):
|
||||
raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
if field.id in seen_order_fields or inventory_field in seen_inventory_fields:
|
||||
raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
seen_order_fields.add(field.id)
|
||||
seen_inventory_fields.add(inventory_field)
|
||||
normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': inventory_field})
|
||||
@@ -142,20 +151,20 @@ def _require_sample_evidence(
|
||||
definition: dict[str, Any],
|
||||
*,
|
||||
file_format: str,
|
||||
) -> ShippingInventoryStructureAnalysis:
|
||||
) -> FreightRpaOnhandStructureAnalysis:
|
||||
"""校验草稿仅能使用已持久化样本证据中的工作表、表头和来源栏位。"""
|
||||
try:
|
||||
analysis_id = int(sample_analysis_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Parsing profile requires sample analysis evidence',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED',
|
||||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED',
|
||||
) from exc
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
|
||||
analysis = db.session.get(FreightRpaOnhandStructureAnalysis, analysis_id)
|
||||
if analysis is None or analysis.analysis_status != 'ready' or analysis.file_format != file_format:
|
||||
raise ValidationError(
|
||||
'Parsing profile sample analysis evidence is unavailable',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED',
|
||||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_REQUIRED',
|
||||
)
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
|
||||
@@ -165,13 +174,13 @@ def _require_sample_evidence(
|
||||
if not isinstance(selected, dict):
|
||||
raise ValidationError(
|
||||
'Parsing profile worksheet or header row is not present in sample evidence',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
|
||||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
|
||||
)
|
||||
headers = {str(header).strip() for header in selected.get('headers', []) if str(header).strip()}
|
||||
if any(str(header or '').strip() not in headers for header in (definition.get('field_mapping') or {}).values()):
|
||||
raise ValidationError(
|
||||
'Parsing profile mapping is not present in sample evidence',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
|
||||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
|
||||
)
|
||||
duplicates = {
|
||||
str(column.get('header') or '').strip()
|
||||
@@ -180,12 +189,12 @@ def _require_sample_evidence(
|
||||
if any(str(header).strip() in duplicates for header in (definition.get('field_mapping') or {}).values()):
|
||||
raise ValidationError(
|
||||
'Parsing profile mapping uses duplicate sample headers',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
|
||||
code='SHIPPING.ONHAND_SAMPLE_EVIDENCE_INVALID',
|
||||
)
|
||||
return analysis
|
||||
|
||||
|
||||
def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
|
||||
def payload(profile: FreightRpaParsingProfile) -> dict[str, Any]:
|
||||
"""序列化解析 Profile 管理 DTO。"""
|
||||
sample_analysis = profile.sample_analysis
|
||||
return {
|
||||
@@ -211,49 +220,49 @@ def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
|
||||
|
||||
def list_profiles() -> list[dict[str, Any]]:
|
||||
"""列出全部解析 Profile 版本。"""
|
||||
return [payload(item) for item in ShippingInventoryParsingProfile.query.order_by(
|
||||
ShippingInventoryParsingProfile.profile_code, ShippingInventoryParsingProfile.version.desc(),
|
||||
return [payload(item) for item in FreightRpaParsingProfile.query.order_by(
|
||||
FreightRpaParsingProfile.profile_code, FreightRpaParsingProfile.version.desc(),
|
||||
).all()]
|
||||
|
||||
|
||||
def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建或更新解析 Profile 草稿;必须绑定样本证据,published 版本不可原地修改。"""
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id) if profile_id else None
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id) if profile_id else None
|
||||
if profile_id and profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile is not None and profile.status != 'draft':
|
||||
raise ConflictError('Published parsing profile is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
|
||||
raise ConflictError('Published parsing profile is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
|
||||
code = str(data.get('profile_code') or '').strip().upper()
|
||||
if not code:
|
||||
raise ValidationError('profile_code is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('profile_code is required', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
if profile is not None and code != profile.profile_code:
|
||||
raise ConflictError('Draft profile_code is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
|
||||
raise ConflictError('Draft profile_code is immutable', code='SHIPPING.ONHAND_PARSING_PROFILE_IMMUTABLE')
|
||||
if profile is None:
|
||||
next_version = int(db.session.query(func.max(ShippingInventoryParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
|
||||
profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
|
||||
next_version = int(db.session.query(func.max(FreightRpaParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
|
||||
profile = FreightRpaParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
|
||||
db.session.add(profile)
|
||||
purpose = str(data.get('purpose') or profile.purpose or 'inventory').strip().lower()
|
||||
if purpose not in {'inventory', 'movement'}:
|
||||
raise ValidationError('purpose is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
purpose = str(data.get('purpose') or profile.purpose or 'onhand').strip().lower()
|
||||
if purpose not in {'onhand', 'inbound', 'outbound'}:
|
||||
raise ValidationError('purpose is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
if profile_id and purpose != profile.purpose:
|
||||
raise ValidationError(
|
||||
'Draft parsing profile purpose is immutable',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
profile.purpose = purpose
|
||||
profile.display_name = str(data.get('display_name') or code).strip()
|
||||
requested_file_format = str(data.get('file_format') or 'xlsx').lower()
|
||||
if requested_file_format not in {'xls', 'xlsx', 'csv'}:
|
||||
raise ValidationError('file_format is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('file_format is invalid', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
if profile_id and requested_file_format != profile.file_format:
|
||||
raise ValidationError(
|
||||
'Draft parsing profile file format is immutable',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
profile.file_format = requested_file_format
|
||||
definition = _validate_definition(data.get('definition'), purpose=purpose)
|
||||
if profile.file_format == 'csv' and definition.get('sheet_name'):
|
||||
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.ONHAND_PARSING_PROFILE_INVALID')
|
||||
sample_analysis = _require_sample_evidence(
|
||||
data.get('sample_analysis_id', profile.sample_analysis_id), definition, file_format=profile.file_format,
|
||||
)
|
||||
@@ -261,7 +270,7 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int |
|
||||
if not bool(data.get('confirm_sample_replacement')):
|
||||
raise ValidationError(
|
||||
'Replacing inventory sample evidence requires confirmation',
|
||||
code='SHIPPING.INVENTORY_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED',
|
||||
code='SHIPPING.ONHAND_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED',
|
||||
)
|
||||
history = list(profile.sample_evidence_history_json or [])
|
||||
history.append({
|
||||
@@ -279,23 +288,23 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int |
|
||||
|
||||
def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""发布解析 Profile;既有 published 版本继续供已绑定库存源稳定使用。"""
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'draft':
|
||||
raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID')
|
||||
raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID')
|
||||
_require_sample_evidence(
|
||||
profile.sample_analysis_id, profile.definition_json or {}, file_format=profile.file_format,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
# movement 用途无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;inventory 维持原约束。
|
||||
# inbound/outbound 无订单匹配键(端点为定死异动字段),跳过订单 Schema 契约校验;onhand 维持原约束。
|
||||
referenced_field_ids = {
|
||||
str(item.get('order_field_id') or '')
|
||||
for item in (profile.definition_json or {}).get('match_keys', [])
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
if profile.purpose != 'movement':
|
||||
if profile.purpose == 'onhand':
|
||||
published_field_ids = {
|
||||
str(item.get('field_id') or '')
|
||||
for item in order_schema_service.get_published_contract().get('fields', [])
|
||||
@@ -303,7 +312,7 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
if not referenced_field_ids or not referenced_field_ids <= published_field_ids:
|
||||
raise ValidationError(
|
||||
'Parsing profile match keys must reference the current published order schema',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID',
|
||||
code='SHIPPING.ONHAND_PARSING_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
encoded = json.dumps(profile.definition_json, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
profile.checksum = hashlib.sha256(encoded).hexdigest()
|
||||
@@ -315,14 +324,20 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
|
||||
|
||||
def retire(profile_id: int) -> dict[str, Any]:
|
||||
"""退役无库存源引用的 published Profile,避免使现有 Source 静默失效。"""
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
"""退役无库存源/入站/出站报表配置引用的 published Profile,避免使现有绑定静默失效。"""
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'published':
|
||||
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_INVALID')
|
||||
if ShippingInventorySource.query.filter_by(parsing_profile_id=profile.id).count():
|
||||
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED')
|
||||
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_INVALID')
|
||||
# s18 起库存站点绑定归 FreightRpaOnhandReportConfig 配置行,站点行不再承载该外键。
|
||||
bound_sources = FreightRpaOnhandReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
|
||||
# 入站/出站报表配置同样绑定解析 Profile:退役前必须一并核查,
|
||||
# 否则入站/出站文件解析链会静默失去规则。
|
||||
bound_inbound_configs = FreightRpaInboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
|
||||
bound_outbound_configs = FreightRpaOutboundReportConfig.query.filter_by(parsing_profile_id=profile.id).count()
|
||||
if bound_sources or bound_inbound_configs or bound_outbound_configs:
|
||||
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.ONHAND_PARSING_PROFILE_RETIRE_BLOCKED')
|
||||
profile.status = 'retired'
|
||||
db.session.commit()
|
||||
return payload(profile)
|
||||
@@ -330,18 +345,20 @@ def retire(profile_id: int) -> dict[str, Any]:
|
||||
|
||||
def delete_draft(profile_id: int) -> None:
|
||||
"""删除从未发布的解析 Profile 草稿。"""
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
profile = db.session.get(FreightRpaParsingProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.ONHAND_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'draft':
|
||||
raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.INVENTORY_PARSING_PROFILE_DELETE_BLOCKED')
|
||||
raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.ONHAND_PARSING_PROFILE_DELETE_BLOCKED')
|
||||
db.session.delete(profile)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def require_source_profile(source: Any) -> ShippingInventoryParsingProfile:
|
||||
def require_source_profile(source: Any) -> FreightRpaParsingProfile:
|
||||
"""读取库存源绑定的 published 解析 Profile;缺失或非发布状态时阻断自动解析。"""
|
||||
profile = getattr(source, 'parsing_profile', None)
|
||||
# s18 起解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系。
|
||||
config = getattr(source, 'onhand_report_config', None)
|
||||
profile = config.parsing_profile if config is not None else None
|
||||
if profile is None or profile.status != 'published':
|
||||
raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.ONHAND_PARSING_PROFILE_REQUIRED')
|
||||
return profile
|
||||
@@ -0,0 +1,51 @@
|
||||
"""freight_rpa/reports/__init__.py
|
||||
|
||||
用途:报表读域——发货(shipping_notice 域)与在途调拨
|
||||
(in_transit_transfer 域)读取货代 RPA 报表事实的唯一入口包(含出站配置视图)。
|
||||
依赖:facts(报表事实与 report kind 白名单)、queries(只读查询与解析失败标记)。
|
||||
逻辑:仅做门面转发;调用方(后续 in_transit_transfer / shipping_notice)
|
||||
一律 import 本包,禁止绕过直接引用 freight_rpa 模型表。
|
||||
本包不得 import app.services.shipping_notice 或 app.services.in_transit_transfer
|
||||
(import 边界由 tests/services/freight_rpa/test_report_queries.py 与
|
||||
test_import_boundary.py 锁定)。
|
||||
"""
|
||||
|
||||
from app.services.freight_rpa.reports.facts import REPORT_KINDS, ReportFact, require_report_kind
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
InboundConfigView,
|
||||
InboundFileView,
|
||||
OnhandConfigView,
|
||||
OutboundConfigView,
|
||||
SiteView,
|
||||
clear_inbound_parse_failure,
|
||||
get_inbound_config,
|
||||
get_onhand_config,
|
||||
get_outbound_config,
|
||||
get_site,
|
||||
latest_usable_inbound_file,
|
||||
list_outbound_configured_source_codes,
|
||||
mark_inbound_parse_failure,
|
||||
read_inbound_file_bytes,
|
||||
usable_inbound_file_condition,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'REPORT_KINDS',
|
||||
'InboundConfigView',
|
||||
'InboundFileView',
|
||||
'OnhandConfigView',
|
||||
'OutboundConfigView',
|
||||
'ReportFact',
|
||||
'SiteView',
|
||||
'clear_inbound_parse_failure',
|
||||
'get_inbound_config',
|
||||
'get_onhand_config',
|
||||
'get_outbound_config',
|
||||
'get_site',
|
||||
'latest_usable_inbound_file',
|
||||
'list_outbound_configured_source_codes',
|
||||
'mark_inbound_parse_failure',
|
||||
'read_inbound_file_bytes',
|
||||
'require_report_kind',
|
||||
'usable_inbound_file_condition',
|
||||
]
|
||||
@@ -0,0 +1,79 @@
|
||||
"""freight_rpa/reports/dispatch.py
|
||||
|
||||
用途:报表事实(ReportFact)处理函数注册表与分发缝——RPA 回调「先 commit
|
||||
终态、再投递事实」的第二段分发(批次 B Task 6)。
|
||||
依赖:app.core.errors.AppError、freight_rpa.reports.facts(ReportFact、
|
||||
require_report_kind)。
|
||||
逻辑:组合根(shipping_notice.rpa_sinks.register_onhand_sinks /
|
||||
in_transit_transfer.rpa_sinks.register_inbound_sinks /
|
||||
register_outbound_sinks)在应用启动时调用 register_report_handler 注入各
|
||||
kind 的业务处理函数;归档入口(如 freight_rpa.inbound.report_archive.
|
||||
ingest_inbound_callback)在每个终态 db.session.commit() 之后调用
|
||||
dispatch_report_fact。kind 未注册时显式 404(FREIGHT_RPA.
|
||||
SINK_NOT_REGISTERED,与 common.callback_sinks.dispatch_sink 同码),
|
||||
绝不静默吞事实;处理函数异常原样向外抛(供 Worker/上层重试整笔回调)。
|
||||
本模块不 commit、不 rollback。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Callable
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind
|
||||
|
||||
# 报表事实处理函数契约:接收单个 ReportFact,返回 None;
|
||||
# 异常由调用方外抛重试,处理函数内部禁止自行吞异常。
|
||||
Handler = Callable[[ReportFact], None]
|
||||
|
||||
# kind → 处理函数注册表(模块级单例;同 kind 重复注册为覆盖)。
|
||||
_REPORT_HANDLERS: dict[str, Handler] = {}
|
||||
|
||||
|
||||
def register_report_handler(report_kind: str, handler: Handler) -> None:
|
||||
"""
|
||||
注册一个报表事实处理函数(由组合根在应用启动时调用)。
|
||||
|
||||
【AI 触发时机】:组合根装配(register_onhand_sinks / register_inbound_sinks /
|
||||
register_outbound_sinks)时调用;测试直接调用注入临时处理函数。
|
||||
核心逻辑:kind 先经 require_report_kind 白名单校验(onhand / inbound /
|
||||
outbound,非法即 400 fail-closed);同一 kind 重复注册为覆盖。
|
||||
Args:
|
||||
report_kind: 报表种类字符串(必须在 REPORT_KINDS 白名单内)。
|
||||
handler: 处理函数(Handler 契约见模块 docstring);本模块只保存引用,
|
||||
不校验其内部行为。
|
||||
Raises:
|
||||
ValidationError: report_kind 不在白名单(code=SHIPPING.INBOUND_CALLBACK_INVALID)。
|
||||
"""
|
||||
kind = require_report_kind(report_kind)
|
||||
_REPORT_HANDLERS[kind] = handler
|
||||
|
||||
|
||||
def dispatch_report_fact(fact: ReportFact) -> None:
|
||||
"""
|
||||
把已随终态 commit 的报表事实投递给对应 kind 的处理函数。
|
||||
|
||||
【AI 触发时机】:归档入口(如 ingest_inbound_callback)在每个终态
|
||||
db.session.commit() 之后调用;禁止用于 commit 之前的路径(非法载荷 /
|
||||
单元不存在 / 落库失败均不得投递)。
|
||||
核心逻辑:kind 经 require_report_kind 校验后查注册表;命中即调用处理函数,
|
||||
其异常原样向外抛(不包日志、不吞);未注册抛
|
||||
AppError(code='FREIGHT_RPA.SINK_NOT_REGISTERED', http_status=404)。
|
||||
本函数不 commit、不 rollback。
|
||||
Args:
|
||||
fact: 终态已落库后构造好的报表事实(report_kind/source_code/file_id/
|
||||
sha256/ok/error_code/error_message)。
|
||||
Raises:
|
||||
ValidationError: fact.report_kind 不在白名单。
|
||||
AppError: kind 未注册处理函数(404;归档终态已提交不回滚,
|
||||
Worker 重试整笔回调即可补投递)。
|
||||
"""
|
||||
kind = require_report_kind(fact.report_kind)
|
||||
handler = _REPORT_HANDLERS.get(kind)
|
||||
if handler is None:
|
||||
raise AppError(
|
||||
code='FREIGHT_RPA.SINK_NOT_REGISTERED',
|
||||
message=f'No report handler registered for kind: {kind}',
|
||||
http_status=404,
|
||||
)
|
||||
handler(fact)
|
||||
@@ -0,0 +1,71 @@
|
||||
"""freight_rpa/reports/facts.py
|
||||
|
||||
用途:定义跨域报表「事实」的传输契约——report kind 白名单与 ReportFact。
|
||||
依赖:app.core.errors.ValidationError(非法 kind 的统一失败出口)。
|
||||
逻辑:本模块是纯契约层(dataclass + 校验函数),不做任何数据库/IO 操作;
|
||||
report kind 只认 onhand / inbound / outbound,非法值抛
|
||||
ValidationError(code='SHIPPING.INBOUND_CALLBACK_INVALID'),
|
||||
与收料回调契约共用既有错误码(后续任务 6/7 的回调分发依赖此约定)。
|
||||
本模块不 import shipping_notice / in_transit_transfer。
|
||||
【Task 7 修复轮 2】ReportFact 末位新增可选 unit_run_id——归档入口每次投递
|
||||
必从单元行回填,供消费方处理函数精确定位本次回调收尾的执行单元。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
# 【AI 触发时机】AI 或调用方在构造 ReportFact / 分发报表回调前必须先用
|
||||
# require_report_kind 归一化校验 kind;白名单之外的取值一律拒绝。
|
||||
REPORT_KINDS = ('onhand', 'inbound', 'outbound')
|
||||
|
||||
# 非法 report kind 复用收料回调契约错误码:同一回调入口族共享一个客户端可辨识码,
|
||||
# 避免为同一类入参错误分裂出多个近义 code。
|
||||
_INVALID_KIND_ERROR_CODE = 'SHIPPING.INBOUND_CALLBACK_INVALID'
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReportFact:
|
||||
"""一份回报表的事实行(跨域只读传输对象)。
|
||||
|
||||
用途:RPA 回调归档后,由 freight_rpa 域产生、发货/调拨域消费的最小事实快照;
|
||||
ok=False 时 error_code/error_message 描述失败原因。
|
||||
约束:frozen 不可变;file_id/sha256 允许 None(抓取失败时无产物可指);
|
||||
unit_run_id 为归档入口回填的执行单元主键(Task 7 修复轮 2 起每次投递
|
||||
必带——处理函数据此精确定位「本次回调收尾的单元」,禁止按来源猜最新),
|
||||
允许 None 仅为兼容手工构造事实的旧调用方,dispatch 产线恒非空。
|
||||
"""
|
||||
|
||||
report_kind: str
|
||||
source_code: str
|
||||
file_id: int | None
|
||||
sha256: str | None
|
||||
ok: bool
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
unit_run_id: int | None = None
|
||||
|
||||
|
||||
def require_report_kind(value: str) -> str:
|
||||
"""校验并原样返回合法的 report kind。
|
||||
|
||||
用途:构造 ReportFact、注册/分发报表处理器前,把 kind 校验收敛到唯一入口。
|
||||
核心逻辑:value 不在 REPORT_KINDS 白名单(onhand / inbound / outbound)即抛
|
||||
ValidationError(code='SHIPPING.INBOUND_CALLBACK_INVALID'),fail-closed。
|
||||
|
||||
Args:
|
||||
value: 待校验的报表种类字符串;空值/大小写敏感不匹配同样视为非法。
|
||||
Returns:
|
||||
原样返回通过校验的 value(不含默认值/归一化,调用方以返回值为准)。
|
||||
Raises:
|
||||
ValidationError: value 不在白名单内(HTTP 400,不可重试)。
|
||||
"""
|
||||
if value not in REPORT_KINDS:
|
||||
raise ValidationError(
|
||||
f"Unsupported report kind: {value!r}",
|
||||
code=_INVALID_KIND_ERROR_CODE,
|
||||
details={'report_kind': value, 'allowed': list(REPORT_KINDS)},
|
||||
)
|
||||
return value
|
||||
@@ -0,0 +1,869 @@
|
||||
"""freight_rpa/reports/queries.py
|
||||
|
||||
用途:本模块是发货与调拨读报表的唯一入口——以只读视图(View dataclass)+
|
||||
解析失败标记的方式,向 in_transit_transfer / shipping_notice 域暴露
|
||||
freight_rpa 报表事实(站点、登录连接、在手/入站/出站报表配置、入站解析方案、
|
||||
入站归档文件),使消费方不再直接 import freight_rpa 模型表。
|
||||
依赖:app.db、app.models(FreightRpaSource / FreightRpaOnhandReportConfig /
|
||||
FreightRpaInboundReportConfig / FreightRpaOutboundReportConfig /
|
||||
FreightRpaInboundReportFile;登录连接
|
||||
(RpaProfile)与解析方案(ParsingProfile)经站点/配置关系连线引用)、
|
||||
app.core.errors(NotFoundError)、
|
||||
file_assets.storage.file_asset_storage(按 storage_key 读对象字节)。
|
||||
逻辑:【禁止】import app.services.shipping_notice 或 app.services.in_transit_transfer
|
||||
——方向只能反过来(门禁模块阶段 B Task 4 起引用本模块的过滤表达式)。
|
||||
usable / expired_inbound_file_condition 是入站归档文件「可用/失效」过滤
|
||||
表达式的唯一权威(自 in_transit_transfer/inbound_file_gate.py 迁移,
|
||||
两条件同核 _fresh_and_retention_valid 推导,规则文本只此一份):可用 =
|
||||
未删除(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取 +
|
||||
未过期(archive_expires_at 为空视为长期有效或晚于当前时刻);失效 =
|
||||
未删除 且 核心不成立。业务日窗口换算(date_policy.business_date_utc_window
|
||||
的数学)以私有 helper 内联在本文件,就是为了不 import in_transit_transfer
|
||||
(import 禁令)而保持口径逐位一致。
|
||||
【阶段 B Task 4】站点视图补主键/连接绑定/仓库识别方式与入站配置视图补
|
||||
config_id/config_version;新增登录连接(get_rpa_login_profile)、入站解析
|
||||
方案(get_inbound_parsing_profile / get_outbound_parsing_profile)、失效文件
|
||||
存在性(has_expired_inbound_file)、重建通道归档清单
|
||||
(list_reparseable_inbound_files / list_reparseable_outbound_files)、入站/
|
||||
出站可用站点编码清单(list_inbound_configured_source_codes /
|
||||
list_outbound_configured_source_codes)——供 in_transit_transfer 收敛为
|
||||
「只按 source_code / file_id 读取」的只读函数消费面。
|
||||
mark/clear 解析失败只 flush 不 commit——事务提交时机归属调用方。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy import ColumnElement, and_, not_, or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
FreightRpaInboundReportConfig,
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
FreightRpaOnhandReportConfig,
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaSource,
|
||||
)
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
# 解析失败分层三列的截断上限,对齐列宽(String(64) / Text≈2000),
|
||||
# 防止上游超长错误信息把写入顶爆。
|
||||
_PARSE_ERROR_CODE_MAX = 64
|
||||
_PARSE_ERROR_MESSAGE_MAX = 2000
|
||||
|
||||
# 业务时区固定 Asia/Shanghai(与 in_transit_transfer.date_policy 同值;本包内
|
||||
# 复制而非 import,见文件头 import 禁令)。
|
||||
_SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
|
||||
_UTC_TZ = ZoneInfo("UTC")
|
||||
|
||||
|
||||
def _business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
|
||||
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
|
||||
|
||||
自 in_transit_transfer/date_policy.business_date_utc_window 逐位内联(阶段 B
|
||||
Task 3 修复轮 1):数据库统一存 naive UTC,直接取 .date() 与业务日比较会
|
||||
漂移 8 小时,必须先换算窗口再比较;不能 import date_policy,故复制其数学
|
||||
并保持口径一致(此处内联即唯一权威,门禁模块后续引用本包)。
|
||||
|
||||
Args:
|
||||
now: 可选时刻;naive 按 UTC 兼容处理(与 date_policy 口径一致),
|
||||
缺省取当前 Asia/Shanghai 时刻。
|
||||
Returns:
|
||||
(窗口起, 窗口止);两者均为 naive UTC datetime,止为开区间(时长 24h)。
|
||||
"""
|
||||
if now is None:
|
||||
now = datetime.now(_SHANGHAI_TZ)
|
||||
if now.tzinfo is None:
|
||||
now = now.replace(tzinfo=_UTC_TZ)
|
||||
sh_now = now.astimezone(_SHANGHAI_TZ)
|
||||
start_utc = (
|
||||
datetime(sh_now.year, sh_now.month, sh_now.day, tzinfo=_SHANGHAI_TZ)
|
||||
.astimezone(_UTC_TZ)
|
||||
.replace(tzinfo=None)
|
||||
)
|
||||
return start_utc, start_utc + timedelta(hours=24)
|
||||
|
||||
|
||||
def _fresh_and_retention_valid(now: datetime) -> ColumnElement:
|
||||
"""新鲜度 + 保留期核心条件(不含删除态;可用/失效两条件同核推导,规则文本只此一份)。"""
|
||||
window_start, window_end = _business_date_utc_window(now)
|
||||
return and_(
|
||||
FreightRpaInboundReportFile.created_at >= window_start,
|
||||
FreightRpaInboundReportFile.created_at < window_end,
|
||||
or_(
|
||||
FreightRpaInboundReportFile.archive_expires_at.is_(None),
|
||||
FreightRpaInboundReportFile.archive_expires_at > now,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def usable_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
|
||||
"""返回「当前可用的入站归档文件」SQL 条件(唯一权威,供门禁模块引用)。
|
||||
|
||||
判定(与 in_transit_transfer/inbound_file_gate 现行口径逐位一致):
|
||||
未删除(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
|
||||
(created_at ∈ 业务日 UTC [窗口起, 窗口止) 窗口,naive UTC 存储)+
|
||||
未过期(archive_expires_at 为空视为长期有效,否则须晚于判定时刻)。
|
||||
本表达式全量自 inbound_file_gate.py 复制(阶段 B Task 3),此后以此为单一
|
||||
事实来源,门禁模块改为引用本函数(禁止反向 import 出现环)。
|
||||
|
||||
Args:
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
可直接并入 .filter() 的单个 SQLAlchemy 条件。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
return and_(
|
||||
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
|
||||
_fresh_and_retention_valid(now),
|
||||
)
|
||||
|
||||
|
||||
def expired_inbound_file_condition(*, now: datetime | None = None) -> ColumnElement:
|
||||
"""返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。
|
||||
|
||||
判定:未删除(archive_deleted_at 为空)且 新鲜度+保留期核心不成立
|
||||
(保留期已到 或 非当天业务日抓取)——与可用条件同核(_fresh_and_retention_valid)
|
||||
推导,口径只存在一处。阶段 B Task 4 自 in_transit_transfer/inbound_file_gate
|
||||
迁移至此(语义逐位一致),此后以本文件为唯一权威;命中即提示重试重抓,
|
||||
不报 ready,也不等待保留期清理任务落位。
|
||||
|
||||
Args:
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
可直接并入 .filter() 的单个 SQLAlchemy 条件。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
return and_(
|
||||
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
|
||||
not_(_fresh_and_retention_valid(now)),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SiteView:
|
||||
"""库存站点的只读视图:连接与模板绑定、启停状态(不含报表定义,s18 起)。
|
||||
|
||||
阶段 B Task 4 增补三字段(调拨域路由/触发按 source_code 读站点主键与识别
|
||||
方式时不再引用站点模型):source_id(站点主键,供映射查询等 FK 路径)、
|
||||
rpa_profile_id(登录连接绑定)、warehouse_resolution_mode(仓库识别方式)。
|
||||
"""
|
||||
|
||||
source_code: str
|
||||
display_name: str
|
||||
connector_type: str
|
||||
excel_template_id: int | None
|
||||
enabled: bool
|
||||
source_id: int = 0
|
||||
rpa_profile_id: int = 0
|
||||
warehouse_resolution_mode: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RpaLoginProfileView:
|
||||
"""RPA 登录连接只读视图(freight_rpa_profiles 行)。
|
||||
|
||||
凭据密文原样透传(username/password_ciphertext)——仅限投递 RPA Worker
|
||||
trigger,禁止出现在任何日志/接口响应中。
|
||||
"""
|
||||
|
||||
profile_id: int
|
||||
profile_code: str
|
||||
login_url: str
|
||||
login_config: dict
|
||||
username_ciphertext: str | None
|
||||
password_ciphertext: str | None
|
||||
enabled: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OnhandConfigView:
|
||||
"""在手报表配置只读视图(freight_rpa_onhand_report_configs 行)。"""
|
||||
|
||||
report_path_json: dict
|
||||
query_parameters_json: list
|
||||
parsing_profile_id: int | None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InboundConfigView:
|
||||
"""入站报表配置只读视图(freight_rpa_inbound_report_configs 行),与在手同构。
|
||||
|
||||
阶段 B Task 4 增补 config_id / config_version(调拨入站触发落可审计单元行
|
||||
快照需要配置行主键与版本,不再引用配置模型)。
|
||||
"""
|
||||
|
||||
report_path_json: dict
|
||||
query_parameters_json: list
|
||||
parsing_profile_id: int | None
|
||||
config_id: int = 0
|
||||
config_version: int = 1
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OutboundConfigView:
|
||||
"""出站报表配置只读视图(freight_rpa_outbound_report_configs 行),与入站同构。
|
||||
|
||||
config_id / config_version 供调拨出站触发落可审计单元行快照使用,
|
||||
不再引用配置模型。
|
||||
"""
|
||||
|
||||
report_path_json: dict
|
||||
query_parameters_json: list
|
||||
parsing_profile_id: int | None
|
||||
config_id: int = 0
|
||||
config_version: int = 1
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InboundProfileView:
|
||||
"""入站解析方案只读视图(freight_rpa_parsing_profiles 行)。
|
||||
|
||||
定义(definition_json:field_mapping / sheet_name / header_row_index 等)
|
||||
原样透出;status/purpose 的 published-inbound 门禁决策归调用方按场景
|
||||
自行 fail-closed(运行期取数、重建、触发守卫口径一致,见各自消费方)。
|
||||
"""
|
||||
|
||||
profile_id: int
|
||||
profile_code: str
|
||||
version: int
|
||||
status: str
|
||||
purpose: str
|
||||
definition_json: dict
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InboundFileView:
|
||||
"""入站归档文件的只读视图;source_code 取自其所属执行单元行。
|
||||
|
||||
parse_failed_at 为解析失败分层的事实列(None=未失败/已清除)——阶段 B
|
||||
Task 4 增补,供来源状态投影与证据同步判断 parse_failed,免除调用方二次查询。
|
||||
"""
|
||||
|
||||
file_id: int
|
||||
source_code: str
|
||||
sha256: str
|
||||
storage_key: str
|
||||
original_filename: str
|
||||
created_at: datetime
|
||||
parse_failed_at: datetime | None = None
|
||||
|
||||
|
||||
def get_site(source_code: str) -> SiteView | None:
|
||||
"""按 source_code 返回库存站点只读视图。
|
||||
|
||||
用途:调拨/发货域读取站点连接、模板绑定与启停(例如入站触发预检)时调用,
|
||||
替代直接查询 FreightRpaSource。
|
||||
核心逻辑:按 source_code 精确查第一条;命中即映射为 SiteView(frozen),否则 None。
|
||||
|
||||
Args:
|
||||
source_code: 站点实例编码(大小写敏感,禁止传入模糊值)。
|
||||
Returns:
|
||||
SiteView;站点不存在返回 None(调用方自行 fail-closed)。
|
||||
"""
|
||||
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
|
||||
if site is None:
|
||||
return None
|
||||
return SiteView(
|
||||
source_code=site.source_code,
|
||||
display_name=site.display_name,
|
||||
connector_type=site.connector_type,
|
||||
excel_template_id=site.excel_template_id,
|
||||
enabled=bool(site.enabled),
|
||||
# [阶段 B Task 4] 调拨域(路由解析/入站触发)所需站点主键与识别方式。
|
||||
source_id=site.id,
|
||||
rpa_profile_id=site.rpa_profile_id,
|
||||
warehouse_resolution_mode=str(site.warehouse_resolution_mode or ""),
|
||||
)
|
||||
|
||||
|
||||
def get_onhand_config(source_code: str) -> OnhandConfigView | None:
|
||||
"""按 source_code 返回在手报表配置只读视图。
|
||||
|
||||
用途:RPA 触发读路径取报表路径、查询条件与解析方案绑定(s18 起配置挂在
|
||||
freight_rpa_onhand_report_configs,站点行不再承载这三列)。
|
||||
核心逻辑:join 站点表按 source_code 查配置行,命中即映射视图;站点或配置行
|
||||
缺失一律返回 None(fail-closed,调用方判 None 后阻断触发)。
|
||||
|
||||
Args:
|
||||
source_code: 站点实例编码。
|
||||
Returns:
|
||||
OnhandConfigView;站点无配置返回 None。
|
||||
"""
|
||||
config = (
|
||||
FreightRpaOnhandReportConfig.query
|
||||
.join(FreightRpaSource, FreightRpaOnhandReportConfig.source_id == FreightRpaSource.id)
|
||||
.filter(FreightRpaSource.source_code == source_code)
|
||||
.first()
|
||||
)
|
||||
if config is None:
|
||||
return None
|
||||
return OnhandConfigView(
|
||||
report_path_json=dict(config.report_path_json or {}),
|
||||
query_parameters_json=list(config.query_parameters_json or []),
|
||||
parsing_profile_id=config.parsing_profile_id,
|
||||
)
|
||||
|
||||
|
||||
def get_inbound_config(source_code: str) -> InboundConfigView | None:
|
||||
"""按 source_code 返回入站报表配置只读视图(与在手配置同构)。
|
||||
|
||||
用途:调拨入站触发读路径取收料报表定义;收料不设独立启停,是否运行由站点
|
||||
enabled 与本配置行是否存在决定。
|
||||
核心逻辑:join 站点表按 source_code 查 freight_rpa_inbound_report_configs 行,
|
||||
命中即映射视图;缺失返回 None。
|
||||
|
||||
Args:
|
||||
source_code: 站点实例编码。
|
||||
Returns:
|
||||
InboundConfigView;站点或配置不存在返回 None。
|
||||
"""
|
||||
config = (
|
||||
FreightRpaInboundReportConfig.query
|
||||
.join(FreightRpaSource, FreightRpaInboundReportConfig.source_id == FreightRpaSource.id)
|
||||
.filter(FreightRpaSource.source_code == source_code)
|
||||
.first()
|
||||
)
|
||||
if config is None:
|
||||
return None
|
||||
return InboundConfigView(
|
||||
report_path_json=dict(config.report_path_json or {}),
|
||||
query_parameters_json=list(config.query_parameters_json or []),
|
||||
parsing_profile_id=config.parsing_profile_id,
|
||||
# [阶段 B Task 4] 触发快照(config_snapshot)所需的配置行主键与版本。
|
||||
config_id=config.id,
|
||||
config_version=int(config.config_version or 1),
|
||||
)
|
||||
|
||||
|
||||
def get_outbound_config(source_code: str) -> OutboundConfigView | None:
|
||||
"""按 source_code 返回出站报表配置只读视图(与入站配置同构)。
|
||||
|
||||
用途:调拨出站触发读路径取出站报表定义;出站不设独立启停,是否运行由站点
|
||||
enabled 与本配置行是否存在决定。
|
||||
核心逻辑:join 站点表按 source_code 查 freight_rpa_outbound_report_configs 行,
|
||||
命中即映射视图;缺失返回 None。
|
||||
|
||||
Args:
|
||||
source_code: 站点实例编码。
|
||||
Returns:
|
||||
OutboundConfigView;站点或配置不存在返回 None。
|
||||
"""
|
||||
config = (
|
||||
FreightRpaOutboundReportConfig.query
|
||||
.join(FreightRpaSource, FreightRpaOutboundReportConfig.source_id == FreightRpaSource.id)
|
||||
.filter(FreightRpaSource.source_code == source_code)
|
||||
.first()
|
||||
)
|
||||
if config is None:
|
||||
return None
|
||||
return OutboundConfigView(
|
||||
report_path_json=dict(config.report_path_json or {}),
|
||||
query_parameters_json=list(config.query_parameters_json or []),
|
||||
parsing_profile_id=config.parsing_profile_id,
|
||||
config_id=config.id,
|
||||
config_version=int(config.config_version or 1),
|
||||
)
|
||||
|
||||
|
||||
def get_rpa_login_profile(source_code: str) -> RpaLoginProfileView | None:
|
||||
"""按 source_code 返回站点绑定的 RPA 登录连接只读视图。
|
||||
|
||||
用途:调拨入站 RPA 触发装配 trigger unit(登录页、凭据密文信封、连接编码)
|
||||
时调用,替代直接查询站点与其登录连接模型。
|
||||
核心逻辑:按 source_code 取站点行再走 rpa_profile 关系;站点或连接缺失一律
|
||||
返回 None(fail-closed,调用方判 None 后阻断触发)。凭据密文
|
||||
原样透出(仅限投递 Worker trigger,调用方禁止落日志/响应)。
|
||||
|
||||
Args:
|
||||
source_code: 站点实例编码(大小写敏感)。
|
||||
Returns:
|
||||
RpaLoginProfileView;站点或连接不存在返回 None。
|
||||
"""
|
||||
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
|
||||
profile = site.rpa_profile if site is not None else None
|
||||
if profile is None:
|
||||
return None
|
||||
return RpaLoginProfileView(
|
||||
profile_id=profile.id,
|
||||
profile_code=profile.profile_code,
|
||||
login_url=profile.login_url,
|
||||
login_config=dict(profile.login_config_json or {}),
|
||||
username_ciphertext=profile.username_ciphertext,
|
||||
password_ciphertext=profile.password_ciphertext,
|
||||
enabled=bool(profile.enabled),
|
||||
)
|
||||
|
||||
|
||||
def get_inbound_parsing_profile(source_code: str) -> InboundProfileView | None:
|
||||
"""按 source_code 返回入站配置绑定的解析方案只读视图。
|
||||
|
||||
用途:调拨运行期取数(movement_file_repository)、清空重建
|
||||
(backlog_reparse_service)与 RPA 触发守卫(deps)读取入站文件解析
|
||||
规则定义时调用,替代直接持有配置模型关系。
|
||||
核心逻辑:站点 → 入站配置 → 配置绑定的解析方案,任一环节缺失返回 None;
|
||||
不校验 status/purpose(调用方按场景自行 fail-closed,见
|
||||
InboundProfileView docstring)。
|
||||
|
||||
Args:
|
||||
source_code: 站点实例编码。
|
||||
Returns:
|
||||
InboundProfileView;无配置、未绑定或方案行缺失返回 None。
|
||||
"""
|
||||
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
|
||||
config = site.inbound_report_config if site is not None else None
|
||||
profile = config.parsing_profile if config is not None else None
|
||||
if profile is None:
|
||||
return None
|
||||
return InboundProfileView(
|
||||
profile_id=profile.id,
|
||||
profile_code=profile.profile_code,
|
||||
version=int(profile.version or 1),
|
||||
status=profile.status,
|
||||
purpose=profile.purpose,
|
||||
definition_json=dict(profile.definition_json or {}),
|
||||
)
|
||||
|
||||
|
||||
def get_outbound_parsing_profile(source_code: str) -> InboundProfileView | None:
|
||||
"""按 source_code 返回出站配置绑定的解析方案只读视图(与入站同形)。
|
||||
|
||||
用途:调拨出站运行期落档(outbound_evidence_sync)与清空重建
|
||||
(backlog_reparse_service record_kind=outbound)读取出站文件解析规则。
|
||||
核心逻辑:站点 → 出站配置 → 配置绑定的解析方案,任一环节缺失返回 None;
|
||||
不校验 status/purpose(调用方按场景自行 fail-closed)。
|
||||
|
||||
Args:
|
||||
source_code: 站点实例编码。
|
||||
Returns:
|
||||
InboundProfileView(字段同入站方案视图);无配置/未绑定/方案缺失返回 None。
|
||||
"""
|
||||
site = FreightRpaSource.query.filter_by(source_code=source_code).first()
|
||||
config = site.outbound_report_config if site is not None else None
|
||||
profile = config.parsing_profile if config is not None else None
|
||||
if profile is None:
|
||||
return None
|
||||
return InboundProfileView(
|
||||
profile_id=profile.id,
|
||||
profile_code=profile.profile_code,
|
||||
version=int(profile.version or 1),
|
||||
status=profile.status,
|
||||
purpose=profile.purpose,
|
||||
definition_json=dict(profile.definition_json or {}),
|
||||
)
|
||||
|
||||
|
||||
def _inbound_file_view(report: FreightRpaInboundReportFile) -> InboundFileView:
|
||||
"""把归档文件 ORM 行映射为冻结只读视图(本模块内唯一映射点,字段增补只改此处)。"""
|
||||
return InboundFileView(
|
||||
file_id=report.id,
|
||||
source_code=report.unit_run.source_code,
|
||||
sha256=report.sha256,
|
||||
storage_key=report.storage_key,
|
||||
original_filename=report.original_filename,
|
||||
created_at=report.created_at,
|
||||
parse_failed_at=report.parse_failed_at,
|
||||
)
|
||||
|
||||
|
||||
def has_expired_inbound_file(source_code: str, *, now: datetime | None = None) -> bool:
|
||||
"""返回某来源是否存在「未删除但已失效」的入站归档文件(expired 投影依据)。
|
||||
|
||||
用途:调拨来源状态投影(source_file_status.resolve_source_file_status)判断
|
||||
该来源是否需要因文件失效(隔日旧文件 / 保留期已到但清理未落位)提示
|
||||
重抓时调用;只读不写,判定与 usable/expired 条件同核不漂移。
|
||||
|
||||
核心逻辑:经执行单元行的 source_code 过滤 + expired_inbound_file_condition,
|
||||
存在任一命中即 True(纯存在性判断,不取列数据不排序)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(写在执行单元行上)。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
bool:存在失效但未清理的归档文件 → True;否则 False。
|
||||
"""
|
||||
expired = (
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaInboundReportFile.unit_run.has(source_code=source_code),
|
||||
expired_inbound_file_condition(now=now),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
return expired is not None
|
||||
|
||||
|
||||
def list_reparseable_inbound_files(source_code: str, *, now: datetime | None = None) -> list[InboundFileView]:
|
||||
"""维护通道:列出某来源全部可重建入站归档(未删除 + 未过保留期),不设当日门禁。
|
||||
|
||||
用途:调拨待匹配桶「清空并重新解析」(movement_file_repository →
|
||||
backlog_reparse_service,spec §6)按来源取重建清单时调用。
|
||||
运行期取数(latest_usable_inbound_file)的当日 fail-closed 门禁是
|
||||
运行期语义;本方法是显式的历史重建通道(spec §6),两者不得混用。
|
||||
|
||||
核心逻辑:join 路径与 latest_usable_inbound_file 同款(经执行单元行
|
||||
source_code 过滤),但【刻意无当日门禁】——重建对象正是历史
|
||||
归档;保留期口径一致(archive_expires_at 为空视为长期有效)、
|
||||
未删除(archive_deleted_at 为空)。按 created_at/id 升序返回
|
||||
(重建必须按归档时间序重落,保证幂等重放顺序确定)。只读查询,
|
||||
不触碰对象存储字节(字节由调用方按需经 read_inbound_file_bytes 取)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(经执行单元行 source_code 关联)。
|
||||
now: 保留期判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
InboundFileView 列表(created_at 升序;无可重建归档为空表)。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
reports = (
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaInboundReportFile.unit_run.has(source_code=source_code),
|
||||
FreightRpaInboundReportFile.archive_deleted_at.is_(None),
|
||||
or_(
|
||||
FreightRpaInboundReportFile.archive_expires_at.is_(None),
|
||||
FreightRpaInboundReportFile.archive_expires_at > now,
|
||||
),
|
||||
)
|
||||
.order_by(FreightRpaInboundReportFile.created_at.asc(), FreightRpaInboundReportFile.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [_inbound_file_view(report) for report in reports]
|
||||
|
||||
|
||||
def _outbound_file_view(report: FreightRpaOutboundReportFile) -> InboundFileView:
|
||||
"""出站归档 → 与入站同形的只读视图(重建/投影消费面字段对齐)。"""
|
||||
return InboundFileView(
|
||||
file_id=report.id,
|
||||
source_code=report.unit_run.source_code,
|
||||
sha256=report.sha256,
|
||||
storage_key=report.storage_key,
|
||||
original_filename=report.original_filename,
|
||||
created_at=report.created_at,
|
||||
parse_failed_at=report.parse_failed_at,
|
||||
)
|
||||
|
||||
|
||||
def list_reparseable_outbound_files(source_code: str, *, now: datetime | None = None) -> list[InboundFileView]:
|
||||
"""维护通道:列出某来源全部可重建出站归档(未删除 + 未过保留期),不设当日门禁。
|
||||
|
||||
用途:调拨待匹配桶「清空并重新解析」出站流(backlog_reparse_service
|
||||
record_kind=outbound)按来源取重建清单;与 list_reparseable_inbound_files
|
||||
同口径,禁止与运行期 latest_usable_outbound_file 混用。
|
||||
|
||||
核心逻辑:经出站执行单元行 source_code 过滤;【无当日门禁】;保留期口径
|
||||
archive_expires_at 为空视为长期有效;按 created_at/id 升序。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
now: 保留期判定时刻;缺省当前 UTC。
|
||||
Returns:
|
||||
InboundFileView 列表(created_at 升序;无可重建归档为空表)。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
reports = (
|
||||
FreightRpaOutboundReportFile.query
|
||||
.join(FreightRpaOutboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaOutboundReportFile.unit_run.has(source_code=source_code),
|
||||
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
|
||||
or_(
|
||||
FreightRpaOutboundReportFile.archive_expires_at.is_(None),
|
||||
FreightRpaOutboundReportFile.archive_expires_at > now,
|
||||
),
|
||||
)
|
||||
.order_by(
|
||||
FreightRpaOutboundReportFile.created_at.asc(),
|
||||
FreightRpaOutboundReportFile.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return [_outbound_file_view(report) for report in reports]
|
||||
|
||||
|
||||
def list_inbound_configured_source_codes() -> list[str]:
|
||||
"""列出已配置入站报表的启用站点编码(调拨排程缺省执行范围)。
|
||||
|
||||
用途:在途自动调拨排程 source_codes 留空时的缺省范围
|
||||
(inbound_trigger_service.list_inbound_capable_source_codes 委托本函数)
|
||||
——入站文件只能来自已配置入站报表的启用站点。
|
||||
核心逻辑:站点 join 入站配置行、仅启用站点、按 source_code 排序;只读查询。
|
||||
|
||||
Returns:
|
||||
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
|
||||
"""
|
||||
rows = db.session.query(FreightRpaSource.source_code).join(
|
||||
FreightRpaInboundReportConfig,
|
||||
FreightRpaInboundReportConfig.source_id == FreightRpaSource.id,
|
||||
).filter(FreightRpaSource.enabled.is_(True)).order_by(FreightRpaSource.source_code).all()
|
||||
return [str(code) for (code,) in rows]
|
||||
|
||||
|
||||
def list_outbound_configured_source_codes() -> list[str]:
|
||||
"""列出已配置出站报表的启用站点编码(调拨排程缺省执行范围)。
|
||||
|
||||
用途:在途自动调拨排程 source_codes 留空时的缺省范围
|
||||
(outbound_trigger_service.list_outbound_capable_source_codes 委托本函数)
|
||||
——出站文件只能来自已配置出站报表的启用站点。
|
||||
核心逻辑:站点 join 出站配置行、仅启用站点、按 source_code 排序;只读查询。
|
||||
|
||||
Returns:
|
||||
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
|
||||
"""
|
||||
rows = db.session.query(FreightRpaSource.source_code).join(
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaOutboundReportConfig.source_id == FreightRpaSource.id,
|
||||
).filter(FreightRpaSource.enabled.is_(True)).order_by(FreightRpaSource.source_code).all()
|
||||
return [str(code) for (code,) in rows]
|
||||
|
||||
|
||||
def latest_usable_inbound_file(
|
||||
source_code: str,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> InboundFileView | None:
|
||||
"""返回某来源当前「可用」的入站归档文件只读视图,最新优先。
|
||||
|
||||
用途:调拨匹配取文件、证据下载等读路径调用;口径与匹配链路原有
|
||||
_latest_usable_report_file 相同——经执行单元行的 source_code 过滤,
|
||||
可用门禁(未删除 + 当天业务日抓取 + 未过期,见
|
||||
usable_inbound_file_condition),按 created_at/id 倒序取第一条。
|
||||
只读不写、不 flush 不 commit。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(写在 FreightRpaInboundUnitRun.source_code 上)。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
仅供测试冻结窗口或调用方显式指定业务时刻,生产调用缺省即可。
|
||||
Returns:
|
||||
InboundFileView;来源无可用文件(未抓取/已失效/已清理)返回 None。
|
||||
"""
|
||||
report = (
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaInboundReportFile.unit_run.has(source_code=source_code),
|
||||
usable_inbound_file_condition(now=now),
|
||||
)
|
||||
.order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc())
|
||||
.first()
|
||||
)
|
||||
if report is None:
|
||||
return None
|
||||
return _inbound_file_view(report)
|
||||
|
||||
|
||||
def latest_usable_inbound_files_by_source(
|
||||
source_ids: list[int],
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, InboundFileView]:
|
||||
"""一次取出这批来源各自最新的可用入站归档(来源状态批量投影用)。
|
||||
|
||||
用途:调拨 GET /sources 批量渲染来源卡时按批取文件身份,查询次数不随
|
||||
来源个数增长;口径与 latest_usable_inbound_file 完全一致(同一
|
||||
usable_inbound_file_condition 权威),只是按来源主键集合一次取回。
|
||||
|
||||
Args:
|
||||
source_ids: 来源主键集合(FreightRpaInboundUnitRun.source_id)。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
source_code → InboundFileView;没有可用文件的来源不出现,每个来源
|
||||
只留 created_at/id 最新一条。
|
||||
"""
|
||||
rows = (
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaInboundUnitRun.source_id.in_([int(i) for i in source_ids]),
|
||||
usable_inbound_file_condition(now=now),
|
||||
)
|
||||
.order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc())
|
||||
.all()
|
||||
)
|
||||
picked: dict[str, InboundFileView] = {}
|
||||
for report in rows:
|
||||
view = _inbound_file_view(report)
|
||||
if view.source_code not in picked:
|
||||
picked[view.source_code] = view
|
||||
return picked
|
||||
|
||||
|
||||
def expired_inbound_source_codes(
|
||||
source_ids: list[int],
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> set[str]:
|
||||
"""一次找出仍有失效未清理入站归档的来源编码(expired 投影依据,存在性判断)。
|
||||
|
||||
用途:调拨来源状态批量投影判断哪些来源因隔日旧文件/保留期已到提示重抓;
|
||||
口径与 has_expired_inbound_file 同核(expired_inbound_file_condition)。
|
||||
|
||||
Args:
|
||||
source_ids: 来源主键集合。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
至少有一份失效未清理入站归档的 source_code 集合。
|
||||
"""
|
||||
rows = (
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaInboundUnitRun.source_id.in_([int(i) for i in source_ids]),
|
||||
expired_inbound_file_condition(now=now),
|
||||
)
|
||||
.with_entities(FreightRpaInboundUnitRun.source_code)
|
||||
.distinct()
|
||||
.all()
|
||||
)
|
||||
return {str(row[0]) for row in rows}
|
||||
|
||||
|
||||
def read_inbound_file_bytes(file_id: int) -> bytes:
|
||||
"""按 file_id 读取入站归档文件的对象字节。
|
||||
|
||||
用途:调拨/发货域需要文件原文(匹配重解析、证据下载)时调用,替代各自
|
||||
持有模型 + file_asset_storage 的双跳查询。
|
||||
核心逻辑:[STEP 1] 按主键取 FreightRpaInboundReportFile,缺失抛 NotFoundError
|
||||
(fail-closed);[STEP 2] 以文件的 storage_key 调
|
||||
file_asset_storage.get_bytes 读取并返回字节(不含元数据)。
|
||||
|
||||
Args:
|
||||
file_id: 归档文件主键(int;禁止传入非整数 ID)。
|
||||
Returns:
|
||||
文件完整字节内容。
|
||||
Raises:
|
||||
NotFoundError: file_id 对应的归档文件不存在(HTTP 404)。
|
||||
"""
|
||||
report = db.session.get(FreightRpaInboundReportFile, file_id)
|
||||
if report is None:
|
||||
raise NotFoundError(
|
||||
f"Inbound report file not found: {file_id}",
|
||||
details={'file_id': file_id},
|
||||
)
|
||||
return file_asset_storage.get_bytes(report.storage_key)
|
||||
|
||||
|
||||
def mark_inbound_parse_failure(file_id: int, *, error_code: str, error_message: str) -> None:
|
||||
"""标记一份入站归档文件解析失败(写入解析失败三分层列)。
|
||||
|
||||
用途:入站归档文件解析(schema/字段校验)失败时把失败事实落到文件上,
|
||||
使来源状态投影为 parse_failed、阻止下游当作 ready 使用。
|
||||
核心逻辑:[STEP 1] 按主键取文件,缺失抛 NotFoundError;[STEP 2] 只更新
|
||||
parse_failed_at(当前 UTC)/ parse_error_code(截断 64)/
|
||||
parse_error_message(截断 2000)三列;[STEP 3] db.session.flush()
|
||||
使同事务内投影立即可见。【不 commit】——调用方处于自己的事务,
|
||||
提交/回滚归属调用方,service 层禁止越权提交。
|
||||
|
||||
Args:
|
||||
file_id: 归档文件主键(须已入库)。
|
||||
error_code: 机器可读错误码,超 64 字符截断(对齐列宽)。
|
||||
error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。
|
||||
Returns:
|
||||
None。失败标记随调用方事务落库。
|
||||
Raises:
|
||||
NotFoundError: file_id 对应的归档文件不存在。
|
||||
"""
|
||||
report = db.session.get(FreightRpaInboundReportFile, file_id)
|
||||
if report is None:
|
||||
raise NotFoundError(
|
||||
f"Inbound report file not found: {file_id}",
|
||||
details={'file_id': file_id},
|
||||
)
|
||||
report.parse_failed_at = datetime.utcnow()
|
||||
report.parse_error_code = (error_code or '')[:_PARSE_ERROR_CODE_MAX]
|
||||
report.parse_error_message = (error_message or '')[:_PARSE_ERROR_MESSAGE_MAX]
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def clear_inbound_parse_failure(file_id: int) -> None:
|
||||
"""清除一份入站归档文件的解析失败标记(三列置空),投影恢复 ready。
|
||||
|
||||
用途:同一文件重新解析成功、或确认可恢复后调用;不要在文件已被
|
||||
清理/过期后调用(无业务意义)。
|
||||
核心逻辑:[STEP 1] 按主键取文件,缺失抛 NotFoundError(与其他按 id 操作
|
||||
同口径,避免静默吞掉错配);[STEP 2] 将 parse_failed_at /
|
||||
parse_error_code / parse_error_message 置 None(三者全空即未失败的
|
||||
约定态);[STEP 3] flush。【不 commit】——事务归属调用方。
|
||||
|
||||
Args:
|
||||
file_id: 归档文件主键(须已入库)。
|
||||
Returns:
|
||||
None。清除随调用方事务落库。
|
||||
Raises:
|
||||
NotFoundError: file_id 对应的归档文件不存在。
|
||||
"""
|
||||
report = db.session.get(FreightRpaInboundReportFile, file_id)
|
||||
if report is None:
|
||||
raise NotFoundError(
|
||||
f"Inbound report file not found: {file_id}",
|
||||
details={'file_id': file_id},
|
||||
)
|
||||
report.parse_failed_at = None
|
||||
report.parse_error_code = None
|
||||
report.parse_error_message = None
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def mark_outbound_parse_failure(file_id: int, *, error_code: str, error_message: str) -> None:
|
||||
"""标记一份出站归档文件解析失败(写入解析失败三分层列;与入站同名函数对称)。
|
||||
|
||||
用途:出站归档文件解析(schema/字段校验)失败时把失败事实落到文件上,
|
||||
使来源出站流状态投影为 parse_failed、阻止下游当作 ready 使用
|
||||
(resolve_source_file_status(record_kind='outbound') 同一投影顺序)。
|
||||
核心逻辑:与 mark_inbound_parse_failure 同款(错误码截 64/错误信息截
|
||||
2000/flush 不 commit——事务归属调用方),仅目标表为
|
||||
FreightRpaOutboundReportFile。
|
||||
|
||||
Args:
|
||||
file_id: 出站归档文件主键(须已入库)。
|
||||
error_code: 机器可读错误码,超 64 字符截断(对齐列宽)。
|
||||
error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。
|
||||
Returns:
|
||||
None。失败标记随调用方事务落库。
|
||||
Raises:
|
||||
NotFoundError: file_id 对应的出站归档文件不存在。
|
||||
"""
|
||||
report = db.session.get(FreightRpaOutboundReportFile, file_id)
|
||||
if report is None:
|
||||
raise NotFoundError(
|
||||
f"Outbound report file not found: {file_id}",
|
||||
details={'file_id': file_id},
|
||||
)
|
||||
report.parse_failed_at = datetime.utcnow()
|
||||
report.parse_error_code = (error_code or '')[:_PARSE_ERROR_CODE_MAX]
|
||||
report.parse_error_message = (error_message or '')[:_PARSE_ERROR_MESSAGE_MAX]
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def clear_outbound_parse_failure(file_id: int) -> None:
|
||||
"""清除一份出站归档文件的解析失败标记(三列置空),投影恢复 ready。
|
||||
|
||||
用途:同一出站文件重新解析成功后调用;不要在文件已被清理/过期后调用
|
||||
(无业务意义)。与 clear_inbound_parse_failure 同款,仅目标表为
|
||||
FreightRpaOutboundReportFile。
|
||||
|
||||
Args:
|
||||
file_id: 出站归档文件主键(须已入库)。
|
||||
Returns:
|
||||
None。清除随调用方事务落库。
|
||||
Raises:
|
||||
NotFoundError: file_id 对应的出站归档文件不存在。
|
||||
"""
|
||||
report = db.session.get(FreightRpaOutboundReportFile, file_id)
|
||||
if report is None:
|
||||
raise NotFoundError(
|
||||
f"Outbound report file not found: {file_id}",
|
||||
details={'file_id': file_id},
|
||||
)
|
||||
report.parse_failed_at = None
|
||||
report.parse_error_code = None
|
||||
report.parse_error_message = None
|
||||
db.session.flush()
|
||||
@@ -0,0 +1 @@
|
||||
"""upload:货代上传 RPA。"""
|
||||
@@ -0,0 +1,234 @@
|
||||
"""
|
||||
services/freight_rpa/upload/crane_recheck.py
|
||||
|
||||
用途:Crane 发货单进入分配中之后的状态回查。
|
||||
依赖:ShippingUploadAttempt、freight_rpa.upload.trigger_io、page_contract。
|
||||
逻辑:自动上传只排一次 10 分钟后的回查;手动刷新另写一条 status_check trigger,
|
||||
不顺延、不取消那一次定时。两条回查都只让 Worker 重新登录并按 Pull Request # 看行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingExportArtifact, ShippingNotice, ShippingUploadAttempt
|
||||
from app.services.freight_rpa.upload.page_contract import crane_recheck_due_at
|
||||
from app.services.freight_rpa.upload.trigger_io import write_upload_trigger
|
||||
|
||||
CRANE_ALLOCATING_CODE = 'CRANE_ALLOCATING'
|
||||
|
||||
|
||||
def is_crane_allocating(attempt: ShippingUploadAttempt | None) -> bool:
|
||||
"""当前尝试是否停在 Crane 已接收、尚未分配完成。"""
|
||||
return (
|
||||
attempt is not None
|
||||
and attempt.status == 'running'
|
||||
and attempt.error_code == CRANE_ALLOCATING_CODE
|
||||
)
|
||||
|
||||
|
||||
def _evidence(attempt: ShippingUploadAttempt) -> dict[str, Any]:
|
||||
raw = attempt.success_evidence_json
|
||||
return dict(raw) if isinstance(raw, dict) else {}
|
||||
|
||||
|
||||
def _recheck(evidence: dict[str, Any]) -> dict[str, Any]:
|
||||
raw = evidence.get('crane_recheck')
|
||||
return dict(raw) if isinstance(raw, dict) else {}
|
||||
|
||||
|
||||
def remember_crane_allocating(
|
||||
attempt: ShippingUploadAttempt,
|
||||
artifact: ShippingExportArtifact,
|
||||
callback_id: str,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> ShippingUploadAttempt:
|
||||
"""把尝试标成分配中,并在首次进入时记下唯一一次定时回查。
|
||||
|
||||
核心逻辑:due_at 只在还没有时写入。后续回查回调仍是分配中时,不改到期时间,
|
||||
也不把定时标记成已触发。
|
||||
|
||||
Args:
|
||||
attempt: 本次上传尝试。
|
||||
artifact: 已提交的发货 Excel。
|
||||
callback_id: 本次回调幂等键。重复的同一个键直接返回。
|
||||
now: 测试注入的当前时间。
|
||||
|
||||
Returns:
|
||||
ShippingUploadAttempt: 仍为 running、错误码为 CRANE_ALLOCATING 的尝试。
|
||||
"""
|
||||
evidence = _evidence(attempt)
|
||||
if evidence.get('last_callback_id') == callback_id or attempt.callback_id == callback_id:
|
||||
return attempt
|
||||
recheck = _recheck(evidence)
|
||||
if not recheck.get('due_at'):
|
||||
pull_request_no = str(artifact.file_name or '').rsplit('.', 1)[0] or str(artifact.file_name or '')
|
||||
recheck = {
|
||||
'due_at': crane_recheck_due_at(now).isoformat(timespec='seconds'),
|
||||
'fired': False,
|
||||
'pull_request_no': pull_request_no,
|
||||
}
|
||||
evidence['crane_recheck'] = recheck
|
||||
evidence['last_callback_id'] = callback_id
|
||||
evidence['manual_refresh_inflight'] = False
|
||||
attempt.success_evidence_json = evidence
|
||||
attempt.status = 'running'
|
||||
attempt.error_code = CRANE_ALLOCATING_CODE
|
||||
attempt.error_message = None
|
||||
attempt.finished_at = None
|
||||
if not attempt.callback_id:
|
||||
attempt.callback_id = callback_id
|
||||
artifact.status = 'uploading'
|
||||
db.session.flush()
|
||||
return attempt
|
||||
|
||||
|
||||
def _write_status_check(
|
||||
attempt: ShippingUploadAttempt,
|
||||
upload_source: dict[str, Any],
|
||||
*,
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
pull_request_no: str,
|
||||
kind: str,
|
||||
) -> str | None:
|
||||
"""写入一条只查状态的上传 trigger。文件复制失败时返回 None。"""
|
||||
# 定时回查的回调键固定,重复心跳不会写成两次有效回调。
|
||||
# 手动刷新每次使用新键,避免上一次「仍在分配」把这一次回调当成重复而跳过。
|
||||
callback_id = f'crane-recheck:{attempt.id}:scheduled'
|
||||
trigger_filename = f'upload_recheck_{task_no}_scheduled.json'
|
||||
if kind == 'manual':
|
||||
callback_id = f'crane-recheck:{attempt.id}:manual:{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}'
|
||||
trigger_filename = f'upload_recheck_{task_no}_manual.json'
|
||||
_queue, trigger_path, _callback = write_upload_trigger(
|
||||
task_no,
|
||||
export_file_path,
|
||||
{'mode': 'status_check', 'recheck_kind': kind, 'pull_request_no': pull_request_no},
|
||||
attempt_id=int(attempt.id),
|
||||
artifact_id=int(attempt.artifact_id),
|
||||
connector_type='crane',
|
||||
upload_config={'enabled': True},
|
||||
login_url=str(upload_source.get('login_url') or '').strip() or None,
|
||||
credential_envelope=upload_source.get('credential_envelope') if isinstance(upload_source.get('credential_envelope'), dict) else None,
|
||||
callback_id=callback_id,
|
||||
business_no=pull_request_no,
|
||||
trigger_filename=trigger_filename,
|
||||
)
|
||||
return trigger_path
|
||||
|
||||
|
||||
def fire_scheduled_crane_recheck(
|
||||
attempt: ShippingUploadAttempt,
|
||||
upload_source: dict[str, Any],
|
||||
*,
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
now: datetime | None = None,
|
||||
) -> bool:
|
||||
"""到期后写入唯一一次定时回查。未到期、已触发或不是分配中时不写文件。
|
||||
|
||||
Returns:
|
||||
bool: 本次是否新写了 trigger。
|
||||
"""
|
||||
if not is_crane_allocating(attempt):
|
||||
return False
|
||||
evidence = _evidence(attempt)
|
||||
recheck = _recheck(evidence)
|
||||
if recheck.get('fired') or not recheck.get('due_at'):
|
||||
return False
|
||||
due_at = datetime.fromisoformat(str(recheck['due_at']))
|
||||
if due_at > (now or datetime.utcnow()):
|
||||
return False
|
||||
pull_request_no = str(recheck.get('pull_request_no') or '').strip()
|
||||
trigger_path = _write_status_check(
|
||||
attempt, upload_source, task_no=task_no, export_file_path=export_file_path,
|
||||
pull_request_no=pull_request_no, kind='scheduled',
|
||||
)
|
||||
if not trigger_path:
|
||||
return False
|
||||
recheck['fired'] = True
|
||||
evidence['crane_recheck'] = recheck
|
||||
attempt.success_evidence_json = evidence
|
||||
db.session.flush()
|
||||
return True
|
||||
|
||||
|
||||
def request_manual_crane_refresh(
|
||||
attempt: ShippingUploadAttempt,
|
||||
upload_source: dict[str, Any],
|
||||
*,
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
) -> str:
|
||||
"""手动刷新:立刻写一条状态回查,不改定时回查的到期时间和已触发标记。
|
||||
|
||||
Raises:
|
||||
ConflictError: 当前不是分配中,或上一次手动刷新还没回调。
|
||||
ValidationError: 共享目录写不出 trigger。
|
||||
"""
|
||||
if not is_crane_allocating(attempt):
|
||||
raise ConflictError(
|
||||
'Crane upload is not waiting for allocation',
|
||||
code='SHIPPING.UPLOAD_CRANE_ALLOCATING',
|
||||
)
|
||||
evidence = _evidence(attempt)
|
||||
if evidence.get('manual_refresh_inflight'):
|
||||
raise ConflictError(
|
||||
'A Crane status refresh is already queued',
|
||||
code='SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT',
|
||||
)
|
||||
recheck = _recheck(evidence)
|
||||
pull_request_no = str(recheck.get('pull_request_no') or '').strip()
|
||||
due_at = recheck.get('due_at')
|
||||
fired = bool(recheck.get('fired'))
|
||||
trigger_path = _write_status_check(
|
||||
attempt, upload_source, task_no=task_no, export_file_path=export_file_path,
|
||||
pull_request_no=pull_request_no, kind='manual',
|
||||
)
|
||||
if not trigger_path:
|
||||
raise ValidationError(
|
||||
'Crane status refresh trigger directory is unavailable',
|
||||
code='SHIPPING.UPLOAD_TRIGGER_UNAVAILABLE',
|
||||
)
|
||||
evidence['manual_refresh_inflight'] = True
|
||||
evidence['crane_recheck'] = {**recheck, 'due_at': due_at, 'fired': fired, 'pull_request_no': pull_request_no}
|
||||
attempt.success_evidence_json = evidence
|
||||
db.session.flush()
|
||||
return trigger_path
|
||||
|
||||
|
||||
def materialize_due_crane_rechecks(now: datetime | None = None) -> int:
|
||||
"""心跳时把已到期且尚未触发的 Crane 定时回查写成 trigger。
|
||||
|
||||
Returns:
|
||||
int: 新写入的 trigger 数量。
|
||||
"""
|
||||
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
|
||||
|
||||
moment = now or datetime.utcnow()
|
||||
written = 0
|
||||
attempts = ShippingUploadAttempt.query.filter_by(status='running', error_code=CRANE_ALLOCATING_CODE).all()
|
||||
for attempt in attempts:
|
||||
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id)
|
||||
notice = db.session.get(ShippingNotice, artifact.task_id) if artifact is not None else None
|
||||
if artifact is None or notice is None or not artifact.file_path:
|
||||
continue
|
||||
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
|
||||
|
||||
snapshot = task_rpa_inventory_source(notice) or {}
|
||||
source_code = str(snapshot.get('source_code') or '').strip()
|
||||
upload_source = get_rpa_trigger_inventory_source(source_code) if source_code else None
|
||||
if not isinstance(upload_source, dict) or str(upload_source.get('connector_type') or '').lower() != 'crane':
|
||||
continue
|
||||
if fire_scheduled_crane_recheck(
|
||||
attempt, upload_source, task_no=str(notice.task_no),
|
||||
export_file_path=str(artifact.file_path), now=moment,
|
||||
):
|
||||
written += 1
|
||||
if written:
|
||||
db.session.commit()
|
||||
return written
|
||||
@@ -0,0 +1,68 @@
|
||||
"""
|
||||
services/freight_rpa/upload/page_contract.py
|
||||
|
||||
用途:货代发货 Excel 上传的平台页面契约。入口路径、文件控件和成功条件由代码固定。
|
||||
依赖:标准库 urllib。
|
||||
逻辑:系统连接只保存是否启用自动上传;Worker 用登录地址的主机拼出上传页。
|
||||
DBS 上传后当页即可判定;Crane 先进入分配中,10 分钟后再查一次。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
CRANE_RECHECK_DELAY = timedelta(minutes=10)
|
||||
DBS_UPLOAD_PATH = '/main/portal/frame/WMSUpload2'
|
||||
CRANE_UPLOAD_HASH = '/#/shipping-order-upload'
|
||||
|
||||
|
||||
def build_upload_entry_url(connector_type: str, login_url: str) -> str:
|
||||
"""按平台把登录地址的主机拼成上传页。
|
||||
|
||||
核心逻辑:页面路径属于连接器代码。管理端不再保存上传入口 URL。
|
||||
|
||||
Args:
|
||||
connector_type: dbs 或 crane。
|
||||
login_url: 系统连接上的 HTTPS 登录地址。
|
||||
|
||||
Returns:
|
||||
str: 该平台固定上传页。
|
||||
|
||||
Raises:
|
||||
ValueError: 连接类型或登录地址无法构成上传页。
|
||||
"""
|
||||
kind = str(connector_type or '').strip().lower()
|
||||
parsed = urlsplit(str(login_url or '').strip())
|
||||
host = parsed.netloc.strip()
|
||||
if parsed.scheme.lower() != 'https' or not host or not parsed.hostname:
|
||||
raise ValueError('login_url must be HTTPS with a host')
|
||||
if kind == 'dbs':
|
||||
return f'https://{host}{DBS_UPLOAD_PATH}'
|
||||
if kind == 'crane':
|
||||
return f'https://{host}{CRANE_UPLOAD_HASH}'
|
||||
raise ValueError(f'unsupported connector_type: {connector_type or "<empty>"}')
|
||||
|
||||
|
||||
def classify_crane_order_row(order_status: str, order_status_description: str) -> str:
|
||||
"""判断 Crane 发货单行处于分配中、已分配,还是都不是。
|
||||
|
||||
Args:
|
||||
order_status: Order Status 列文本。
|
||||
order_status_description: Order Status Description 列文本。
|
||||
|
||||
Returns:
|
||||
str: allocated、allocating 或 other。
|
||||
"""
|
||||
status = ' '.join(str(order_status or '').split()).lower()
|
||||
description = ' '.join(str(order_status_description or '').split()).lower()
|
||||
if status == 'processing' and description == 'shipping order allocated':
|
||||
return 'allocated'
|
||||
if status == 'processing' and description == 'allocating the shipping order':
|
||||
return 'allocating'
|
||||
return 'other'
|
||||
|
||||
|
||||
def crane_recheck_due_at(now: datetime | None = None) -> datetime:
|
||||
"""自动上传进入分配中之后,唯一一次定时回查的到期时间。"""
|
||||
return (now or datetime.utcnow()) + CRANE_RECHECK_DELAY
|
||||
@@ -0,0 +1,153 @@
|
||||
"""
|
||||
services/freight_rpa/upload/trigger_io.py
|
||||
|
||||
用途:upload(货代上传)RPA 的纯文件 IO——上传队列/trigger 目录解析、Excel 复制入队、
|
||||
上传 trigger JSON 原子写入(含凭据信封固化)。
|
||||
依赖:Flask current_app 配置、Path/shutil/uuid/JSON/文件系统工具;不 import 任何业务编排模块
|
||||
(import 边界由 tests/services/freight_rpa/test_import_boundary.py 锁死)。
|
||||
逻辑:由 shipping_notice.fulfillment_workflow(upload_to_freight 触发上传)、
|
||||
freight_rpa.common.worker_heartbeat(上传目录就绪探测)调用,
|
||||
与外部 RPA Worker 的文件投递目录交互;trigger 契约串以本文件常量为单一真相。
|
||||
upload 是与 onhand/inbound/outbound 同级的独立域;action 对齐心跳能力
|
||||
freight_rpa_upload(FREIGHT_RPA_UPLOAD_CAPABILITY),禁止 outbound_* / shipment_* 作为 upload action;
|
||||
schema 为 freight_rpa.upload.v1(批次 R 曾误用 outbound 词根,已纠回 freight_rpa_upload)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
# Worker 触发契约常量:后端写入侧单一真相,禁止再写字面量(Worker 侧常量见
|
||||
# scripts/freight_rpa/common/rpa_callbacks.py 邻域的 inbound/onhand 对齐方式)。
|
||||
SCHEMA = "freight_rpa.upload.v1"
|
||||
ACTION_FREIGHT_RPA_UPLOAD = "freight_rpa_upload"
|
||||
|
||||
|
||||
def _path(key: str) -> Path | None:
|
||||
value = str(current_app.config.get(key) or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
return Path(value)
|
||||
|
||||
|
||||
def _write_trigger_json_atomic(path: Path, body: dict[str, Any]) -> None:
|
||||
"""原子发布 trigger,避免 Worker 读取到写入中的半截 JSON。"""
|
||||
temp_path = path.with_name(f'.{path.name}.{os.getpid()}.tmp')
|
||||
try:
|
||||
with open(temp_path, 'w', encoding='utf-8') as handle:
|
||||
json.dump(body, handle, ensure_ascii=False, indent=2)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temp_path, path)
|
||||
finally:
|
||||
if temp_path.exists():
|
||||
temp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def upload_queue_dir() -> Path | None:
|
||||
"""货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。"""
|
||||
return _path("FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR")
|
||||
|
||||
|
||||
def upload_trigger_dir() -> Path | None:
|
||||
"""RPA 货代上传触发 JSON 目录。"""
|
||||
return _path("FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR")
|
||||
|
||||
|
||||
def write_upload_trigger(
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
payload: dict[str, Any] | None = None,
|
||||
*,
|
||||
attempt_id: int | None = None,
|
||||
artifact_id: int | None = None,
|
||||
connector_type: str | None = None,
|
||||
upload_config: dict[str, Any] | None = None,
|
||||
upload_config_hash: str | None = None,
|
||||
login_url: str | None = None,
|
||||
credential_envelope: dict[str, Any] | None = None,
|
||||
callback_id: str | None = None,
|
||||
business_no: str | None = None,
|
||||
trigger_filename: str | None = None,
|
||||
) -> tuple[str | None, str | None, str | None]:
|
||||
"""
|
||||
复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。
|
||||
【AI 触发时机】:upload_to_freight(mode=auto|retry_upload) 触发货代上传时调用。
|
||||
|
||||
触发文件固化本次上传契约快照,Worker 据此进入 DSV/Crane 受控流程:
|
||||
schema_version / task_no / attempt_id / artifact_id / callback_id(非空)/
|
||||
connector_type / upload_config(本次快照 + upload_config_hash)/ login_url / credential_envelope / file_path。
|
||||
平台页面动作由 Worker 连接器代码固定;upload_config 只携带是否启用自动上传。
|
||||
写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。
|
||||
|
||||
Args:
|
||||
task_no: 发货任务号。
|
||||
export_file_path: 待上传发货 Excel 的服务端路径。
|
||||
payload: 附加字段(如 mode),与下列具名参数合并。
|
||||
attempt_id: 本次 Upload Attempt 主键。
|
||||
artifact_id: 当前上传目标 Artifact 主键。
|
||||
connector_type: 业务连接类型(dbs / crane)。
|
||||
upload_config: 本次上传使用的连接级受控配置快照(enabled/entry_url/selector 等)。
|
||||
upload_config_hash: 该快照的 sha256,用于审计关联。
|
||||
login_url: 该连接登录地址(先登录,再访问 upload_config.entry_url 进入上传页)。
|
||||
credential_envelope: 连接凭据密文信封(Worker 据此登录)。
|
||||
callback_id: 回调幂等 ID;为空时自动生成,保证非空。
|
||||
business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。
|
||||
trigger_filename: 触发文件名。状态回查使用独立文件名,避免覆盖正在上传的 trigger。
|
||||
|
||||
Returns:
|
||||
tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id);
|
||||
失败时 (None, None, None)。
|
||||
"""
|
||||
queue = upload_queue_dir()
|
||||
trigger_dir = upload_trigger_dir()
|
||||
if not queue or not trigger_dir:
|
||||
return None, None, None
|
||||
queue.mkdir(parents=True, exist_ok=True)
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
src = Path(export_file_path)
|
||||
status_check = str((payload or {}).get('mode') or '') == 'status_check'
|
||||
if not src.is_file() and not status_check:
|
||||
return None, None, None
|
||||
# [STEP] 精简上传文件名:仅用业务编号(业务单号),避免 task_no 与导出文件名重复拼接过长;
|
||||
# 业务编号为空时回退到内部任务号,扩展名沿用源文件(无扩展名时按 xlsx 兜底)。
|
||||
emit_no = str(business_no or '').strip() or task_no
|
||||
suffix = str(src.suffix or '.xlsx').lower()
|
||||
dest = queue / f"{emit_no}{suffix}"
|
||||
if src.is_file():
|
||||
shutil.copy2(src, dest)
|
||||
queued_file = str(dest)
|
||||
elif status_check:
|
||||
queued_file = ''
|
||||
else:
|
||||
return None, None, None
|
||||
|
||||
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
|
||||
body = {
|
||||
"action": ACTION_FREIGHT_RPA_UPLOAD,
|
||||
"schema_version": SCHEMA,
|
||||
"task_no": task_no,
|
||||
"attempt_id": attempt_id,
|
||||
"artifact_id": artifact_id,
|
||||
"callback_id": resolved_callback_id,
|
||||
"connector_type": str(connector_type or '').strip() or None,
|
||||
"upload_config": upload_config,
|
||||
"upload_config_hash": upload_config_hash,
|
||||
"login_url": login_url,
|
||||
"credential_envelope": credential_envelope,
|
||||
"file_path": queued_file,
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
**(payload or {}),
|
||||
}
|
||||
trigger_path = trigger_dir / (trigger_filename or f"upload_{task_no}.json")
|
||||
_write_trigger_json_atomic(trigger_path, body)
|
||||
return str(dest), str(trigger_path), resolved_callback_id
|
||||
@@ -108,7 +108,7 @@ def archive_snapshot(
|
||||
"""归档一份对象并持久化索引 + 审计。
|
||||
|
||||
Args:
|
||||
object_type: 对象类型(external_inventory_snapshot / exception_excel / receipt_file)。
|
||||
object_type: 对象类型(external_inventory_snapshot / exception_excel / inbound_file)。
|
||||
object_id: 业务对象编号(matching_no / run_no)。
|
||||
data: 待归档字节。
|
||||
original_filename: 原始文件名。
|
||||
|
||||
@@ -32,8 +32,9 @@ class AutoTransferOutcome:
|
||||
def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
||||
source_codes: list[str] | None = None,
|
||||
recover_history: bool = True,
|
||||
receipt_date_from: str | None = None,
|
||||
receipt_date_to: str | None = None,
|
||||
movement_date_from: str | None = None,
|
||||
movement_date_to: str | None = None,
|
||||
transfer_type: str | None = None,
|
||||
sender: WeComSender | None = None,
|
||||
recipients: list[str] | None = None) -> AutoTransferOutcome:
|
||||
"""执行一次自动调拨排程。
|
||||
@@ -46,8 +47,10 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
||||
deps: 注入依赖。
|
||||
source_codes: 来源实例列表(缺省全部启用来源)。
|
||||
recover_history: 是否执行历史恢复。
|
||||
receipt_date_from / receipt_date_to: 可选收料日期范围(测试/排障缩小
|
||||
匹配面;留空=全部成熟积压;非法范围由匹配层抛 ValidationError)。
|
||||
movement_date_from / movement_date_to: 可选异动日期范围(测试/排障缩小
|
||||
匹配面;留空=全部积压;非法范围由匹配层抛 ValidationError)。
|
||||
transfer_type: 调拨类型编码(D8 匹配创建必填——排程任务参数承载;
|
||||
缺省 None 时匹配层 fail-closed 抛 TRANSFER_TYPE_REQUIRED)。
|
||||
sender / recipients: 企微通知(None 则跳过通知;run_no 为空时不发送)。
|
||||
Returns:
|
||||
AutoTransferOutcome;空数据日时 run_no/run_status 均为 None 且 errors 为空。
|
||||
@@ -63,8 +66,9 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
||||
source_codes=source_codes or [],
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
receipt_date_from=receipt_date_from,
|
||||
receipt_date_to=receipt_date_to,
|
||||
movement_date_from=movement_date_from,
|
||||
movement_date_to=movement_date_to,
|
||||
transfer_type=transfer_type,
|
||||
)
|
||||
# [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、
|
||||
# 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
"""services/in_transit_transfer/backlog_reparse_service.py
|
||||
|
||||
用途:待匹配桶整桶重建的内部实现(spec §6/D7)。2026-10-22 起不再挂 HTTP:
|
||||
预检/执行路由已下线,待匹配界面不再提供入口。本模块仅保留给既有单测,
|
||||
锁住「先全量解析、失败一行不删」;禁止重新挂回
|
||||
/backlog/pending-match/reparse*。重解析产品入口只有当天最新归档
|
||||
(current_file_reparse)。
|
||||
历史语义:按来源 + 记录类型把旧映射档行清空,并以当前规则重解析全部
|
||||
可重建归档后幂等重落。
|
||||
依赖:movement_file_repository(ReparseableArchiveFile + _extract_movement_rows)、
|
||||
evidence_sync.parse_archive_to_ledger_rows(解析+组装单一口径)与
|
||||
_detect_natural_key_collapses/_natural_key_collapse_event、ledger_sync
|
||||
(sync_ledger_rows / RECORD_KIND_* / FileMeta / movement_file_version)、
|
||||
matching_service.
|
||||
_effective_occupancy_filter、freight_rpa.reports.queries(站点与入站/出站
|
||||
解析方案、可重建归档清单)、file_asset_storage、audit。
|
||||
逻辑:桶数据 100% 可由 MinIO 归档重建。安全不变量:先全量预解析入内存,
|
||||
任一归档解析失败 → 整体中止 AppError(TRANSFER.REPARSE_PARSE_FAILED),
|
||||
一行不删。删除范围:source_code + record_kind + transfer_executed=false +
|
||||
未被有效 items 占用 + source_file_id ∈ 可重建归档。入站/出站分流仅体现在
|
||||
规则门禁(published purpose)、归档清单表与落档 record_kind;其余步骤同源。
|
||||
commit 在本服务内做一次。审计 TRANSFER_PENDING_MATCH_REPARSED 含 record_kind。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.models import TransferInvoiceItem, TransferMovementLedger
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
get_inbound_parsing_profile,
|
||||
get_outbound_parsing_profile,
|
||||
get_site,
|
||||
list_reparseable_inbound_files,
|
||||
list_reparseable_outbound_files,
|
||||
)
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.evidence_sync import (
|
||||
_detect_natural_key_collapses,
|
||||
_natural_key_collapse_event,
|
||||
parse_archive_to_ledger_rows,
|
||||
)
|
||||
from app.services.in_transit_transfer.ledger_sync import (
|
||||
RECORD_KIND_INBOUND,
|
||||
RECORD_KIND_OUTBOUND,
|
||||
FileMeta,
|
||||
movement_file_version,
|
||||
sync_ledger_rows,
|
||||
)
|
||||
from app.services.in_transit_transfer.matching_service import _effective_occupancy_filter
|
||||
from app.services.in_transit_transfer.movement_file_repository import (
|
||||
ReparseableArchiveFile,
|
||||
_extract_movement_rows,
|
||||
)
|
||||
|
||||
REPARSE_EVENT = "TRANSFER_PENDING_MATCH_REPARSED"
|
||||
REPARSE_PARSE_FAILED = "TRANSFER.REPARSE_PARSE_FAILED"
|
||||
_RECORD_KINDS = frozenset({RECORD_KIND_INBOUND, RECORD_KIND_OUTBOUND})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReparseOutcome:
|
||||
"""一次清空重建的结果计数与文件概要(审计/端点响应的数据源)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
record_kind: inbound 或 outbound。
|
||||
cleared / reinserted / date_skipped / kept_unrebuildable / unlinked_items /
|
||||
collapses / files: 同入站重建语义。
|
||||
"""
|
||||
|
||||
source_code: str
|
||||
record_kind: str = RECORD_KIND_INBOUND
|
||||
cleared: int = 0
|
||||
reinserted: int = 0
|
||||
date_skipped: int = 0
|
||||
kept_unrebuildable: int = 0
|
||||
unlinked_items: int = 0
|
||||
collapses: int = 0
|
||||
files: tuple[dict, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
def _normalize_record_kind(record_kind: str | None) -> str:
|
||||
"""规范化记录类型;非法值 fail-closed。"""
|
||||
kind = str(record_kind or RECORD_KIND_INBOUND).strip() or RECORD_KIND_INBOUND
|
||||
if kind not in _RECORD_KINDS:
|
||||
raise ValidationError(
|
||||
"record_kind must be inbound or outbound",
|
||||
details={"record_kind": kind},
|
||||
)
|
||||
return kind
|
||||
|
||||
|
||||
def _load_published_profile(source_code: str, record_kind: str):
|
||||
"""加载来源当前绑定的「已发布」解析规则(与运行期取数同口径)。
|
||||
|
||||
核心逻辑:来源 enabled → 入站/出站配置绑定方案;须 published 且
|
||||
purpose 等于 record_kind。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
record_kind: inbound 或 outbound。
|
||||
Returns:
|
||||
解析方案视图;无通道时 None。
|
||||
"""
|
||||
site = get_site(source_code)
|
||||
if site is None or not site.enabled:
|
||||
return None
|
||||
if record_kind == RECORD_KIND_OUTBOUND:
|
||||
profile = get_outbound_parsing_profile(source_code)
|
||||
else:
|
||||
profile = get_inbound_parsing_profile(source_code)
|
||||
if profile is None or profile.status != "published" or profile.purpose != record_kind:
|
||||
return None
|
||||
return profile
|
||||
|
||||
|
||||
def _list_reparseable_files(
|
||||
source_code: str, now: datetime, record_kind: str,
|
||||
) -> list[ReparseableArchiveFile]:
|
||||
"""按记录类型列出可重建归档,映射为维护契约 ReparseableArchiveFile。"""
|
||||
if record_kind == RECORD_KIND_OUTBOUND:
|
||||
views = list_reparseable_outbound_files(source_code, now=now)
|
||||
else:
|
||||
views = list_reparseable_inbound_files(source_code, now=now)
|
||||
return [
|
||||
ReparseableArchiveFile(
|
||||
file_id=view.file_id,
|
||||
storage_key=view.storage_key,
|
||||
sha256=view.sha256,
|
||||
file_version=movement_file_version(view.sha256),
|
||||
archived_at=view.created_at,
|
||||
original_filename=view.original_filename,
|
||||
)
|
||||
for view in views
|
||||
]
|
||||
|
||||
|
||||
def _partition_deletable(
|
||||
source_code: str,
|
||||
files: list[ReparseableArchiveFile],
|
||||
record_kind: str,
|
||||
) -> tuple[list[TransferMovementLedger], list[TransferMovementLedger]]:
|
||||
"""把「未封存且未被占用」的指定 record_kind 档行按证据可得性分成两组。"""
|
||||
available_ids = {record.file_id for record in files}
|
||||
candidates = (
|
||||
TransferMovementLedger.query.filter(
|
||||
TransferMovementLedger.source_code == source_code,
|
||||
TransferMovementLedger.record_kind == record_kind,
|
||||
TransferMovementLedger.transfer_executed.is_(False),
|
||||
_effective_occupancy_filter(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
deletable = [row for row in candidates if row.source_file_id in available_ids]
|
||||
return candidates, deletable
|
||||
|
||||
|
||||
def preview_pending_match_reparse(
|
||||
*, source_code: str, now: datetime, record_kind: str = RECORD_KIND_INBOUND,
|
||||
) -> dict:
|
||||
"""清空并重新解析预检(只读;按 record_kind 分流入站/出站归档与档行)。
|
||||
|
||||
【AI 触发时机】不要调用。2026-10-22 起产品入口已下线,仅单测覆盖本函数。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
now: 保留期判定时刻。
|
||||
record_kind: inbound(默认,兼容旧调用)或 outbound。
|
||||
Returns:
|
||||
{record_kind, files, profile, clearable_rows, kept_rows}
|
||||
"""
|
||||
kind = _normalize_record_kind(record_kind)
|
||||
files = _list_reparseable_files(source_code, now, kind)
|
||||
profile = _load_published_profile(source_code, kind)
|
||||
_candidates, deletable = _partition_deletable(source_code, files, kind)
|
||||
file_ids = [record.file_id for record in files]
|
||||
counts: dict[int, int] = {}
|
||||
if file_ids:
|
||||
counts = {
|
||||
source_file_id: count
|
||||
for source_file_id, count in db.session.query(
|
||||
TransferMovementLedger.source_file_id,
|
||||
func.count(TransferMovementLedger.id),
|
||||
)
|
||||
.filter(
|
||||
TransferMovementLedger.source_code == source_code,
|
||||
TransferMovementLedger.record_kind == kind,
|
||||
TransferMovementLedger.source_file_id.in_(file_ids),
|
||||
)
|
||||
.group_by(TransferMovementLedger.source_file_id)
|
||||
.all()
|
||||
}
|
||||
return {
|
||||
"record_kind": kind,
|
||||
"files": [
|
||||
{
|
||||
"archived_at": record.archived_at.isoformat(),
|
||||
"sha256": record.sha256,
|
||||
"rows": counts.get(record.file_id, 0),
|
||||
}
|
||||
for record in files
|
||||
],
|
||||
"profile": (
|
||||
{"code": profile.profile_code, "version": profile.version}
|
||||
if profile is not None else None
|
||||
),
|
||||
"clearable_rows": len(deletable),
|
||||
"kept_rows": len(_candidates) - len(deletable),
|
||||
}
|
||||
|
||||
|
||||
def reparse_pending_match(
|
||||
*,
|
||||
source_code: str,
|
||||
operator: str,
|
||||
now: datetime,
|
||||
record_kind: str = RECORD_KIND_INBOUND,
|
||||
) -> ReparseOutcome:
|
||||
"""清空并重新解析一个来源指定记录类型的待匹配桶(单事务,本函数提交)。
|
||||
|
||||
【AI 触发时机】不要调用。2026-10-22 起产品入口已下线,仅单测覆盖本函数。
|
||||
record_kind=outbound 时清出站档、用 purpose=outbound 规则与出站归档重建。
|
||||
|
||||
Raises:
|
||||
ValidationError: record_kind 非法。
|
||||
AppError: TRANSFER.REPARSE_PARSE_FAILED——无已发布对应流解析规则,或
|
||||
任一归档解析失败(整体中止且未删除任何行)。
|
||||
"""
|
||||
kind = _normalize_record_kind(record_kind)
|
||||
# [STEP 1] 重建通道与可重建文件清单。
|
||||
profile = _load_published_profile(source_code, kind)
|
||||
if profile is None:
|
||||
raise AppError(
|
||||
code=REPARSE_PARSE_FAILED,
|
||||
message=(
|
||||
f"reparse aborted: no published {kind} parsing profile "
|
||||
f"(source={source_code})"
|
||||
),
|
||||
http_status=422,
|
||||
details={
|
||||
"source_code": source_code,
|
||||
"record_kind": kind,
|
||||
"reason": f"no_published_{kind}_profile",
|
||||
},
|
||||
)
|
||||
files = _list_reparseable_files(source_code, now, kind)
|
||||
definition = profile.definition_json or {}
|
||||
|
||||
# [STEP 2] 全量预解析入内存;任一失败整体中止。
|
||||
prepared: list[tuple[ReparseableArchiveFile, list[dict]]] = []
|
||||
for record in files:
|
||||
try:
|
||||
data = file_asset_storage.get_bytes(record.storage_key)
|
||||
raw_rows = _extract_movement_rows(
|
||||
data,
|
||||
field_mapping=dict(definition.get("field_mapping") or {}),
|
||||
sheet_name=str(definition.get("sheet_name") or "").strip() or None,
|
||||
header_row_index=definition.get("header_row_index"),
|
||||
)
|
||||
assembled = parse_archive_to_ledger_rows(source_code=source_code, rows=raw_rows)
|
||||
except Exception as exc: # noqa: BLE001 —— 安全不变量
|
||||
raise AppError(
|
||||
code=REPARSE_PARSE_FAILED,
|
||||
message=f"reparse aborted: archive file failed to parse (source={source_code})",
|
||||
http_status=422,
|
||||
details={
|
||||
"source_code": source_code,
|
||||
"record_kind": kind,
|
||||
"file_id": record.file_id,
|
||||
"storage_key": record.storage_key,
|
||||
"sha256": record.sha256,
|
||||
"reason": str(exc)[:500],
|
||||
},
|
||||
) from exc
|
||||
prepared.append((record, assembled))
|
||||
|
||||
# [STEP 3] 删除可重建未占用行(先解引用废弃 items)。
|
||||
candidates, deletable = _partition_deletable(source_code, files, kind)
|
||||
kept_unrebuildable = len(candidates) - len(deletable)
|
||||
deletable_ids = [row.id for row in deletable]
|
||||
unlinked_items = 0
|
||||
if deletable_ids:
|
||||
unlinked_items = (
|
||||
TransferInvoiceItem.query
|
||||
.filter(TransferInvoiceItem.ledger_record_id.in_(deletable_ids))
|
||||
.update({TransferInvoiceItem.ledger_record_id: None}, synchronize_session=False)
|
||||
)
|
||||
for row in deletable:
|
||||
db.session.delete(row)
|
||||
db.session.flush()
|
||||
|
||||
# [STEP 4] 按归档时间升序逐文件重落。
|
||||
reinserted = 0
|
||||
date_skipped = 0
|
||||
collapses = 0
|
||||
file_summaries: list[dict[str, Any]] = []
|
||||
for record, assembled in prepared:
|
||||
outcome = sync_ledger_rows(
|
||||
source_code=source_code,
|
||||
record_kind=kind,
|
||||
parsed_rows=assembled,
|
||||
file_meta=FileMeta(
|
||||
source_file_id=record.file_id,
|
||||
file_version=record.file_version,
|
||||
file_sha256=record.sha256,
|
||||
),
|
||||
now=now,
|
||||
)
|
||||
reinserted += outcome.inserted
|
||||
date_skipped += outcome.date_skipped
|
||||
if outcome.inserted or outcome.updated:
|
||||
file_collapses = _detect_natural_key_collapses(assembled)
|
||||
for collapse in file_collapses:
|
||||
db.session.add(_natural_key_collapse_event(
|
||||
source_code=source_code, collapse=collapse, record_kind=kind,
|
||||
))
|
||||
collapses += len(file_collapses)
|
||||
file_summaries.append({
|
||||
"file_id": record.file_id,
|
||||
"sha256": record.sha256,
|
||||
"archived_at": record.archived_at.isoformat(),
|
||||
"inserted": outcome.inserted,
|
||||
})
|
||||
|
||||
# [STEP 5] 审计 + commit。
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type=REPARSE_EVENT,
|
||||
aggregate_type="transfer_source",
|
||||
aggregate_id=source_code,
|
||||
actor_type="user",
|
||||
actor_id=operator,
|
||||
actor_display=operator,
|
||||
result="success",
|
||||
after={
|
||||
"operator": operator,
|
||||
"source_code": source_code,
|
||||
"record_kind": kind,
|
||||
"files": [
|
||||
{"file_id": record.file_id, "sha256": record.sha256}
|
||||
for record, _assembled in prepared
|
||||
],
|
||||
"profile_code": profile.profile_code,
|
||||
"profile_version": profile.version,
|
||||
"cleared": len(deletable),
|
||||
"reinserted": reinserted,
|
||||
"date_skipped": date_skipped,
|
||||
"kept": kept_unrebuildable,
|
||||
"unlinked_items": unlinked_items,
|
||||
"collapses": collapses,
|
||||
},
|
||||
))
|
||||
db.session.commit()
|
||||
return ReparseOutcome(
|
||||
source_code=source_code,
|
||||
record_kind=kind,
|
||||
cleared=len(deletable),
|
||||
reinserted=reinserted,
|
||||
date_skipped=date_skipped,
|
||||
kept_unrebuildable=kept_unrebuildable,
|
||||
unlinked_items=unlinked_items,
|
||||
collapses=collapses,
|
||||
files=tuple(file_summaries),
|
||||
)
|
||||
@@ -1,22 +1,44 @@
|
||||
"""在途调拨历史待处理池与老化分级。
|
||||
"""services/in_transit_transfer/backlog_service.py
|
||||
|
||||
在途调拨历史待处理池与老化分级 + 首页「待匹配」桶(D16)。
|
||||
|
||||
用途:聚合未成功且未人工关闭的可恢复异常、已关闭与结果未知项,
|
||||
按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘。
|
||||
依赖:models、status。
|
||||
按 3/5/7 天阈值输出老化等级,防止历史失败被遗忘;
|
||||
并提供首页待办看板「待匹配」桶(已落档尚未匹配的外部出入站记录,
|
||||
规格 §10/D16:只读清单 + 计数,不可勾选执行)。
|
||||
依赖:models、status、matching_service(待匹配全量圈档 + 启用类型范围并集)。
|
||||
逻辑:可恢复=blocked_recoverable;result_unknown 单独高风险展示且只读;
|
||||
manually_closed / success / duplicate_success 永久排除。
|
||||
待匹配桶=成熟未占用的出入站全量(pending_ledger_query:未封存/有异动日期/
|
||||
未被有效 items 占用/T−2,不按调拨类型范围过滤)。清单再按来源+记录类型+
|
||||
外部单号合计数量,不再展开外部项次;没有外部单号的档行仍逐行返回。
|
||||
首页待匹配、可匹配计数与清单行数同一合并口径。【2026-10-22 SQL 下推】
|
||||
计数=合并键 GROUP BY 计数、清单分页=组首行锚点 OFFSET/LIMIT 后只召回
|
||||
本页档行、行桶汇总=轻量元组单条查询;口径不变,禁止再整段装载内存切片。池行带出生匹配的
|
||||
transfer_type,供待恢复/已关闭/结果未知表展示调拨类别。可匹配=启用类型范围并集,
|
||||
供库存匹配卡计数,并给清单行打 matchable。无 item_id 不可执行;
|
||||
匹配圈定后记录离开本桶,
|
||||
取消匹配释放后回归。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy import String, and_, case, cast, func, literal, or_
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.models import TransferAttempt, TransferInvoiceItem
|
||||
from app.models import TransferAttempt, TransferInvoiceItem, TransferMovementLedger
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
circle_ledger_record_ids_scope_union,
|
||||
pending_ledger_query,
|
||||
ledger_external_doc_no,
|
||||
transfer_type_code_of,
|
||||
)
|
||||
from app.services.in_transit_transfer.status import TransferStatus
|
||||
|
||||
AGING_NORMAL = "normal"
|
||||
@@ -28,6 +50,32 @@ AGING_CLOSED = "closed"
|
||||
|
||||
_BACKLOG_RECOVERABLE = TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
|
||||
# 结果筛选切片(前端首页计数卡切片与池内筛选同口径);all=三态并集。
|
||||
RESULT_FILTER_RECOVERABLE = "recoverable"
|
||||
RESULT_FILTER_CLOSED = "closed"
|
||||
RESULT_FILTER_UNKNOWN = "unknown"
|
||||
RESULT_FILTER_ALL = "all"
|
||||
_ALL_BACKLOG_STATUSES = (
|
||||
_BACKLOG_RECOVERABLE,
|
||||
TransferStatus.RESULT_UNKNOWN.value,
|
||||
TransferStatus.MANUALLY_CLOSED.value,
|
||||
)
|
||||
_RESULT_FILTER_STATUSES: dict[str, tuple[str, ...]] = {
|
||||
RESULT_FILTER_ALL: _ALL_BACKLOG_STATUSES,
|
||||
RESULT_FILTER_RECOVERABLE: (_BACKLOG_RECOVERABLE,),
|
||||
RESULT_FILTER_CLOSED: (TransferStatus.MANUALLY_CLOSED.value,),
|
||||
RESULT_FILTER_UNKNOWN: (TransferStatus.RESULT_UNKNOWN.value,),
|
||||
}
|
||||
RESULT_FILTER_CHOICES = (RESULT_FILTER_ALL, *_RESULT_FILTER_STATUSES.keys())
|
||||
|
||||
# 服务端分页默认值/上限(与已执行单 /documents 接口同口径:默认 20、上限 100)。
|
||||
BACKLOG_PAGE_DEFAULT = 1
|
||||
BACKLOG_PAGE_SIZE_DEFAULT = 20
|
||||
BACKLOG_PAGE_SIZE_MAX = 100
|
||||
# 跨页全选 id 上限(2026-10-22):防误拉超大规模池;超出截断并由 API 透出
|
||||
# truncated 标记(千行级池单次全量 id 拉取成本可忽略,上限为防御性兜底)。
|
||||
BACKLOG_SELECT_ALL_MAX = 5000
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BacklogItemDTO:
|
||||
@@ -42,20 +90,49 @@ class BacklogItemDTO:
|
||||
age_days: int
|
||||
aging_level: str
|
||||
last_attempt_at: Optional[str] = None
|
||||
receipt_date: Optional[str] = None
|
||||
movement_date: Optional[str] = None
|
||||
material_name: Optional[str] = None
|
||||
from_warehouse: Optional[str] = None
|
||||
to_warehouse: Optional[str] = None
|
||||
lot_no: Optional[str] = None
|
||||
receipt_quantity: Optional[str] = None
|
||||
movement_quantity: Optional[str] = None
|
||||
external_quantity: Optional[str] = None
|
||||
# 最近一次结果码(如 blocked_file_removed);供前端区分「文件已移除」徽标
|
||||
result_code: Optional[str] = None
|
||||
# 出生匹配快照上的调拨类型 code。空串表示行没有匹配或快照未写类型。
|
||||
transfer_type: str = ""
|
||||
# 档上的外部单号。空串表示这行没有外部单号。
|
||||
external_doc_no: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PendingMatchRecordDTO:
|
||||
"""「待匹配」桶单项(D16):按外部单号收口后的只读投影——无 item_id,不可勾选执行。
|
||||
|
||||
有外部单号时,同一来源、同一记录类型下的多项次合成一行。quantity 为这些档行
|
||||
数量之和(Decimal 文本,与 items.movement_quantity 同约定)。没有外部单号的
|
||||
档行仍逐行返回。单号/料号/品名/异动日期在组内不一致时为空,前端显示占位。
|
||||
ledger_record_id 是组内最小档 id,只作行键,不代表整组只有这一条档。
|
||||
"""
|
||||
|
||||
ledger_record_id: int
|
||||
doc_no: str
|
||||
material_code: Optional[str] = None
|
||||
material_name: Optional[str] = None
|
||||
movement_date: Optional[str] = None
|
||||
source_code: str = ""
|
||||
# 档记录类型(inbound/outbound)。
|
||||
record_kind: str = "inbound"
|
||||
# 外部单号(WMS Order #)。空串=该行没有外部单号,未与其他行合并。
|
||||
external_doc_no: str = ""
|
||||
quantity: Optional[str] = None
|
||||
# 当前启用类型范围并集罩得住。分段查询里同一组的标记一致。
|
||||
matchable: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class BacklogSummaryDTO:
|
||||
"""待处理池汇总(含老化分级计数)。"""
|
||||
"""待处理池汇总(含老化分级计数 + 待匹配桶计数)。"""
|
||||
|
||||
recoverable_count: int = 0
|
||||
closed_count: int = 0
|
||||
@@ -63,6 +140,36 @@ class BacklogSummaryDTO:
|
||||
warn_3d: int = 0
|
||||
escalate_5d: int = 0
|
||||
critical_7d: int = 0
|
||||
# 首页「待匹配」卡:与待匹配清单同一合并口径的行数(不含类型范围)。
|
||||
pending_match_count: int = 0
|
||||
# 首页「匹配可调拨库存」卡:与清单「当前可匹配」同一合并口径的行数。
|
||||
matchable_count: int = 0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BacklogPageDTO:
|
||||
"""待处理池分页结果(2026-10-16 服务端分页:池为无界增长集合,
|
||||
全量拉取在千行级放大网络载荷与老化批量查询规模;items=当前页切片,
|
||||
total=筛选后全量计数供前端分页器)。"""
|
||||
|
||||
items: list[BacklogItemDTO]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
|
||||
|
||||
_PENDING_SEGMENTS = ("all", "matchable", "outside")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PendingMatchPageDTO:
|
||||
"""「待匹配」桶分页结果。total 与 records 都是外部单号合并后的行,
|
||||
不是档行数。没有外部单号的档行仍各占一行。"""
|
||||
|
||||
records: list[PendingMatchRecordDTO]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
|
||||
|
||||
def aging_level_for(age_days: int, *, warn: int = 3, escalate: int = 5, critical: int = 7) -> str:
|
||||
@@ -100,40 +207,62 @@ def _latest_attempt_times(item_ids: list[int]) -> dict[int, datetime]:
|
||||
return {item_id: latest for item_id, latest in rows}
|
||||
|
||||
|
||||
def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]:
|
||||
"""列出待处理池项(可恢复 + 已关闭 + 结果未知)。
|
||||
def _backlog_base_query(statuses, *, source_code: str | None = None, keyword: str | None = None):
|
||||
"""待处理池基础查询(状态集合 + 可选来源/关键字过滤)。
|
||||
|
||||
排序:收料日期 → 数据源 → Invoice → 创建时间(全链路统一业务稳定键,
|
||||
与可调拨明细/匹配卡视图同口径,2026-09-29 统一;与重查/恢复等操作无关)。
|
||||
不用 updated_at 排序——它是行级新鲜度时间戳,重查/恢复会刷新它,
|
||||
以此排序会让正在处理的行在列表中跳位。
|
||||
keyword 与前端池内筛选同字段集(单号/外部单号/料号/品名/来源,2026-10-16 随
|
||||
服务端分页下推),大小写不敏感子串匹配(ilike)。
|
||||
|
||||
Args:
|
||||
now: 判定时刻(默认当前时间)。
|
||||
statuses: 池内状态白名单(result_filter 切片或三态并集)。
|
||||
source_code: 可选来源过滤。
|
||||
keyword: 可选关键字(子串大小写不敏感)。
|
||||
Returns:
|
||||
BacklogItemDTO 列表。
|
||||
未排序的 SQLAlchemy Query(排序由调用方统一拼 _BACKLOG_ORDER_BY)。
|
||||
"""
|
||||
current = now or datetime.utcnow()
|
||||
query = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.status.in_([
|
||||
_BACKLOG_RECOVERABLE,
|
||||
TransferStatus.RESULT_UNKNOWN.value,
|
||||
TransferStatus.MANUALLY_CLOSED.value,
|
||||
]),
|
||||
)
|
||||
query = TransferInvoiceItem.query.filter(TransferInvoiceItem.status.in_(statuses))
|
||||
if source_code:
|
||||
query = query.filter_by(source_code=source_code)
|
||||
pool_rows = query.order_by(
|
||||
TransferInvoiceItem.receipt_date.asc().nulls_last(),
|
||||
TransferInvoiceItem.source_code.asc(),
|
||||
TransferInvoiceItem.invoice_no.asc(),
|
||||
TransferInvoiceItem.created_at.asc(),
|
||||
TransferInvoiceItem.id.asc(),
|
||||
).all()
|
||||
latest_map = _latest_attempt_times([row.id for row in pool_rows])
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
query = (
|
||||
query.outerjoin(
|
||||
TransferMovementLedger,
|
||||
TransferInvoiceItem.ledger_record_id == TransferMovementLedger.id,
|
||||
)
|
||||
.filter(or_(
|
||||
TransferInvoiceItem.invoice_no.ilike(like),
|
||||
TransferMovementLedger.external_doc_no.ilike(like),
|
||||
TransferInvoiceItem.material_no.ilike(like),
|
||||
TransferInvoiceItem.material_name.ilike(like),
|
||||
TransferInvoiceItem.source_code.ilike(like),
|
||||
))
|
||||
)
|
||||
return query
|
||||
|
||||
|
||||
# 全链路统一业务稳定键排序(异动日期→数据源→Invoice→创建时间→id 兜底)。
|
||||
_BACKLOG_ORDER_BY = (
|
||||
TransferInvoiceItem.movement_date.asc().nulls_last(),
|
||||
TransferInvoiceItem.source_code.asc(),
|
||||
TransferInvoiceItem.invoice_no.asc(),
|
||||
TransferInvoiceItem.created_at.asc(),
|
||||
TransferInvoiceItem.id.asc(),
|
||||
)
|
||||
|
||||
|
||||
def _backlog_dtos(rows: list[TransferInvoiceItem], current: datetime) -> list[BacklogItemDTO]:
|
||||
"""池行 → DTO 组装(老化判定需 Attempt 最近时间,批量单条 GROUP BY 查询)。
|
||||
|
||||
Args:
|
||||
rows: 当前页(或全量)池行,须已按业务稳定键排序。
|
||||
current: 老化判定的当前时刻。
|
||||
Returns:
|
||||
BacklogItemDTO 列表(与输入同序)。
|
||||
"""
|
||||
latest_map = _latest_attempt_times([row.id for row in rows])
|
||||
output: list[BacklogItemDTO] = []
|
||||
for item in pool_rows:
|
||||
for item in rows:
|
||||
latest = latest_map.get(item.id)
|
||||
base = latest if latest is not None else item.updated_at
|
||||
age = max(0, int((current - base).total_seconds() // 86400))
|
||||
@@ -147,39 +276,612 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
|
||||
item_id=item.id,
|
||||
source_code=item.source_code,
|
||||
invoice_no=item.invoice_no,
|
||||
external_doc_no=ledger_external_doc_no(item),
|
||||
material_no=item.material_no,
|
||||
status=item.status,
|
||||
reason=item.result_message or item.result_code or "",
|
||||
age_days=age,
|
||||
aging_level=level,
|
||||
last_attempt_at=latest.isoformat() if latest is not None else None,
|
||||
receipt_date=item.receipt_date,
|
||||
movement_date=item.movement_date,
|
||||
material_name=item.material_name,
|
||||
from_warehouse=item.from_warehouse,
|
||||
to_warehouse=item.to_warehouse,
|
||||
lot_no=item.lot_no,
|
||||
receipt_quantity=str(item.receipt_quantity) if item.receipt_quantity is not None else None,
|
||||
movement_quantity=str(item.movement_quantity) if item.movement_quantity is not None else None,
|
||||
external_quantity=str(item.external_quantity) if item.external_quantity is not None else None,
|
||||
result_code=item.result_code,
|
||||
transfer_type=transfer_type_code_of(item),
|
||||
))
|
||||
return output
|
||||
|
||||
|
||||
def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO:
|
||||
"""计算待处理池汇总计数与老化分级。"""
|
||||
items = list_backlog(now=now)
|
||||
summary = BacklogSummaryDTO()
|
||||
for item in items:
|
||||
if item.status == TransferStatus.MANUALLY_CLOSED.value:
|
||||
summary.closed_count += 1
|
||||
elif item.status == TransferStatus.RESULT_UNKNOWN.value:
|
||||
summary.unknown_count += 1
|
||||
def list_backlog(*, now: datetime | None = None, source_code: str | None = None) -> list[BacklogItemDTO]:
|
||||
"""列出待处理池项(可恢复 + 已关闭 + 结果未知)——全量(兼容口径,未分页)。
|
||||
|
||||
排序:异动日期 → 数据源 → Invoice → 创建时间(全链路统一业务稳定键,
|
||||
与可调拨明细/匹配卡视图同口径,2026-09-29 统一;与重查/恢复等操作无关)。
|
||||
不用 updated_at 排序——它是行级新鲜度时间戳,重查/恢复会刷新它,
|
||||
以此排序会让正在处理的行在列表中跳位。
|
||||
分页场景请用 list_backlog_page(2026-10-16),本函数保留供无参兼容调用。
|
||||
|
||||
Args:
|
||||
now: 判定时刻(默认当前时间)。
|
||||
source_code: 可选来源过滤。
|
||||
Returns:
|
||||
BacklogItemDTO 列表。
|
||||
"""
|
||||
current = now or datetime.utcnow()
|
||||
rows = (
|
||||
_backlog_base_query(_ALL_BACKLOG_STATUSES, source_code=source_code)
|
||||
.options(
|
||||
joinedload(TransferInvoiceItem.matching),
|
||||
joinedload(TransferInvoiceItem.ledger_record),
|
||||
)
|
||||
.order_by(*_BACKLOG_ORDER_BY)
|
||||
.all()
|
||||
)
|
||||
return _backlog_dtos(rows, current)
|
||||
|
||||
|
||||
def list_backlog_page(
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
source_code: str | None = None,
|
||||
keyword: str | None = None,
|
||||
result_filter: str = RESULT_FILTER_ALL,
|
||||
page: int = BACKLOG_PAGE_DEFAULT,
|
||||
page_size: int = BACKLOG_PAGE_SIZE_DEFAULT,
|
||||
) -> BacklogPageDTO:
|
||||
"""待处理池分页查询(2026-10-16 服务端分页 + 筛选下推)。
|
||||
|
||||
【AI 触发时机】前端待处理池视图按页/筛选拉取时经 API 调用;禁止绕过
|
||||
result_filter 白名单(fail-closed,非 all/recoverable/closed/unknown 由
|
||||
API 层 400)。筛选(result_filter/keyword)与计数口径一致:total 为
|
||||
筛选后全量计数,供前端分页器展示;老化批量查询只对当前页行执行
|
||||
(千行级池的响应规模从 O(池) 降到 O(页))。
|
||||
|
||||
Args:
|
||||
now: 判定时刻(默认当前时间)。
|
||||
source_code: 可选来源过滤。
|
||||
keyword: 可选关键字(单号/外部单号/料号/品名/来源,子串大小写不敏感)。
|
||||
result_filter: 结果切片(all/recoverable/closed/unknown)。
|
||||
page: 页码(1 起)。
|
||||
page_size: 每页行数(1..100)。
|
||||
Returns:
|
||||
BacklogPageDTO(items=当前页切片,total=筛选后全量计数)。
|
||||
"""
|
||||
current = now or datetime.utcnow()
|
||||
statuses = _RESULT_FILTER_STATUSES.get(result_filter)
|
||||
if statuses is None:
|
||||
# 防御:API 层已做白名单 400,这里兜底回三态并集(service 直调场景不炸)
|
||||
statuses = _ALL_BACKLOG_STATUSES
|
||||
base = _backlog_base_query(statuses, source_code=source_code, keyword=keyword or None)
|
||||
total = base.count()
|
||||
rows = (
|
||||
base.options(
|
||||
joinedload(TransferInvoiceItem.matching),
|
||||
joinedload(TransferInvoiceItem.ledger_record),
|
||||
)
|
||||
.order_by(*_BACKLOG_ORDER_BY)
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return BacklogPageDTO(items=_backlog_dtos(rows, current), total=total, page=page, page_size=page_size)
|
||||
|
||||
|
||||
def list_backlog_item_ids(
|
||||
*,
|
||||
source_code: str | None = None,
|
||||
keyword: str | None = None,
|
||||
result_filter: str = RESULT_FILTER_ALL,
|
||||
limit: int = BACKLOG_SELECT_ALL_MAX,
|
||||
) -> tuple[list[int], int]:
|
||||
"""跨页全选支持(2026-10-22):当前筛选下全部待处理明细 id(轻量 id 列表)。
|
||||
|
||||
【AI 触发时机】前端待处理池「选择全部 N 行」时经 API 调用——服务端分页下
|
||||
勾选集合只能覆盖当前页,本函数按同一筛选口径取全量 id 供批量操作
|
||||
(重查/恢复/关闭端点本就按 item_ids 列表逐行隔离,无需新批量契约)。
|
||||
|
||||
Args:
|
||||
source_code: 可选来源过滤。
|
||||
keyword: 可选关键字(与 list_backlog_page 同字段集)。
|
||||
result_filter: 结果切片(all/recoverable/closed/unknown)。
|
||||
limit: id 上限(防误拉超大规模池;超出截断,truncated 标记随 API 透出)。
|
||||
Returns:
|
||||
(ids, total):ids=item_id 升序列表(≤limit),total=筛选后全量计数
|
||||
(含未返回部分,供前端提示截断)。
|
||||
"""
|
||||
statuses = _RESULT_FILTER_STATUSES.get(result_filter)
|
||||
if statuses is None:
|
||||
# 防御:API 层已做白名单 400,这里兜底回三态并集(service 直调场景不炸)
|
||||
statuses = _ALL_BACKLOG_STATUSES
|
||||
base = _backlog_base_query(statuses, source_code=source_code, keyword=keyword or None)
|
||||
total = base.count()
|
||||
rows = (
|
||||
base.order_by(TransferInvoiceItem.id.asc())
|
||||
.limit(limit)
|
||||
.with_entities(TransferInvoiceItem.id)
|
||||
.all()
|
||||
)
|
||||
return [int(row[0]) for row in rows], total
|
||||
|
||||
|
||||
def _pending_match_dto(record, *, matchable_ids: set[int]) -> PendingMatchRecordDTO:
|
||||
"""把单条档行投影成待匹配清单项,并标出是否落在启用类型范围并集内。
|
||||
|
||||
本函数不做外部单号合并。合并在 _aggregate_pending_match_records。
|
||||
|
||||
Args:
|
||||
record: TransferMovementLedger 或带同名字段的行。
|
||||
matchable_ids: circle_ledger_record_ids_scope_union 的 id 集合。
|
||||
Returns:
|
||||
只读 PendingMatchRecordDTO。无 item_id。
|
||||
"""
|
||||
return PendingMatchRecordDTO(
|
||||
ledger_record_id=record.id,
|
||||
doc_no=record.doc_no,
|
||||
material_code=record.material_code,
|
||||
material_name=record.material_name,
|
||||
movement_date=record.movement_date,
|
||||
source_code=record.source_code,
|
||||
record_kind=str(getattr(record, "record_kind", None) or "inbound"),
|
||||
external_doc_no=str(getattr(record, "external_doc_no", None) or ""),
|
||||
quantity=record.quantity,
|
||||
matchable=record.id in matchable_ids,
|
||||
)
|
||||
|
||||
|
||||
def _uniform_text(values: list[object]) -> str | None:
|
||||
"""组内去掉空白后只有一个取值时返回它。
|
||||
|
||||
核心逻辑:空串不参与比较;出现第二个不同取值即视为不一致。
|
||||
|
||||
Args:
|
||||
values: 档行上的文本字段。None 与空白视为没有值。
|
||||
Returns:
|
||||
唯一非空文本;没有值或取值不一致时返回 None。
|
||||
"""
|
||||
seen: list[str] = []
|
||||
for raw in values:
|
||||
text = str(raw or "").strip()
|
||||
if not text or text in seen:
|
||||
continue
|
||||
seen.append(text)
|
||||
if len(seen) > 1:
|
||||
return None
|
||||
return seen[0] if seen else None
|
||||
|
||||
|
||||
def _sum_quantity_text(values: list[object]) -> str | None:
|
||||
"""把一组数量文本相加,输出不带多余尾零的十进制文本。
|
||||
|
||||
核心逻辑:能解析的按 Decimal 相加;全组都无法解析时保留第一条非空原文,
|
||||
避免把脏数据收成空白。
|
||||
|
||||
Args:
|
||||
values: 档上的 quantity 文本。
|
||||
Returns:
|
||||
合计文本;全空时返回 None。
|
||||
"""
|
||||
total = Decimal(0)
|
||||
seen = False
|
||||
fallback: str | None = None
|
||||
for raw in values:
|
||||
text = str(raw or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
if fallback is None:
|
||||
fallback = text
|
||||
try:
|
||||
total += Decimal(text)
|
||||
except InvalidOperation:
|
||||
continue
|
||||
seen = True
|
||||
if not seen:
|
||||
return fallback
|
||||
rendered = format(total, "f")
|
||||
if "." in rendered:
|
||||
rendered = rendered.rstrip("0").rstrip(".")
|
||||
return rendered or "0"
|
||||
|
||||
|
||||
def _pending_match_group_key(record: PendingMatchRecordDTO) -> tuple:
|
||||
"""待匹配清单的合并键。
|
||||
|
||||
有外部单号时按来源、记录类型、外部单号合并,项次不进键。
|
||||
没有外部单号时每条档单独成组,避免把互无关的行加成一笔。
|
||||
|
||||
Args:
|
||||
record: 尚未合并的单条档投影。
|
||||
Returns:
|
||||
可哈希分组键。
|
||||
"""
|
||||
external_doc_no = record.external_doc_no.strip()
|
||||
if external_doc_no:
|
||||
return ("external", record.source_code, record.record_kind, external_doc_no)
|
||||
return ("line", record.ledger_record_id)
|
||||
|
||||
|
||||
def _collapse_pending_match_group(rows: list[PendingMatchRecordDTO]) -> PendingMatchRecordDTO:
|
||||
"""把同一合并键下的档行收成清单上的一行。
|
||||
|
||||
核心逻辑:数量相加;单号、料号、品名、异动日期只在组内一致时保留。
|
||||
行键用最小档 id,保证翻页和表格行键稳定。
|
||||
|
||||
Args:
|
||||
rows: 同一组合并键下的档投影,至少一条。
|
||||
Returns:
|
||||
合并后的 PendingMatchRecordDTO。
|
||||
"""
|
||||
head = rows[0]
|
||||
external_doc_no = head.external_doc_no.strip()
|
||||
return PendingMatchRecordDTO(
|
||||
ledger_record_id=min(row.ledger_record_id for row in rows),
|
||||
doc_no=_uniform_text([row.doc_no for row in rows]) or "",
|
||||
material_code=_uniform_text([row.material_code for row in rows]),
|
||||
material_name=_uniform_text([row.material_name for row in rows]),
|
||||
movement_date=_uniform_text([row.movement_date for row in rows]),
|
||||
source_code=head.source_code,
|
||||
record_kind=head.record_kind,
|
||||
external_doc_no=external_doc_no,
|
||||
quantity=_sum_quantity_text([row.quantity for row in rows]),
|
||||
matchable=all(row.matchable for row in rows),
|
||||
)
|
||||
|
||||
|
||||
def _aggregate_pending_match_records(records: list[PendingMatchRecordDTO]) -> list[PendingMatchRecordDTO]:
|
||||
"""按外部单号合并待匹配清单,并保持档查询的先后顺序。
|
||||
|
||||
核心逻辑:沿用 pending_ledger_query 的排序(异动日期 → 来源 → 单号 → id)。
|
||||
一组的位置取该组第一条档的位置,这样同一外部单号不会被分页切开后再加总。
|
||||
|
||||
Args:
|
||||
records: 未合并的档投影,已按圈档稳定排序。
|
||||
Returns:
|
||||
合并后的清单。没有外部单号的行原样留下。
|
||||
"""
|
||||
grouped: dict[tuple, list[PendingMatchRecordDTO]] = {}
|
||||
order: list[tuple] = []
|
||||
for record in records:
|
||||
key = _pending_match_group_key(record)
|
||||
bucket = grouped.get(key)
|
||||
if bucket is None:
|
||||
grouped[key] = [record]
|
||||
order.append(key)
|
||||
else:
|
||||
summary.recoverable_count += 1
|
||||
if item.aging_level == AGING_WARN_3D:
|
||||
bucket.append(record)
|
||||
return [_collapse_pending_match_group(grouped[key]) for key in order]
|
||||
|
||||
|
||||
def _load_pending_match_records(*, segment: str, matchable_ids: set[int]) -> list[PendingMatchRecordDTO]:
|
||||
"""读取一段待匹配档并按外部单号合并。
|
||||
|
||||
分页单位是合并后的外部单,所以这里先取整段再合并,不能先按档行 limit。
|
||||
|
||||
Args:
|
||||
segment: all、matchable 或 outside。调用方已校验。
|
||||
matchable_ids: 启用类型范围并集的档 id。
|
||||
Returns:
|
||||
该段合并后的全量清单。
|
||||
"""
|
||||
rows = pending_ledger_query(matchable_ids=matchable_ids, segment=segment).all()
|
||||
return _aggregate_pending_match_records([
|
||||
_pending_match_dto(record, matchable_ids=matchable_ids) for record in rows
|
||||
])
|
||||
|
||||
|
||||
def _count_pending_match_groups(query) -> int:
|
||||
"""按清单合并键计数,不把档行装进内存。
|
||||
|
||||
核心逻辑:有外部单号(去掉首尾空白后非空)时按来源、记录类型、外部单号分组;
|
||||
没有外部单号时一行一组。分组键与 _pending_match_group_key 一致。
|
||||
查询上的排序会拿掉,否则数据库拒绝按非分组列排序。
|
||||
|
||||
Args:
|
||||
query: pending_ledger_query 的某一段。
|
||||
Returns:
|
||||
合并后的行数。
|
||||
"""
|
||||
external = func.trim(func.coalesce(TransferMovementLedger.external_doc_no, ""))
|
||||
grouped_kind = case((external != "", literal("external")), else_=literal("line"))
|
||||
grouped_source = case((external != "", TransferMovementLedger.source_code), else_=literal(""))
|
||||
grouped_record_kind = case((external != "", TransferMovementLedger.record_kind), else_=literal(""))
|
||||
grouped_doc = case((external != "", external), else_=cast(TransferMovementLedger.id, String))
|
||||
grouped = (
|
||||
query.order_by(None)
|
||||
.with_entities(grouped_kind, grouped_source, grouped_record_kind, grouped_doc)
|
||||
.group_by(grouped_kind, grouped_source, grouped_record_kind, grouped_doc)
|
||||
.subquery()
|
||||
)
|
||||
return int(db.session.query(func.count()).select_from(grouped).scalar() or 0)
|
||||
|
||||
|
||||
def _matchable_ids() -> set[int]:
|
||||
"""启用类型现在圈得住的档 id。无启用类型时为空集。只取 id,不装载整行。"""
|
||||
return circle_ledger_record_ids_scope_union()
|
||||
|
||||
|
||||
def list_pending_match_records(*, segment: str = "all") -> list[PendingMatchRecordDTO]:
|
||||
"""首页待办看板「待匹配」桶清单(已抓取尚未匹配的外部异动记录,只读)。
|
||||
|
||||
数据源=pending_ledger_query:未封存、有异动日期、未被有效 items 占用、
|
||||
movement_date ≤ T−2 的出入站记录,不按调拨类型范围过滤。
|
||||
segment=matchable 只留启用类型范围并集;segment=outside 是其余已落档。
|
||||
每行 matchable 标记并集成员,供清单把「当前可匹配」和其余行分开。
|
||||
【2026-10-22 清单收口】返回前按来源 + 记录类型 + 外部单号合并,quantity
|
||||
为组内数量之和;没有外部单号的档行不合并。首页计数走同一合并。
|
||||
数字变化口径:文件落地→涨;被匹配圈定→离开(占用);取消匹配→回归;
|
||||
执行成功→封存恒排除。停用类型只减少可匹配行,不把其余行移出本桶。
|
||||
|
||||
不可执行:记录尚未经匹配/库存核对(无 items),本桶仅提供只读清单与
|
||||
「去匹配」引导,禁止任何勾选执行入口。
|
||||
|
||||
Args:
|
||||
segment: all、matchable 或 outside。
|
||||
Returns:
|
||||
合并后的 PendingMatchRecordDTO 列表。一组的位置取其最早一条档
|
||||
(异动日期 → 来源 → 单号 → id)。
|
||||
Raises:
|
||||
ValidationError: segment 不是上述三值。
|
||||
"""
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
if segment not in _PENDING_SEGMENTS:
|
||||
raise ValidationError("segment must be all, matchable, or outside")
|
||||
return _load_pending_match_records(segment=segment, matchable_ids=_matchable_ids())
|
||||
|
||||
|
||||
def list_pending_match_records_page(
|
||||
*,
|
||||
page: int = BACKLOG_PAGE_DEFAULT,
|
||||
page_size: int = BACKLOG_PAGE_SIZE_DEFAULT,
|
||||
segment: str = "all",
|
||||
) -> PendingMatchPageDTO:
|
||||
"""「待匹配」桶分页清单(服务端分页;只读语义与全量版一致)。
|
||||
|
||||
【2026-10-22 分页下推】总数与页圈定都在 SQL 完成:total=合并键 GROUP BY
|
||||
计数(_count_pending_match_groups);本页组经 row_number 组首行锚点
|
||||
OFFSET/LIMIT 圈定(_pending_group_anchor_rows),再只召回本页组的档行做
|
||||
合并投影(_load_page_group_records)——分页单位仍是外部单,但不能先按档行
|
||||
limit(同一外部单号会被切进两页),也不能整段装载后内存切片(千行级池上
|
||||
每页都 O(全池))。
|
||||
|
||||
Args:
|
||||
page: 页码(1 起)。
|
||||
page_size: 每页行数(1..100)。
|
||||
segment: all、matchable 或 outside。
|
||||
Returns:
|
||||
PendingMatchPageDTO(records=当前页切片,total=该段合并后的行数)。
|
||||
Raises:
|
||||
ValidationError: segment 不是上述三值。
|
||||
"""
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
if segment not in _PENDING_SEGMENTS:
|
||||
raise ValidationError("segment must be all, matchable, or outside")
|
||||
matchable_ids = _matchable_ids()
|
||||
base = pending_ledger_query(matchable_ids=matchable_ids, segment=segment)
|
||||
total = _count_pending_match_groups(base)
|
||||
start = (page - 1) * page_size
|
||||
anchors = _pending_group_anchor_rows(base, offset=start, limit=page_size) if total > start else []
|
||||
records = _load_page_group_records(base, anchors, matchable_ids=matchable_ids) if anchors else []
|
||||
return PendingMatchPageDTO(
|
||||
records=records,
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
|
||||
def _pending_group_anchor_rows(base, *, offset: int, limit: int) -> list[Any]:
|
||||
"""按合并键取一页「组首行」锚点(row_number 窗口下推,不装载整段档行)。
|
||||
|
||||
核心逻辑:分区键与 _count_pending_match_groups / _pending_match_group_key
|
||||
同一口径(外部单号去空白非空=来源+记录类型+外部单号一组;否则每行一组);
|
||||
分区排序与 pending_ledger_query 的圈档稳定排序一致(异动日期→来源→单号→
|
||||
id),rn=1 即该组在清单上的第一条档——组位置语义与
|
||||
_aggregate_pending_match_records「一组的位置取其第一条档」完全一致,
|
||||
翻页顺序与全量版逐行相同。
|
||||
|
||||
Args:
|
||||
base: pending_ledger_query 的某一段(已含固定条件与分段过滤)。
|
||||
offset: 起始组数((page-1)*page_size)。
|
||||
limit: 本页组数(page_size)。
|
||||
Returns:
|
||||
锚点行列表(属性 id/movement_date/source_code/doc_no/group_kind/
|
||||
group_source/group_record_kind/group_doc),按组首行位置排序。
|
||||
"""
|
||||
external = func.trim(func.coalesce(TransferMovementLedger.external_doc_no, ""))
|
||||
group_kind = case((external != "", literal("external")), else_=literal("line"))
|
||||
group_source = case((external != "", TransferMovementLedger.source_code), else_=literal(""))
|
||||
group_record_kind = case((external != "", TransferMovementLedger.record_kind), else_=literal(""))
|
||||
group_doc = case((external != "", external), else_=cast(TransferMovementLedger.id, String))
|
||||
ledger_order = (
|
||||
TransferMovementLedger.movement_date.asc(),
|
||||
TransferMovementLedger.source_code.asc(),
|
||||
TransferMovementLedger.doc_no.asc(),
|
||||
TransferMovementLedger.id.asc(),
|
||||
)
|
||||
ranked = (
|
||||
base.order_by(None)
|
||||
.with_entities(
|
||||
TransferMovementLedger.id.label("id"),
|
||||
TransferMovementLedger.movement_date.label("movement_date"),
|
||||
TransferMovementLedger.source_code.label("source_code"),
|
||||
TransferMovementLedger.doc_no.label("doc_no"),
|
||||
group_kind.label("group_kind"),
|
||||
group_source.label("group_source"),
|
||||
group_record_kind.label("group_record_kind"),
|
||||
group_doc.label("group_doc"),
|
||||
func.row_number().over(
|
||||
partition_by=(group_kind, group_source, group_record_kind, group_doc),
|
||||
order_by=ledger_order,
|
||||
).label("rn"),
|
||||
)
|
||||
.subquery()
|
||||
)
|
||||
return (
|
||||
db.session.query(
|
||||
ranked.c.id,
|
||||
ranked.c.movement_date,
|
||||
ranked.c.source_code,
|
||||
ranked.c.doc_no,
|
||||
ranked.c.group_kind,
|
||||
ranked.c.group_source,
|
||||
ranked.c.group_record_kind,
|
||||
ranked.c.group_doc,
|
||||
)
|
||||
.filter(ranked.c.rn == 1)
|
||||
.order_by(
|
||||
ranked.c.movement_date.asc(),
|
||||
ranked.c.source_code.asc(),
|
||||
ranked.c.doc_no.asc(),
|
||||
ranked.c.id.asc(),
|
||||
)
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def _load_page_group_records(
|
||||
base,
|
||||
anchors: list[Any],
|
||||
*,
|
||||
matchable_ids: set[int],
|
||||
) -> list[PendingMatchRecordDTO]:
|
||||
"""只召回本页各组涉及的档行,复用 Python 合并投影出页内清单。
|
||||
|
||||
核心逻辑:外部单号组按 (来源, 记录类型, trim(外部单号)) 条件召回兄弟行,
|
||||
行组按锚点 id 召回;装载量只随本页组数与组内项次数增长,不受池规模影响。
|
||||
召回行沿用 _pending_match_dto + _aggregate_pending_match_records 收口,
|
||||
口径与全量版完全一致(含 matchable=组内全部行可匹配);最后按锚点顺序
|
||||
还原页序(召回顺序是档序,不是组序)。
|
||||
|
||||
Args:
|
||||
base: pending_ledger_query 的某一段(与锚点同一查询,口径天然一致)。
|
||||
anchors: _pending_group_anchor_rows 的本页锚点,非空。
|
||||
matchable_ids: 启用类型范围并集的档 id(matchable 标记用)。
|
||||
Returns:
|
||||
本页合并后的清单,顺序与锚点(组首行位置)一致。
|
||||
"""
|
||||
external_keys: list[tuple[str, str, str]] = []
|
||||
line_ids: list[int] = []
|
||||
for anchor in anchors:
|
||||
if anchor.group_kind == "external":
|
||||
external_keys.append((anchor.group_source, str(anchor.group_record_kind or "inbound"), anchor.group_doc))
|
||||
else:
|
||||
line_ids.append(anchor.id)
|
||||
conds = []
|
||||
if external_keys:
|
||||
conds.append(or_(*[
|
||||
and_(
|
||||
TransferMovementLedger.source_code == source,
|
||||
TransferMovementLedger.record_kind == record_kind,
|
||||
func.trim(func.coalesce(TransferMovementLedger.external_doc_no, "")) == doc,
|
||||
)
|
||||
for source, record_kind, doc in external_keys
|
||||
]))
|
||||
if line_ids:
|
||||
conds.append(TransferMovementLedger.id.in_(line_ids))
|
||||
rows = (
|
||||
base.filter(or_(*conds))
|
||||
.order_by(
|
||||
TransferMovementLedger.movement_date.asc(),
|
||||
TransferMovementLedger.source_code.asc(),
|
||||
TransferMovementLedger.doc_no.asc(),
|
||||
TransferMovementLedger.id.asc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
merged = _aggregate_pending_match_records([
|
||||
_pending_match_dto(row, matchable_ids=matchable_ids) for row in rows
|
||||
])
|
||||
# 页序还原:合并键与锚点分区键同构(record_kind 与 DTO 投影同样取
|
||||
# 「空回退 inbound」),据此把组序从档序纠正回组首行位置序。
|
||||
position = {
|
||||
(("external", anchor.group_source, str(anchor.group_record_kind or "inbound"), anchor.group_doc)
|
||||
if anchor.group_kind == "external" else ("line", anchor.id)): index
|
||||
for index, anchor in enumerate(anchors)
|
||||
}
|
||||
return sorted(merged, key=lambda record: position[_pending_match_group_key(record)])
|
||||
|
||||
|
||||
def _pending_match_counts() -> tuple[int, int]:
|
||||
"""首页待匹配、可匹配计数,与清单合并后的行数一致。
|
||||
|
||||
核心逻辑:在数据库里按外部单号合并键计数,不把整段档行装进 Python。
|
||||
可匹配 id 为空时直接记 0,不再扫一遍全量。
|
||||
|
||||
Returns:
|
||||
(pending_match_count, matchable_count)。
|
||||
"""
|
||||
matchable_ids = _matchable_ids()
|
||||
pending_count = _count_pending_match_groups(
|
||||
pending_ledger_query(matchable_ids=matchable_ids, segment="all"),
|
||||
)
|
||||
if not matchable_ids:
|
||||
return pending_count, 0
|
||||
matchable_count = _count_pending_match_groups(
|
||||
pending_ledger_query(matchable_ids=matchable_ids, segment="matchable"),
|
||||
)
|
||||
return pending_count, matchable_count
|
||||
|
||||
|
||||
def backlog_summary(*, now: datetime | None = None) -> BacklogSummaryDTO:
|
||||
"""计算待处理池汇总计数、老化分级与待匹配桶计数。
|
||||
|
||||
【2026-10-22 汇总下推】行桶汇总单条查询取 (status, 老化基准时刻) 轻量元组:
|
||||
老化基准=最近 Attempt 时刻(LEFT JOIN GROUP BY 子查询,与
|
||||
_latest_attempt_times 同口径),无 Attempt 回退 updated_at;三态计数与
|
||||
老化分级在 Python 单趟折叠。不再经 list_backlog 整池装载 ORM 实体(含
|
||||
matching joinedload)——千行级池上 summary 的行桶部分从 O(池) 实体 +
|
||||
Attempt 批查降到 1 条轻量查询。待匹配/可匹配计数走 _pending_match_counts
|
||||
(SQL 按外部单号合并键计数),与清单合并后的行数一致。
|
||||
|
||||
Args:
|
||||
now: 老化判定的当前时刻(默认当前时间;测试注入用)。
|
||||
Returns:
|
||||
BacklogSummaryDTO(三态计数 + warn_3d/escalate_5d/critical_7d +
|
||||
pending_match_count/matchable_count)。
|
||||
"""
|
||||
current = now or datetime.utcnow()
|
||||
summary = BacklogSummaryDTO()
|
||||
latest_attempt = (
|
||||
db.session.query(TransferAttempt.item_id, func.max(TransferAttempt.created_at).label("latest"))
|
||||
.group_by(TransferAttempt.item_id)
|
||||
.subquery()
|
||||
)
|
||||
rows = (
|
||||
db.session.query(
|
||||
TransferInvoiceItem.status,
|
||||
func.coalesce(latest_attempt.c.latest, TransferInvoiceItem.updated_at),
|
||||
)
|
||||
.outerjoin(latest_attempt, latest_attempt.c.item_id == TransferInvoiceItem.id)
|
||||
.filter(TransferInvoiceItem.status.in_(_ALL_BACKLOG_STATUSES))
|
||||
.all()
|
||||
)
|
||||
for status, base_time in rows:
|
||||
# [STEP 1] 三态计数:closed/unknown 单独计数且不进老化桶(与
|
||||
# _backlog_dtos 的 AGING_CLOSED/AGING_UNKNOWN 口径一致)。
|
||||
if status == TransferStatus.MANUALLY_CLOSED.value:
|
||||
summary.closed_count += 1
|
||||
continue
|
||||
if status == TransferStatus.RESULT_UNKNOWN.value:
|
||||
summary.unknown_count += 1
|
||||
continue
|
||||
# [STEP 2] 可恢复行的老化分级(天数算法与 _backlog_dtos 一致)。
|
||||
summary.recoverable_count += 1
|
||||
age = max(0, int((current - base_time).total_seconds() // 86400))
|
||||
level = aging_level_for(age)
|
||||
if level == AGING_WARN_3D:
|
||||
summary.warn_3d += 1
|
||||
elif item.aging_level == AGING_ESCALATE_5D:
|
||||
elif level == AGING_ESCALATE_5D:
|
||||
summary.escalate_5d += 1
|
||||
elif item.aging_level == AGING_CRITICAL_7D:
|
||||
elif level == AGING_CRITICAL_7D:
|
||||
summary.critical_7d += 1
|
||||
# [待匹配桶计数] 与行桶相互独立,并与清单外部单号合并后的行数一致。
|
||||
summary.pending_match_count, summary.matchable_count = _pending_match_counts()
|
||||
return summary
|
||||
@@ -3,7 +3,13 @@
|
||||
用途:取消尚未开始的 Invoice(cancelled),已成功单据保留、不撤销;
|
||||
原因必填;取消前后状态进入审计。
|
||||
依赖:models、status、core.errors。
|
||||
逻辑:只作用于 ready_to_execute 且未生成单据的项;终态 Run 不可取消。
|
||||
逻辑:只作用于 ready_to_execute 且未生成单据的项;终态 Run 不可取消;
|
||||
Run 转取消时其名下匹配(TransferMatching)同步转 cancelled,并按
|
||||
matching_id 圈定名下 ready 未建单行退役为 cancelled——
|
||||
【出生翻转/D17 占用释放出口(规格 §9)】出生行 run_id=None,必须按匹配
|
||||
圈定才能命中:ready 行退役(队列不再可见、执行门禁拒绝)+ 匹配→cancelled
|
||||
(阻断行不再占用其圈定的档记录),档记录随即释放、可被后续匹配
|
||||
重新圈定;取消路径不写档(占用释放由状态判定自然达成)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,7 +18,7 @@ from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.models import TransferInvoiceItem, TransferMatching, TransferRun
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
|
||||
|
||||
@@ -60,6 +66,28 @@ def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request
|
||||
).count()
|
||||
if active == 0:
|
||||
run.status = status_machine.TransferRunStatus.CANCELLED.value
|
||||
# [D17 占用释放 + 可执行行退役(规格 §9)] Run 取消时名下未终态匹配同步
|
||||
# 转 cancelled,并按 matching_id 圈定其名下 items 退役:
|
||||
# - ready 且未建单的行 → cancelled(出生行 run_id=None,必须按匹配圈定
|
||||
# 才能命中——否则取消后行仍 ready,队列双份可见、可与重圈匹配双双
|
||||
# 执行=同批档记录二次写 ERP);
|
||||
# - blocked 行保留阻断解释(不占执行面),其占用
|
||||
# 随匹配状态=cancelled 释放(占用判定见 matching_service);
|
||||
# - executing/result_unknown 行不触碰(在飞/结果裁决中,既有取消语义)。
|
||||
# 取消路径不写档(占用释放由状态判定自然达成)。
|
||||
for matching in db.session.query(TransferMatching).filter_by(run_id=run.id).all():
|
||||
if matching.status in {"success", "failed", "cancelled", "expired"}:
|
||||
continue
|
||||
matching.status = status_machine.TransferRunStatus.CANCELLED.value
|
||||
for item in db.session.query(TransferInvoiceItem).filter_by(matching_id=matching.id).all():
|
||||
if (
|
||||
item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
and not item.external_document_no
|
||||
):
|
||||
item.status = status_machine.TransferStatus.CANCELLED.value
|
||||
item.result_code = "cancelled"
|
||||
item.result_message = reason_value
|
||||
cancelled += 1
|
||||
run.completed_at = run.completed_at or datetime.utcnow()
|
||||
db.session.commit()
|
||||
return {"run_no": run.run_no, "cancelled_count": cancelled}
|
||||
@@ -14,8 +14,9 @@ from decimal import Decimal
|
||||
from typing import Iterable
|
||||
|
||||
# ---- 一期冻结错误码(TDD §7.3)-------------------------------------------
|
||||
# 【TRANSFER_INBOUND_NOT_MATURED 已退役 2026-10-16】成熟概念删除(未上线期不设
|
||||
# 兼容层);前端四语言 errors.json 同键一并移除。
|
||||
TRANSFER_PERMISSION_DENIED = "TRANSFER_PERMISSION_DENIED"
|
||||
TRANSFER_RECEIPT_NOT_MATURED = "TRANSFER_RECEIPT_NOT_MATURED"
|
||||
TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY"
|
||||
TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
|
||||
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
|
||||
@@ -32,7 +33,6 @@ TRANSFER_NOTIFICATION_FAILED = "TRANSFER_NOTIFICATION_FAILED"
|
||||
|
||||
KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
|
||||
TRANSFER_PERMISSION_DENIED,
|
||||
TRANSFER_RECEIPT_NOT_MATURED,
|
||||
TRANSFER_FILE_NOT_READY,
|
||||
TRANSFER_FILE_SCHEMA_INVALID,
|
||||
TRANSFER_INVOICE_CONFLICT,
|
||||
@@ -67,7 +67,6 @@ class MatchingCountsDTO:
|
||||
"""匹配计数。"""
|
||||
|
||||
file_invoice_count: int = 0
|
||||
not_matured_count: int = 0
|
||||
matched_count: int = 0
|
||||
executable_count: int = 0
|
||||
blocked_count: int = 0
|
||||
@@ -101,13 +100,13 @@ class MatchingItemDTO:
|
||||
to_warehouse: str
|
||||
to_quantity: Decimal
|
||||
result: str
|
||||
receipt_date: str | None = None
|
||||
movement_date: str | None = None
|
||||
reason: str = ""
|
||||
external_document_no: str | None = None
|
||||
raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple)
|
||||
lot_no: str = ""
|
||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
|
||||
receipt_warehouse_code: str = ""
|
||||
# 入站文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
|
||||
movement_warehouse_code: str = ""
|
||||
# 交易单位原值(movement 契约第 11 字段 unit,计划 D4):展示与 ERP 写入行输入,
|
||||
# 不参与匹配身份与 Hash 快照;空值行在匹配阶段落 blocked_missing_unit。
|
||||
unit: str = ""
|
||||
@@ -122,6 +121,11 @@ class MatchingItemDTO:
|
||||
# (execution_service.prepare_execution 同款 .strip() 口径)。匹配评估路径填齐,
|
||||
# 供「预计 ERP 单据数」按五元组去重与前端勾选行预估;restore 视图路径缺省 ""。
|
||||
external_org: str = ""
|
||||
# 出生匹配快照上的调拨类型 code。可调拨明细跨类型混排时用来展示类别;
|
||||
# 无匹配或快照未写类型时为空串。
|
||||
transfer_type: str = ""
|
||||
# 档上的外部单号(WMS Order #)。空串表示这行没有外部单号。
|
||||
external_doc_no: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -129,14 +133,13 @@ class MatchingSummaryDTO:
|
||||
"""匹配摘要(含预计调拨数量、预计 ERP 单据数与匹配 Hash)。
|
||||
|
||||
estimated_external_write_count(2026-10-12 口径修正):可执行行按执行建单
|
||||
五元组 (external_org, source_code, receipt_date, from_warehouse, to_warehouse)
|
||||
五元组 (external_org, source_code, movement_date, from_warehouse, to_warehouse)
|
||||
去重后的单据数,非可执行行数——同组多行在执行期合并一张 ERP 单。
|
||||
"""
|
||||
|
||||
matching_id: str
|
||||
status: str
|
||||
business_date: str
|
||||
eligible_receipt_date_to: str
|
||||
expires_at: str
|
||||
counts: MatchingCountsDTO
|
||||
estimated_transfer_quantity: str
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
"""services/in_transit_transfer/current_file_reparse.py
|
||||
|
||||
用途:对当前最新可用入站/出站归档做一次本地重解析并落档(不触发 RPA)。
|
||||
依赖:evidence_sync.sync_source_rows、outbound_evidence_sync.sync_outbound_source_rows、
|
||||
source_file_status(latest_usable_outbound_file、resolve_source_file_status)、
|
||||
freight_rpa.reports.queries(latest_usable_inbound_file、mark_inbound_parse_failure、
|
||||
mark_outbound_parse_failure)、date_policy.business_date_now、deps.get_transfer_dependencies、
|
||||
file_parser.MovementFileSchemaError、core.errors、flask.current_app(非 schema 失败记日志)。
|
||||
逻辑:先确认可用归档与已发布规则门禁,再委托既有 sync_*_source_rows 落档并 commit;
|
||||
schema 失败 rollback 后 mark 解析失败并单独 commit;无规则/无文件 fail-closed;
|
||||
其他异常(含非 NO_PROFILE 的 AppError)rollback、记日志、不标 parse_failed,返回 ok=False。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
latest_usable_inbound_file,
|
||||
mark_inbound_parse_failure,
|
||||
mark_outbound_parse_failure,
|
||||
)
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.deps import get_transfer_dependencies
|
||||
from app.services.in_transit_transfer.evidence_sync import sync_source_rows
|
||||
from app.services.in_transit_transfer.file_parser import MovementFileSchemaError
|
||||
from app.services.in_transit_transfer.outbound_evidence_sync import sync_outbound_source_rows
|
||||
from app.services.in_transit_transfer.source_file_status import (
|
||||
latest_usable_outbound_file,
|
||||
resolve_source_file_status,
|
||||
)
|
||||
|
||||
_RECORD_KINDS = frozenset({"inbound", "outbound"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CurrentReparseResult:
|
||||
"""一次当前归档重解析的返回。"""
|
||||
|
||||
source_code: str
|
||||
record_kind: str
|
||||
ok: bool
|
||||
file_status: str
|
||||
file_id: int | None
|
||||
inserted: int = 0
|
||||
updated: int = 0
|
||||
skipped: int = 0
|
||||
sealed_skipped: int = 0
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
def reparse_current_file(*, source_code: str, record_kind: str, now: datetime) -> CurrentReparseResult:
|
||||
"""重解析该来源当前最新可用归档并提交。
|
||||
|
||||
核心逻辑:先取 latest usable 文件。没有文件抛 CURRENT_REPARSE_NO_FILE。
|
||||
有文件则调用既有 sync_*_source_rows。返回 None 表示没有已发布规则,抛
|
||||
CURRENT_REPARSE_NO_PROFILE,不写 parse_failed。结构错误回滚后 mark_*_parse_failure
|
||||
并单独提交。其他异常(含非 NO_PROFILE 的 AppError,如存储不可用)只回滚、
|
||||
记 TRANSFER_CURRENT_REPARSE_FAILED 日志,不标解析失败,返回 ok=False。
|
||||
error_message 取异常 message,为空再退回 str(exc)。成功路径由 sync 函数里的
|
||||
movement_file_version 写版本戳,本函数不拼 sha256: 前缀。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
record_kind: inbound 或 outbound。
|
||||
now: 落档与新鲜度判定时刻。
|
||||
Returns:
|
||||
CurrentReparseResult。结构错误和其他落档异常(含非 NO_PROFILE 的 AppError)时 ok 为 False。
|
||||
Raises:
|
||||
ValidationError: record_kind 不是 inbound 或 outbound。
|
||||
AppError: 仅 TRANSFER.CURRENT_REPARSE_NO_FILE 或 TRANSFER.CURRENT_REPARSE_NO_PROFILE,HTTP 422。
|
||||
"""
|
||||
kind = record_kind.strip()
|
||||
if kind not in _RECORD_KINDS:
|
||||
raise ValidationError("record_kind must be inbound or outbound")
|
||||
|
||||
if kind == "outbound":
|
||||
file_view = latest_usable_outbound_file(source_code, now=now)
|
||||
else:
|
||||
file_view = latest_usable_inbound_file(source_code, now=now)
|
||||
|
||||
if file_view is None:
|
||||
raise AppError(
|
||||
code="TRANSFER.CURRENT_REPARSE_NO_FILE",
|
||||
message="no usable archive file",
|
||||
http_status=422,
|
||||
details={"source_code": source_code, "record_kind": kind},
|
||||
)
|
||||
|
||||
file_id = file_view.file_id
|
||||
|
||||
try:
|
||||
if kind == "outbound":
|
||||
outcome = sync_outbound_source_rows(source_code=source_code, now=now)
|
||||
else:
|
||||
outcome = sync_source_rows(
|
||||
source_code=source_code,
|
||||
deps=get_transfer_dependencies(),
|
||||
business_date=business_date_now(),
|
||||
now=now,
|
||||
)
|
||||
|
||||
if outcome is None:
|
||||
raise AppError(
|
||||
code="TRANSFER.CURRENT_REPARSE_NO_PROFILE",
|
||||
message="no published parsing profile",
|
||||
http_status=422,
|
||||
details={"source_code": source_code, "record_kind": kind},
|
||||
)
|
||||
|
||||
db.session.commit()
|
||||
status = resolve_source_file_status(source_code=source_code, record_kind=kind)
|
||||
return CurrentReparseResult(
|
||||
source_code=source_code,
|
||||
record_kind=kind,
|
||||
ok=True,
|
||||
file_status=str(status["file_status"]),
|
||||
file_id=file_id,
|
||||
inserted=outcome.inserted,
|
||||
updated=outcome.updated,
|
||||
skipped=outcome.skipped,
|
||||
sealed_skipped=outcome.sealed_skipped,
|
||||
)
|
||||
except MovementFileSchemaError as exc:
|
||||
db.session.rollback()
|
||||
error_message = (getattr(exc, "message", "") or str(exc))[:2000]
|
||||
error_code = exc.code
|
||||
if kind == "outbound":
|
||||
mark_outbound_parse_failure(
|
||||
file_id, error_code=error_code, error_message=error_message)
|
||||
else:
|
||||
mark_inbound_parse_failure(
|
||||
file_id, error_code=error_code, error_message=error_message)
|
||||
db.session.commit()
|
||||
status = resolve_source_file_status(source_code=source_code, record_kind=kind)
|
||||
return CurrentReparseResult(
|
||||
source_code=source_code,
|
||||
record_kind=kind,
|
||||
ok=False,
|
||||
file_status=str(status["file_status"]),
|
||||
file_id=file_id,
|
||||
error_code=error_code,
|
||||
error_message=error_message,
|
||||
)
|
||||
except Exception as exc:
|
||||
# 无已发布规则仍是 422;其余 AppError(存储不可用等)与普通异常同一失败分支。
|
||||
if isinstance(exc, AppError) and exc.code == "TRANSFER.CURRENT_REPARSE_NO_PROFILE":
|
||||
raise
|
||||
db.session.rollback()
|
||||
current_app.logger.exception(
|
||||
"TRANSFER_CURRENT_REPARSE_FAILED source=%s kind=%s",
|
||||
source_code,
|
||||
kind,
|
||||
)
|
||||
status = resolve_source_file_status(source_code=source_code, record_kind=kind)
|
||||
error_message = (getattr(exc, "message", "") or str(exc))[:500]
|
||||
return CurrentReparseResult(
|
||||
source_code=source_code,
|
||||
record_kind=kind,
|
||||
ok=False,
|
||||
file_status=str(status["file_status"]),
|
||||
file_id=file_id,
|
||||
error_code="TRANSFER.CURRENT_REPARSE_FAILED",
|
||||
error_message=error_message,
|
||||
)
|
||||
@@ -1,11 +1,15 @@
|
||||
"""在途调拨业务日期与成熟度策略。
|
||||
"""在途调拨业务日期与日期解析。
|
||||
|
||||
用途:固定业务时区 Asia/Shanghai,实现 T+lag 成熟规则(默认 T+2:收料日期 ≤ T-2
|
||||
可匹配,T-1/当天 not_matured,未来日期阻断);统一 parse_date 归一化收料日期
|
||||
(ISO + DSV SSRS 美式 MM/DD/YYYY[ HH:MM:SS])。
|
||||
依赖:标准库 zoneinfo / datetime;可选 Flask current_app(读成熟滞后配置)。
|
||||
用途:固定业务时区 Asia/Shanghai,统一 parse_date 归一化异动日期(ISO + DSV SSRS
|
||||
美式 MM/DD/YYYY[ HH:MM:SS]);提供业务日换算、UTC 存储窗口换算与可匹配
|
||||
截止日(T−2)换算。
|
||||
依赖:标准库 zoneinfo / datetime。
|
||||
逻辑:所有日期判定集中在本模块,供 matching_service / file_parser / evidence_sync
|
||||
复用,避免各服务各自计算导致口径漂移。
|
||||
【T−2 管控恢复 2026-10-21】T−2 之前的数据全部成熟,T−2 之后(T−1/当天/
|
||||
未来)无成熟数据不可进入异动日期范围——matching_service 以
|
||||
eligible_movement_date_to 卡控范围截止;未来日期阻断(数据错误)保留。
|
||||
(2026-10-16 曾随成熟规则退役放开到「截止 ≤ 业务日期」,本次按业务口径收回。)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,14 +19,9 @@ from zoneinfo import ZoneInfo
|
||||
|
||||
SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
|
||||
|
||||
# 成熟度结果
|
||||
MATURITY_ELIGIBLE = "eligible"
|
||||
MATURITY_NOT_MATURED = "not_matured"
|
||||
MATURITY_FUTURE = "future"
|
||||
|
||||
# 成熟滞后天数默认值(T+2:收料日期 ≤ T-2 才可匹配;与海外的时差余量)。
|
||||
# 可经环境变量 IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS 覆盖(settings 装载)。
|
||||
DEFAULT_MATURITY_LAG_DAYS = 2
|
||||
# 可匹配截止滞后天数:T−2 之前数据全部成熟(与前端 transferDate.ts
|
||||
# DEFAULT_LOOKBACK_DAYS 同口径,两侧须同步调整)。
|
||||
MOVEMENT_DATE_MAX_LAG_DAYS = 2
|
||||
|
||||
# DSV SSRS Date Received 常见美式格式(月/日/年,可选时分秒);%m/%d 亦接受单位数。
|
||||
_US_DATE_FORMATS = (
|
||||
@@ -35,7 +34,7 @@ _US_DATE_FORMATS = (
|
||||
def parse_date(value: date | datetime | str) -> date:
|
||||
"""将 date/datetime 或日期字符串归一化为 date。
|
||||
|
||||
核心逻辑:先认 ISO(含带时间),再认美式 MM/DD/YYYY[ HH:MM[:SS]](DSV 收料);
|
||||
核心逻辑:先认 ISO(含带时间),再认美式 MM/DD/YYYY[ HH:MM[:SS]](DSV 入站文件);
|
||||
均失败则 ValueError(fail-closed)。
|
||||
|
||||
Args:
|
||||
@@ -59,7 +58,7 @@ def parse_date(value: date | datetime | str) -> date:
|
||||
return datetime.fromisoformat(text).date()
|
||||
except ValueError:
|
||||
pass
|
||||
# [STEP] DSV SSRS 收料 Date Received:美式月/日/年(可带时分秒)。
|
||||
# [STEP] DSV SSRS 入站 Date Received:美式月/日/年(可带时分秒)。
|
||||
for fmt in _US_DATE_FORMATS:
|
||||
try:
|
||||
return datetime.strptime(text, fmt).date()
|
||||
@@ -84,6 +83,22 @@ def business_date_now(moment: datetime | None = None) -> date:
|
||||
return moment.astimezone(SHANGHAI_TZ).date()
|
||||
|
||||
|
||||
def eligible_movement_date_to(business_date: date | str,
|
||||
lag_days: int = MOVEMENT_DATE_MAX_LAG_DAYS) -> date:
|
||||
"""返回可进入异动日期范围的截止日(业务日期 T − lag 天,默认 T−2)。
|
||||
|
||||
【AI 触发时机】matching_service 校验异动日期范围、或任何需要「最远可选到
|
||||
哪天」的场景;与前端 transferDate.ts defaultMovementDate 同口径。
|
||||
|
||||
Args:
|
||||
business_date: 当前业务日期 T。
|
||||
lag_days: 截止滞后天数;缺省 MOVEMENT_DATE_MAX_LAG_DAYS。
|
||||
Returns:
|
||||
T − lag 天。
|
||||
"""
|
||||
return parse_date(business_date) - timedelta(days=lag_days)
|
||||
|
||||
|
||||
def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
|
||||
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
|
||||
|
||||
@@ -105,53 +120,3 @@ def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, dat
|
||||
.replace(tzinfo=None)
|
||||
)
|
||||
return start_utc, start_utc + timedelta(hours=24)
|
||||
|
||||
|
||||
def maturity_lag_days() -> int:
|
||||
"""读取成熟滞后天数(app 配置优先,缺省回退 DEFAULT_MATURITY_LAG_DAYS)。
|
||||
|
||||
Returns:
|
||||
成熟滞后天数 lag;无 Flask app 上下文(纯单元测试/脚本)时回退默认值,
|
||||
保持策略函数可纯调用。
|
||||
"""
|
||||
try:
|
||||
from flask import current_app
|
||||
return int(current_app.config.get(
|
||||
"IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS") or DEFAULT_MATURITY_LAG_DAYS)
|
||||
except RuntimeError: # 无 app 上下文
|
||||
return DEFAULT_MATURITY_LAG_DAYS
|
||||
|
||||
|
||||
def maturity_status(receipt_date: date | str, business_date: date | str,
|
||||
lag_days: int | None = None) -> str:
|
||||
"""按 T+lag 规则判定收料日期成熟度(默认 lag=2)。
|
||||
|
||||
Args:
|
||||
receipt_date: 收料日期。
|
||||
business_date: 当前业务日期 T。
|
||||
lag_days: 显式滞后天数;None 时读 maturity_lag_days()。
|
||||
Returns:
|
||||
'eligible'(receipt ≤ T-lag)、'not_matured'(T-lag < receipt ≤ T)或
|
||||
'future'(receipt > T,结构化阻断)。
|
||||
"""
|
||||
receipt = parse_date(receipt_date)
|
||||
business = parse_date(business_date)
|
||||
lag = maturity_lag_days() if lag_days is None else int(lag_days)
|
||||
if receipt > business:
|
||||
return MATURITY_FUTURE
|
||||
if receipt > business - timedelta(days=lag):
|
||||
return MATURITY_NOT_MATURED
|
||||
return MATURITY_ELIGIBLE
|
||||
|
||||
|
||||
def eligible_receipt_date_to(business_date: date | str, lag_days: int | None = None) -> date:
|
||||
"""返回可进入匹配的收料截止日期(业务日期 T - lag 天,默认 T-2)。
|
||||
|
||||
Args:
|
||||
business_date: 当前业务日期。
|
||||
lag_days: 显式滞后天数;None 时读 maturity_lag_days()。
|
||||
Returns:
|
||||
T - lag 天。
|
||||
"""
|
||||
lag = maturity_lag_days() if lag_days is None else int(lag_days)
|
||||
return parse_date(business_date) - timedelta(days=lag)
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
|
||||
依赖:movement_file_repository / capability_client / matching_service / models / Flask config。
|
||||
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
|
||||
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
|
||||
逻辑:默认实现直接接线真实链路 —— 入站文件行读取走 movement_file_repository
|
||||
(复用 ShippingInboundReport 归档 + inbound 解析规则,无文件/无规则时返回 None 由
|
||||
匹配走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
|
||||
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed);
|
||||
策略经 _strategy_from_config 从 Flask 配置装配——IN_TRANSIT_TRANSFER_
|
||||
@@ -18,9 +18,14 @@ from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
|
||||
from app.models import FreightRpaOnhandExternalMapping
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
get_inbound_config,
|
||||
get_inbound_parsing_profile,
|
||||
get_site,
|
||||
)
|
||||
from app.services.in_transit_transfer.capability_client import CapabilityClient
|
||||
from app.services.in_transit_transfer.movement_file_repository import ShippingReceiptFileRepository
|
||||
from app.services.in_transit_transfer.movement_file_repository import ShippingInboundFileRepository
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
RouteMapping,
|
||||
RouteNotResolvedError,
|
||||
@@ -39,7 +44,7 @@ class DefaultRouteResolver:
|
||||
|
||||
拨出库位 = 映射行的在途仓编码(in_transit_warehouse_code);拨入仓库 = 映射的
|
||||
目标仓库代码;组织 = 映射的外部组织编码。映射行按库存源识别方式选择:
|
||||
inventory_match 源优先「收料文件仓库列 == 货代仓库」精确匹配,匹配不到回退
|
||||
inventory_match 源优先「入站文件仓库列 == 货代仓库」精确匹配,匹配不到回退
|
||||
货代仓库为空的默认映射行(空库位兜底);fixed 源仅一条启用映射直接取用。
|
||||
不借用站点固定仓库(那是货代发货/库存导出链路的字段)。
|
||||
"""
|
||||
@@ -47,24 +52,29 @@ class DefaultRouteResolver:
|
||||
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
|
||||
"""按来源识别方式选择映射行并解析路由;无法归属时抛 RouteNotResolvedError。
|
||||
|
||||
【阶段 B Task 4】站点行(主键/启停/识别方式)读取改经
|
||||
freight_rpa.reports.queries.get_site 只读视图,不再引用站点模型;
|
||||
外部仓库映射仍为调拨域自有表(freight_rpa_onhand_external_mappings
|
||||
不改归属,见计划 Global Constraints),按站点主键直查。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(须启用)。
|
||||
invoice_no: Invoice 单号(当前不参与匹配,保留协议兼容)。
|
||||
warehouse_code: 收料文件「仓库」列原值(inventory_match 源的映射匹配键)。
|
||||
warehouse_code: 入站文件「仓库」列原值(inventory_match 源的映射匹配键)。
|
||||
Returns:
|
||||
RouteMapping(external_org / from_warehouse=在途仓编码 / to_warehouse)。
|
||||
Raises:
|
||||
RouteNotResolvedError: 来源不存在、无可用映射行或在途仓编码未维护。
|
||||
"""
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
site = get_site(source_code)
|
||||
if site is None or not site.enabled:
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
mappings = ShippingInventoryExternalMapping.query.filter_by(
|
||||
inventory_source_id=source.id, enabled=True,
|
||||
mappings = FreightRpaOnhandExternalMapping.query.filter_by(
|
||||
source_id=site.source_id, enabled=True,
|
||||
).all()
|
||||
selected = None
|
||||
if getattr(source, 'warehouse_resolution_mode', '') == 'inventory_match':
|
||||
# [匹配] 收料仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。
|
||||
if site.warehouse_resolution_mode == 'inventory_match':
|
||||
# [匹配] 入站仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。
|
||||
# 部分唯一索引保证同源「精确/默认」各最多一条启用映射,选择结果确定。
|
||||
key = str(warehouse_code or '').strip().upper()
|
||||
if key:
|
||||
@@ -147,7 +157,7 @@ def get_transfer_dependencies() -> TransferDeps:
|
||||
if _override is not None:
|
||||
return _override
|
||||
return TransferDeps(
|
||||
file_repository=ShippingReceiptFileRepository(),
|
||||
file_repository=ShippingInboundFileRepository(),
|
||||
rpa_trigger=_DefaultRpaTrigger(),
|
||||
route_resolver=DefaultRouteResolver(),
|
||||
capabilities=_build_capability_client(),
|
||||
@@ -156,30 +166,30 @@ def get_transfer_dependencies() -> TransferDeps:
|
||||
|
||||
|
||||
class _DefaultRpaTrigger:
|
||||
"""默认收料 RPA 触发器:委托真实触发服务(trigger_receipt_rpa)。
|
||||
"""默认入站 RPA 触发器:委托真实触发服务(trigger_inbound_rpa)。
|
||||
|
||||
真实链路 = 落单元行 + 原子写 trigger 文件;来源/收料配置缺失或 trigger
|
||||
真实链路 = 落单元行 + 原子写 trigger 文件;站点/入站配置缺失或 trigger
|
||||
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
|
||||
另在本类前置守卫:收料配置存在但未绑定已发布 movement 解析规则时
|
||||
直接返回 RPA_RECEIPT_MOVEMENT_PROFILE_MISSING,不触发徒劳抓取。
|
||||
另在本类前置守卫:入站配置存在但未绑定已发布 inbound 解析规则时
|
||||
直接返回 RPA_INBOUND_PROFILE_MISSING,不触发徒劳抓取。
|
||||
【阶段 B Task 4】守卫读取改经 freight_rpa.reports.queries 只读入口
|
||||
(get_site / get_inbound_config / get_inbound_parsing_profile)。
|
||||
"""
|
||||
|
||||
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
|
||||
from app.services.in_transit_transfer.inbound_trigger_service import trigger_inbound_rpa
|
||||
|
||||
# [守卫] 收料配置存在但未绑定已发布 movement 解析规则时,触发 RPA 必然徒劳:
|
||||
# [守卫] 入站配置存在但未绑定已发布 inbound 解析规则时,触发 RPA 必然徒劳:
|
||||
# 抓回的文件无法被 latest_ready_file 复用,匹配会反复重抓。fail-closed 返回明确错误码。
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is not None:
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
|
||||
site = get_site(source_code)
|
||||
if site is not None and site.enabled:
|
||||
config = get_inbound_config(source_code)
|
||||
if config is not None:
|
||||
profile = config.parsing_profile
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
|
||||
return {'ok': False, 'error_code': 'RPA_RECEIPT_MOVEMENT_PROFILE_MISSING'}
|
||||
profile = get_inbound_parsing_profile(source_code)
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
|
||||
return {'ok': False, 'error_code': 'RPA_INBOUND_PROFILE_MISSING'}
|
||||
|
||||
outcome = trigger_receipt_rpa(source_code=source_code, business_date=business_date, reason=reason)
|
||||
outcome = trigger_inbound_rpa(source_code=source_code, business_date=business_date, reason=reason)
|
||||
return {
|
||||
"ok": bool(outcome.get("ok")),
|
||||
"callback_id": outcome.get("callback_id"),
|
||||
|
||||
@@ -1,94 +1,331 @@
|
||||
"""services/in_transit_transfer/evidence_sync.py
|
||||
|
||||
用途:收料证据同步——把来源最新可用收料文件解析为调拨待办行(文件落地即写,
|
||||
主链路),并提供「行版本戳 vs 最新文件 sha」的对齐入口(匹配/重查兜底)。
|
||||
依赖:file_parser / invoice_aggregator / transfer_type / source_file_status /
|
||||
matching_service(_item_evaluated_sha、_latest_usable_report_file 复用)/
|
||||
contracts / models / audit。
|
||||
逻辑:一次解析写入——文件里有、本地没有 → 插入待查行;有且 sha 未变 →
|
||||
整行跳过(幂等,不续新鲜度);sha 变了证据没变 → 刷新名称/规格展示值并只换
|
||||
版本戳;证据变了(数量/批号/仓库)→ 刷新证据并重置回待查(旧库存是对旧数量
|
||||
查的,作废);历史残留 blocked_file_removed 行复现 → 无论证据变化与否无条件
|
||||
恢复待查(防御路径,2026-09-28 起同步不再新产生该码);缺席存续(只换版本戳
|
||||
到最新文件 sha,状态与结果码原样保留——收料 RPA 非全量导出,缺席≠删除;行
|
||||
复现时经 STEP 2 正常刷新)。全程零外部调用(不查 ERP、不触发 RPA);终态行
|
||||
绝不触碰,终态四元组入去重圈——同文件重落地不复活已执行行(防二次真实调拨);
|
||||
不 commit 只 flush(提交归调用方:落地桥自行 commit,匹配/重查随主事务)。
|
||||
13 状态冻结契约内表达待查态:status='matching' + result_code='pending_stock_check'。
|
||||
【解析失败分层 2026-09-29】同步成功 = 当前可用文件解析成功 → 清除其解析失败
|
||||
标记(parse_failed 三列置空,投影恢复 ready);桥入口同步失败先 rollback
|
||||
(保持桥隔离),仅 schema 类解析失败(TRANSFER_FILE_SCHEMA_INVALID /
|
||||
ReceiptFileSchemaError)把失败事实独立 commit 落到当前可用文件上。
|
||||
用途:入站证据同步——把来源最新可用入站文件(freight_rpa 入站 RPA 产物)解析并镜像落档(库存异动档
|
||||
transfer_movement_ledger,主链路),一次解析、写档不写明细。
|
||||
依赖:file_parser / ledger_sync / freight_rpa.reports.queries(最新可用归档视图
|
||||
latest_usable_inbound_file 与解析失败标记 mark/clear——只读只写入口唯一权威)/
|
||||
source_file_status(状态投影)/ contracts / audit。
|
||||
【阶段 B Task 4】文件取数不再经 matching_service._latest_usable_report_file
|
||||
(该函数已删除),改按 source_code 直调 freight_rpa.reports.queries;解析失败
|
||||
标记改按 file_id 调 mark_inbound_parse_failure / clear_inbound_parse_failure。
|
||||
逻辑:【2026-10-14 出生翻转(ADR 0001/D3/D4)】本模块不再写 transfer_invoice_items
|
||||
——items 改为匹配创建时从档圈定(见 matching_service);落地产物=档行:
|
||||
①按自然键查档不存在 → 插入(record_kind/溯源五列随行);
|
||||
②同文件重落(sha 一致)→ 幂等跳过(档无 TTL,完全不动行);
|
||||
③证据变化 → 原行更新业务镜像列 + 换溯源(ledger_sync 六分类语义);
|
||||
④文件缺席的档行保留不删(入站 RPA 非全量导出,缺席≠删除);
|
||||
⑤已执行封存行(transfer_executed=true)永不更新永不复活。
|
||||
组装口径:解析行按调拨明细粒度 (doc_no, material_code, movement_date)
|
||||
聚合为领域行(数量相加、其余取组内首行、sheet/row_no 取首行)——与旧
|
||||
items 汇总粒度一致(档断言等价于原 items 断言),保证「档 → 匹配圈定 →
|
||||
严格数量比对」的数量语义不因翻转漂移。
|
||||
全程零外部调用(不查 ERP、不触发 RPA);不 commit 只 flush(提交归调用
|
||||
方:落地桥自行 commit,匹配/重查随主事务)。
|
||||
【档自然键坍缩守卫 终审 I3】组装产物按档自然键行级六成分 (doc_no, line_no,
|
||||
line_seq, in_out_flag, carton_id, lot_no) 复检:同键批内 ≥2 行且 material_code
|
||||
不同(同单号多料号且
|
||||
行级项次全空的输入)→ 每个坍缩键写一条 ledger_natural_key_collapse 审计
|
||||
事件(结果=第二料号行被幂等吞掉,首见为准,数据行为不变)——把静默丢行
|
||||
变显式可观测;事件只在批内实际落档(inserted/updated>0)时打,幂等重落
|
||||
不重复打(防只追加审计表被同文件重落刷爆,与 ledger_sync 交叉校验事件
|
||||
同款防刷口径)。
|
||||
【解析失败分层 2026-09-29】同步成功 = 当前可用文件解析成功 → 清除其解析
|
||||
失败标记(parse_failed 三列置空);桥入口同步失败先 rollback(保持桥隔离),
|
||||
仅 schema 类解析失败(TRANSFER_FILE_SCHEMA_INVALID / MovementFileSchemaError)
|
||||
把失败事实独立 commit 落到当前可用文件上。
|
||||
【对齐入口退役 2026-10-14】align_scope_rows 已删除:匹配/重查不再对文件
|
||||
兜底重解析,改为对档对账(重查见 retry_service.requery_items 对档 reconciliation)。
|
||||
【解析口径单一化 2026-10-15(spec §6)】「原始行→档行」的解析+组装抽为模块级
|
||||
纯函数 parse_archive_to_ledger_rows:运行期本模块与维护重建
|
||||
(backlog_reparse_service 清空并重解析)共用同一实现,杜绝两套解析漂移;
|
||||
归档字节→原始行的提取段仍在 movement_file_repository._extract_movement_rows。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, Mapping
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
clear_inbound_parse_failure,
|
||||
latest_usable_inbound_file,
|
||||
mark_inbound_parse_failure,
|
||||
)
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID
|
||||
from app.services.in_transit_transfer.file_parser import ReceiptFileSchemaError, parse_movement_rows
|
||||
from app.services.in_transit_transfer.invoice_aggregator import aggregate_invoices
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
RESULT_FILE_REMOVED,
|
||||
RouteNotResolvedError,
|
||||
_item_evaluated_sha,
|
||||
_latest_usable_report_file,
|
||||
from app.services.in_transit_transfer.file_parser import (
|
||||
MovementFileSchemaError,
|
||||
ParsedMovementRow,
|
||||
parse_movement_rows,
|
||||
)
|
||||
from app.services.in_transit_transfer.source_file_status import (
|
||||
clear_receipt_parse_failure,
|
||||
record_receipt_parse_failure,
|
||||
resolve_source_file_status,
|
||||
)
|
||||
from app.services.in_transit_transfer.transfer_type import (
|
||||
TransferType,
|
||||
filter_invoices_for_type,
|
||||
from app.services.in_transit_transfer.ledger_sync import (
|
||||
RECORD_KIND_INBOUND,
|
||||
FileMeta,
|
||||
sync_ledger_rows,
|
||||
)
|
||||
|
||||
# 待查态结果码:13 状态冻结契约内的表达(status='matching' + 本结果码),
|
||||
# 表示「收料文件已落地、库存侧尚未核对」;禁用新状态值。
|
||||
# 表示「已出生/已重置、库存侧尚未核对」;禁用新状态值。出生翻转后该态出现在
|
||||
# 匹配创建的出生行(评估前置)与重查对账的证据刷新行(重置待查)。
|
||||
SYNC_RESULT_PENDING = "pending_stock_check"
|
||||
|
||||
# 终态集合与 matching_service 原地刷新口径一致:同步永不触碰既定事实。
|
||||
_TERMINAL_ITEM_STATUSES = frozenset({
|
||||
status_machine.TransferStatus.SUCCESS.value,
|
||||
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
|
||||
status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||
status_machine.TransferStatus.CANCELLED.value,
|
||||
status_machine.TransferStatus.EXECUTING.value,
|
||||
status_machine.TransferStatus.RESULT_UNKNOWN.value,
|
||||
})
|
||||
# 档自然键坍缩审计事件 kind(终审 I3 冻结字面量;仓库事件 kind 无集中常量表,
|
||||
# 行内常量惯例——ledger_sync.LEDGER_CROSS_CHECK_EVENT 同款)。与交叉校验矛盾
|
||||
# (in_out_flag 错位)分 kind:修复动作不同(前者查导出模板项次列,后者查进出
|
||||
# 库别映射),运维按 kind 检索互不干扰。
|
||||
LEDGER_NATURAL_KEY_COLLAPSE_EVENT = "ledger_natural_key_collapse"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SyncOutcome:
|
||||
"""一次来源同步的结果计数(审计与兜底日志的数据源)。"""
|
||||
"""一次来源落档的结果计数(审计与兜底日志的数据源;计数随 ledger_sync 同源,
|
||||
date_skipped(异动日期空值)在 ledger_sync 落档过滤阶段消化,不透传本层)。"""
|
||||
|
||||
source_code: str
|
||||
file_sha256: str
|
||||
inserted: int = 0 # 文件有、本地无 → 插入待查行
|
||||
refreshed: int = 0 # sha 变了、业务值没变 → 只换版本戳,状态保留
|
||||
reset_pending: int = 0 # 业务值变了 → 刷新值 + 重置待查(旧库存作废)
|
||||
absent_kept: int = 0 # 文件里缺席 → 换戳保留状态(存续:缺席≠删除,2026-09-28)
|
||||
skipped: int = 0 # sha 未变的幂等跳过;终态四元组重落地亦计入(不复活)
|
||||
inserted: int = 0 # 自然键不存在 → 插入新档行
|
||||
updated: int = 0 # 证据变化 → 原行更新业务镜像列 + 换溯源
|
||||
skipped: int = 0 # sha 未变的幂等跳过;封存行命中亦计入(sealed_skipped 另计)
|
||||
sealed_skipped: int = 0 # 封存行(transfer_executed=true):永不更新永不复活
|
||||
cross_flagged: int = 0 # record_kind 与 in_out_flag 矛盾且本次实际落档的行数
|
||||
|
||||
|
||||
def _assemble_ledger_rows(
|
||||
parsed: list[ParsedMovementRow],
|
||||
raw_rows: list[Any],
|
||||
) -> list[dict]:
|
||||
"""把解析行组装为落档领域行 dict(档断言等价于原 items 断言的粒度桥)。
|
||||
|
||||
核心逻辑:[STEP 1] 原始行按 (sheet, row_no) 建索引——ParsedMovementRow 无扩展
|
||||
字段槽位(Task 8 事实),扩展 7 字段(line_no/line_seq/in_out_flag/order_type/
|
||||
odm_*/carton_id/pallet_id 及 🔖预留)与外部单据身份(external_doc_no/
|
||||
external_line_no,2026-10-21 扩展)从原始领域行 dict 取。[STEP 2] 按调拨明细
|
||||
粒度 (doc_no, material_code, movement_date, 外部单号, 外部项次) 聚合:数量
|
||||
Decimal 相加,其余字段取组内首行,sheet_name/row_no 取首行——与旧 aggregate_
|
||||
invoices 汇总键一致,保证翻转后严格数量比对(ASN 合计 vs ERP 账面)语义不变;
|
||||
外部单据身份入聚合键(2026-10-21):不同 WMS 单号/项次的行不得数量相加折叠
|
||||
(外部身份是档自然键成分,折叠即丢行)。
|
||||
注意:原始行无「项次」且同单号多料号时,自然键 (doc_no, line_no='', ...,
|
||||
carton_id 等值, lot_no 等值) 会折叠多料号行为一条档记录(档自然键不含料号,
|
||||
规格 §4.2;carton_id/lot_no 为键成分,批内等值才折叠)——真实 WMS 导出
|
||||
携带项次列,不命中该形态;该坍缩形态由 _detect_natural_key_collapses 检测并
|
||||
落 ledger_natural_key_collapse 审计事件(终审 I3,静默丢行 → 显式可观测)。
|
||||
|
||||
Args:
|
||||
parsed: 已校验解析行(parse_movement_rows 产物)。
|
||||
raw_rows: 原始领域行 dict 列表(ReadyInboundFile.rows,扩展字段来源)。
|
||||
Returns:
|
||||
领域行 dict 列表(键=movement 契约 field code + 行级溯源 sheet_name/row_no,
|
||||
即 sync_ledger_rows 的 parsed_rows 契约)。
|
||||
"""
|
||||
raw_by_key: dict[tuple[str, Any], Mapping] = {}
|
||||
for raw in raw_rows or []:
|
||||
if not isinstance(raw, Mapping):
|
||||
continue
|
||||
raw_by_key[(str(raw.get("sheet") or "").strip(), raw.get("row_no"))] = raw
|
||||
|
||||
groups: dict[tuple[str, str, str, str, str], dict] = {}
|
||||
ordered: list[dict] = []
|
||||
for row in parsed:
|
||||
raw = raw_by_key.get((row.sheet, row.row_no)) or {}
|
||||
# 聚合键含外部单据身份(2026-10-21):不同外部单号/项次不折叠、不数量相加。
|
||||
key = (row.invoice_no, row.material_no, row.movement_date.isoformat(),
|
||||
_natural_key_text(raw.get("external_doc_no")),
|
||||
_natural_key_text(raw.get("external_line_no")))
|
||||
group = groups.get(key)
|
||||
if group is None:
|
||||
group = {
|
||||
"doc_no": row.invoice_no,
|
||||
# 无项次列的导出按空串落自然键(可空成分 NOT NULL + default '')。
|
||||
"line_no": str(raw.get("line_no") or "").strip(),
|
||||
"in_out_flag": str(raw.get("in_out_flag") or "").strip(),
|
||||
"material_code": row.material_no,
|
||||
"material_name": row.material_name,
|
||||
"specification": row.specification,
|
||||
"warehouse_code": row.warehouse_code,
|
||||
"storage_code": str(raw.get("storage_code") or "").strip(),
|
||||
"lot_no": row.lot_no,
|
||||
"quantity": Decimal(str(row.movement_quantity)),
|
||||
"unit": row.unit,
|
||||
"movement_date": row.movement_date.isoformat(),
|
||||
"line_seq": str(raw.get("line_seq") or "").strip(),
|
||||
"order_type": str(raw.get("order_type") or "").strip(),
|
||||
"odm_id": str(raw.get("odm_id") or "").strip(),
|
||||
"odm_name": str(raw.get("odm_name") or "").strip(),
|
||||
"carton_id": str(raw.get("carton_id") or "").strip(),
|
||||
"pallet_id": str(raw.get("pallet_id") or "").strip(),
|
||||
# 外部单据身份(2026-10-21 扩展:外部单号/外部项次=WMS Order #/
|
||||
# 行号)——异动档自然键成分(档幂等主键管控),缺列按空串落键。
|
||||
"external_doc_no": str(raw.get("external_doc_no") or "").strip(),
|
||||
"external_line_no": str(raw.get("external_line_no") or "").strip(),
|
||||
# 🔖预留列(出货报告确认后直接映射):入站侧照常透传原值。
|
||||
"doc_nature": str(raw.get("doc_nature") or "").strip(),
|
||||
"movement_type": str(raw.get("movement_type") or "").strip(),
|
||||
"reason_code": str(raw.get("reason_code") or "").strip(),
|
||||
"source_ref_no": str(raw.get("source_ref_no") or "").strip(),
|
||||
"partner_code": str(raw.get("partner_code") or "").strip(),
|
||||
"remark": str(raw.get("remark") or "").strip(),
|
||||
"sheet_name": row.sheet,
|
||||
"row_no": row.row_no,
|
||||
}
|
||||
groups[key] = group
|
||||
ordered.append(group)
|
||||
else:
|
||||
# [数量聚合] 同 (单号,料号,日期) 多行数量相加(与旧 items 汇总同口径)。
|
||||
group["quantity"] = group["quantity"] + Decimal(str(row.movement_quantity))
|
||||
|
||||
rows: list[dict] = []
|
||||
for group in ordered:
|
||||
flattened = dict(group)
|
||||
flattened["quantity"] = str(group["quantity"])
|
||||
rows.append(flattened)
|
||||
return rows
|
||||
|
||||
|
||||
def _natural_key_text(value: Any) -> str:
|
||||
"""自然键/料号成分归一化(与 ledger_sync._key_text 同口径):None → 空串 + strip。
|
||||
|
||||
Args:
|
||||
value: 领域行 dict 成分原值。
|
||||
Returns:
|
||||
可比对的归一化文本。
|
||||
"""
|
||||
return "" if value is None else str(value).strip()
|
||||
|
||||
|
||||
def _detect_natural_key_collapses(rows: list[dict]) -> list[dict]:
|
||||
"""检测批内档自然键坍缩(终审 I3,纯函数不改行)。
|
||||
|
||||
【AI 触发时机】sync_source_rows 组装落档前调用;不要在匹配/执行链路调用。
|
||||
判定:档自然键行级八成分 (doc_no, line_no, line_seq, in_out_flag, carton_id,
|
||||
lot_no, external_doc_no, external_line_no)(source_code/record_kind 整批恒定
|
||||
不入键;carton_id/lot_no 随 tt14 键扩维入检;外部单据身份随 2026-10-21 键
|
||||
扩维入检——批内等值才可能与既有档行同键)批内出现 ≥2 行且 material_code
|
||||
不同 → 该键坍缩(落地侧第二料号行必被幂等吞掉)。同料号多行不算坍缩(数量
|
||||
聚合合法形态,且规格 §4.2 判据即料号不同)。首见序返回,保证审计内容确定。
|
||||
|
||||
Args:
|
||||
rows: _assemble_ledger_rows 产物(成分已归一化)。
|
||||
Returns:
|
||||
坍缩键信息列表(仅含坍缩键):doc_no/line_no/line_seq/in_out_flag/
|
||||
carton_id/lot_no/external_doc_no/external_line_no + material_codes
|
||||
(首见序全量料号)+ dropped_material_codes(首见后被吞料号)。
|
||||
"""
|
||||
seen: dict[tuple[str, ...], dict] = {}
|
||||
for row in rows:
|
||||
key = (
|
||||
_natural_key_text(row.get("doc_no")),
|
||||
_natural_key_text(row.get("line_no")),
|
||||
_natural_key_text(row.get("line_seq")),
|
||||
_natural_key_text(row.get("in_out_flag")),
|
||||
_natural_key_text(row.get("carton_id")),
|
||||
_natural_key_text(row.get("lot_no")),
|
||||
_natural_key_text(row.get("external_doc_no")),
|
||||
_natural_key_text(row.get("external_line_no")),
|
||||
)
|
||||
material = _natural_key_text(row.get("material_code"))
|
||||
entry = seen.get(key)
|
||||
if entry is None:
|
||||
seen[key] = {"key": key, "materials": [material], "dropped": []}
|
||||
elif material not in entry["materials"]:
|
||||
entry["materials"].append(material)
|
||||
entry["dropped"].append(material)
|
||||
return [
|
||||
{
|
||||
"doc_no": entry["key"][0], "line_no": entry["key"][1],
|
||||
"line_seq": entry["key"][2], "in_out_flag": entry["key"][3],
|
||||
"carton_id": entry["key"][4], "lot_no": entry["key"][5],
|
||||
"external_doc_no": entry["key"][6], "external_line_no": entry["key"][7],
|
||||
"material_codes": entry["materials"],
|
||||
"dropped_material_codes": entry["dropped"],
|
||||
}
|
||||
for entry in seen.values() if entry["dropped"]
|
||||
]
|
||||
|
||||
|
||||
def _natural_key_collapse_event(*, source_code: str, collapse: dict,
|
||||
record_kind: str = RECORD_KIND_INBOUND):
|
||||
"""构造档自然键坍缩审计事件(未落库,由调用方 add——build 契约同 ledger_sync)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(自然键成分,整批一致)。
|
||||
collapse: _detect_natural_key_collapses 的单条坍缩键信息。
|
||||
record_kind: 记录类型(入站/出站共用检测口径;聚合键与快照随流声明)。
|
||||
Returns:
|
||||
已计算 Hash 的 TransferAuditEvent(event_type=ledger_natural_key_collapse,
|
||||
result='failure':数据质量降级——行被吞是既成事实,须运维介入核导出模板)。
|
||||
"""
|
||||
natural_key = "/".join((
|
||||
source_code, record_kind,
|
||||
collapse["doc_no"], collapse["line_no"], collapse["line_seq"], collapse["in_out_flag"],
|
||||
collapse["carton_id"], collapse["lot_no"],
|
||||
collapse["external_doc_no"], collapse["external_line_no"],
|
||||
))
|
||||
return build_transfer_audit_event(
|
||||
event_type=LEDGER_NATURAL_KEY_COLLAPSE_EVENT,
|
||||
aggregate_type="transfer_movement_ledger",
|
||||
# aggregate_id 列宽 String(128):超长截断防御(全量字段在 after 快照留存,
|
||||
# 与 ledger_sync._cross_check_event 同款防御)。
|
||||
aggregate_id=natural_key[:128],
|
||||
actor_type="system",
|
||||
result="failure",
|
||||
after={
|
||||
"source_code": source_code, "record_kind": record_kind,
|
||||
"doc_no": collapse["doc_no"], "line_no": collapse["line_no"],
|
||||
"line_seq": collapse["line_seq"], "in_out_flag": collapse["in_out_flag"],
|
||||
"carton_id": collapse["carton_id"], "lot_no": collapse["lot_no"],
|
||||
"external_doc_no": collapse["external_doc_no"],
|
||||
"external_line_no": collapse["external_line_no"],
|
||||
"material_codes": collapse["material_codes"],
|
||||
"dropped_material_codes": collapse["dropped_material_codes"],
|
||||
"resolution": "first_seen_wins",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def parse_archive_to_ledger_rows(*, source_code: str, rows: list[dict]) -> list[dict]:
|
||||
"""归档原始行 → 档行领域 dict 列表(解析+组装单一口径,运行期/重建共用)。
|
||||
|
||||
【AI 触发时机】运行期落档(sync_source_rows)与维护重建
|
||||
(backlog_reparse_service 清空并重解析,spec §6)在把归档原始行组装为落档
|
||||
领域行时都必须经本函数;禁止任何一方绕开自组解析(两套解析=映射漂移温床)。
|
||||
「归档字节 → 本函数入参原始行」的提取段在
|
||||
movement_file_repository._extract_movement_rows(latest_ready_file 与重建路径
|
||||
同一实现),本函数承接其后的行校验解析(parse_movement_rows)与明细粒度
|
||||
聚合组装(_assemble_ledger_rows)——两段合起来才是完整的「归档字节→档行」。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(解析行来源身份一致性校验)。
|
||||
rows: 归档原始行 dict 列表(ReadyInboundFile.rows 同构:领域字段 +
|
||||
溯源 sheet/row_no)。
|
||||
Returns:
|
||||
领域行 dict 列表(sync_ledger_rows 的 parsed_rows 契约)。
|
||||
Raises:
|
||||
MovementFileSchemaError: 任一行必填缺失/非法值(调用方按场景分层处理:
|
||||
运行期落解析失败标记;重建整体中止 TRANSFER.REPARSE_PARSE_FAILED)。
|
||||
"""
|
||||
parsed = parse_movement_rows(source_code=source_code, rows=rows)
|
||||
return _assemble_ledger_rows(parsed, rows)
|
||||
|
||||
|
||||
def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetime) -> SyncOutcome | None:
|
||||
"""解析来源最新可用收料文件并三分类写入待办行(零外部调用,flush 不 commit)。
|
||||
"""解析来源最新可用入站文件并幂等落档(零外部调用,flush 不 commit)。
|
||||
|
||||
【AI 触发时机】入站 RPA 回调桥(sync_and_commit_for_callback)与来源解析
|
||||
失败重试入口调用;不要在匹配/重查链路调用(匹配从档圈定,不写档)。
|
||||
|
||||
【解析失败分层 2026-09-29】成功返回前清除当前可用文件的解析失败标记
|
||||
(parse_failed 三列置空,来源投影恢复 ready)——能走到成功返回即代表该
|
||||
文件已成功解析;无标记时为 no-op。
|
||||
(parse_failed 三列置空)——能走到成功返回即代表该文件已成功解析;无标记时
|
||||
为 no-op。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
deps: TransferDeps(只用 file_repository 与 route_resolver)。
|
||||
deps: TransferDeps(只用 file_repository)。
|
||||
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
|
||||
now: 新鲜度基准(显式续 updated_at,执行门禁展示依据)。
|
||||
now: 落档时间基准(插入/更新显式续 updated_at)。
|
||||
Returns:
|
||||
SyncOutcome;来源无可用文件(未抓取/已过期/已清理)返回 None(该分支
|
||||
不触碰解析失败标记——没有成功解析的事实不得清除失败标记)。
|
||||
@@ -96,152 +333,46 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
|
||||
ready = deps.file_repository.latest_ready_file(source_code=source_code, business_date=business_date)
|
||||
if ready is None:
|
||||
return None
|
||||
parsed = parse_movement_rows(source_code=source_code, rows=ready.rows)
|
||||
invoices = filter_invoices_for_type(
|
||||
aggregate_invoices(parsed, file_version=ready.file_version),
|
||||
TransferType.IN_TRANSIT_TO_HUB,
|
||||
# [STEP 1] 解析+组装领域行(明细粒度聚合):经 parse_archive_to_ledger_rows
|
||||
# 单一口径(运行期与重建共用,schema 类失败原样上抛——桥内 rollback +
|
||||
# 落解析失败标记)。
|
||||
assembled = parse_archive_to_ledger_rows(source_code=source_code, rows=list(ready.rows))
|
||||
|
||||
# [STEP 2] 幂等落档;ledger_sync 只 flush 不 commit(提交归调用方:桥自行
|
||||
# commit,匹配/重查随主事务)。溯源文件 id:当前可用归档文件(Fake 仓库
|
||||
# 测试场景/文件已清理时为 None,档事实留存不依赖文件存在)。
|
||||
# 【阶段 B Task 4】文件身份改取 freight_rpa.reports.queries 只读视图(主键 file_id)。
|
||||
file_view = latest_usable_inbound_file(source_code)
|
||||
outcome = sync_ledger_rows(
|
||||
source_code=source_code,
|
||||
record_kind=RECORD_KIND_INBOUND,
|
||||
parsed_rows=assembled,
|
||||
file_meta=FileMeta(
|
||||
source_file_id=file_view.file_id if file_view is not None else None,
|
||||
file_version=ready.file_version,
|
||||
file_sha256=ready.checksum,
|
||||
),
|
||||
now=now,
|
||||
)
|
||||
# [档自然键坍缩守卫 终审 I3] 组装产物复检:同自然键批内料号不同(同单号多
|
||||
# 料号且项次全空)→ 每个坍缩键写一条审计事件(行处理不变,首见为准——把
|
||||
# 静默丢行变显式可观测)。只在批内实际落档(inserted/updated>0)时打事件:
|
||||
# 幂等重落(sha 未变全跳过)不重复打,防只追加审计表被同文件重落刷爆
|
||||
# (与 ledger_sync 交叉校验事件「矛盾标记随落档动作发生」同款防刷口径)。
|
||||
collapses = _detect_natural_key_collapses(assembled)
|
||||
if collapses and (outcome.inserted or outcome.updated):
|
||||
for collapse in collapses:
|
||||
db.session.add(_natural_key_collapse_event(
|
||||
source_code=source_code, collapse=collapse))
|
||||
result = SyncOutcome(
|
||||
source_code=source_code,
|
||||
file_sha256=ready.checksum or "",
|
||||
inserted=outcome.inserted,
|
||||
updated=outcome.updated,
|
||||
skipped=outcome.skipped,
|
||||
sealed_skipped=outcome.sealed_skipped,
|
||||
cross_flagged=outcome.cross_flagged,
|
||||
)
|
||||
|
||||
# [STEP 1] 圈定本来源全部非终态既有行,按四元组建索引(matching_id 已放开
|
||||
# 非空,落地行不受 uq_transfer_invoice_items_matching_grain 保护,幂等去重
|
||||
# 由本应用层四元组负责)。
|
||||
existing = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.source_code == source_code,
|
||||
TransferInvoiceItem.status.not_in(_TERMINAL_ITEM_STATUSES),
|
||||
).all()
|
||||
by_key = {(r.source_code, r.invoice_no, r.material_no, r.receipt_date): r for r in existing}
|
||||
|
||||
# [终态去重圈] 终态行同样纳入四元组去重范围(只查四列,轻量):若只在非终态
|
||||
# 行内去重,来源全终态后同文件重落地(同日 RPA 重试再触发落地桥 / align 兜底
|
||||
# 重解析)时 quad 缺席索引会被当全新行重插 pending——已执行的调拨单「复活」
|
||||
# 回待办池,存在以新 doc_no 二次真实执行的风险。终态不复活是冻结约束:
|
||||
# 重落地对终态行既不重插也不触碰。
|
||||
terminal_keys = {
|
||||
tuple(r)
|
||||
for r in TransferInvoiceItem.query.with_entities(
|
||||
TransferInvoiceItem.source_code,
|
||||
TransferInvoiceItem.invoice_no,
|
||||
TransferInvoiceItem.material_no,
|
||||
TransferInvoiceItem.receipt_date,
|
||||
).filter(
|
||||
TransferInvoiceItem.source_code == source_code,
|
||||
TransferInvoiceItem.status.in_(_TERMINAL_ITEM_STATUSES),
|
||||
).all()
|
||||
}
|
||||
|
||||
counters = {"inserted": 0, "refreshed": 0, "reset_pending": 0, "absent_kept": 0, "skipped": 0}
|
||||
incoming_keys: set[tuple] = set()
|
||||
|
||||
# [STEP 2] 文件内单逐张三分类:跳过 / 插入 / 刷新+重置。
|
||||
for invoice in invoices:
|
||||
receipt_date_iso = invoice.receipt_date.isoformat()
|
||||
key = (source_code, invoice.invoice_no, invoice.material_no, receipt_date_iso)
|
||||
incoming_keys.add(key)
|
||||
row = by_key.get(key)
|
||||
# [终态不复活] 该四元组已有终态行(已执行/已关闭等):同文件重落地跳过
|
||||
# 整行——不重插新 pending 行,也不触碰终态行本身(计数归 skipped 口径)。
|
||||
# 必须在插入判定之前拦截,否则全终态来源重落地会重开已执行的调拨单。
|
||||
if row is None and key in terminal_keys:
|
||||
counters["skipped"] += 1
|
||||
continue
|
||||
# [证据变化判定] 只比对收料事实(数量/批号/仓库);material_name 等展示
|
||||
# 字段不触发重置(重置会作废旧库存查询,代价是重查)。
|
||||
evidence_changed = row is None or (
|
||||
str(row.receipt_quantity) != str(invoice.receipt_quantity)
|
||||
or (row.lot_no or "") != (invoice.lot_no or "")
|
||||
or (row.receipt_warehouse_code or "") != (invoice.warehouse_code or "")
|
||||
)
|
||||
if row is not None and not evidence_changed and _item_evaluated_sha(row) == ready.checksum:
|
||||
counters["skipped"] += 1 # [幂等] 同文件重复落地:零写入(不续新鲜度)
|
||||
continue
|
||||
if row is None:
|
||||
from_wh, to_wh = _resolve_route_best_effort(deps, source_code, invoice)
|
||||
db.session.add(TransferInvoiceItem(
|
||||
matching_id=None, # 落地行尚无匹配归属(列已放开非空)
|
||||
source_code=source_code,
|
||||
invoice_no=invoice.invoice_no,
|
||||
material_no=invoice.material_no,
|
||||
material_name=invoice.material_name,
|
||||
specification=invoice.specification,
|
||||
receipt_date=receipt_date_iso,
|
||||
status=status_machine.TransferStatus.MATCHING.value,
|
||||
result_code=SYNC_RESULT_PENDING,
|
||||
result_message=None,
|
||||
from_warehouse=from_wh,
|
||||
to_warehouse=to_wh,
|
||||
receipt_quantity=str(invoice.receipt_quantity),
|
||||
external_quantity=None,
|
||||
lot_no=invoice.lot_no or "",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
unit="", # 单位只取 ERP stock_unit,匹配查询时落列
|
||||
raw_lines_json=[
|
||||
{"sheet": line.sheet, "row_no": line.row_no,
|
||||
"file_version": line.file_version, "file_sha256": ready.checksum}
|
||||
for line in invoice.raw_lines
|
||||
],
|
||||
updated_at=now,
|
||||
))
|
||||
counters["inserted"] += 1
|
||||
continue
|
||||
# [Important② 复现行] 历史残留消失标记行(blocked_file_removed)重新出现
|
||||
# 在最新文件:无论证据变化与否都必须恢复待查态——其历史解释(文件里消失)
|
||||
# 已失效;若只换戳不恢复,行卡在 blocked 且对齐入口直通,永久隐藏。
|
||||
# 非终态行恢复不违反终态冻结。历史残留行防御(2026-09-28 起同步不再新产生该码)。
|
||||
restored_from_removed = row.result_code == RESULT_FILE_REMOVED
|
||||
# [版本戳] 行随最新文件版本刷新(复现行与普通行同路径换新戳,对齐入口
|
||||
# 据此收敛直通)。
|
||||
row.raw_lines_json = [
|
||||
{"sheet": line.sheet, "row_no": line.row_no,
|
||||
"file_version": line.file_version, "file_sha256": ready.checksum}
|
||||
for line in invoice.raw_lines
|
||||
]
|
||||
# [Important① 展示字段] 名称/规格属展示字段:进入非跳过分支即刷新
|
||||
# (放在证据分支判断之外)——是否重置待查只由三证据字段决定,避免纯
|
||||
# 名称变更落入 refreshed 后展示值随新戳固化(align 直通后永不更新)。
|
||||
row.material_name = invoice.material_name
|
||||
row.specification = invoice.specification
|
||||
if evidence_changed:
|
||||
# [STEP 3] 收料事实变化:刷新证据值(数量/批号/仓库)。
|
||||
row.receipt_quantity = str(invoice.receipt_quantity)
|
||||
row.lot_no = invoice.lot_no or ""
|
||||
row.receipt_warehouse_code = invoice.warehouse_code or ""
|
||||
if evidence_changed or restored_from_removed:
|
||||
# [重置/恢复] 值变 → 重置回待查(旧库存是对旧数量查的,作废);
|
||||
# 复现行 → 恢复待查(重新进入待办池,计数同归 reset_pending 口径)。
|
||||
row.status = status_machine.TransferStatus.MATCHING.value
|
||||
row.result_code = SYNC_RESULT_PENDING
|
||||
row.result_message = None
|
||||
row.external_quantity = None # 旧库存对旧数量,作废待重查
|
||||
# [库存查得时刻] 库存作废即置空取数时刻(不变式:本字段=当前
|
||||
# external_quantity 的取数时间;NULL=无库存数据,stale 不判定)。
|
||||
row.inventory_checked_at = None
|
||||
counters["reset_pending"] += 1
|
||||
else:
|
||||
counters["refreshed"] += 1
|
||||
# refreshed/absent_kept 只换文件版本戳——本分支不续期 inventory_checked_at
|
||||
#(2026-09-29 起 stale 判定时钟,换戳≠查过库存),仅 updated_at 照常续期。
|
||||
row.updated_at = now
|
||||
|
||||
# [STEP 4] 文件里缺席的非终态行 → 存续处理(2026-09-28 语义升级):收料 RPA
|
||||
# 导出非全量,缺席≠删除(行业存续原则)——保留原 status/result_code/message,
|
||||
# 只把版本戳换到最新文件 sha(保留 sheet/row_no 行定位):对齐入口 row_shas
|
||||
# 收敛直通、执行门禁②继续放行(历史行不会被 TRANSFER.FILE_CHANGED 死锁)。
|
||||
# 行日后复现时 evaluated_sha≠新文件 sha,自然走 STEP 2 刷新/重置分支;真实
|
||||
# 删除由人工关闭兜底(待处理池 3/5/7 天老化防遗忘)。终态行不在 by_key,
|
||||
# 绝不触碰。
|
||||
for key, row in by_key.items():
|
||||
if key in incoming_keys:
|
||||
continue
|
||||
row.raw_lines_json = [
|
||||
{**line, "file_version": ready.file_version, "file_sha256": ready.checksum}
|
||||
for line in (row.raw_lines_json or [])
|
||||
]
|
||||
row.updated_at = now
|
||||
counters["absent_kept"] += 1
|
||||
|
||||
# [STEP 5] 只 flush 不 commit:落地桥自行 commit,匹配/重查随主事务。
|
||||
db.session.flush()
|
||||
outcome = SyncOutcome(source_code=source_code, file_sha256=ready.checksum or "", **counters)
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_EVIDENCE_SYNCED",
|
||||
aggregate_type="transfer_source",
|
||||
@@ -249,92 +380,38 @@ def sync_source_rows(*, source_code: str, deps, business_date: str, now: datetim
|
||||
actor_type="system",
|
||||
result="success",
|
||||
after={
|
||||
"file_sha256": outcome.file_sha256,
|
||||
"inserted": outcome.inserted, "refreshed": outcome.refreshed,
|
||||
"reset_pending": outcome.reset_pending, "absent_kept": outcome.absent_kept,
|
||||
"skipped": outcome.skipped,
|
||||
"file_sha256": result.file_sha256,
|
||||
"record_kind": RECORD_KIND_INBOUND,
|
||||
"inserted": result.inserted, "updated": result.updated,
|
||||
"skipped": result.skipped, "sealed_skipped": result.sealed_skipped,
|
||||
"cross_flagged": result.cross_flagged,
|
||||
},
|
||||
))
|
||||
# [解析失败分层 2026-09-29] 同步成功 = 当前可用文件已成功解析:清除其解析
|
||||
# 失败标记(若此前失败过),来源状态投影随之恢复 ready。查询口径与
|
||||
# source_file_status 一致(_latest_usable_report_file);只 flush 不 commit,
|
||||
# 提交归调用方(桥自行 commit / 匹配随主事务)。无可用 ORM 文件(Fake
|
||||
# 仓库测试场景/文件已清理)时为 no-op。
|
||||
report = _latest_usable_report_file(source_code)
|
||||
if report is not None and report.parse_failed_at is not None:
|
||||
clear_receipt_parse_failure(report=report)
|
||||
return outcome
|
||||
|
||||
|
||||
def align_scope_rows(*, source_codes: list[str], deps, business_date: str, now: datetime) -> dict:
|
||||
"""兜底对齐入口:行版本戳 ≠ 最新文件 sha 的来源才重新解析(一致直通零开销)。
|
||||
|
||||
【AI 触发时机】:匹配(run_matching STEP 0)与重查(requery_* STEP 0)调用;
|
||||
落地同步(主链路)失败的静默兜底——稳态下 sha 一致,本函数零解析直通。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例编码列表。
|
||||
deps: TransferDeps(透传 sync_source_rows)。
|
||||
business_date: 业务日期(文件新鲜度口径)。
|
||||
now: 新鲜度基准。
|
||||
Returns:
|
||||
{source_code: SyncOutcome|None};None=已对齐或无可用文件(未解析)。
|
||||
"""
|
||||
outcomes: dict = {}
|
||||
for code in source_codes:
|
||||
latest = resolve_source_file_status(source_code=code) or {}
|
||||
latest_sha = latest.get("file_sha256")
|
||||
if not latest_sha:
|
||||
outcomes[code] = None
|
||||
continue
|
||||
rows = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.source_code == code,
|
||||
TransferInvoiceItem.status.not_in(_TERMINAL_ITEM_STATUSES),
|
||||
).all()
|
||||
row_shas = {_item_evaluated_sha(r) for r in rows}
|
||||
if row_shas == {latest_sha}:
|
||||
outcomes[code] = None # 已对齐:直通
|
||||
continue
|
||||
outcomes[code] = sync_source_rows(source_code=code, deps=deps,
|
||||
business_date=business_date, now=now)
|
||||
return outcomes
|
||||
|
||||
|
||||
def _resolve_route_best_effort(deps, source_code: str, invoice) -> tuple[str, str]:
|
||||
"""同步期预解析路由落列(纯配置查表);解析失败留空不阻断(匹配时再解析)。
|
||||
|
||||
Args:
|
||||
deps: TransferDeps(只用 route_resolver)。
|
||||
source_code: 来源实例编码。
|
||||
invoice: AggregatedInvoice(取 invoice_no / warehouse_code)。
|
||||
Returns:
|
||||
(from_warehouse, to_warehouse);未配置路由返回 ("", "")。
|
||||
"""
|
||||
try:
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=source_code, invoice_no=invoice.invoice_no,
|
||||
warehouse_code=invoice.warehouse_code or "",
|
||||
)
|
||||
return route.from_warehouse, route.to_warehouse
|
||||
except RouteNotResolvedError:
|
||||
return "", ""
|
||||
# 失败标记(若此前失败过),来源状态投影随之恢复 ready。只 flush 不 commit,
|
||||
# 提交归调用方。无可用归档时为 no-op。
|
||||
if file_view is not None and file_view.parse_failed_at is not None:
|
||||
clear_inbound_parse_failure(file_view.file_id)
|
||||
return result
|
||||
|
||||
|
||||
def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: datetime) -> bool:
|
||||
"""收料回调桥专用入口:同步 + 自行 commit + 异常全吞(仅 warning 日志)。
|
||||
"""入站回调桥专用入口:落档 + 自行 commit + 异常全吞(仅 warning 日志)。
|
||||
|
||||
【AI 触发时机】:收料 RPA 回调 success 终态落文件后由
|
||||
shipping_notice.receipt_report_storage 的桥函数调用——桥是记账不是收料链路
|
||||
的正确性依赖,任何异常不得向收料归档主链路传播(B3:必须自行 commit)。
|
||||
【AI 触发时机】:入站 RPA 回调 success 终态落文件后由
|
||||
shipping_notice 域 ShippingInboundReport 归档存储的桥函数调用——桥是记账
|
||||
不是入站链路的正确性依赖,任何异常不得向 ShippingInboundReport 归档主链路传播(B3:必须自行 commit)。
|
||||
【解析失败分层 2026-09-29】失败路径先 rollback(桥隔离),仅 schema 类
|
||||
解析失败把失败事实(parse_failed 三列)独立 commit 落到当前可用文件上。
|
||||
解析失败把失败事实(parse_failed 三列)独立 commit 落到当前可用文件上;
|
||||
丢失的落档由回调重试/来源「重试 RPA」入口(本地重解析)兜底
|
||||
(原 align 兜底入口已随对档对账切换退役)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(收料单元行上的 source_code)。
|
||||
source_code: 来源实例编码(入站单元行上的 source_code)。
|
||||
business_date: 业务日期(文件仓库「当天抓取」新鲜度口径)。
|
||||
now: 新鲜度基准(显式续 updated_at)。
|
||||
now: 落档时间基准。
|
||||
Returns:
|
||||
True=同步成功或无事可做(无可用文件);False=同步失败(已记日志;
|
||||
True=落档成功或无事可做(无可用文件);False=落档失败(已记日志;
|
||||
schema 类失败尽力把解析失败标记落库并独立提交,标记失败仅告警不影响返回)。
|
||||
"""
|
||||
from flask import current_app
|
||||
@@ -344,37 +421,37 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
|
||||
business_date=business_date, now=now)
|
||||
# [桥隔离] sync_source_rows 只 flush 不 commit;桥由回调主链路在归档
|
||||
# commit 之后独立调用,提交时机不归调用方管(B3 持久性教训),必须
|
||||
# 在此自行提交,否则请求结束 session 回滚会丢掉已解析的待办行。
|
||||
# 在此自行提交,否则请求结束 session 回滚会丢掉已解析的档行。
|
||||
db.session.commit()
|
||||
if outcome is not None:
|
||||
current_app.logger.info(
|
||||
"TRANSFER_EVIDENCE_SYNC source=%s inserted=%s refreshed=%s reset=%s absent=%s skipped=%s",
|
||||
source_code, outcome.inserted, outcome.refreshed,
|
||||
outcome.reset_pending, outcome.absent_kept, outcome.skipped)
|
||||
"TRANSFER_EVIDENCE_SYNC source=%s inserted=%s updated=%s skipped=%s sealed=%s cross=%s",
|
||||
source_code, outcome.inserted, outcome.updated,
|
||||
outcome.skipped, outcome.sealed_skipped, outcome.cross_flagged)
|
||||
return True
|
||||
except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志(见模块 docstring「落地桥」)
|
||||
# [桥隔离] 为什么吞异常:桥是记账不是收料链路的正确性依赖,同步崩溃
|
||||
# 绝不允许波及收料归档终态;丢失的同步由对齐入口 align_scope_rows 兜底。
|
||||
# [桥隔离] 为什么吞异常:桥是记账不是入站链路的正确性依赖,落档崩溃
|
||||
# 绝不允许波及 ShippingInboundReport 归档终态;丢失的落档由回调重试/人工重取兜底。
|
||||
current_app.logger.warning(
|
||||
"TRANSFER_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc)
|
||||
db.session.rollback()
|
||||
# [解析失败分层 2026-09-29] rollback 之后再写标记,避免脏会话污染写路径;
|
||||
# 仅 schema 类失败(TRANSFER_FILE_SCHEMA_INVALID / ReceiptFileSchemaError)
|
||||
# 仅 schema 类失败(TRANSFER_FILE_SCHEMA_INVALID / MovementFileSchemaError)
|
||||
# 落库——通用异常(网络/DB 故障等)不是文件解析问题,不落标记。标记写入后
|
||||
# 独立 commit(B3:桥自行提交;同步数据已回滚,本次 commit 只持久化失败
|
||||
# 独立 commit(B3:桥自行提交;落档数据已回滚,本次 commit 只持久化失败
|
||||
# 事实),桥隔离语义保持,仍返回 False。
|
||||
# [取消息] AppError 为 dataclass(kwargs 初始化)str() 为空串:按 _matching_rows
|
||||
# 同款兜底链取 message 字段,保证落库的错误信息可用于诊断。
|
||||
# 标记写入是尽力而为:查询/落库/提交若再抛异常(如 DB 抖动)也必须吞掉,
|
||||
# B3(任何异常不得向收料归档主链路传播)优先于标记落库,丢失标记由下次重试补。
|
||||
# B3(任何异常不得向 ShippingInboundReport 归档主链路传播)优先于标记落库,丢失标记由下次重试补。
|
||||
try:
|
||||
code = getattr(exc, "code", None) or ""
|
||||
if code == TRANSFER_FILE_SCHEMA_INVALID or isinstance(exc, ReceiptFileSchemaError):
|
||||
if code == TRANSFER_FILE_SCHEMA_INVALID or isinstance(exc, MovementFileSchemaError):
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
report = _latest_usable_report_file(source_code)
|
||||
if report is not None:
|
||||
record_receipt_parse_failure(
|
||||
report=report,
|
||||
file_view = latest_usable_inbound_file(source_code)
|
||||
if file_view is not None:
|
||||
mark_inbound_parse_failure(
|
||||
file_view.file_id,
|
||||
error_code=str(code or TRANSFER_FILE_SCHEMA_INVALID),
|
||||
error_message=str(detail)[:2000],
|
||||
)
|
||||
@@ -386,7 +463,7 @@ def sync_and_commit_for_callback(*, source_code: str, business_date: str, now: d
|
||||
|
||||
|
||||
def _default_deps():
|
||||
"""装配默认 TransferDeps(桥入口专用:收料链路无 deps 可透传)。
|
||||
"""装配默认 TransferDeps(桥入口专用:入站链路无 deps 可透传)。
|
||||
|
||||
Returns:
|
||||
TransferDeps(测试经 deps._override 注入 Fake 时返回注入值)。
|
||||
|
||||
@@ -82,12 +82,12 @@ def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInv
|
||||
def _sheet_blocked(workbook: Workbook, items: list[TransferInvoiceItem], sheet_name: str, codes: set[str]) -> None:
|
||||
"""按阻断原因归类 Sheet。"""
|
||||
sheet = workbook.create_sheet(sheet_name)
|
||||
sheet.append(["Invoice", "来源", "料号", "收料数量", "外部系统 数量", "原因"])
|
||||
sheet.append(["Invoice", "来源", "料号", "异动数量", "外部系统 数量", "原因"])
|
||||
for item in items:
|
||||
if (item.result_code or "") in codes or item.status in codes:
|
||||
sheet.append([
|
||||
item.invoice_no, item.source_code, item.material_no,
|
||||
item.receipt_quantity, item.external_quantity or "",
|
||||
item.movement_quantity, item.external_quantity or "",
|
||||
item.result_message or item.result_code or item.status,
|
||||
])
|
||||
|
||||
|
||||
@@ -2,15 +2,20 @@
|
||||
|
||||
用途:在途调拨执行服务(单据级重构 + D8 异步拆分):API 同步段 prepare_execution
|
||||
只做门禁 + 建 queued Run + D1 五元组分组建单 + 一次入队;worker 段
|
||||
execute_run 二次门禁复核后逐单执行(final_only 判定 → 非 final_only 写前
|
||||
execute_run 逐单执行(final_only 判定 → 非 final_only 写前
|
||||
库存复查(漂移行 fail-closed 移出本单)→ create_transfer(business_ref=doc_no
|
||||
透传,调用日志按单号锚定)→ 六态落位);
|
||||
retrigger_document 是 result_unknown 单的唯一人工出口(D11)。
|
||||
依赖:orchestrator、capability_client(TransferOrder/StockTarget)、quantity
|
||||
(classify_quantity_match)、document_id、contracts、audit、status、
|
||||
source_file_status、matching_service(门禁/scope/路由契约)、
|
||||
jobs.queue(TRANSFER_RUN 入队)、models。
|
||||
逻辑:防双单锚定「doc_no + submit_timestamp 终身成对复用」(D3/D7):提交时按
|
||||
matching_service(scope/路由契约)、jobs.queue(TRANSFER_RUN 入队)、models。
|
||||
逻辑:执行门禁只做存在性校验(行可执行 + 匹配未取消)。文件版本对账门禁
|
||||
(TRANSFER.FILE_CHANGED,API 侧整批拒绝 + worker 侧整 Run 落败)已于
|
||||
2026-10-22 退役——入站抓取是部分导出,新文件不含旧行 ≠ 旧行失效,按
|
||||
最新文件 sha 对账会错误卡死未处理行;写前安全由逐单执行的写前库存
|
||||
复查(_recheck_stock_for_document,按实时 ERP 账面严格相等核对)承担,
|
||||
行级「文件已更新」徽标保留为纯提示(matching_service._item_dto)。
|
||||
防双单锚定「doc_no + submit_timestamp 终身成对复用」(D3/D7):提交时按
|
||||
五元组建单,同组存在失败单则复用其单号/时间戳全量重跑(doc.run_id 改指新
|
||||
Run,现任归属语义),存在 result_unknown/executing 单则阻断新行
|
||||
(group_order_unresolved);部分唯一索引竞态以 SAVEPOINT + 复用重查重试
|
||||
@@ -37,6 +42,7 @@ from app.models import (
|
||||
TransferDocument,
|
||||
TransferInvoiceItem,
|
||||
TransferMatching,
|
||||
TransferMovementLedger,
|
||||
TransferRun,
|
||||
User,
|
||||
)
|
||||
@@ -56,10 +62,9 @@ from app.services.in_transit_transfer.matching_service import (
|
||||
RESULT_EXECUTABLE,
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
_item_evaluated_sha,
|
||||
scope_item_query,
|
||||
item_external_lot_no,
|
||||
ledger_external_doc_no,
|
||||
)
|
||||
from app.services.in_transit_transfer.movement_contract import external_lot_no
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.orchestrator import (
|
||||
create_execution_run_for_items,
|
||||
@@ -68,7 +73,11 @@ from app.services.in_transit_transfer.orchestrator import (
|
||||
# 单投影统一走公共序列化(Task 17 重构:serializers.serialize_order 为唯一契约源;
|
||||
# serializers 不再顶层引用本模块,无循环导入)。
|
||||
from app.services.in_transit_transfer.serializers import serialize_order
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
|
||||
# [测试补丁锚点] 文件版本对账门禁已退役(2026-10-22),本模块不再消费此符号;
|
||||
# 保留导入仅为存量测试替身(conftest.patch_source_file_status 等 monkeypatch)
|
||||
# 的目标地址不变。新代码禁止再消费——门禁语义见 _gated_items docstring。
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status # noqa: F401
|
||||
|
||||
ITEM_EXECUTION_ERROR_RESULT = "item_execution_error"
|
||||
# D7① 附加守卫:同组存在未了结单时新行的阻断原因码。
|
||||
@@ -122,19 +131,23 @@ def _item_result_of(item: TransferInvoiceItem) -> str:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _gated_items(*, item_ids: list[int], deps: TransferDeps) -> list[TransferInvoiceItem]:
|
||||
"""执行两道门禁(顺序校验,命中即抛、后续不执行,fail-closed 零写入)。
|
||||
"""执行存在性门禁(命中即抛、后续不执行,fail-closed 零写入)。
|
||||
|
||||
门禁:
|
||||
① 存在且可执行:id 存在且 status == ready_to_execute,否则
|
||||
ValidationError(code="TRANSFER.EXECUTE_ITEMS_INVALID")。
|
||||
② 文件版本对账:行评估版本戳(_item_evaluated_sha)≠ 来源最新可用文件
|
||||
sha(含来源无可用文件/行无版本戳)→ ValidationError(code="TRANSFER.FILE_CHANGED")。
|
||||
ValidationError(code="TRANSFER.EXECUTE_ITEMS_INVALID");所属匹配已
|
||||
取消的行一并拒绝(防御性双保险,规格 §9)。
|
||||
|
||||
[2026-09-25 TTL 退役] 原门禁②「行级新鲜度(updated_at 距 now 超过
|
||||
confirm_ttl_seconds → TRANSFER.ITEMS_STALE)」已删除:匹配 10 分钟后必被拒
|
||||
是 2026-09-24 事故的死锁根因;TTL 降级为纯展示阈值(stale 徽标,见
|
||||
matching_service._item_dto),防错由本函数门禁②的文件版本对账 + worker
|
||||
写前库存复查(_execute_document 的 _recheck_stock_for_document)承担。
|
||||
[2026-09-25 TTL 退役] 原门禁「行级新鲜度(updated_at 距 now 超过
|
||||
confirm_ttl_seconds → TRANSFER.ITEMS_STALE)」删除:匹配 10 分钟后必被拒
|
||||
是 2026-09-24 事故的死锁根因;TTL 降级为纯展示阈值(stale 徽标)。
|
||||
[2026-10-22 文件版本对账门禁退役] 原「行评估 sha ≠ 证据流最新可用文件 sha
|
||||
→ TRANSFER.FILE_CHANGED 整批拒绝」删除:入站抓取是**部分导出**——新文件
|
||||
不含某行 ≠ 该行失效/已处理,按「最新文件 sha」对账会把大量未处理行错误
|
||||
卡死(业务实测 557 行积压被卡)。证据变化的保护下沉两层:①行级「文件
|
||||
已更新」徽标(file_current=false,仅提示不拦截,见 matching_service
|
||||
_item_dto);②worker 写前库存复查(_recheck_stock_for_document)——按
|
||||
实时 ERP 账面严格相等核对,数量/批号漂移的行在写前被行级阻断,不会错写。
|
||||
|
||||
Returns:
|
||||
去重并保持首现顺序的可执行行列表。
|
||||
@@ -151,34 +164,32 @@ def _gated_items(*, item_ids: list[int], deps: TransferDeps) -> list[TransferInv
|
||||
).all()
|
||||
by_id = {row.id: row for row in rows}
|
||||
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
# [防御性双保险(规格 §9)] 所属匹配已取消的行不得执行:取消路径已把匹配
|
||||
# 名下 ready 行退役,此处按匹配状态再拒一次(防绕过取消路径的状态组合)。
|
||||
from app.models import TransferMatching as _Matching
|
||||
|
||||
row_matching_ids = {row.matching_id for row in rows if row.matching_id is not None}
|
||||
cancelled_matching_ids: set[int] = set()
|
||||
if row_matching_ids:
|
||||
cancelled_matching_ids = {
|
||||
mid for (mid,) in (
|
||||
db.session.query(_Matching.id)
|
||||
.filter(_Matching.id.in_(row_matching_ids), _Matching.status == "cancelled")
|
||||
.all()
|
||||
)
|
||||
}
|
||||
invalid = [
|
||||
i for i in ordered_ids
|
||||
if by_id.get(i) is None or by_id[i].status != ready_status
|
||||
if by_id.get(i) is None
|
||||
or by_id[i].status != ready_status
|
||||
or by_id[i].matching_id in cancelled_matching_ids
|
||||
]
|
||||
if invalid:
|
||||
raise ValidationError(
|
||||
"items not executable", code="TRANSFER.EXECUTE_ITEMS_INVALID",
|
||||
details={"invalid_item_ids": invalid},
|
||||
)
|
||||
items = [by_id[i] for i in ordered_ids]
|
||||
|
||||
# [门禁②] 文件版本对账(按去重来源投影最新可用文件,行评估 sha 必须一致)。
|
||||
latest_files: dict[str, dict] = {
|
||||
source_code: resolve_source_file_status(source_code=source_code)
|
||||
for source_code in sorted({item.source_code for item in items})
|
||||
}
|
||||
changed = []
|
||||
for item in items:
|
||||
evaluated_sha = _item_evaluated_sha(item)
|
||||
latest = latest_files.get(item.source_code) or {}
|
||||
if not evaluated_sha or evaluated_sha != latest.get("file_sha256"):
|
||||
changed.append(item.id)
|
||||
if changed:
|
||||
raise ValidationError(
|
||||
"source receipt file changed since evaluation", code="TRANSFER.FILE_CHANGED",
|
||||
details={"changed_item_ids": changed},
|
||||
)
|
||||
return items
|
||||
return [by_id[i] for i in ordered_ids]
|
||||
|
||||
|
||||
def prepare_execution(
|
||||
@@ -197,7 +208,7 @@ def prepare_execution(
|
||||
|
||||
核心逻辑:[STEP 1] 两道门禁(见 _gated_items);[STEP 2] 建 queued Run 并关联
|
||||
行(orchestrator);[STEP 3] 写前路由解析取 external_org,按 D1 五元组
|
||||
(external_org, source_code, receipt_date, from_warehouse, to_warehouse,全部
|
||||
(external_org, source_code, movement_date, from_warehouse, to_warehouse,全部
|
||||
.strip() 规范化)分组建单(_ensure_document:新建/复用/阻断三分支);
|
||||
[STEP 4] TRANSFER_RUN {run_id, item_ids} 恰入队一次 → 返回 queued 摘要。
|
||||
|
||||
@@ -223,13 +234,13 @@ def prepare_execution(
|
||||
for item in items:
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
warehouse_code=item.movement_warehouse_code or "",
|
||||
)
|
||||
org = str(route.external_org or "").strip()
|
||||
key = (
|
||||
org,
|
||||
str(item.source_code or "").strip(),
|
||||
str(item.receipt_date or "").strip(),
|
||||
str(item.movement_date or "").strip(),
|
||||
str(item.from_warehouse or "").strip(),
|
||||
str(item.to_warehouse or "").strip(),
|
||||
)
|
||||
@@ -302,7 +313,7 @@ def _ensure_document(
|
||||
) -> tuple[TransferDocument | None, list[TransferInvoiceItem]]:
|
||||
"""D7① 三分支组建单:同组无单新建 / 失败单复用 / result_unknown·executing 阻断。
|
||||
|
||||
组键 = D1 五元组(external_org, source_code, receipt_date, from_warehouse,
|
||||
组键 = D1 五元组(external_org, source_code, movement_date, from_warehouse,
|
||||
to_warehouse,全部 .strip() 规范化)。
|
||||
|
||||
分支语义:
|
||||
@@ -322,7 +333,7 @@ def _ensure_document(
|
||||
Returns:
|
||||
(单或 None, 处理后的 items)——分支③返回 (None, blocked items)。
|
||||
"""
|
||||
org, source_code, receipt_date, from_wh, to_wh = group_key
|
||||
org, source_code, movement_date, from_wh, to_wh = group_key
|
||||
|
||||
def _live() -> TransferDocument | None:
|
||||
"""查同组未完结单(no_autoflush 防止半建对象提前落库干扰判定)。"""
|
||||
@@ -331,7 +342,7 @@ def _ensure_document(
|
||||
TransferDocument.query.filter(
|
||||
TransferDocument.source_code == source_code,
|
||||
TransferDocument.external_org == org,
|
||||
TransferDocument.receipt_date == receipt_date,
|
||||
TransferDocument.movement_date == movement_date,
|
||||
TransferDocument.from_warehouse == from_wh,
|
||||
TransferDocument.to_warehouse == to_wh,
|
||||
TransferDocument.status.in_(UNRESOLVED_DOC_STATUSES),
|
||||
@@ -347,7 +358,7 @@ def _ensure_document(
|
||||
# [分支①] 新建 pending 单(D2/D3 幂等锚一次生成终身复用)。
|
||||
doc = TransferDocument(
|
||||
run_id=run.id, source_code=source_code, external_org=org,
|
||||
receipt_date=receipt_date, from_warehouse=from_wh, to_warehouse=to_wh,
|
||||
movement_date=movement_date, from_warehouse=from_wh, to_warehouse=to_wh,
|
||||
doc_no=next_document_no(org, sequence_loader=_sequence_loader),
|
||||
submit_timestamp=new_submit_timestamp(),
|
||||
status="pending",
|
||||
@@ -485,13 +496,12 @@ def execute_run(
|
||||
run.status = status_machine.TransferRunStatus.EXECUTING.value
|
||||
run.started_at = run.started_at or datetime.utcnow()
|
||||
db.session.flush()
|
||||
if doc_id is None:
|
||||
# [二次门禁] 文件 Hash 复核(fail-closed):失败则整 Run 落败,零外部写入。
|
||||
failure = _recheck_gates(run, deps)
|
||||
if failure is not None:
|
||||
_mark_recheck_failed(run, docs, failure)
|
||||
db.session.commit()
|
||||
return run.status
|
||||
# [2026-10-22 文件版本对账门禁退役] 原 worker 二次门禁 _recheck_gates(文件
|
||||
# Hash 复核失败 → 整 Run technical_failed 零写入)随 API 侧门禁②一并退役:
|
||||
# 入站抓取是部分导出,新文件不含旧行 ≠ 旧行失效,按最新文件 sha 对账会错误
|
||||
# 卡死未处理行。写前安全由逐单执行的写前库存复查(_execute_document 的
|
||||
# _recheck_stock_for_document)独立承担——按实时 ERP 账面严格相等核对,
|
||||
# 数量/批号漂移的行在写前被行级阻断,不会错写。
|
||||
# [逐单执行] 单间失败隔离:单单异常落 technical_failed,不影响其他单。
|
||||
for doc in docs:
|
||||
try:
|
||||
@@ -513,62 +523,6 @@ def execute_run(
|
||||
return run.status
|
||||
|
||||
|
||||
def _recheck_gates(run: TransferRun, deps: TransferDeps) -> tuple[str, str] | None: # noqa: ARG001 —— 本函数只做文件 Hash 门禁;库存写前复查在 _execute_document(_recheck_stock_for_document)
|
||||
"""worker 二次门禁复核(文件 Hash),返回 None 表示通过。
|
||||
|
||||
[2026-09-25 TTL 退役] 原新鲜度复核(updated_at 距 now 超过
|
||||
confirm_ttl_seconds → items_stale 整 Run 落败)已删除:worker 排队/等待
|
||||
超 10 分钟即被拒是 2026-09-24 事故的死锁根因;TTL 降级为纯展示阈值
|
||||
(stale 徽标),写前安全由文件版本对账(本函数)+ 逐单执行的写前库存
|
||||
复查(_recheck_stock_for_document)承担。
|
||||
|
||||
Args:
|
||||
run: 执行 Run(其关联行即本次执行范围)。
|
||||
deps: 注入依赖(文件门禁不消费外部能力,仅为签名对称保留)。
|
||||
Returns:
|
||||
None=通过;否则 (原因码, 原因消息)。
|
||||
"""
|
||||
items = [
|
||||
item for item in run.items
|
||||
if item.status in (
|
||||
status_machine.TransferStatus.EXECUTING.value,
|
||||
status_machine.TransferStatus.READY_TO_EXECUTE.value,
|
||||
)
|
||||
]
|
||||
latest_files: dict[str, dict] = {
|
||||
source_code: resolve_source_file_status(source_code=source_code)
|
||||
for source_code in sorted({item.source_code for item in items})
|
||||
}
|
||||
for item in items:
|
||||
evaluated_sha = _item_evaluated_sha(item)
|
||||
latest = latest_files.get(item.source_code) or {}
|
||||
if not evaluated_sha or evaluated_sha != latest.get("file_sha256"):
|
||||
return ("file_changed", "source receipt file changed since evaluation")
|
||||
return None
|
||||
|
||||
|
||||
def _mark_recheck_failed(run: TransferRun, docs: list[TransferDocument], failure: tuple[str, str]) -> None:
|
||||
"""二次门禁失败落位(fail-closed):单 technical_failed、行阻断、Run failed。"""
|
||||
code, message = failure
|
||||
for doc in docs:
|
||||
# [P2-1] pending(未起跑)与 executing(上次 worker 中途搁浅)统一落
|
||||
# technical_failed:零外部写入;stage 已成的单后续全量重跑由 stage SQL
|
||||
# DELETE 同时间戳幂等兜底;落失败态使其可被 D18 关闭释放组锁,不留悬挂。
|
||||
if doc.status in ("pending", "executing"):
|
||||
doc.status = "technical_failed"
|
||||
doc.error_code = code
|
||||
doc.error_message = message
|
||||
blocked_status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
for item in run.items:
|
||||
if item.status not in _PROTECTED_ITEM_STATUSES and item.status != blocked_status:
|
||||
item.status = blocked_status
|
||||
item.result_code = code
|
||||
item.result_message = message
|
||||
run.status = status_machine.TransferRunStatus.FAILED.value
|
||||
run.completed_at = run.completed_at or datetime.utcnow()
|
||||
db.session.flush()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 逐单执行(计划 [STEP 1-4] 伪码逐字落实)
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -584,7 +538,7 @@ def _recheck_stock_for_document(
|
||||
|
||||
【为什么】TTL 门禁退役(2026-09-25)后写前安全的最后防线:匹配到 worker 执行
|
||||
之间存在时间窗,账面可能已被其他业务挪用/清零;在 create_transfer 之前按
|
||||
「收料数量 == 账面」严格相等再裁一次,防止对错误数量建单。
|
||||
「异动数量 == 账面」严格相等再裁一次,防止对错误数量建单。
|
||||
【为什么不复查 final_only】result_unknown/executing 续跑(final_only=True)单
|
||||
可能已在 ERP 建成,D7② 只触发末步——此时任何阻断都是假失败,故调用方保证
|
||||
final_only 路径不进入本函数。
|
||||
@@ -606,18 +560,18 @@ def _recheck_stock_for_document(
|
||||
"""
|
||||
grouped: dict[str, list[tuple[TransferInvoiceItem, RouteMapping]]] = {}
|
||||
for item in items:
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
# [外部形态 + 仓库定义] 行级路由解析叠加行所属匹配类型的仓库定义
|
||||
# (fixed 覆盖映射档);批号经匹配快照转换规则派生(与匹配/重查同一口径)。
|
||||
from app.services.in_transit_transfer.retry_service import _route_for_item
|
||||
|
||||
route = _route_for_item(deps, item)
|
||||
grouped.setdefault(str(route.external_org or "").strip(), []).append((item, route))
|
||||
kept: list[TransferInvoiceItem] = []
|
||||
for external_org, entries in grouped.items():
|
||||
# [外部形态] 写前复查与匹配/重查同一批号派生口径(movement_contract.external_lot_no)。
|
||||
targets = [
|
||||
StockTarget(
|
||||
material_no=item.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(item.lot_no),
|
||||
lot_no=item_external_lot_no(item),
|
||||
)
|
||||
for item, route in entries
|
||||
]
|
||||
@@ -632,7 +586,7 @@ def _recheck_stock_for_document(
|
||||
for item, route in entries:
|
||||
row = stock.lookup_row(
|
||||
material_no=item.material_no,
|
||||
warehouse_code=route.from_warehouse, lot_no=external_lot_no(item.lot_no),
|
||||
warehouse_code=route.from_warehouse, lot_no=item_external_lot_no(item),
|
||||
)
|
||||
# [库存查得时刻] 写前复查是真实取数:无论查无/漂移/通过,随后落定的
|
||||
# external_quantity 都以本次取数为准(stale 判定时钟,见 _item_dto)。
|
||||
@@ -644,7 +598,7 @@ def _recheck_stock_for_document(
|
||||
item.result_message = "external inventory not found (write recheck)"
|
||||
item.external_quantity = "0"
|
||||
continue
|
||||
if classify_quantity_match(Decimal(item.receipt_quantity), row.quantity) != RESULT_EXECUTABLE:
|
||||
if classify_quantity_match(Decimal(item.movement_quantity), row.quantity) != RESULT_EXECUTABLE:
|
||||
# 数量漂移:原位刷新最新账面并移出本单(fail-closed,不写 ERP)。
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = "blocked_quantity_mismatch"
|
||||
@@ -695,7 +649,7 @@ def _execute_document(
|
||||
continue # 人工关闭/取消行不复活(D18 语义:人工决定不被自动覆盖)。
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
warehouse_code=item.movement_warehouse_code or "",
|
||||
)
|
||||
if (
|
||||
route.from_warehouse != item.from_warehouse
|
||||
@@ -746,8 +700,8 @@ def _execute_document(
|
||||
external_org=doc.external_org,
|
||||
doc_no=doc.doc_no,
|
||||
submit_timestamp=doc.submit_timestamp,
|
||||
# D1:制单日期(gls_cm06)必须等于组收料日期;过账日期=执行当天业务日。
|
||||
doc_date=doc.receipt_date,
|
||||
# D1:制单日期(gls_cm06)必须等于组异动日期;过账日期=执行当天业务日。
|
||||
doc_date=doc.movement_date,
|
||||
posting_date=str(business_date_now()),
|
||||
from_warehouse=doc.from_warehouse,
|
||||
to_warehouse=doc.to_warehouse,
|
||||
@@ -852,21 +806,21 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
||||
ERP 行粒度 = 物料+批号:同单同料号同批号跨 Invoice 聚合为一行,数量按
|
||||
Decimal 精确相加后取 6 位小数;客户端行数量为数值型(能力 Schema number,
|
||||
且须可 JSON 序列化进引擎审计),快照文本(6 位小数字符串)随 D14 留档。
|
||||
行内附带 invoice_no 溯源(逗号连接,供测试替身/排障;ERP 契约无此字段,
|
||||
真实绑定未映射即透传为惰性键)。
|
||||
行内附带 invoice_no 与 external_doc_no 溯源(各自逗号连接,供清单展示与排障;
|
||||
ERP 契约无这两字段,真实绑定未映射即透传为惰性键)。
|
||||
|
||||
Returns:
|
||||
行 dict 列表:line_no/material_no/from_warehouse/to_warehouse/lot_no/
|
||||
quantity/unit/invoice_no/quantity_text(quantity_text 仅供快照,调用方裁剪)。
|
||||
quantity/unit/invoice_no/external_doc_no/quantity_text(quantity_text 仅供快照,调用方裁剪)。
|
||||
"""
|
||||
grouped: dict[tuple[str, str, str, str], list[TransferInvoiceItem]] = {}
|
||||
for item in items:
|
||||
# [外部形态] 聚合键批号按 WTP→HOW 派生(movement_contract.external_lot_no):
|
||||
# ERP 行粒度=外部批号身份,同一 ERP 批次不得因 WMS 前缀形态差异拆行;
|
||||
# 行下传 lot_no(key[1])随键即为外部形态。
|
||||
# [外部形态] 聚合键批号经行所属匹配快照转换规则派生(类型配置驱动,
|
||||
# 如 WTP→HOW):ERP 行粒度=外部批号身份,同一 ERP 批次不得因 WMS 前缀
|
||||
# 形态差异拆行;行下传 lot_no(key[1])随键即为外部形态,行落库保持原值。
|
||||
key = (
|
||||
str(item.material_no or "").strip(),
|
||||
external_lot_no(item.lot_no),
|
||||
item_external_lot_no(item),
|
||||
str(item.from_warehouse or "").strip(),
|
||||
str(item.to_warehouse or "").strip(),
|
||||
)
|
||||
@@ -874,10 +828,13 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
||||
lines: list[dict] = []
|
||||
for index, key in enumerate(sorted(grouped), start=1):
|
||||
group = grouped[key]
|
||||
total = sum((Decimal(item.receipt_quantity) for item in group), Decimal("0"))
|
||||
total = sum((Decimal(item.movement_quantity) for item in group), Decimal("0"))
|
||||
quantity = total.quantize(_QUANTITY_QUANT)
|
||||
unit = next((str(item.unit or "").strip() for item in group if str(item.unit or "").strip()), "")
|
||||
invoices = ",".join(sorted({item.invoice_no for item in group}))
|
||||
external_docs = ",".join(sorted({
|
||||
doc for item in group if (doc := ledger_external_doc_no(item))
|
||||
}))
|
||||
lines.append({
|
||||
"line_no": index,
|
||||
"material_no": key[0],
|
||||
@@ -887,6 +844,7 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
||||
"quantity": float(quantity),
|
||||
"unit": unit,
|
||||
"invoice_no": invoices,
|
||||
"external_doc_no": external_docs,
|
||||
"quantity_text": f"{quantity:.6f}",
|
||||
})
|
||||
return lines
|
||||
@@ -922,15 +880,47 @@ def _order_snapshot(*, run_no: str, order: TransferOrder, final_only: bool, line
|
||||
}
|
||||
|
||||
|
||||
def _seal_ledger_records(items: list[TransferInvoiceItem], *, executed_doc_no: str | None) -> None:
|
||||
"""档级封存回写(规格 §9 防二次执行的档级兜底)。
|
||||
|
||||
【AI 触发时机】仅 _apply_result 的 success/duplicate_success 分支调用——票据
|
||||
执行成功落 ERP 单号时,把单内行关联的档记录置 transfer_executed=true +
|
||||
executed_doc_no。失败/未知态不得调用(执行未成事实,记录仍可被圈定、
|
||||
仍应可见于待匹配桶)。幂等:等值重复回写无副作用(封存位布尔语义,首次/
|
||||
末次等效,复用单 duplicate_success 重跑恒封存);行无档关联(遗留行)跳过。
|
||||
回写只 flush 不 commit(随调用方事务,与六态落位同生命周期)。
|
||||
|
||||
Args:
|
||||
items: 本单(或遗留单行路径)参与落位的行集。
|
||||
executed_doc_no: 回写单号(ERP 单号优先,缺失回退平台单号;为空直接跳过)。
|
||||
"""
|
||||
if not executed_doc_no:
|
||||
return
|
||||
record_ids = {item.ledger_record_id for item in items if item.ledger_record_id is not None}
|
||||
if not record_ids:
|
||||
return
|
||||
records = (
|
||||
db.session.query(TransferMovementLedger)
|
||||
.filter(TransferMovementLedger.id.in_(record_ids))
|
||||
.all()
|
||||
)
|
||||
for record in records:
|
||||
record.transfer_executed = True
|
||||
record.executed_doc_no = executed_doc_no
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _apply_result(*, doc: TransferDocument | None, items: list[TransferInvoiceItem], attempt: TransferAttempt, result: Any) -> None:
|
||||
"""按写结果六态落位单、行与 Attempt(result_unknown 为终态,禁止自动重试)。
|
||||
|
||||
六态落位(D7②/D11):
|
||||
- success / duplicate_success → 单与行推进成功族 + ERP 单号一致。
|
||||
- success / duplicate_success → 单与行推进成功族 + ERP 单号一致;
|
||||
并档级封存回写(_seal_ledger_records:items 关联档记录
|
||||
transfer_executed=true + executed_doc_no,规格 §9 防二次执行)。
|
||||
- result_unknown → 单/行 result_unknown 终态(唯一出口 = 人工 retrigger)。
|
||||
- business_failed / technical_failed → 行 blocked_recoverable
|
||||
(R6 裁决后非末步超时/失败已由引擎归 technical_failed),单保留失败态
|
||||
待人工关闭(D18)或复用重跑(D7①②)。
|
||||
待人工关闭(D18)或复用重跑(D7①②);档记录不封存(未成事实)。
|
||||
"""
|
||||
attempt.response_summary_json = {
|
||||
"status": result.status,
|
||||
@@ -950,6 +940,14 @@ def _apply_result(*, doc: TransferDocument | None, items: list[TransferInvoiceIt
|
||||
item.external_document_no = result.document_no
|
||||
item.result_code = None
|
||||
item.result_message = None
|
||||
# [档级封存回写(规格 §9)] 票据成功落 ERP 单号即封存其档记录:
|
||||
# 防同一外部入站记录经新匹配二次执行;圈档/待匹配桶/队列的固定条件
|
||||
# transfer_executed=false 恒排除已封存记录。幂等等值覆盖(复用单重跑恒封存)。
|
||||
_seal_ledger_records(
|
||||
items,
|
||||
executed_doc_no=str(result.document_no or "").strip()
|
||||
or (doc.doc_no if doc is not None else None),
|
||||
)
|
||||
attempt.status = "success"
|
||||
elif result.status == "result_unknown":
|
||||
for item in items:
|
||||
@@ -1116,7 +1114,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r
|
||||
# [遗留兜底] 路由复查 → 单行临时单 → 写 Attempt → 调用 → 行级六态落位。
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
warehouse_code=item.movement_warehouse_code or "",
|
||||
)
|
||||
if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse:
|
||||
_mark_recheck_blocked(item, "matching_expired", "route mapping changed since matching")
|
||||
@@ -1126,7 +1124,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r
|
||||
external_org=str(route.external_org or "").strip(),
|
||||
doc_no=f"LEGACY-{item.id}",
|
||||
submit_timestamp=new_submit_timestamp(),
|
||||
doc_date=item.receipt_date or "",
|
||||
doc_date=item.movement_date or "",
|
||||
posting_date=str(business_date_now()),
|
||||
from_warehouse=item.from_warehouse,
|
||||
to_warehouse=item.to_warehouse,
|
||||
@@ -1204,10 +1202,10 @@ def execute_matching_items(
|
||||
actor_id: int | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> ExecuteOutcome:
|
||||
"""按匹配 scope 圈定 ready 行并按单执行(chat action / 自动排程共用入口)。
|
||||
"""按匹配自有 items 圈定 ready 行并按单执行(chat action / 自动排程共用入口)。
|
||||
|
||||
行归属与匹配解耦(原地刷新)后,"这份匹配覆盖哪些行"由 scope 重新圈定
|
||||
(scope_item_query:来源 + 收料日期区间 + 调拨类型前缀);本入口按 scope 取
|
||||
【出生翻转】行由匹配创建时从档圈定且创建即绑定(matching_id),"这份匹配
|
||||
覆盖哪些行"=自有 items(scope_item_query 实时圈行已退役);本入口按匹配取
|
||||
ready_to_execute 行(可选 invoice_nos 过滤)后委托 execute_items 执行,
|
||||
两道门禁与单据级组建单由 execute_items/prepare_execution 统一裁定。
|
||||
|
||||
@@ -1222,8 +1220,11 @@ def execute_matching_items(
|
||||
raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND")
|
||||
ready_status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
ready_rows = (
|
||||
scope_item_query(matching)
|
||||
.filter(TransferInvoiceItem.status == ready_status)
|
||||
TransferInvoiceItem.query
|
||||
.filter(
|
||||
TransferInvoiceItem.matching_id == matching.id,
|
||||
TransferInvoiceItem.status == ready_status,
|
||||
)
|
||||
.order_by(TransferInvoiceItem.id.asc())
|
||||
.all()
|
||||
)
|
||||
@@ -1277,15 +1278,16 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
|
||||
material_name=item.material_name,
|
||||
specification=item.specification,
|
||||
invoice_no=item.invoice_no,
|
||||
receipt_date=item.receipt_date,
|
||||
external_doc_no=ledger_external_doc_no(item),
|
||||
movement_date=item.movement_date,
|
||||
from_warehouse=item.from_warehouse,
|
||||
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
||||
to_warehouse=item.to_warehouse,
|
||||
to_quantity=Decimal(item.receipt_quantity),
|
||||
to_quantity=Decimal(item.movement_quantity),
|
||||
result=result,
|
||||
reason=item.result_message or "",
|
||||
external_document_no=item.external_document_no,
|
||||
receipt_warehouse_code=item.receipt_warehouse_code or "",
|
||||
movement_warehouse_code=item.movement_warehouse_code or "",
|
||||
# T7 交接补齐:交易单位原值透传(执行结果视图 unit 不再恒空,计划 D4)。
|
||||
unit=str(item.unit or ""),
|
||||
))
|
||||
@@ -1305,7 +1307,7 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
|
||||
reason=result,
|
||||
# 行级人话原因(阻断单号等),前端优先展示、状态码标签兜底。
|
||||
message=str(item.result_message or "").strip(),
|
||||
facts=f"收料 {item.receipt_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""),
|
||||
facts=f"异动 {item.movement_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""),
|
||||
))
|
||||
return RunResultDTO(
|
||||
run_no=run.run_no,
|
||||
@@ -1363,7 +1365,7 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]:
|
||||
(D9,无独立进度卡);逐单亮 ERP 单号与状态徽标。
|
||||
|
||||
核心逻辑:[STEP 1] 按 run_id 取单(复用单 run_id 指现任 Run,投影不丢),
|
||||
展示序对齐可调拨明细/待处理池口径(2026-09-29 统一):收料日期 → 数据源 →
|
||||
展示序对齐可调拨明细/待处理池口径(2026-09-29 统一):异动日期 → 数据源 →
|
||||
拨出/拨入库位升序,created_at/id 兜底稳定排序(跨数据源不再按建单序出现
|
||||
日期乱序);[STEP 2] 每单行集取自单挂接行(document_id →
|
||||
items,复用单新旧行全量),按 ERP 行粒度(物料+批号+拨出/拨入库位,与
|
||||
@@ -1375,7 +1377,7 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]:
|
||||
|
||||
Returns:
|
||||
orders 数组(计划 Task 11 JSON 规格逐键 + T13-3 控制器裁决扩充):
|
||||
[{doc_no, receipt_date, from_warehouse, to_warehouse, status,
|
||||
[{doc_no, movement_date, from_warehouse, to_warehouse, status,
|
||||
erp_document_no, error_message, lines: [{invoice_no, material_no,
|
||||
material_name, lot_no, quantity(6 位小数字符串), unit, reason}]}]。
|
||||
行 reason 契约(框线图失败行原因展示,偏离 Task 11 五键字面属控制器裁决):
|
||||
@@ -1387,7 +1389,7 @@ def serialize_run_orders(run: TransferRun) -> list[dict[str, Any]]:
|
||||
docs = (
|
||||
TransferDocument.query.filter_by(run_id=run.id)
|
||||
.order_by(
|
||||
TransferDocument.receipt_date.asc(),
|
||||
TransferDocument.movement_date.asc(),
|
||||
TransferDocument.source_code.asc(),
|
||||
TransferDocument.from_warehouse.asc(),
|
||||
TransferDocument.to_warehouse.asc(),
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""services/in_transit_transfer/field_transforms.py
|
||||
|
||||
用途:调拨类型字段转换规则引擎——「外部系统值→ERP 值」的受控派生
|
||||
(一期仅 lot_no 前缀替换),只在系统边界生效;行与档保持文件原值。
|
||||
依赖:app.core.errors.ValidationError。
|
||||
逻辑:parse 校验白名单 → TransformRule 元组;apply 按序链式派生(未命中恒等)。
|
||||
【AI 触发时机】任何把行上字段值发往外部系统或按派生值聚合/展示的场景
|
||||
(库存查询 targets、写前复查、建单单行、票行聚合键、前端批号展示),
|
||||
必须经本引擎按当前匹配快照的规则求值;禁止直接调用硬编码前缀转换。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Sequence
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
# 受控字段/转换方式词表(封闭可扩展;新增须同步管理页下拉与 technical.md)。
|
||||
TRANSFORM_FIELDS: frozenset[str] = frozenset({"lot_no"})
|
||||
TRANSFORM_OPS: frozenset[str] = frozenset({"prefix_replace"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransformRule:
|
||||
"""单条转换规则:field 字段 / op 转换方式 / source 原前缀 / target 新前缀。"""
|
||||
|
||||
field: str
|
||||
op: str
|
||||
source: str
|
||||
target: str
|
||||
|
||||
|
||||
def parse_transform_rules(raw: list[dict] | None) -> tuple[TransformRule, ...]:
|
||||
"""校验并解析转换规则 JSON;空列表/None = 恒等(无转换)。
|
||||
|
||||
Args:
|
||||
raw: [{"field", "op", "source", "target"}],来自调拨类型配置 JSON;
|
||||
空列表/None 合法(= 该类型不做字段转换)。
|
||||
Returns:
|
||||
TransformRule 元组(source/target 统一大写,保证匹配口径一致)。
|
||||
Raises:
|
||||
ValidationError: field 不在 TRANSFORM_FIELDS、op 不在 TRANSFORM_OPS、
|
||||
或 source/target 为空(code=TRANSFER.TRANSFORM_RULE_INVALID)。
|
||||
"""
|
||||
rules: list[TransformRule] = []
|
||||
for item in raw or []:
|
||||
field, op = str(item.get("field", "")), str(item.get("op", ""))
|
||||
source, target = str(item.get("source", "")), str(item.get("target", ""))
|
||||
if field not in TRANSFORM_FIELDS or op not in TRANSFORM_OPS or not source or not target:
|
||||
raise ValidationError(
|
||||
f"invalid transform rule: {field}/{op}", code="TRANSFER.TRANSFORM_RULE_INVALID",
|
||||
details={"field": field, "op": op},
|
||||
)
|
||||
rules.append(TransformRule(field=field, op=op, source=source.upper(), target=target.upper()))
|
||||
return tuple(rules)
|
||||
|
||||
|
||||
def apply_field_transforms(field: str, value: str | None, rules: Sequence[TransformRule]) -> str | None:
|
||||
"""按规则序链式派生;未命中规则恒等返回原值(None/空串透传)。
|
||||
|
||||
Args:
|
||||
field: 行字段名(仅 TRANSFORM_FIELDS 内的字段会被规则命中)。
|
||||
value: 该字段当前原值(来自行/档,永不被本函数改写——只返回新值)。
|
||||
rules: parse_transform_rules 产出的规则元组,按配置序链式生效。
|
||||
Returns:
|
||||
派生后的新值;None 与空串原样透传(不做前缀替换)。
|
||||
"""
|
||||
result = value
|
||||
for rule in rules:
|
||||
if rule.field != field or not result:
|
||||
continue
|
||||
if rule.op == "prefix_replace" and result.upper().startswith(rule.source):
|
||||
result = rule.target + result[len(rule.source):]
|
||||
return result
|
||||
|
||||
|
||||
def transform_rules_note(rules: Sequence[TransformRule]) -> str:
|
||||
"""转换规则审计说明。
|
||||
|
||||
Args:
|
||||
rules: parse_transform_rules 产出的规则元组。
|
||||
Returns:
|
||||
如 "lot_no prefix_replace WTP->HOW THEN lot_no prefix_replace HOW->HOWX"
|
||||
的人读字符串(空规则返回空串),供审计日志/详情页展示。
|
||||
"""
|
||||
return " THEN ".join(f"{r.field} {r.op} {r.source}->{r.target}" for r in rules)
|
||||
@@ -1,9 +1,12 @@
|
||||
"""在途调拨收料文件字段/结构校验。
|
||||
"""在途调拨异动文件字段/结构校验。
|
||||
|
||||
用途:校验收料文件必填列(Invoice No/料号/收料日期/收料数量)、数量与日期合法性、
|
||||
来源身份一致性,输出 ParsedReceiptRow 供 Invoice 汇总。
|
||||
依赖:app.core.errors.AppError、date_policy.parse_date、quantity.validate_receipt_quantity。
|
||||
逻辑:任何必填缺失或非法值整行阻断并携带行号细节;本模块不接触文件存储。
|
||||
用途:校验异动文件必填列(单号/异动日期/异动数量;料号为空的行静默跳过)、
|
||||
数量与日期合法性、来源身份一致性,输出 ParsedMovementRow 供 Invoice 汇总。
|
||||
依赖:app.core.errors.AppError、date_policy.parse_date、quantity.validate_inbound_quantity。
|
||||
逻辑:必填缺失或非法值整行阻断并携带行号细节;料号空行跳过不管控不落档
|
||||
(2026-10-21 CRANE/Lognet 出站报告实测);本模块不接触文件存储。
|
||||
tt14 入站化后统一走 movement 契约字段(parse_movement_rows 单一入口,
|
||||
旧字段投影链路已并入,无兼容层)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,14 +19,11 @@ from typing import Any, Iterable, Mapping
|
||||
from app.core.errors import AppError
|
||||
from app.services.in_transit_transfer.contracts import TRANSFER_FILE_SCHEMA_INVALID
|
||||
from app.services.in_transit_transfer.date_policy import parse_date
|
||||
from app.services.in_transit_transfer.quantity import QuantityValidationError, validate_receipt_quantity
|
||||
|
||||
REQUIRED_FIELDS = ("sheet", "row_no", "invoice_no", "material_no", "receipt_date", "receipt_quantity")
|
||||
|
||||
from app.services.in_transit_transfer.quantity import QuantityValidationError, validate_inbound_quantity
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ParsedReceiptRow:
|
||||
"""单行已校验收料记录。"""
|
||||
class ParsedMovementRow:
|
||||
"""单行已校验异动记录。"""
|
||||
|
||||
source_code: str
|
||||
sheet: str
|
||||
@@ -32,20 +32,21 @@ class ParsedReceiptRow:
|
||||
material_no: str
|
||||
material_name: str
|
||||
specification: str
|
||||
receipt_date: date
|
||||
receipt_quantity: Decimal
|
||||
# 异动日期/异动数量(tt14 入站化:明细方向中立,与异动档 movement_date 对齐)。
|
||||
movement_date: date
|
||||
movement_quantity: Decimal
|
||||
lot_no: str = ""
|
||||
# 收料文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。
|
||||
# 来源文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。
|
||||
warehouse_code: str = ""
|
||||
# 交易单位列原值(movement 契约第 11 字段 unit,计划 D4):仅 trim 空白、
|
||||
# 不做单位换算/清洗;空值不产生解析失败,由匹配阶段行级 blocked_missing_unit 阻断。
|
||||
unit: str = ""
|
||||
|
||||
|
||||
class ReceiptFileSchemaError(AppError):
|
||||
"""收料文件结构/字段校验失败(整行阻断)。"""
|
||||
class MovementFileSchemaError(AppError):
|
||||
"""异动文件结构/字段校验失败(整行阻断)。"""
|
||||
|
||||
def __init__(self, message: str = "receipt file schema invalid", *, rows: list[dict[str, Any]] | None = None):
|
||||
def __init__(self, message: str = "movement file schema invalid", *, rows: list[dict[str, Any]] | None = None):
|
||||
super().__init__(
|
||||
code=TRANSFER_FILE_SCHEMA_INVALID,
|
||||
message=message,
|
||||
@@ -59,48 +60,52 @@ def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None:
|
||||
rows.append({"row_no": row_no, "reason": reason})
|
||||
|
||||
|
||||
def _is_unusable_receipt_row(date_value: Any, quantity_raw: Any) -> bool:
|
||||
"""判断是否为"非可用收料事实"的行:跳过,不参与匹配,也不阻断整文件。
|
||||
def _is_unusable_movement_row(date_value: Any, quantity_raw: Any) -> bool:
|
||||
"""判断是否为"非可用异动事实"的行:跳过,不参与匹配,也不阻断整文件。
|
||||
|
||||
WMS 异动报告会携带三类非可用收料行,均不是可用的收料事实:
|
||||
① 未收料在途 ASN(Date Received 空、Qty Received 0);
|
||||
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章);
|
||||
③ 零数量收料行(Date Received 已盖章但 Qty Received = 0;2026-10-08 CRANE
|
||||
WMS 异动报告会携带三类非可用异动行,均不是可用的异动事实:
|
||||
① 未收货在途 ASN(Date Received 空、Qty Received 0);
|
||||
② 收货执行中(ASN Status=Executing,Qty Received 已计数但收货日期未盖章);
|
||||
③ 零数量异动行(Date Received 已盖章但 Qty Received = 0;2026-10-08 CRANE
|
||||
WTP26082227 实测——扫码收货数量记在他行/收货取消的占位行)。
|
||||
收料日期与正数量是行级匹配身份与成熟过滤的必要字段;此类行跳过后由下次排程
|
||||
异动日期与正数量是行级匹配身份与日期圈定的必要字段;此类行跳过后由下次排程
|
||||
抓取补齐(WMS 补数量/盖章后自然带出),不得整文件阻断。
|
||||
"""
|
||||
if not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip()):
|
||||
return True
|
||||
try:
|
||||
# 只跳过恰好为 0 的零收料行;负数属数据损坏,交由 validate_receipt_quantity 阻断。
|
||||
# 只跳过恰好为 0 的零异动行;负数属数据损坏,交由 validate_inbound_quantity 阻断。
|
||||
return Decimal(str(quantity_raw)) == 0
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
# 数量缺失/空:日期已盖章但无数量,同为零收料家族;非数字垃圾交由
|
||||
# validate_receipt_quantity 按非法数量阻断,不在此吞掉。
|
||||
# 数量缺失/空:日期已盖章但无数量,同为零异动家族;非数字垃圾交由
|
||||
# validate_inbound_quantity 按非法数量阻断,不在此吞掉。
|
||||
return not str(quantity_raw or "").strip()
|
||||
|
||||
|
||||
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
|
||||
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedMovementRow]:
|
||||
"""把通用异动/移动字段(doc_no/line_no/in_out_flag/material_code/...)映射为调拨解析行。
|
||||
|
||||
字段契约(领域定死)见 movement_contract.MOVEMENT_FIELDS;映射关系:
|
||||
doc_no → invoice_no(幂等/汇总键)
|
||||
quantity → receipt_quantity(严格数量匹配)
|
||||
movement_date → receipt_date(成熟过滤)
|
||||
quantity → movement_quantity(严格数量匹配)
|
||||
movement_date → movement_date(日期圈定;tt14 入站化后明细侧同名对齐)
|
||||
其余字段(material_code→material_no、material_name、doc_no)透传/展示保留;
|
||||
warehouse_code 透传至 ParsedReceiptRow.warehouse_code(inventory_match 源路由匹配键);
|
||||
unit 原值透传至 ParsedReceiptRow.unit(movement 契约第 11 字段,仅 trim,
|
||||
warehouse_code 透传至 ParsedMovementRow.warehouse_code(inventory_match 源路由匹配键);
|
||||
unit 原值透传至 ParsedMovementRow.unit(movement 契约第 11 字段,仅 trim,
|
||||
空值不阻断解析——行级 missing_unit 阻断在匹配阶段);
|
||||
storage_code 仍仅展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
|
||||
external_doc_no/external_line_no(2026-10-21 扩展:外部单号/外部项次)经原始行
|
||||
透传至落档组装(_assemble_ledger_rows 从原始行取扩展字段,解析行不设槽位),
|
||||
作为异动档自然键成分承担档幂等主键管控;
|
||||
storage_code 仍仅展示保留。旧字段名投影链路(tt14 前的直连列名解析)已并入
|
||||
本函数(入站化,无兼容层),校验逻辑一致。
|
||||
|
||||
Args:
|
||||
source_code: 任务来源实例(行内来源身份一致性校验)。
|
||||
rows: 通用异动原始行 dict。
|
||||
Returns:
|
||||
已校验的 ParsedReceiptRow 列表。
|
||||
已校验的 ParsedMovementRow 列表。
|
||||
Raises:
|
||||
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
|
||||
MovementFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
|
||||
"""
|
||||
return _parse_rows(
|
||||
source_code=source_code,
|
||||
@@ -108,31 +113,8 @@ def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]])
|
||||
projection={
|
||||
"invoice_no": "doc_no",
|
||||
"material_no": "material_code",
|
||||
"receipt_quantity": "quantity",
|
||||
"receipt_date": "movement_date",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def parse_receipt_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
|
||||
"""校验并解析收料文件行。
|
||||
|
||||
Args:
|
||||
source_code: 任务来源实例(用于校验行内来源身份一致性)。
|
||||
rows: 原始文件行 dict。
|
||||
Returns:
|
||||
已校验的 ParsedReceiptRow 列表。
|
||||
Raises:
|
||||
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
|
||||
"""
|
||||
return _parse_rows(
|
||||
source_code=source_code,
|
||||
rows=rows,
|
||||
projection={
|
||||
"invoice_no": "invoice_no",
|
||||
"material_no": "material_no",
|
||||
"receipt_quantity": "receipt_quantity",
|
||||
"receipt_date": "receipt_date",
|
||||
"movement_quantity": "quantity",
|
||||
"movement_date": "movement_date",
|
||||
},
|
||||
)
|
||||
|
||||
@@ -142,61 +124,64 @@ def _parse_rows(
|
||||
source_code: str,
|
||||
rows: Iterable[Mapping[str, Any]],
|
||||
projection: Mapping[str, str],
|
||||
) -> list[ParsedReceiptRow]:
|
||||
) -> list[ParsedMovementRow]:
|
||||
"""按字段名投影校验并解析原始行。
|
||||
|
||||
Args:
|
||||
source_code: 任务来源实例(行内来源身份一致性校验)。
|
||||
rows: 原始文件行 dict。
|
||||
projection: 调拨语义字段(invoice_no/material_no/receipt_quantity/receipt_date)
|
||||
projection: 调拨语义字段(invoice_no/material_no/movement_quantity/movement_date)
|
||||
到原始行字段名的映射(如 {invoice_no: doc_no})。
|
||||
Returns:
|
||||
已校验的 ParsedReceiptRow 列表("无异动日期"的在途/执行中行已跳过)。
|
||||
已校验的 ParsedMovementRow 列表("无异动日期"的在途/执行中行已跳过)。
|
||||
Raises:
|
||||
ReceiptFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
|
||||
MovementFileSchemaError: 任一必填缺失、非法数量/日期或来源不一致。
|
||||
"""
|
||||
invoice_key = str(projection.get("invoice_no") or "invoice_no")
|
||||
material_key = str(projection.get("material_no") or "material_no")
|
||||
quantity_key = str(projection.get("receipt_quantity") or "receipt_quantity")
|
||||
date_key = str(projection.get("receipt_date") or "receipt_date")
|
||||
quantity_key = str(projection.get("movement_quantity") or "movement_quantity")
|
||||
date_key = str(projection.get("movement_date") or "movement_date")
|
||||
|
||||
errors: list[dict[str, Any]] = []
|
||||
parsed: list[ParsedReceiptRow] = []
|
||||
parsed: list[ParsedMovementRow] = []
|
||||
for raw in rows:
|
||||
row = raw if isinstance(raw, Mapping) else {}
|
||||
row_no = row.get("row_no")
|
||||
invoice_no = str(row.get(invoice_key) or "").strip()
|
||||
material_no = str(row.get(material_key) or "").strip()
|
||||
sheet = str(row.get("sheet") or "").strip()
|
||||
receipt_date_value = row.get(date_key)
|
||||
movement_date_value = row.get(date_key)
|
||||
quantity_raw = row.get(quantity_key)
|
||||
|
||||
if not sheet or not row_no:
|
||||
_fail(errors, row_no=row_no, reason="missing_sheet_or_row_no")
|
||||
continue
|
||||
if not material_no:
|
||||
# [料号空行跳过 2026-10-21] 料号为空=非可用异动行(CRANE/Lognet 出站
|
||||
# 报告的说明行/占位行实测):不做必填管控、不进异动表,静默跳过——
|
||||
# 与 _is_unusable_movement_row 同家族(跳过不阻断整文件)。其余必填
|
||||
#(单号)管控不变,仅对有料号的行生效。
|
||||
continue
|
||||
if not invoice_no:
|
||||
_fail(errors, row_no=row_no, reason="missing_invoice_no")
|
||||
continue
|
||||
if not material_no:
|
||||
_fail(errors, row_no=row_no, reason="missing_material_no")
|
||||
continue
|
||||
row_source = str(row.get("source_code") or "").strip()
|
||||
if row_source and row_source.upper() != str(source_code).upper():
|
||||
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
|
||||
continue
|
||||
if _is_unusable_receipt_row(receipt_date_value, quantity_raw):
|
||||
if _is_unusable_movement_row(movement_date_value, quantity_raw):
|
||||
continue
|
||||
try:
|
||||
receipt_date = parse_date(receipt_date_value)
|
||||
movement_date = parse_date(movement_date_value)
|
||||
except ValueError:
|
||||
_fail(errors, row_no=row_no, reason=f"invalid_receipt_date: {receipt_date_value!r}")
|
||||
_fail(errors, row_no=row_no, reason=f"invalid_movement_date: {movement_date_value!r}")
|
||||
continue
|
||||
try:
|
||||
quantity = validate_receipt_quantity(quantity_raw)
|
||||
quantity = validate_inbound_quantity(quantity_raw)
|
||||
except QuantityValidationError as exc:
|
||||
_fail(errors, row_no=row_no, reason=str(exc))
|
||||
continue
|
||||
parsed.append(ParsedReceiptRow(
|
||||
parsed.append(ParsedMovementRow(
|
||||
source_code=str(source_code),
|
||||
sheet=sheet,
|
||||
row_no=int(row_no),
|
||||
@@ -204,8 +189,8 @@ def _parse_rows(
|
||||
material_no=material_no,
|
||||
material_name=str(row.get("material_name") or "").strip(),
|
||||
specification=str(row.get("specification") or "").strip(),
|
||||
receipt_date=receipt_date,
|
||||
receipt_quantity=quantity,
|
||||
movement_date=movement_date,
|
||||
movement_quantity=quantity,
|
||||
lot_no=str(row.get("lot_no") or "").strip(),
|
||||
warehouse_code=str(row.get("warehouse_code") or "").strip(),
|
||||
# unit 原值透传(movement 契约第 11 字段):仅 trim,空值解析放行。
|
||||
@@ -215,5 +200,5 @@ def _parse_rows(
|
||||
# 诊断落库:消息携带前 3 条行级明细(行号+原因),随 parse_error_message
|
||||
# 落库自描述(2026-10-08 CRANE 零数量行事故:此前只有通用消息、无法定位)。
|
||||
summary = '; '.join(f"row {r.get('row_no')}: {r.get('reason')}" for r in errors[:3])
|
||||
raise ReceiptFileSchemaError(f"receipt file schema invalid: {summary}", rows=errors)
|
||||
raise MovementFileSchemaError(f"movement file schema invalid: {summary}", rows=errors)
|
||||
return parsed
|
||||
@@ -1,7 +1,8 @@
|
||||
"""在途调拨收料文件 Ready 复用与来源级 RPA 触发。
|
||||
"""在途调拨入站文件 Ready 复用与来源级 RPA 触发。
|
||||
|
||||
用途:按 (source_code, business_date, purpose=receipt) 检查最新 ready 文件;
|
||||
存在则复用,不存在则按来源实例触发一次收料 RPA;存在活动 Source Job
|
||||
用途:按 (source_code, business_date, 入站解析规则绑定) 检查最新 ready 文件;
|
||||
存在则复用,不存在则按来源实例触发一次入站 RPA(入站证据 = ShippingInboundReport RPA
|
||||
产物,shipping_notice 域术语保留);存在活动 Source Job
|
||||
时绑定已有任务,保证并发请求只触发一次抓取。
|
||||
依赖:typing.Protocol 依赖注入(文件仓库 / RPA 触发)。
|
||||
逻辑:文件仓库与 RPA 触发均通过协议注入,测试使用 Fake 替身;
|
||||
@@ -19,8 +20,8 @@ STAGE_FAILED = "failed"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReadyReceiptFile:
|
||||
"""当日最新 ready 收料文件快照(含已提取行,供解析)。"""
|
||||
class ReadyInboundFile:
|
||||
"""当日最新 ready 入站文件快照(含已提取行,供解析)。"""
|
||||
|
||||
source_code: str
|
||||
business_date: str
|
||||
@@ -35,30 +36,30 @@ class FilePreparationResult:
|
||||
"""来源级文件准备结果。"""
|
||||
|
||||
stage: str
|
||||
file: ReadyReceiptFile | None = None
|
||||
file: ReadyInboundFile | None = None
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
class ReceiptFileRepository(Protocol):
|
||||
"""收料 ready 文件仓库协议。"""
|
||||
class InboundFileRepository(Protocol):
|
||||
"""入站 ready 文件仓库协议。"""
|
||||
|
||||
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
|
||||
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyInboundFile | None:
|
||||
"""返回该来源当日最新 ready 文件;不存在返回 None。"""
|
||||
|
||||
|
||||
class RpaTrigger(Protocol):
|
||||
"""收料 RPA 触发协议(DBS/Crane 共用)。"""
|
||||
"""入站 RPA 触发协议(DBS/Crane 共用)。"""
|
||||
|
||||
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
|
||||
"""触发一次收料抓取,返回 {'ok': bool, 'callback_id'|'error_code': ...}。"""
|
||||
"""触发一次入站抓取,返回 {'ok': bool, 'callback_id'|'error_code': ...}。"""
|
||||
|
||||
|
||||
def ensure_receipt_file_ready(
|
||||
def ensure_inbound_file_ready(
|
||||
*,
|
||||
source_code: str,
|
||||
business_date: str,
|
||||
repository: ReceiptFileRepository,
|
||||
repository: InboundFileRepository,
|
||||
rpa_trigger: RpaTrigger,
|
||||
active_source_job_key: str | None = None,
|
||||
) -> FilePreparationResult:
|
||||
|
||||
+19
-14
@@ -1,10 +1,15 @@
|
||||
"""在途调拨收料回调桥。
|
||||
"""在途调拨入站回调桥。
|
||||
|
||||
用途:货代收料 RPA 回调落文件后,按来源推进调拨等待中的 TransferSourceJob:
|
||||
用途:货代入站 RPA(入站证据 = ShippingInboundReport RPA 产物,shipping_notice 域,术语保留)
|
||||
回调落文件后,按来源推进调拨等待中的 TransferSourceJob:
|
||||
success/有文件 → file_ready(绑定 file_no/sha256);failed/empty → failed。
|
||||
依赖:models(TransferSourceJob)、datetime。
|
||||
逻辑:只推进 status='waiting_rpa_callback' 的来源任务(门禁);无匹配则不动作,
|
||||
避免回调迟到误推进其他阶段任务。SourceJob 状态为字符串常量(见 models)。
|
||||
避免回调迟到误推进其他阶段任务。生产调用方为调拨侧报表事实处理函数
|
||||
handle_inbound_report(Task 7,inbound_report_handler.py——归档终态 commit 后
|
||||
经 dispatch_report_fact 调入;返回 None 时调用方跳过提交分支);回归测试桥
|
||||
(handle_inbound_report / 历史测试桥)仍走本函数。
|
||||
SourceJob 状态为字符串常量(见 models)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,7 +24,7 @@ _WAITING_RPA_CALLBACK = 'waiting_rpa_callback'
|
||||
_FAILED = 'failed'
|
||||
|
||||
|
||||
def advance_source_job_from_receipt_callback(
|
||||
def advance_source_job_from_inbound_callback(
|
||||
*, source_code: str, file_no: str | None = None, file_sha256: str | None = None,
|
||||
callback_ok: bool = True, error_code: str | None = None, error_message: str | None = None,
|
||||
) -> TransferSourceJob | None:
|
||||
@@ -27,8 +32,8 @@ def advance_source_job_from_receipt_callback(
|
||||
|
||||
Args:
|
||||
source_code: 回调所属来源实例。
|
||||
file_no: 收料文件号(success 时)。
|
||||
file_sha256: 收料文件 sha256(success 时)。
|
||||
file_no: 入站文件号(success 时)。
|
||||
file_sha256: 入站文件 sha256(success 时)。
|
||||
callback_ok / error_code / error_message: 回调终态。
|
||||
Returns:
|
||||
被推进的任务;无等待任务或已终态时返回 None。
|
||||
@@ -50,25 +55,25 @@ def advance_source_job_from_receipt_callback(
|
||||
job.finished_at = datetime.utcnow()
|
||||
else:
|
||||
job.status = _FAILED
|
||||
job.error_code = error_code or 'RPA_RECEIPT_CALLBACK_FAILED'
|
||||
job.error_message = error_message or 'receipt rpa callback failed'
|
||||
job.error_code = error_code or 'RPA_INBOUND_CALLBACK_FAILED'
|
||||
job.error_message = error_message or 'inbound rpa callback failed'
|
||||
job.finished_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
return job
|
||||
|
||||
|
||||
def recover_stale_waiting_source_jobs() -> int:
|
||||
"""把超过收料回调超时仍 waiting_rpa_callback 的调拨来源任务回收为 failed。
|
||||
"""把超过入站回调超时仍 waiting_rpa_callback 的调拨来源任务回收为 failed。
|
||||
|
||||
【AI 触发时机】:仅由排程队列周期扫描(queue_service)与收料超时回收同批调用;
|
||||
不自动重试 RPA——用户可在来源选择卡手动重试(与收料回收"绝不自动重试"口径一致)。
|
||||
【AI 触发时机】:仅由排程队列周期扫描(queue_service)与入站超时回收同批调用;
|
||||
不自动重试 RPA——用户可在来源选择卡手动重试(与入站回收"绝不自动重试"口径一致)。
|
||||
Returns:
|
||||
本次回收的任务数。
|
||||
"""
|
||||
from flask import current_app
|
||||
|
||||
try:
|
||||
timeout = max(60, int(current_app.config.get('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
|
||||
timeout = max(60, int(current_app.config.get('FREIGHT_RPA_INBOUND_TIMEOUT_SECONDS', 900)))
|
||||
except (TypeError, ValueError):
|
||||
timeout = 900
|
||||
cutoff = datetime.utcnow() - timedelta(seconds=timeout)
|
||||
@@ -79,8 +84,8 @@ def recover_stale_waiting_source_jobs() -> int:
|
||||
)
|
||||
for job in stale:
|
||||
job.status = _FAILED
|
||||
job.error_code = 'RPA_RECEIPT_CALLBACK_TIMEOUT'
|
||||
job.error_message = f'receipt rpa callback not received within {timeout}s'
|
||||
job.error_code = 'RPA_INBOUND_CALLBACK_TIMEOUT'
|
||||
job.error_message = f'inbound rpa callback not received within {timeout}s'
|
||||
job.finished_at = datetime.utcnow()
|
||||
if stale:
|
||||
db.session.commit()
|
||||
@@ -0,0 +1,20 @@
|
||||
"""在途调拨入站归档文件的可用性门禁(口径唯一,语义归 freight_rpa.reports 维护)。
|
||||
|
||||
用途:把「一份入站归档文件是否可用于调拨链路」的判定收敛为
|
||||
freight_rpa/reports/queries 的权威实现,并向调拨域既有 import 路径
|
||||
(api 下载、历史消费方)透传,防止口径漂移。
|
||||
依赖:freight_rpa.reports.queries(usable / expired 过滤表达式的唯一权威)。
|
||||
逻辑:【阶段 B Task 4】本模块不再自带表达式实现,自身不 import 任何
|
||||
freight_rpa 报表模型;可用 = 未删除 + 当天(Asia/Shanghai 业务日)抓取
|
||||
+ 未过保留期;已失效(expired)= 未删除 且 该核心不成立——两条件同核
|
||||
推导,规则文本与业务日窗口换算见 queries.py(禁止反向 import 出现环)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
expired_inbound_file_condition,
|
||||
usable_inbound_file_condition,
|
||||
)
|
||||
|
||||
__all__ = ["expired_inbound_file_condition", "usable_inbound_file_condition"]
|
||||
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
services/in_transit_transfer/inbound_report_handler.py
|
||||
|
||||
用途:inbound 报表事实的调拨侧业务处理函数(阶段 B Task 7)——收料归档
|
||||
终态 commit 后由 dispatch_report_fact 投递的 ReportFact 只在此推进
|
||||
调拨自己的任务:TransferSourceJob 终态推进、调拨证据同步、收料排程收口。
|
||||
依赖:app.db、app.models(FreightRpaInboundUnitRun——执行单元读取;报表文件/
|
||||
配置模型禁止在本包引用,边界由 test_inbound_report_read_boundary 锁定)、
|
||||
app.core.errors.ValidationError、freight_rpa.reports.facts(ReportFact /
|
||||
require_report_kind——只消费事实契约,不 import freight_rpa 工作流)、
|
||||
in_transit_transfer.inbound_callback_bridge / evidence_sync(同包)。
|
||||
逻辑:由组合根(app.create_app → in_transit_transfer.rpa_sinks.register_inbound_sinks)
|
||||
注册为 'inbound' kind 处理函数;freight_rpa.inbound.report_archive.
|
||||
ingest_inbound_callback 在每个终态 db.session.commit() 之后经
|
||||
dispatch_report_fact 调入本函数。处理函数只改调拨自己的行;
|
||||
【不捕获异常】——任何失败原样外抛,归档文件已提交不回滚,
|
||||
Worker 重试整笔回调即可补齐推进(先 commit 再投递的顺序契约)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import FreightRpaInboundUnitRun
|
||||
from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind
|
||||
from app.services.in_transit_transfer.inbound_callback_bridge import (
|
||||
advance_source_job_from_inbound_callback,
|
||||
)
|
||||
|
||||
|
||||
def handle_inbound_report(fact: ReportFact) -> None:
|
||||
"""report_kind 必须是 inbound。ok 且 file_id 有值时把等待中的 TransferSourceJob 推进到 file_ready;
|
||||
ok 为假时推进到 failed。没有 waiting_rpa_callback 行则 return。第二次调用时该行已离开等待态,不再改。
|
||||
|
||||
(Task 7 契约 docstring 逐字保留如上;以下为补充说明。)
|
||||
|
||||
核心逻辑:
|
||||
[STEP 1] kind 门禁(fail-closed);[STEP 2] 经桥推进等待中的来源任务(桥只改
|
||||
status='waiting_rpa_callback' 的行,无等待行返回 None——「没有等待行则 return」
|
||||
指调拨侧无任务行可改,第二次投递时该行已离开等待态,桥天然不重复推进);
|
||||
[STEP 3] 桥只 flush 不 commit,推进结果必须在此提交(B3 持久性);[STEP 4]
|
||||
success 事实触发调拨证据同步(与拆分前终态收尾同口径:按 ok 触发、不依赖
|
||||
等待任务存在——独立收料批次无调拨任务也须把最新可用文件镜像落档;
|
||||
桥内自吞异常并自行 commit,本处不包 try);[STEP 5] 精确定位「本次回调收尾的
|
||||
执行单元」并回写收料排程进度、归集终态(finalize 函数住在 schedule 包——
|
||||
freight_rpa 禁止 import 它,只能由本处理函数调用;「仍由该处理函数调用」= 拆分
|
||||
前每笔终态回调后的收口行为保持不变;Task 7 修复轮 2 起定位依据为 fact.unit_run_id
|
||||
——归档入口每次投递(含 failure/empty 与幂等重放)自单元行回填,success 与
|
||||
failure 同一机制,绝不按来源/错误文本猜「最新单元」)。
|
||||
【不捕获异常】任何一步失败原样外抛供 Worker 重试。
|
||||
|
||||
Args:
|
||||
fact: 终态已提交后由归档入口构造的报表事实(report_kind/source_code/
|
||||
file_id/sha256/ok/error_code/error_message)。
|
||||
Returns:
|
||||
None(推进/同步/收口结果全部写库,不返回业务值)。
|
||||
Raises:
|
||||
ValidationError: report_kind 非 inbound(误注册/误分发,fail-closed)。
|
||||
"""
|
||||
# [STEP 1] kind 门禁:本函数只消费 inbound 事实(dispatch 已按 kind 路由,
|
||||
# 此处防御性复核,防止误注册成其他 kind 的处理函数后静默错写调拨行)。
|
||||
kind = require_report_kind(fact.report_kind)
|
||||
if kind != 'inbound':
|
||||
raise ValidationError(
|
||||
f"handle_inbound_report only accepts inbound facts, got: {kind!r}",
|
||||
code='SHIPPING.INBOUND_CALLBACK_INVALID',
|
||||
details={'report_kind': fact.report_kind},
|
||||
)
|
||||
|
||||
# [STEP 2] 推进等待中的调拨来源任务:ok 且 file_id 有值 → file_ready(绑定
|
||||
# 文件号/指纹);否则 → failed(带错误码/描述)。桥只改 waiting_rpa_callback 行;
|
||||
# 无等待行返回 None(调拨侧无行可改,直接结束推进分支)。
|
||||
if fact.ok and fact.file_id is not None:
|
||||
advanced = advance_source_job_from_inbound_callback(
|
||||
source_code=fact.source_code,
|
||||
file_no=str(fact.file_id),
|
||||
file_sha256=fact.sha256,
|
||||
callback_ok=True,
|
||||
)
|
||||
else:
|
||||
advanced = advance_source_job_from_inbound_callback(
|
||||
source_code=fact.source_code,
|
||||
callback_ok=False,
|
||||
error_code=fact.error_code,
|
||||
error_message=fact.error_message,
|
||||
)
|
||||
|
||||
# [STEP 3] 桥只 flush 不 commit:推进落库必须在此提交,否则请求结束回滚会
|
||||
# 丢掉已推进的任务(B3 持久性——empty/failed 且后续收口提前返回时无人提交)。
|
||||
if advanced is not None:
|
||||
db.session.commit()
|
||||
|
||||
# [STEP 4] 证据同步:success 事实(ok 且 file_id 有值)后把该来源最新可用
|
||||
# 入站文件镜像落档。与拆分前终态收尾同口径(按 ok 触发、不依赖等待任务
|
||||
# 存在——独立收料批次没有调拨任务,但其文件仍是运行期取数的证据源)。
|
||||
# sync_and_commit_for_callback 桥内自吞异常并自行 commit;本处不包 try,
|
||||
# 若有异常原样外抛(文件已提交,Worker 重试即可补齐落档)。
|
||||
if fact.ok and fact.file_id is not None:
|
||||
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
|
||||
|
||||
now = datetime.utcnow()
|
||||
sync_and_commit_for_callback(
|
||||
source_code=fact.source_code,
|
||||
business_date=str(now.date()),
|
||||
now=now,
|
||||
)
|
||||
|
||||
# [STEP 5] 收料排程收口:精确定位「本次回调收尾的执行单元」的排程 run(Task 7
|
||||
# 修复轮 2——事实自带 unit_run_id(归档入口每次投递自单元行回填),不再按来源/
|
||||
# 错误文本猜单元:同来源、同错误文本的新单元存在时旧回调不得收口错误的 run)。
|
||||
schedule_run_id: int | None = None
|
||||
if fact.unit_run_id is not None:
|
||||
# 归档入口产线恒回填 unit_run_id;None 仅为兼容手工构造事实的旧调用方——
|
||||
# 无单元标识时不猜(跳过收口,不做任何「最新单元」式近似)。
|
||||
unit = db.session.get(FreightRpaInboundUnitRun, int(fact.unit_run_id))
|
||||
if unit is None:
|
||||
# 分发紧跟终态 commit:单元行缺失属硬性不一致,fail-closed 而非静默跳过。
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
raise NotFoundError(
|
||||
f"Inbound RPA unit not found: {fact.unit_run_id}",
|
||||
details={'unit_run_id': fact.unit_run_id},
|
||||
)
|
||||
schedule_run_id = unit.schedule_run_id
|
||||
if schedule_run_id:
|
||||
from app.services.schedule.freight_rpa_inbound_finalize import (
|
||||
finalize_inbound_schedule_run_if_complete,
|
||||
refresh_inbound_schedule_run_progress,
|
||||
)
|
||||
|
||||
refresh_inbound_schedule_run_progress(schedule_run_id)
|
||||
finalize_inbound_schedule_run_if_complete(schedule_run_id)
|
||||
+84
-72
@@ -1,15 +1,20 @@
|
||||
"""在途调拨真实收料 RPA 触发服务。
|
||||
"""在途调拨入站 RPA 触发服务。
|
||||
|
||||
用途:为单个或多个来源触发收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
|
||||
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
|
||||
先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达),
|
||||
再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
|
||||
依赖:write_receipt_export_batch_trigger(默认 writer)、models、db。
|
||||
逻辑:list_receipt_capable_source_codes 供排程 source_codes 留空时的缺省范围;
|
||||
一源一单元,query_parameters 原样下发;来源停用/收料配置缺失/rpa_profile 缺失时
|
||||
用途:为单个或多个来源触发入站 RPA 抓取(入站证据 = freight_rpa 入站 RPA 产物,
|
||||
复用货代入站 trigger 链路),不创建排程。按来源取站点、入站配置与登录连接
|
||||
(全部经 freight_rpa.reports.queries 只读入口),先落 RPA 单元运行行
|
||||
(awaiting_rpa,回调按 callback_id 查库可达),再装配入站 trigger unit 并
|
||||
调用 write_inbound_export_batch_trigger 原子写 trigger。
|
||||
依赖:write_inbound_export_batch_trigger(默认 writer,freight_rpa.inbound.trigger_io)、
|
||||
freight_rpa.reports.queries(get_site / get_inbound_config / get_rpa_login_profile /
|
||||
list_inbound_configured_source_codes——站点、配置与登录连接读取唯一权威)、db。
|
||||
逻辑:list_inbound_capable_source_codes 供排程 source_codes 留空时的缺省范围;
|
||||
一源一单元,query_parameters 原样下发;来源停用/入站配置缺失/登录连接缺失时
|
||||
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
|
||||
trigger_receipt_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件:
|
||||
trigger_inbound_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件:
|
||||
Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。
|
||||
【阶段 B Task 4】trigger unit 载荷键集与 Worker 契约(freight_rpa.inbound.v1)
|
||||
逐键不变;读取改走只读函数后不再引用 freight_rpa 报表模型。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,7 +23,17 @@ import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
from app.services.freight_rpa.inbound.trigger_io import (
|
||||
ACTION_INBOUND_EXPORT_BATCH,
|
||||
SCHEMA,
|
||||
write_inbound_export_batch_trigger,
|
||||
)
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
get_inbound_config,
|
||||
get_rpa_login_profile,
|
||||
get_site,
|
||||
list_inbound_configured_source_codes,
|
||||
)
|
||||
|
||||
RouteTriggerWriter = Callable[..., str | None]
|
||||
|
||||
@@ -26,41 +41,42 @@ RouteTriggerWriter = Callable[..., str | None]
|
||||
def _build_trigger_unit(
|
||||
*, source_code: str, business_date: str, reason: str,
|
||||
) -> dict[str, Any]:
|
||||
"""装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。
|
||||
"""装配单来源入站 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。
|
||||
|
||||
核心逻辑:一源一单元,query_parameters 原样下发;空条件表示 Worker 走页面默认。
|
||||
【阶段 B Task 4】站点(get_site)/ 入站配置(get_inbound_config)/ 登录连接
|
||||
(get_rpa_login_profile)读取改经 freight_rpa.reports.queries 只读入口;装配出的
|
||||
unit 载荷键集与 Worker 契约逐键保持不变(快照含配置行主键与版本)。
|
||||
"""
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
site = get_site(source_code)
|
||||
if site is None or not site.enabled:
|
||||
raise RuntimeError(f'source not enabled: {source_code}')
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
|
||||
config = get_inbound_config(source_code)
|
||||
if config is None:
|
||||
raise RuntimeError(f'receipt config missing: {source_code}')
|
||||
profile = source.rpa_profile
|
||||
raise RuntimeError(f'inbound config missing: {source_code}')
|
||||
profile = get_rpa_login_profile(source_code)
|
||||
if profile is None or not profile.enabled:
|
||||
raise RuntimeError(f'receipt source profile unavailable: {source_code}')
|
||||
raise RuntimeError(f'inbound source profile unavailable: {source_code}')
|
||||
query_parameters = [
|
||||
dict(item) for item in (config.query_parameters_json or []) if isinstance(item, dict)
|
||||
]
|
||||
snapshot = {
|
||||
'config_id': config.id, 'config_version': config.config_version,
|
||||
'connector_type': source.connector_type,
|
||||
'config_id': config.config_id, 'config_version': config.config_version,
|
||||
'connector_type': site.connector_type,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': query_parameters,
|
||||
'warehouse_id': None, 'rpa_profile_id': source.rpa_profile_id,
|
||||
'warehouse_id': None, 'rpa_profile_id': profile.profile_id,
|
||||
}
|
||||
return {
|
||||
'inventory_source_id': source.id,
|
||||
'callback_id': f'receipt:{uuid.uuid4().hex}',
|
||||
'source_code': source.source_code,
|
||||
'connector_type': source.connector_type,
|
||||
'source_id': site.source_id,
|
||||
'callback_id': f'inbound:{uuid.uuid4().hex}',
|
||||
'source_code': site.source_code,
|
||||
'connector_type': site.connector_type,
|
||||
'warehouse_id': None,
|
||||
'rpa_profile_id': profile.id,
|
||||
'rpa_profile_id': profile.profile_id,
|
||||
'rpa_profile_code': profile.profile_code,
|
||||
'login_url': profile.login_url,
|
||||
'login_config': dict(profile.login_config_json or {}),
|
||||
'login_config': dict(profile.login_config or {}),
|
||||
'credential_envelope': {
|
||||
'username_ciphertext': profile.username_ciphertext,
|
||||
'password_ciphertext': profile.password_ciphertext,
|
||||
@@ -73,38 +89,34 @@ def _build_trigger_unit(
|
||||
}
|
||||
|
||||
|
||||
def list_receipt_capable_source_codes() -> list[str]:
|
||||
"""列出可产出收料文件的启用来源实例(enabled 库存源 + 已配置收料报表)。
|
||||
def list_inbound_capable_source_codes() -> list[str]:
|
||||
"""列出可产出入站文件的启用来源实例(已配置入站报表的启用站点)。
|
||||
|
||||
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——收料文件只能
|
||||
来自已配置收料报表的站点,与货代收料 RPA 排程的站点口径保持一致。
|
||||
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——入站文件
|
||||
只能来自已配置入站报表的站点,与货代入站 RPA 排程的站点口径一致。
|
||||
【阶段 B Task 4】站点×入站配置 join 查询改委托
|
||||
freight_rpa.reports.queries.list_inbound_configured_source_codes;本函数
|
||||
保留为调拨域语义出口(既有调用方 import 路径不变)。
|
||||
Returns:
|
||||
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
|
||||
rows = db.session.query(ShippingInventorySource.source_code).join(
|
||||
ShippingReceiptReportConfig,
|
||||
ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
|
||||
).filter(ShippingInventorySource.enabled.is_(True)).order_by(ShippingInventorySource.source_code).all()
|
||||
return [str(code) for (code,) in rows]
|
||||
return list_inbound_configured_source_codes()
|
||||
|
||||
|
||||
def trigger_receipt_rpa(
|
||||
def trigger_inbound_rpa(
|
||||
*,
|
||||
source_code: str,
|
||||
business_date: str,
|
||||
reason: str = 'transfer_retry_receipt',
|
||||
reason: str = 'transfer_retry_inbound',
|
||||
writer: RouteTriggerWriter | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""触发一次来源收料 RPA 抓取(先落单元行再写 trigger,保证回调可达)。
|
||||
"""触发一次来源入站 RPA 抓取(先落单元行再写 trigger,保证回调可达)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
business_date: 业务日期。
|
||||
reason: 触发原因(写入 trigger)。
|
||||
writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。
|
||||
writer: 触发写者;缺省复用 write_inbound_export_batch_trigger。
|
||||
Returns:
|
||||
{"ok": True, "callback_id": ..., "trigger_path": ...} 或
|
||||
{"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。
|
||||
@@ -112,16 +124,16 @@ def trigger_receipt_rpa(
|
||||
try:
|
||||
unit_payload = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
|
||||
except RuntimeError as exc:
|
||||
return {"ok": False, "error_code": "RPA_RECEIPT_CONFIG_MISSING", "error_message": str(exc)}
|
||||
return {"ok": False, "error_code": "RPA_INBOUND_CONFIG_MISSING", "error_message": str(exc)}
|
||||
|
||||
# [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库,
|
||||
# 不落行则回调必然 404(与排程路径 _build_unit 同一模式)。
|
||||
from app import db
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun
|
||||
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
unit = FreightRpaInboundUnitRun(
|
||||
# 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。
|
||||
inventory_source_id=unit_payload['inventory_source_id'],
|
||||
source_id=unit_payload['source_id'],
|
||||
source_code=unit_payload['source_code'],
|
||||
connector_type=unit_payload['connector_type'],
|
||||
warehouse_id=unit_payload.get('warehouse_id'),
|
||||
@@ -135,20 +147,20 @@ def trigger_receipt_rpa(
|
||||
|
||||
# [STEP 2] 原子写 trigger;目录不可用则单元标 failed(fail-closed,不留永久 awaiting)。
|
||||
run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}"
|
||||
writer_fn = writer or write_receipt_export_batch_trigger
|
||||
writer_fn = writer or write_inbound_export_batch_trigger
|
||||
path = writer_fn(run_no, [unit_payload], payload={
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'action': 'receipt_export_batch',
|
||||
'schema_version': SCHEMA,
|
||||
'action': ACTION_INBOUND_EXPORT_BATCH,
|
||||
'source_code': source_code,
|
||||
'business_date': business_date,
|
||||
'reason': reason,
|
||||
})
|
||||
if not path:
|
||||
unit.status = 'failed'
|
||||
unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
|
||||
unit.error_message = 'receipt trigger directory unavailable'
|
||||
unit.error_code = 'RPA_INBOUND_TRIGGER_UNAVAILABLE'
|
||||
unit.error_message = 'inbound trigger directory unavailable'
|
||||
db.session.commit()
|
||||
return {"ok": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE"}
|
||||
return {"ok": False, "error_code": "RPA_INBOUND_TRIGGER_UNAVAILABLE"}
|
||||
|
||||
# [STEP 3] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
|
||||
unit.trigger_snapshot_json = unit_payload
|
||||
@@ -156,28 +168,28 @@ def trigger_receipt_rpa(
|
||||
return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path}
|
||||
|
||||
|
||||
def trigger_receipt_rpa_batch(
|
||||
def trigger_inbound_rpa_batch(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
business_date: str,
|
||||
reason: str = 'transfer_retry_receipt',
|
||||
reason: str = 'transfer_retry_inbound',
|
||||
writer: RouteTriggerWriter | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""批量触发多来源收料 RPA:全部有效来源合并写**一个** batch trigger 文件。
|
||||
"""批量触发多来源入站 RPA:全部有效来源合并写**一个** batch trigger 文件。
|
||||
|
||||
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
|
||||
行级单来源重试仍走 trigger_receipt_rpa(一源一文件语义不变)。
|
||||
行级单来源重试仍走 trigger_inbound_rpa(一源一文件语义不变)。
|
||||
|
||||
核心逻辑:逐来源装配 unit(来源级隔离——配置缺失/停用跳过并记录,不炸整批;
|
||||
parse_failed 先本地重解析,恢复 ready 则不触发 RPA),有效 units 先各落一行
|
||||
ShippingReceiptRpaUnitRun 再一次性 write_receipt_export_batch_trigger 原子落盘。
|
||||
RPA 单元运行行再一次性 write_inbound_export_batch_trigger 原子落盘。
|
||||
Worker 对单文件按 profile 分组共享一次浏览器会话串行导出,避免逐来源开/关浏览器。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例编码列表(去重保序;空串自动剔除)。
|
||||
business_date: 业务日期。
|
||||
reason: 触发原因(写入 trigger payload)。
|
||||
writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。
|
||||
writer: 触发写者;缺省复用 write_inbound_export_batch_trigger。
|
||||
|
||||
Returns:
|
||||
{"ok": True/False, "triggered": bool, "results": [...], "trigger_path"?/「error_code」?}。
|
||||
@@ -187,13 +199,13 @@ def trigger_receipt_rpa_batch(
|
||||
跳过:{source_code, ok: false, error_code, error_message})。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun as FreightRpaInboundUnitRun
|
||||
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
|
||||
codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip()))
|
||||
results: list[dict[str, Any]] = []
|
||||
units: list[ShippingReceiptRpaUnitRun] = []
|
||||
units: list[FreightRpaInboundUnitRun] = []
|
||||
unit_payloads: list[dict[str, Any]] = []
|
||||
|
||||
# [STEP 1] 解析失败分层(对齐单来源端点)+ 逐来源装配 unit;单源失败跳过不阻断整批。
|
||||
@@ -216,7 +228,7 @@ def trigger_receipt_rpa_batch(
|
||||
except RuntimeError as exc:
|
||||
results.append({
|
||||
'source_code': code, 'ok': False,
|
||||
'error_code': 'RPA_RECEIPT_CONFIG_MISSING', 'error_message': str(exc),
|
||||
'error_code': 'RPA_INBOUND_CONFIG_MISSING', 'error_message': str(exc),
|
||||
})
|
||||
|
||||
if not unit_payloads:
|
||||
@@ -225,12 +237,12 @@ def trigger_receipt_rpa_batch(
|
||||
db.session.commit()
|
||||
if reparse_recovered:
|
||||
return {"ok": True, "triggered": False, "results": results}
|
||||
return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_NO_TRIGGERABLE_SOURCE", "results": results}
|
||||
return {"ok": False, "triggered": False, "error_code": "RPA_INBOUND_NO_TRIGGERABLE_SOURCE", "results": results}
|
||||
|
||||
# [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。
|
||||
for payload in unit_payloads:
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
inventory_source_id=payload['inventory_source_id'],
|
||||
unit = FreightRpaInboundUnitRun(
|
||||
source_id=payload['source_id'],
|
||||
source_code=payload['source_code'],
|
||||
connector_type=payload['connector_type'],
|
||||
warehouse_id=payload.get('warehouse_id'),
|
||||
@@ -246,10 +258,10 @@ def trigger_receipt_rpa_batch(
|
||||
|
||||
# [STEP 3] 一个 batch trigger 原子落盘;目录不可用则本批单元全部标 failed(不留永久 awaiting)。
|
||||
run_no = f"TRIG-BATCH-{uuid.uuid4().hex[:8].upper()}"
|
||||
writer_fn = writer or write_receipt_export_batch_trigger
|
||||
writer_fn = writer or write_inbound_export_batch_trigger
|
||||
path = writer_fn(run_no, unit_payloads, payload={
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'action': 'receipt_export_batch',
|
||||
'schema_version': SCHEMA,
|
||||
'action': ACTION_INBOUND_EXPORT_BATCH,
|
||||
'business_date': business_date,
|
||||
'reason': reason,
|
||||
'source_codes': [payload['source_code'] for payload in unit_payloads],
|
||||
@@ -257,10 +269,10 @@ def trigger_receipt_rpa_batch(
|
||||
if not path:
|
||||
for unit in units:
|
||||
unit.status = 'failed'
|
||||
unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
|
||||
unit.error_message = 'receipt trigger directory unavailable'
|
||||
unit.error_code = 'RPA_INBOUND_TRIGGER_UNAVAILABLE'
|
||||
unit.error_message = 'inbound trigger directory unavailable'
|
||||
db.session.commit()
|
||||
return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE", "results": results}
|
||||
return {"ok": False, "triggered": False, "error_code": "RPA_INBOUND_TRIGGER_UNAVAILABLE", "results": results}
|
||||
|
||||
# [STEP 4] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
|
||||
for unit, payload in zip(units, unit_payloads):
|
||||
@@ -1,9 +1,10 @@
|
||||
"""在途调拨 Invoice 多行汇总。
|
||||
|
||||
用途:相同 Invoice+料号+收料日期 的多行只汇总收料数量,并永久保留原始
|
||||
用途:相同 Invoice+料号+异动日期 的多行只汇总异动数量,并永久保留原始
|
||||
Sheet/行号/文件版本;同 Invoice 跨料号或跨日期自然拆分为多张发票。
|
||||
依赖:app.core.errors.AppError、contracts.RawLineRefDTO。
|
||||
逻辑:汇总键 (source_code, invoice_no, material_no, receipt_date)。
|
||||
逻辑:汇总键 (source_code, invoice_no, material_no, movement_date)(tt14 入站化:
|
||||
明细字段方向中立,日期/数量键统一 movement_*)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,7 +16,7 @@ from typing import Iterable
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.in_transit_transfer.contracts import TRANSFER_INVOICE_CONFLICT, RawLineRefDTO
|
||||
from app.services.in_transit_transfer.file_parser import ParsedReceiptRow
|
||||
from app.services.in_transit_transfer.file_parser import ParsedMovementRow
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -27,11 +28,11 @@ class AggregatedInvoice:
|
||||
material_no: str
|
||||
material_name: str
|
||||
specification: str
|
||||
receipt_date: date
|
||||
receipt_quantity: Decimal
|
||||
movement_date: date
|
||||
movement_quantity: Decimal
|
||||
raw_lines: tuple[RawLineRefDTO, ...]
|
||||
lot_no: str = ""
|
||||
# 组内首行收料仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。
|
||||
# 组内首行来源仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。
|
||||
warehouse_code: str = ""
|
||||
# 组内首行交易单位原值(movement 契约第 11 字段 unit,计划 D4):与 lot_no 同为
|
||||
# 「组内首行」口径;空值在匹配阶段行级 blocked_missing_unit 阻断,不在此换算/清洗。
|
||||
@@ -39,7 +40,7 @@ class AggregatedInvoice:
|
||||
|
||||
|
||||
class InvoiceConflictError(AppError):
|
||||
"""同一 Invoice 出现冲突(多料号/多收料日期),整单阻断。"""
|
||||
"""同一 Invoice 出现冲突(多料号/多异动日期),整单阻断。"""
|
||||
|
||||
def __init__(self, message: str = "invoice conflict", *, invoice_no: str, conflict: str):
|
||||
super().__init__(
|
||||
@@ -50,11 +51,11 @@ class InvoiceConflictError(AppError):
|
||||
)
|
||||
|
||||
|
||||
def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str = "v1") -> list[AggregatedInvoice]:
|
||||
"""按 Invoice+料号+收料日期 汇总收料数量并保留原始行证据。
|
||||
def aggregate_invoices(rows: Iterable[ParsedMovementRow], *, file_version: str = "v1") -> list[AggregatedInvoice]:
|
||||
"""按 Invoice+料号+异动日期 汇总异动数量并保留原始行证据。
|
||||
|
||||
汇总键 (source_code, invoice_no, material_no, receipt_date):Invoice 语义为
|
||||
调拨拨出单据号(如 WMS 的 External ASN #);同单号跨料号或跨收料日期时
|
||||
汇总键 (source_code, invoice_no, material_no, movement_date):Invoice 语义为
|
||||
调拨拨出单据号(如 WMS 的 External ASN #);同单号跨料号或跨异动日期时
|
||||
自然拆分为多张发票(部分交付场景),不做整单阻断。
|
||||
Args:
|
||||
rows: 已校验的解析行。
|
||||
@@ -62,14 +63,14 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str =
|
||||
Returns:
|
||||
汇总后的 Invoice 列表(按汇总键排序)。
|
||||
"""
|
||||
grouped: dict[tuple[str, str, str, date], list[ParsedReceiptRow]] = {}
|
||||
grouped: dict[tuple[str, str, str, date], list[ParsedMovementRow]] = {}
|
||||
for row in rows:
|
||||
grouped.setdefault(
|
||||
(row.source_code, row.invoice_no, row.material_no, row.receipt_date), [],
|
||||
(row.source_code, row.invoice_no, row.material_no, row.movement_date), [],
|
||||
).append(row)
|
||||
|
||||
invoices: list[AggregatedInvoice] = []
|
||||
for (source_code, invoice_no, material_no, receipt_date), group in sorted(grouped.items()):
|
||||
for (source_code, invoice_no, material_no, movement_date_key), group in sorted(grouped.items()):
|
||||
first = group[0]
|
||||
raw_lines = tuple(
|
||||
RawLineRefDTO(sheet=row.sheet, row_no=row.row_no, file_version=file_version)
|
||||
@@ -81,8 +82,8 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str =
|
||||
material_no=material_no,
|
||||
material_name=first.material_name,
|
||||
specification=first.specification,
|
||||
receipt_date=receipt_date,
|
||||
receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")),
|
||||
movement_date=movement_date_key,
|
||||
movement_quantity=sum((row.movement_quantity for row in group), Decimal("0")),
|
||||
raw_lines=raw_lines,
|
||||
lot_no=first.lot_no,
|
||||
warehouse_code=first.warehouse_code,
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
"""services/in_transit_transfer/ledger_sync.py
|
||||
|
||||
用途:库存异动档落地(ADR 0001)——外部记录镜像落地:把解析产物(movement 契约
|
||||
领域行)按自然键幂等镜像到 transfer_movement_ledger;语义与 evidence_sync
|
||||
三分类同源(插入/跳过/原行更新,ADR 0001),一期入站(record_kind='inbound'),
|
||||
outbound 为预留合法值(出货侧结构就位,校验放行,不特判)。
|
||||
依赖:models/in_transit_transfer.TransferMovementLedger、audit.build_transfer_audit_event、
|
||||
movement_contract.MOVEMENT_FIELDS(档列镜像取值的唯一字段来源)。不解析文件
|
||||
(parsed_rows 由调用方/Task 11 接线从解析产物组装)、不查外部系统、零外部调用。
|
||||
逻辑:file_version 戳由 movement_file_version 统一生成(sha256: 前缀按档列宽度截断),
|
||||
入站仓库、出站落档、清空重建、匹配进度快照都调用它,禁止各处自行拼接。
|
||||
落档前先滤 movement_date 空值行——空=未发生异动(未收 ASN/未发货订单行),
|
||||
落档即幽灵行,计入 date_skipped(解析层已滤一轮,此处为映射无关第二道防线)。
|
||||
规格 §5 五条幂等语义——①自然键 (doc_no, line_no, line_seq, in_out_flag,
|
||||
carton_id, lot_no, external_doc_no, external_line_no)(source_code/
|
||||
record_kind 整批恒定不入行内键;tt14 扩维箱号/批号;2026-10-21 扩维外部
|
||||
单据身份=外部单号+外部项次,作档幂等主键管控)查档不存在 → 插入
|
||||
(record_kind/溯源五列随行写入);②行
|
||||
file_sha256 与来件一致 → 跳过(完全不动行,不续 updated_at——档无 TTL,
|
||||
无新鲜度概念);③证据变化 → 原行更新业务镜像列 + 换溯源(source_file_id/
|
||||
file_version/file_sha256/sheet_name/row_no/updated_at);④文件缺席的档行
|
||||
不删(入站 RPA 非全量导出,缺席≠删除——本函数从不删除,无需显式处理);
|
||||
⑤transfer_executed=true 封存行永不更新永不复活(sealed_skipped 计数;封存
|
||||
是最高优先事实,命中即计,与来件 sha 无关;同文件重落不产生第二行,自然键
|
||||
唯一索引 DB 兜底)。
|
||||
record_kind 与 in_out_flag 矛盾(inbound 行出库语义 '-1')→ 计 cross_flagged
|
||||
并写 ledger_cross_check_failed 审计事件,记录照常落档;矛盾标记随落档动作
|
||||
发生(插入/更新时)——幂等重落不重复打事件,防只追加审计表被同文件重落刷爆;
|
||||
封存行不落档故不标记(sealed_skipped 即信号)。
|
||||
只 flush 不 commit(与 evidence_sync 同契约,提交归调用方:落地桥自行 commit,
|
||||
匹配/执行随主事务)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import TransferMovementLedger
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
|
||||
|
||||
# 契约字段 code ↔ 档列名 1:1 镜像不变式(import 期锁定;MOVEMENT_FIELDS 追加字段
|
||||
# 时必须同步 TransferMovementLedger 模型列,否则此处导入即失败——fail-fast)。
|
||||
_MOVEMENT_CODES: tuple[str, ...] = tuple(f.code for f in MOVEMENT_FIELDS)
|
||||
assert set(_MOVEMENT_CODES) <= {c.name for c in TransferMovementLedger.__table__.columns}
|
||||
|
||||
# record_kind='inbound' 的矛盾进出标志:入站记录出现该值即解析错位(交叉校验矛盾)。
|
||||
INBOUND_CONTRADICTORY_FLAGS: frozenset[str] = frozenset({"-1"})
|
||||
# 自然键 NOT NULL 成分(行级 8 成分;source_code/record_kind 整批恒定不入行内键):
|
||||
# 镜像取值时缺值以空串落库(防 NULL 违反非空约束/逃逸唯一比对,与模型 default '' 同口径)。
|
||||
_NOT_NULL_KEY_CODES: tuple[str, ...] = (
|
||||
"doc_no", "line_no", "line_seq", "in_out_flag",
|
||||
"carton_id", "lot_no", "external_doc_no", "external_line_no",
|
||||
)
|
||||
# 记录种类字面量:inbound=入站(ShippingInboundReport RPA 产物,shipping_notice 域术语保留);
|
||||
# outbound=出站(出货侧结构就位)。
|
||||
RECORD_KIND_INBOUND = "inbound"
|
||||
RECORD_KIND_OUTBOUND = "outbound"
|
||||
# 交叉校验矛盾审计事件 kind(任务简报冻结字面量;仓库事件 kind 无集中常量表,行内字面量惯例)。
|
||||
LEDGER_CROSS_CHECK_EVENT = "ledger_cross_check_failed"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FileMeta:
|
||||
"""一次落地的来源文件证据三元组(溯源的文件级成分;Task 11 从归档文件组装)。
|
||||
|
||||
Args:
|
||||
source_file_id: 入站原样归档文件 id(freight_rpa_inbound_report_files.id;
|
||||
测试/极端场景可为 None——档事实留存不依赖文件存在)。
|
||||
file_version: 文件版本号(Task 13 执行门禁 file_current 比对依据)。
|
||||
file_sha256: 文件 SHA-256(幂等跳过判定的唯一证据指纹)。
|
||||
"""
|
||||
|
||||
source_file_id: int | None = None
|
||||
file_version: str | None = None
|
||||
file_sha256: str | None = None
|
||||
|
||||
|
||||
def movement_file_version(sha256: str) -> str:
|
||||
"""把文件 SHA-256 摘要打成异动档 file_version 戳。
|
||||
|
||||
核心逻辑:前缀 sha256: 加摘要后,按 TransferMovementLedger.file_version 列宽截断。
|
||||
64 位摘要加前缀共 71 字符,超出 varchar(64) 时 PostgreSQL 会整批拒绝插入。
|
||||
列宽取自模型,避免戳长和列定义各写一个 64。
|
||||
|
||||
Args:
|
||||
sha256: 文件 SHA-256 十六进制摘要,不含前缀。
|
||||
|
||||
Returns:
|
||||
以 sha256: 开头、长度不超过档列宽度的版本戳。
|
||||
"""
|
||||
limit = TransferMovementLedger.__table__.c.file_version.type.length
|
||||
return f"sha256:{sha256}"[:limit]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LedgerSyncOutcome:
|
||||
"""一次落档的结果计数(审计与兜底日志的数据源;字段名为冻结契约,顺序自 date_skipped 引入后不再承诺)。"""
|
||||
|
||||
inserted: int = 0 # 自然键不存在 → 插入新档行
|
||||
updated: int = 0 # 证据变化 → 原行更新业务镜像列 + 换溯源
|
||||
skipped: int = 0 # sha 未变的幂等跳过;同批自然键重复的后续行亦计入
|
||||
date_skipped: int = 0 # movement_date 空=未发生异动,不落档
|
||||
sealed_skipped: int = 0 # 封存行(transfer_executed=true)命中即计:永不更新永不复活
|
||||
cross_flagged: int = 0 # record_kind 与 in_out_flag 矛盾且本次实际落档的行数
|
||||
|
||||
|
||||
def _key_text(value: Any) -> str:
|
||||
"""自然键成分归一化:None → 空串,其余 str + strip(键成分 NOT NULL 恒有值可比)。"""
|
||||
return "" if value is None else str(value).strip()
|
||||
|
||||
|
||||
def _mirror_text(value: Any) -> str | None:
|
||||
"""业务镜像值归一化:None 保留(宽松落地可空),其余 str + strip 原样落档。"""
|
||||
return None if value is None else str(value).strip()
|
||||
|
||||
|
||||
def _opt_int(value: Any) -> int | None:
|
||||
"""可选整数(row_no):缺失/无效宽容置 None(溯源缺失不打断落地)。"""
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _cross_check_event(
|
||||
*,
|
||||
source_code: str,
|
||||
record_kind: str,
|
||||
key: tuple[str, str, str, str, str, str, str, str],
|
||||
sheet_name: str | None,
|
||||
row_no: int | None,
|
||||
file_meta: FileMeta,
|
||||
):
|
||||
"""构造交叉校验矛盾审计事件(未落库,由调用方 add——build 契约同 audit 模块)。
|
||||
|
||||
Args:
|
||||
source_code / record_kind: 来源实例编码与记录种类。
|
||||
key: 自然键八成分 (doc_no, line_no, line_seq, in_out_flag, carton_id,
|
||||
lot_no, external_doc_no, external_line_no)(已归一化;箱号/批号随
|
||||
tt14 键扩维入事件,外部单据身份随 2026-10-21 键扩维入事件,保证
|
||||
矛盾行可唯一定位)。
|
||||
sheet_name / row_no: 行级溯源(入事件快照辅助定位来源行)。
|
||||
file_meta: 来源文件证据三元组。
|
||||
Returns:
|
||||
已计算 Hash 的 TransferAuditEvent(event_type=ledger_cross_check_failed)。
|
||||
"""
|
||||
(doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no,
|
||||
external_doc_no, external_line_no) = key
|
||||
natural_key = "/".join((
|
||||
source_code, record_kind, doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no,
|
||||
external_doc_no, external_line_no,
|
||||
))
|
||||
return build_transfer_audit_event(
|
||||
event_type=LEDGER_CROSS_CHECK_EVENT,
|
||||
aggregate_type="transfer_movement_ledger",
|
||||
# aggregate_id 列宽 String(128):超长截断防御(全量字段在 after 快照留存)。
|
||||
aggregate_id=natural_key[:128],
|
||||
actor_type="system",
|
||||
result="failure",
|
||||
after={
|
||||
"source_code": source_code, "record_kind": record_kind,
|
||||
"doc_no": doc_no, "line_no": line_no, "line_seq": line_seq,
|
||||
"in_out_flag": in_out_flag, "carton_id": carton_id, "lot_no": lot_no,
|
||||
"external_doc_no": external_doc_no, "external_line_no": external_line_no,
|
||||
"file_version": file_meta.file_version, "file_sha256": file_meta.file_sha256,
|
||||
"sheet_name": sheet_name, "row_no": row_no,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def sync_ledger_rows(
|
||||
*,
|
||||
source_code: str,
|
||||
record_kind: str,
|
||||
parsed_rows: list[dict],
|
||||
file_meta: FileMeta,
|
||||
now: datetime,
|
||||
) -> LedgerSyncOutcome:
|
||||
"""按自然键幂等落地一批领域行到库存异动档(零外部调用,flush 不 commit)。
|
||||
|
||||
【AI 触发时机】Task 11 接线后由落地主链路(evidence_sync 同步入口)在入站
|
||||
文件落地成功时调用;未来出货报告接入时以 record_kind='outbound' 复用。
|
||||
不要在匹配/执行链路调用本函数(匹配从档圈定,不写档)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(自然键成分,整批一致)。
|
||||
record_kind: 记录种类(文件种类声明,权威):'inbound' 一期(ShippingInboundReport
|
||||
RPA 产物);'outbound' 出货侧(预留合法值,校验放行,不特判)。
|
||||
parsed_rows: 领域行 dict 列表,每行键=movement 契约 field code
|
||||
(movement_contract.MOVEMENT_FIELDS:既有 11 + 扩展 7,与
|
||||
档列名 1:1 镜像),值为解析原值(None=缺失,宽松落地);
|
||||
可另含可选行级溯源键 sheet_name(str)/row_no(int)(由接线方
|
||||
从解析产物 ParsedMovementRow 组装);未知键忽略。行必含自然键
|
||||
成分 doc_no/line_no/line_seq/in_out_flag/carton_id/lot_no
|
||||
(缺失按空串落档,必填校验归解析层,本函数不做二次阻断);
|
||||
movement_date 为空(None/空白)的行不入档(未发生异动,
|
||||
计入 date_skipped)。
|
||||
file_meta: 来源文件证据三元组(FileMeta);file_sha256 为 None 时无法证明
|
||||
与档行同源,一律走更新分支(宁可重写不误跳)。
|
||||
now: 落档时间基准(插入/更新显式续 updated_at;跳过不续——完全不动行)。
|
||||
Returns:
|
||||
LedgerSyncOutcome 六分类计数(inserted/updated/skipped/date_skipped/
|
||||
sealed_skipped/cross_flagged)。
|
||||
"""
|
||||
counters = {
|
||||
"inserted": 0, "updated": 0, "skipped": 0,
|
||||
"date_skipped": 0, "sealed_skipped": 0, "cross_flagged": 0,
|
||||
}
|
||||
|
||||
# [STEP 0] movement_date 非空才落档:空值=未发生异动(未收 ASN/未发货订单行),
|
||||
# 落档即幽灵行(永不进匹配圈档)。解析层 file_parser 已滤一轮(异动语义),
|
||||
# 此处是映射无关的第二道防线:Profile 无论把哪列配到 movement_date,空值都进不了档。
|
||||
total_in = len(parsed_rows)
|
||||
parsed_rows = [raw for raw in parsed_rows if _key_text(raw.get("movement_date"))]
|
||||
counters["date_skipped"] = total_in - len(parsed_rows)
|
||||
|
||||
# [STEP 1] 只圈定批内 doc_no 的既有档行(含封存行——封存命中必须可见),按自然键
|
||||
# 建索引;source_code/record_kind 整批恒定,键只留行级八成分(tt14 扩维:
|
||||
# carton_id/lot_no——真实 WMS 行身份=单据+行+箱/批;2026-10-21 扩维:
|
||||
# external_doc_no/external_line_no——外部单据身份作档幂等主键管控)。档「缺席
|
||||
# 不删、永不删除」行数单调增长(评审 Important 修复):按 source+kind 全量
|
||||
# 水化会使每次落地成本随历史线性膨胀(Task 11 接生产落地热路径),故追加
|
||||
# doc_no IN 批内过滤——批外键本就查不到、不参与任何分支,语义与全量查询 100%
|
||||
# 等价;in_([]) 空批由 SQLAlchemy 渲染恒假子句,安全。
|
||||
doc_nos = sorted({_key_text(raw.get("doc_no")) for raw in parsed_rows})
|
||||
existing = (
|
||||
TransferMovementLedger.query.filter_by(
|
||||
source_code=source_code, record_kind=record_kind,
|
||||
)
|
||||
.filter(TransferMovementLedger.doc_no.in_(doc_nos))
|
||||
.all()
|
||||
)
|
||||
by_key = {
|
||||
(r.doc_no, r.line_no, r.line_seq, r.in_out_flag, r.carton_id, r.lot_no,
|
||||
r.external_doc_no, r.external_line_no): r
|
||||
for r in existing
|
||||
}
|
||||
# 同批自然键去重索引(首见为准):批内重复若不拦截,二次插入会撞
|
||||
# uq_transfer_movement_ledger_natural_key 唯一约束炸 flush。
|
||||
landed: dict[tuple[str, str, str, str, str, str, str, str], TransferMovementLedger] = {}
|
||||
|
||||
# [STEP 2] 逐行六分类:日期空 → 封存 → 跳过 → 插入/更新(矛盾标记随落档动作判定)。
|
||||
for raw in parsed_rows:
|
||||
doc_no = _key_text(raw.get("doc_no"))
|
||||
line_no = _key_text(raw.get("line_no"))
|
||||
line_seq = _key_text(raw.get("line_seq"))
|
||||
in_out_flag = _key_text(raw.get("in_out_flag"))
|
||||
carton_id = _key_text(raw.get("carton_id"))
|
||||
lot_no = _key_text(raw.get("lot_no"))
|
||||
external_doc_no = _key_text(raw.get("external_doc_no"))
|
||||
external_line_no = _key_text(raw.get("external_line_no"))
|
||||
key = (doc_no, line_no, line_seq, in_out_flag, carton_id, lot_no,
|
||||
external_doc_no, external_line_no)
|
||||
sheet_name = _mirror_text(raw.get("sheet_name"))
|
||||
row_no = _opt_int(raw.get("row_no"))
|
||||
|
||||
row = by_key.get(key) or landed.get(key)
|
||||
# [封存不触碰] 封存是最高优先事实:命中即计 sealed_skipped 并跳过一切写
|
||||
# (与来件 sha 无关)——永不更新、永不复活,防已执行记录被二次调拨。
|
||||
if row is not None and row.transfer_executed:
|
||||
counters["sealed_skipped"] += 1
|
||||
continue
|
||||
# [幂等跳过] 行 file_sha256 与来件一致 = 同一文件重落:完全不动行
|
||||
#(不续 updated_at,档无 TTL);meta 无 sha 时无法证明同源,不跳过。
|
||||
if (
|
||||
row is not None
|
||||
and file_meta.file_sha256 is not None
|
||||
and row.file_sha256 == file_meta.file_sha256
|
||||
):
|
||||
counters["skipped"] += 1
|
||||
continue
|
||||
|
||||
# [交叉校验] inbound 行出现出库语义 '-1' 即解析错位:计 cross_flagged 并写
|
||||
# 审计事件,记录照常落档。仅在插入/更新(实际落档)时判定——幂等重落
|
||||
#(sha 未变跳过)不重复打事件,封存行不落档故不标记。
|
||||
if record_kind == RECORD_KIND_INBOUND and in_out_flag in INBOUND_CONTRADICTORY_FLAGS:
|
||||
counters["cross_flagged"] += 1
|
||||
db.session.add(_cross_check_event(
|
||||
source_code=source_code, record_kind=record_kind, key=key,
|
||||
sheet_name=sheet_name, row_no=row_no, file_meta=file_meta,
|
||||
))
|
||||
|
||||
# [镜像取值] 业务值一律从领域行 dict 按契约 code 取(扩展字段无独立槽位);
|
||||
# 自然键 NOT NULL 成分缺值以空串落库(_key_text,防 NULL 违反非空约束/
|
||||
# 逃逸唯一比对——2026-10-21 外部身份扩维时修复的潜在缺陷:此前镜像缺值
|
||||
# 即 None,仅因各组装方恒给空串而未暴露)。自然键成分同源同值,插入/更新
|
||||
# 统一按全字段镜像写入(更新时键成分等值重写为无操作,SQLAlchemy 等值列
|
||||
# 不入 UPDATE)。
|
||||
mirror = {
|
||||
code: (_key_text(raw.get(code)) if code in _NOT_NULL_KEY_CODES
|
||||
else _mirror_text(raw.get(code)))
|
||||
for code in _MOVEMENT_CODES
|
||||
}
|
||||
if row is None:
|
||||
# [插入] 自然键不存在:新档行,record_kind + 溯源五列随行写入。
|
||||
row = TransferMovementLedger(
|
||||
source_code=source_code,
|
||||
record_kind=record_kind,
|
||||
**mirror,
|
||||
source_file_id=file_meta.source_file_id,
|
||||
file_version=file_meta.file_version,
|
||||
file_sha256=file_meta.file_sha256,
|
||||
sheet_name=sheet_name,
|
||||
row_no=row_no,
|
||||
updated_at=now,
|
||||
)
|
||||
db.session.add(row)
|
||||
landed[key] = row
|
||||
counters["inserted"] += 1
|
||||
else:
|
||||
# [原行更新] 证据变化:业务镜像列整体换新 + 换溯源五件套与 updated_at
|
||||
#(sha 变而业务值未变时重写等值为无操作,仅溯源换新,计数同归 updated)。
|
||||
for code, value in mirror.items():
|
||||
setattr(row, code, value)
|
||||
row.source_file_id = file_meta.source_file_id
|
||||
row.file_version = file_meta.file_version
|
||||
row.file_sha256 = file_meta.file_sha256
|
||||
row.sheet_name = sheet_name
|
||||
row.row_no = row_no
|
||||
row.updated_at = now
|
||||
counters["updated"] += 1
|
||||
|
||||
# [STEP 3] 缺席不删:文件里没有的自然键本函数从不触碰(入站 RPA 非全量导出,
|
||||
# 缺席≠删除),无对应计数(Outcome 契约无 absent 字段)。
|
||||
# [STEP 4] 只 flush 不 commit:与 evidence_sync 同契约,提交归调用方
|
||||
#(落地桥自行 commit,匹配/执行随主事务)。
|
||||
db.session.flush()
|
||||
return LedgerSyncOutcome(**counters)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,10 @@
|
||||
"""在途调拨通用异动/移动表领域字段契约。
|
||||
|
||||
用途:定义调拨消费的异动(入库/出库/收料/出货)文件领域字段——业务定死、不配置化。
|
||||
用途:定义调拨消费的异动(入站/出站)文件领域字段——业务定死、不配置化。
|
||||
未来出货/入库 Excel 复用同一套字段,靠 in_out_flag 区分方向。
|
||||
依赖:标准库 dataclasses / enum。
|
||||
逻辑:字段清单是 immutable 常量;幂等键为 doc_no,严格数量字段为 quantity,
|
||||
成熟过滤字段为 movement_date;字段映射由 movement_parser 完成。
|
||||
日期圈定过滤字段为 movement_date;字段映射由 file_parser.parse_movement_rows 完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -40,14 +40,22 @@ class MovementField:
|
||||
required: bool = False
|
||||
|
||||
|
||||
# 定死的 11 个通用异动字段(领域契约,不配置化)。
|
||||
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 收料单号);
|
||||
# 定死的通用异动字段(领域契约,不配置化):11 个核心字段 + 扩展可选维度字段。
|
||||
# [PROMPT_UPDATE] 2026-09-21:Invoice 保持锚定单号(doc_no,WMS 入站单号, ShippingInboundReport External ASN #);
|
||||
# 批号(lot_no)为展示维度——匹配列「拨出/拨入批号」由 lot_no 经 WTP→HOW 转换派生。
|
||||
# [PROMPT_UPDATE] 2026-09-25:WTP→HOW 派生收敛为 external_lot_no() 唯一实现——
|
||||
# 库存查询 / 建单下传 / 单行聚合 / 展示统一按外部形态;落库保持文件原形态(证据原则)。
|
||||
# [PROMPT_UPDATE] 2026-09-25:WTP→HOW 派生曾收敛为 external_lot_no() 唯一实现。
|
||||
# [PROMPT_UPDATE] 2026-10-14(Task 11 切换):external_lot_no() 硬编码退役——批号
|
||||
# 外部形态改由调拨类型配置的转换规则驱动(field_transforms 引擎,匹配快照固化),
|
||||
# 行与档始终保存文件原形态(证据原则不变)。
|
||||
# [PROMPT_UPDATE] 2026-09-24:追加第 11 字段 unit(交易单位,计划 D4)——ERP 写入
|
||||
# 行必填(gls_cm19),但解析层放行空值(不产生解析失败),空值由匹配阶段行级
|
||||
# blocked_missing_unit 阻断;unit 不参与幂等/匹配,也不进匹配 Hash 快照(口径冻结)。
|
||||
# [PROMPT_UPDATE] 2026-10-14:追加 7 个可选维度字段(Task 8,调拨类型配置化+库存
|
||||
# 异动档项目)——line_seq/specification/order_type/odm_id/odm_name/carton_id/pallet_id,
|
||||
# 全部 required=False, is_identity=False,只追加不重排(unit 仍为第 11 字段);
|
||||
# 解析层缺列容忍自动继承(row.get 投影,缺列不报错);幂等键 doc_no 与身份集
|
||||
# (doc_no/material_code/movement_date)不变;字段值由库存异动档按 code 取值落档
|
||||
# (Task 10),管理端字段目录/解析 Profile 映射白名单按 MOVEMENT_FIELDS 派生自动继承。
|
||||
MOVEMENT_FIELDS: tuple[MovementField, ...] = (
|
||||
MovementField("doc_no", "单号", MovementFieldValueType.TEXT, is_identity=True, required=True),
|
||||
MovementField("line_no", "项次", MovementFieldValueType.TEXT),
|
||||
@@ -60,6 +68,22 @@ MOVEMENT_FIELDS: tuple[MovementField, ...] = (
|
||||
MovementField("quantity", "数量", MovementFieldValueType.DECIMAL, required=True),
|
||||
MovementField("movement_date", "异动日期", MovementFieldValueType.DATE, is_identity=True, required=True),
|
||||
MovementField("unit", "单位", MovementFieldValueType.TEXT),
|
||||
# ---- 2026-10-14 扩展:可选维度字段(展示/圈档/异动档取值,非匹配身份) ----
|
||||
MovementField("line_seq", "项序", MovementFieldValueType.TEXT),
|
||||
MovementField("specification", "规格", MovementFieldValueType.TEXT),
|
||||
MovementField("order_type", "订单类型", MovementFieldValueType.TEXT),
|
||||
MovementField("odm_id", "ODM编号", MovementFieldValueType.TEXT),
|
||||
MovementField("odm_name", "ODM名称", MovementFieldValueType.TEXT),
|
||||
MovementField("carton_id", "箱号", MovementFieldValueType.TEXT),
|
||||
MovementField("pallet_id", "栈板号", MovementFieldValueType.TEXT),
|
||||
# ---- 2026-10-21 扩展:外部单据身份(外部单号/外部项次;CRANE/Lognet 出站
|
||||
# 报告的 WMS Order #/行号)——解析放行空值(required=False),不进匹配身份
|
||||
#(is_identity=False:匹配 grain 仍=单号/料号/异动日期,契约测试钉死不受扰);
|
||||
# 但两字段自 2026-10-21 起作为库存异动档自然键成分(模型
|
||||
# uq_transfer_movement_ledger_natural_key + ledger_sync 行级键)承担档幂等
|
||||
# 主键管控:同一外部单号+项次的重复落档/证据更新收敛到同一档行。
|
||||
MovementField("external_doc_no", "外部单号", MovementFieldValueType.TEXT),
|
||||
MovementField("external_line_no", "外部项次", MovementFieldValueType.TEXT),
|
||||
)
|
||||
|
||||
|
||||
@@ -81,25 +105,3 @@ def movement_identity_fields() -> set[str]:
|
||||
def movement_field_codes() -> set[str]:
|
||||
"""全部定死字段名集合。"""
|
||||
return {field.code for field in MOVEMENT_FIELDS}
|
||||
|
||||
|
||||
def external_lot_no(lot_no: str | None) -> str:
|
||||
"""批号外部形态派生:WMS 批号 WTP 前缀 → 外部系统真实批号 HOW 前缀。
|
||||
|
||||
【AI 触发时机】任何把行上 lot_no 发往外部系统的场景——库存查询 targets、
|
||||
写前库存复查、建单单行——组装参数前必须经本函数转换;单行聚合键与展示列
|
||||
「拨出/拨入批号」同规则(前端 features/chat/components/messages/transferBatch.ts
|
||||
deriveBatchNo 为本函数的展示侧镜像,改动须双侧同步)。行上落库值保持文件
|
||||
原形态(证据原则:raw_lines 对账/审计复算以文件为准),转换只发生在外部
|
||||
系统边界。
|
||||
|
||||
Args:
|
||||
lot_no: 行上批号原值(文件证据形态;None/空白按空串处理)。
|
||||
Returns:
|
||||
外部系统批号形态:WTP 前缀识别大小写不敏感,余串逐字保留;
|
||||
非 WTP 前缀原样返回;空输入返回空串。
|
||||
"""
|
||||
value = str(lot_no or "").strip()
|
||||
if value.upper().startswith("WTP"):
|
||||
return f"HOW{value[3:]}"
|
||||
return value
|
||||
@@ -1,31 +1,70 @@
|
||||
"""在途调拨真实异动(收料/出货)文件仓库。
|
||||
"""在途调拨真实异动(入站/出站)文件仓库。
|
||||
|
||||
用途:读取货代收料链路已落库的 ShippingReceiptReportFile(对象存储原始 xlsx),
|
||||
用该来源收料配置绑定的 movement 解析规则(purpose='movement',端点=定死
|
||||
领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyReceiptFile。
|
||||
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
|
||||
movement_contract、receipt_file_gate(可用性门禁)、openpyxl。
|
||||
逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的收料文件;无绑定规则、
|
||||
文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
|
||||
用途:读取货代入站链路已落库的入站归档文件(入站证据 = freight_rpa 入站
|
||||
RPA 产物,对象存储原始 xlsx),用该来源入站报表配置绑定的 inbound
|
||||
解析规则(purpose='inbound',端点=定死领域字段 MOVEMENT_FIELDS)的
|
||||
field_mapping 把列映射为领域行,产出 ReadyInboundFile。
|
||||
依赖:【阶段 B Task 4】freight_rpa.reports.queries(站点 get_site / 入站配置
|
||||
get_inbound_config / 入站解析方案 get_inbound_parsing_profile / 最新可用
|
||||
归档 latest_usable_inbound_file / 归档字节 read_inbound_file_bytes /
|
||||
维护通道清单 list_reparseable_inbound_files——只读入口唯一权威)、
|
||||
file_preparation(ReadyInboundFile 契约)、ledger_sync.movement_file_version
|
||||
(file_version 戳的唯一生成处)、openpyxl。
|
||||
逻辑:按来源取站点(enabled)与配置 → 解析方案须 published inbound → 最新
|
||||
【当天(业务日)抓取】且未过期(未清理)的入站文件;无绑定规则、文件缺失
|
||||
或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
|
||||
字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整
|
||||
校验由下游 file_parser 完成。表头别名匹配前归一化空白/换行(DSV SSRS 单元格内
|
||||
折行如 External\\nASN #),仍以站点绑定规则别名为准,不另造硬编码模板。
|
||||
另提供 list_reparseable_archived_files(spec §6 清空重建专用维护通道):
|
||||
委托 queries 维护通道查询(同一 join 路径但显式去掉当日门禁),仅供
|
||||
backlog_reparse_service 使用,运行期禁用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
from typing import Any, Mapping
|
||||
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
|
||||
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
get_inbound_config,
|
||||
get_inbound_parsing_profile,
|
||||
get_site,
|
||||
latest_usable_inbound_file,
|
||||
list_reparseable_inbound_files,
|
||||
read_inbound_file_bytes,
|
||||
)
|
||||
from app.services.in_transit_transfer.file_preparation import ReadyInboundFile
|
||||
from app.services.in_transit_transfer.ledger_sync import movement_file_version
|
||||
|
||||
# 表头单元格内换行/多空白 → 单空格,使绑定别名与 SSRS 折行表头可精确匹配。
|
||||
_HEADER_WS_RE = re.compile(r"\s+")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReparseableArchiveFile:
|
||||
"""一份「可重建」归档文件的维护视图(清空重建专用记录,非运行期取数契约)。
|
||||
|
||||
Args:
|
||||
file_id: 归档文件 id(入站归档文件表主键,档行溯源列同源)。
|
||||
storage_key: 对象存储键(重建时按此取归档字节)。
|
||||
sha256: 文件 SHA-256(重落幂等指纹 / FileMeta.file_sha256)。
|
||||
file_version: 文件版本戳(sha256: 前缀派生,与 latest_ready_file 同口径)。
|
||||
archived_at: 归档时间(created_at;重建按此升序重落)。
|
||||
original_filename: 原始文件名(预检清单/审计展示)。
|
||||
"""
|
||||
|
||||
file_id: int
|
||||
storage_key: str
|
||||
sha256: str
|
||||
file_version: str
|
||||
archived_at: datetime
|
||||
original_filename: str
|
||||
|
||||
|
||||
def _normalize_header_label(value: Any) -> str:
|
||||
"""归一化表头/别名文本:去首尾空白,内部任意空白(含 \\n)压成单空格。
|
||||
|
||||
@@ -37,64 +76,94 @@ def _normalize_header_label(value: Any) -> str:
|
||||
return _HEADER_WS_RE.sub(" ", str(value or "").strip())
|
||||
|
||||
|
||||
class ShippingReceiptFileRepository:
|
||||
"""真实收料/异动 ready 文件仓库(复用货代收料归档 + movement 解析规则)。"""
|
||||
class ShippingInboundFileRepository:
|
||||
"""真实入站/异动 ready 文件仓库(复用 freight_rpa 入站归档 + inbound 解析规则)。
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._storage = file_asset_storage
|
||||
【阶段 B Task 4】模型/存储读取全部收敛到 freight_rpa.reports.queries 只读
|
||||
入口,本类不再 import freight_rpa 报表模型或对象存储客户端;对调用方
|
||||
(file_preparation / deps / backlog_reparse_service)的类名与方法签名不变。
|
||||
"""
|
||||
|
||||
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
|
||||
"""返回该来源最新且当天(业务日)抓取的未过期收料文件;否则返回 None。
|
||||
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyInboundFile | None:
|
||||
"""返回该来源最新且当天(业务日)抓取的未过期入站文件;否则返回 None。
|
||||
|
||||
核心逻辑:[STEP 1] 站点须启用(get_site)+ 入站配置须存在
|
||||
(get_inbound_config)+ 绑定解析方案须 published inbound
|
||||
(get_inbound_parsing_profile,与运行期规则门禁同一口径);
|
||||
[STEP 2] 取最新可用归档视图(latest_usable_inbound_file,当天
|
||||
fail-closed 门禁见 queries.usable_inbound_file_condition)并按
|
||||
file_id 读归档字节(read_inbound_file_bytes);[STEP 3] 按方案
|
||||
field_mapping 提取领域行。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
|
||||
business_date: 业务日期(用于展示,不强制匹配文件日期)。
|
||||
Returns:
|
||||
ReadyReceiptFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
|
||||
ReadyInboundFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
|
||||
新鲜度/保留期/缺失均 fail-closed 返回 None(fail 消息由上游触发重抓)。
|
||||
"""
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
site = get_site(source_code)
|
||||
if site is None or not site.enabled:
|
||||
return None
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
|
||||
config = get_inbound_config(source_code)
|
||||
if config is None or config.parsing_profile_id is None:
|
||||
return None
|
||||
profile = config.parsing_profile
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'movement':
|
||||
profile = get_inbound_parsing_profile(source_code)
|
||||
if profile is None or profile.status != 'published' or profile.purpose != 'inbound':
|
||||
return None
|
||||
|
||||
report = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)单一事实来源见 receipt_file_gate。
|
||||
usable_receipt_file_condition(),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
||||
.first()
|
||||
)
|
||||
if report is None:
|
||||
view = latest_usable_inbound_file(source_code)
|
||||
if view is None:
|
||||
return None
|
||||
|
||||
data = self._storage.get_bytes(report.storage_key)
|
||||
definition = profile.definition_json or {}
|
||||
data = read_inbound_file_bytes(view.file_id)
|
||||
rows = _extract_movement_rows(
|
||||
data,
|
||||
field_mapping=dict((profile.definition_json or {}).get('field_mapping') or {}),
|
||||
sheet_name=str((profile.definition_json or {}).get('sheet_name') or '').strip() or None,
|
||||
header_row_index=(profile.definition_json or {}).get('header_row_index'),
|
||||
field_mapping=dict(definition.get('field_mapping') or {}),
|
||||
sheet_name=str(definition.get('sheet_name') or '').strip() or None,
|
||||
header_row_index=definition.get('header_row_index'),
|
||||
)
|
||||
return ReadyReceiptFile(
|
||||
return ReadyInboundFile(
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
file_no=report.original_filename or str(report.id),
|
||||
file_version=f"sha256:{report.sha256}"[:64],
|
||||
checksum=report.sha256,
|
||||
file_no=view.original_filename or str(view.file_id),
|
||||
file_version=movement_file_version(view.sha256),
|
||||
checksum=view.sha256,
|
||||
rows=tuple(rows),
|
||||
)
|
||||
|
||||
def list_reparseable_archived_files(self, source_code: str, now: datetime) -> list[ReparseableArchiveFile]:
|
||||
"""清空重建专用:该来源全部可重建归档(未清理+未过保留期),不设当日门禁。
|
||||
|
||||
【AI 触发时机】仅待匹配「清空并重新解析」维护链路使用;运行期落档
|
||||
(evidence_sync)禁止改用本方法——当日 fail-closed 门禁是运行期语义,
|
||||
本方法是显式的历史重建通道(spec §6),两者不得混用。
|
||||
|
||||
核心逻辑:委托 freight_rpa.reports.queries.list_reparseable_inbound_files
|
||||
维护通道查询(同一 join 路径,显式去掉「当天业务日抓取」新鲜度门禁——
|
||||
重建对象正是历史归档;保留期口径一致),并把只读视图映射为本仓库的
|
||||
维护契约 ReparseableArchiveFile。只读查询,不触碰对象存储字节(字节
|
||||
由调用方按需经 file_asset_storage 取)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(经收料执行单元行 source_code 关联)。
|
||||
now: 保留期判定时刻。
|
||||
Returns:
|
||||
ReparseableArchiveFile 列表(archived_at 升序;无可重建归档为空表)。
|
||||
"""
|
||||
return [
|
||||
ReparseableArchiveFile(
|
||||
file_id=view.file_id,
|
||||
storage_key=view.storage_key,
|
||||
sha256=view.sha256,
|
||||
file_version=movement_file_version(view.sha256),
|
||||
archived_at=view.created_at,
|
||||
original_filename=view.original_filename,
|
||||
)
|
||||
for view in list_reparseable_inbound_files(source_code, now=now)
|
||||
]
|
||||
|
||||
|
||||
def _extract_movement_rows(
|
||||
data: bytes,
|
||||
@@ -117,7 +186,7 @@ def _extract_movement_rows(
|
||||
header_row_index: 1-based 表头行;空则自动探测。
|
||||
"""
|
||||
from openpyxl import load_workbook
|
||||
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
|
||||
from app.services.shipping_notice.onhand_snapshot import find_inventory_header_row_index
|
||||
|
||||
wb = load_workbook(filename=BytesIO(data), data_only=True, read_only=True)
|
||||
try:
|
||||
@@ -172,4 +241,4 @@ def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str
|
||||
if codes and index < len(row):
|
||||
for code in codes:
|
||||
output[code] = row[index]
|
||||
return output
|
||||
return output
|
||||
@@ -5,7 +5,8 @@
|
||||
依赖:models、status、date_policy、matching_service(编号生成/TransferDeps)。
|
||||
逻辑:执行 Run 与匹配解耦(不回写 matching.run_id / confirmed_at);D8 异步拆分后
|
||||
Run 初始态为 queued(prepare 段只建 Run+关联行+建单,worker 段置 executing);
|
||||
行归属由调用方按 scope 圈定(见 matching_service.scope_item_query)后显式传入,
|
||||
行归属由调用方圈定(出生翻转后 items 创建即绑定 matching_id,restore/执行
|
||||
入口按匹配自有 items 圈行)后显式传入,
|
||||
本模块只负责"建 Run + 关联选中行",已关联(run_id 非空)的行跳过。
|
||||
"""
|
||||
|
||||
@@ -58,7 +59,6 @@ def create_execution_run_for_items(
|
||||
source_codes_json=sorted({item.source_code for item in candidates}),
|
||||
counts_json={
|
||||
"file_invoice_count": len(candidates),
|
||||
"not_matured_count": 0,
|
||||
"matched_count": len(candidates),
|
||||
"executable_count": len(candidates),
|
||||
"blocked_count": 0,
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
"""services/in_transit_transfer/outbound_evidence_sync.py
|
||||
|
||||
用途:出站证据同步——出站回调 success 后把该来源最新可用出站归档按
|
||||
purpose='outbound' 已发布解析规则解析、以 record_kind='outbound' 幂等落档
|
||||
(transfer_movement_ledger),与 evidence_sync(入站专用,record_kind='inbound')
|
||||
完全对称;解析失败把 parse_failed 三列独立落到出站归档文件上(2026-10-16
|
||||
出站落档桥补齐——此前出站链路止步于归档+状态投影,异动档恒无 outbound 行)。
|
||||
依赖:ledger_sync(sync_ledger_rows / RECORD_KIND_OUTBOUND / FileMeta /
|
||||
movement_file_version)、
|
||||
evidence_sync(parse_archive_to_ledger_rows 解析组装单一口径 +
|
||||
_detect_natural_key_collapses/_natural_key_collapse_event 坍缩守卫 + SyncOutcome)、
|
||||
movement_file_repository._extract_movement_rows(归档字节提取)、
|
||||
source_file_status.latest_usable_outbound_file(出站可用文件视图,当天新鲜度
|
||||
口径)、freight_rpa.reports.queries(get_outbound_config /
|
||||
mark_outbound_parse_failure / clear_outbound_parse_failure)、file_asset_storage、
|
||||
models、audit、db。
|
||||
逻辑:sync_outbound_source_rows 只 flush 不 commit(提交归属调用方,契约同入站
|
||||
sync_source_rows);sync_and_commit_for_outbound_callback 桥自行 commit +
|
||||
异常全吞(B3 桥隔离——出站归档主链路不得被落档失败波及),schema 类失败
|
||||
rollback 后把失败事实独立 commit 到当前可用文件(入站同款解析失败分层)。
|
||||
规则门禁 fail-closed:无配置 / 未绑定规则 / 规则未发布 / purpose≠outbound
|
||||
→ no-op(None)——规则缺失不是文件错误,不落解析失败标记(与入站仓库
|
||||
latest_ready_file 门禁同口径)。cross_flag 交叉校验沿用 ledger_sync 既有
|
||||
口径(当前仅 inbound 定义矛盾标志,outbound 行不计数)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import FreightRpaParsingProfile
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
clear_outbound_parse_failure,
|
||||
get_outbound_config,
|
||||
mark_outbound_parse_failure,
|
||||
)
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.evidence_sync import (
|
||||
SyncOutcome,
|
||||
_detect_natural_key_collapses,
|
||||
_natural_key_collapse_event,
|
||||
parse_archive_to_ledger_rows,
|
||||
)
|
||||
from app.services.in_transit_transfer.file_parser import MovementFileSchemaError
|
||||
from app.services.in_transit_transfer.ledger_sync import (
|
||||
RECORD_KIND_OUTBOUND,
|
||||
FileMeta,
|
||||
movement_file_version,
|
||||
sync_ledger_rows,
|
||||
)
|
||||
from app.services.in_transit_transfer.movement_file_repository import _extract_movement_rows
|
||||
from app.services.in_transit_transfer.source_file_status import latest_usable_outbound_file
|
||||
|
||||
_TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
|
||||
# schema 类解析失败判据与入站桥同一口径(code 或异常类型)。
|
||||
_SCHEMA_FAILURE_CODES = (_TRANSFER_FILE_SCHEMA_INVALID,)
|
||||
|
||||
|
||||
def _load_published_outbound_profile(source_code: str) -> FreightRpaParsingProfile | None:
|
||||
"""加载来源出站配置绑定的「已发布 purpose='outbound'」解析规则(fail-closed 门禁)。
|
||||
|
||||
核心逻辑:出站配置(get_outbound_config,缺失=None)→ parsing_profile_id →
|
||||
规则行须 published 且 purpose='outbound'——与运行期入站取数门禁
|
||||
(movement_file_repository.latest_ready_file 的 published inbound 校验)同构。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
Returns:
|
||||
FreightRpaParsingProfile;任一环节缺失或门禁不符返回 None。
|
||||
"""
|
||||
config = get_outbound_config(source_code)
|
||||
if config is None or config.parsing_profile_id is None:
|
||||
return None
|
||||
profile = db.session.get(FreightRpaParsingProfile, config.parsing_profile_id)
|
||||
if profile is None or profile.status != "published" or profile.purpose != "outbound":
|
||||
return None
|
||||
return profile
|
||||
|
||||
|
||||
def sync_outbound_source_rows(*, source_code: str, now: datetime) -> SyncOutcome | None:
|
||||
"""解析来源最新可用出站归档并幂等落档(零外部调用,flush 不 commit)。
|
||||
|
||||
【AI 触发时机】出站 RPA 回调桥(sync_and_commit_for_outbound_callback)调用;
|
||||
不要在匹配/重查链路调用(匹配从档圈定,不写档)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
now: 落档时间基准(插入/更新显式续 updated_at;文件新鲜度判定时刻)。
|
||||
Returns:
|
||||
SyncOutcome;无可用出站文件或无 published outbound 规则返回 None
|
||||
(该分支不触碰解析失败标记——没有成功解析的事实不得清除失败标记)。
|
||||
Raises:
|
||||
MovementFileSchemaError: 行必填缺失/非法(schema 类失败原样上抛——桥内
|
||||
rollback + 落解析失败标记)。
|
||||
"""
|
||||
file_view = latest_usable_outbound_file(source_code, now=now)
|
||||
if file_view is None:
|
||||
return None
|
||||
profile = _load_published_outbound_profile(source_code)
|
||||
if profile is None:
|
||||
return None
|
||||
definition = profile.definition_json or {}
|
||||
|
||||
# [STEP 1] 归档字节 → 原始行(提取口径与运行期入站/清空重建同源)→ 档行
|
||||
# (parse_archive_to_ledger_rows 解析组装单一口径;schema 类失败原样上抛)。
|
||||
data = file_asset_storage.get_bytes(file_view.storage_key)
|
||||
raw_rows = _extract_movement_rows(
|
||||
data,
|
||||
field_mapping=dict(definition.get("field_mapping") or {}),
|
||||
sheet_name=str(definition.get("sheet_name") or "").strip() or None,
|
||||
header_row_index=definition.get("header_row_index"),
|
||||
)
|
||||
assembled = parse_archive_to_ledger_rows(source_code=source_code, rows=raw_rows)
|
||||
|
||||
# [STEP 2] 幂等落档(record_kind='outbound');溯源文件三元组取当前可用归档。
|
||||
# file_version 走 movement_file_version:出站归档无独立版本列,戳与入站仓库、
|
||||
# 清空重建、匹配进度快照同一函数,避免再在此处自行拼接超长。
|
||||
outcome = sync_ledger_rows(
|
||||
source_code=source_code,
|
||||
record_kind=RECORD_KIND_OUTBOUND,
|
||||
parsed_rows=assembled,
|
||||
file_meta=FileMeta(
|
||||
source_file_id=file_view.file_id,
|
||||
file_version=movement_file_version(file_view.sha256),
|
||||
file_sha256=file_view.sha256,
|
||||
),
|
||||
now=now,
|
||||
)
|
||||
# [档自然键坍缩守卫] 与入站同口径复检(检测按行级六成分、record_kind 声明进
|
||||
# 审计聚合键);仅实际落档时打事件,幂等重落不刷审计。
|
||||
collapses = _detect_natural_key_collapses(assembled)
|
||||
if collapses and (outcome.inserted or outcome.updated):
|
||||
for collapse in collapses:
|
||||
db.session.add(_natural_key_collapse_event(
|
||||
source_code=source_code, collapse=collapse, record_kind=RECORD_KIND_OUTBOUND))
|
||||
result = SyncOutcome(
|
||||
source_code=source_code,
|
||||
file_sha256=file_view.sha256 or "",
|
||||
inserted=outcome.inserted,
|
||||
updated=outcome.updated,
|
||||
skipped=outcome.skipped,
|
||||
sealed_skipped=outcome.sealed_skipped,
|
||||
cross_flagged=outcome.cross_flagged,
|
||||
)
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_EVIDENCE_SYNCED",
|
||||
aggregate_type="transfer_source",
|
||||
aggregate_id=source_code,
|
||||
actor_type="system",
|
||||
result="success",
|
||||
after={
|
||||
"file_sha256": result.file_sha256,
|
||||
"record_kind": RECORD_KIND_OUTBOUND,
|
||||
"inserted": result.inserted, "updated": result.updated,
|
||||
"skipped": result.skipped, "sealed_skipped": result.sealed_skipped,
|
||||
"cross_flagged": result.cross_flagged,
|
||||
},
|
||||
))
|
||||
# [解析失败分层] 同步成功 = 当前可用文件已成功解析:清除失败标记(若此前
|
||||
# 失败过),出站流状态投影随之恢复 ready。只 flush 不 commit。
|
||||
if file_view.parse_failed_at is not None:
|
||||
clear_outbound_parse_failure(file_view.file_id)
|
||||
return result
|
||||
|
||||
|
||||
def sync_and_commit_for_outbound_callback(*, source_code: str, now: datetime) -> bool:
|
||||
"""出站回调桥专用入口:落档 + 自行 commit + 异常全吞(仅 warning 日志)。
|
||||
|
||||
【AI 触发时机】出站 RPA 回调 success 终态落文件后由
|
||||
handle_outbound_report(outbound_report_handler)调用——桥是记账不是出站
|
||||
链路的正确性依赖,任何异常不得向出站归档主链路传播(B3:必须自行 commit)。
|
||||
【解析失败分层】失败路径先 rollback(桥隔离),仅 schema 类解析失败把失败
|
||||
事实(parse_failed 三列)独立 commit 落到当前可用出站文件上;丢失的落档由
|
||||
回调重试/出站重抓兜底。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(出站单元行上的 source_code)。
|
||||
now: 落档时间基准。
|
||||
Returns:
|
||||
True=落档成功或无事可做(无可用文件/无可用规则);False=落档失败
|
||||
(已记日志;schema 类失败尽力把解析失败标记落库并独立提交,标记失败
|
||||
仅告警不影响返回)。
|
||||
"""
|
||||
from flask import current_app
|
||||
|
||||
try:
|
||||
outcome = sync_outbound_source_rows(source_code=source_code, now=now)
|
||||
# [桥隔离] sync_outbound_source_rows 只 flush 不 commit;桥由回调事实
|
||||
# 处理在归档 commit 之后独立调用,必须在此自行提交(B3 持久性教训)。
|
||||
db.session.commit()
|
||||
if outcome is not None:
|
||||
current_app.logger.info(
|
||||
"TRANSFER_OUTBOUND_EVIDENCE_SYNC source=%s inserted=%s updated=%s skipped=%s sealed=%s cross=%s",
|
||||
source_code, outcome.inserted, outcome.updated,
|
||||
outcome.skipped, outcome.sealed_skipped, outcome.cross_flagged)
|
||||
return True
|
||||
except Exception as exc: # noqa: BLE001 —— 桥隔离:失败仅日志
|
||||
# [桥隔离] 落档崩溃绝不波及出站归档终态;丢失的落档由回调重试/重抓兜底。
|
||||
current_app.logger.warning(
|
||||
"TRANSFER_OUTBOUND_EVIDENCE_SYNC_FAILED source=%s error=%s", source_code, exc)
|
||||
db.session.rollback()
|
||||
# [解析失败分层] rollback 之后再写标记;仅 schema 类失败落库——通用异常
|
||||
# (网络/DB 故障等)不是文件解析问题,不落标记。标记写入后独立 commit
|
||||
# (落档数据已回滚,本次 commit 只持久化失败事实),仍返回 False。
|
||||
# 标记写入是尽力而为:再抛异常也必须吞掉(B3 优先),丢失标记由下次重试补。
|
||||
try:
|
||||
code = getattr(exc, "code", None) or ""
|
||||
if code in _SCHEMA_FAILURE_CODES or isinstance(exc, MovementFileSchemaError):
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
file_view = latest_usable_outbound_file(source_code, now=now)
|
||||
if file_view is not None:
|
||||
mark_outbound_parse_failure(
|
||||
file_view.file_id,
|
||||
error_code=str(code or _TRANSFER_FILE_SCHEMA_INVALID),
|
||||
error_message=str(detail)[:2000],
|
||||
)
|
||||
db.session.commit()
|
||||
except Exception as mark_exc: # noqa: BLE001 —— 桥隔离:标记失败仅日志
|
||||
current_app.logger.warning(
|
||||
"TRANSFER_OUTBOUND_PARSE_MARK_FAILED source=%s error=%s", source_code, mark_exc)
|
||||
return False
|
||||
@@ -0,0 +1,161 @@
|
||||
"""
|
||||
services/in_transit_transfer/outbound_report_handler.py
|
||||
|
||||
用途:outbound 报表事实的调拨侧业务处理函数——出站归档终态 commit 后由
|
||||
dispatch_report_fact 投递的 ReportFact 只在此推进调拨自己的任务:
|
||||
TransferSourceJob 等待态推进、出站排程收口。
|
||||
依赖:app.db、app.models(FreightRpaOutboundUnitRun——执行单元读取)、
|
||||
app.core.errors.ValidationError、freight_rpa.reports.facts(ReportFact /
|
||||
require_report_kind——只消费事实契约,不 import freight_rpa 工作流)。
|
||||
逻辑:由组合根(app.create_app → in_transit_transfer.rpa_sinks.register_outbound_sinks)
|
||||
注册为 'outbound' kind 处理函数;freight_rpa.outbound.report_archive.
|
||||
ingest_outbound_callback 在每个终态 db.session.commit() 之后经
|
||||
dispatch_report_fact 调入本函数。处理函数只改调拨自己的行;
|
||||
【不捕获异常】——任何失败原样外抛,归档文件已提交不回滚,
|
||||
Worker 重试整笔回调即可补齐推进(先 commit 再投递的顺序契约)。
|
||||
状态机字段与入站同一套:waiting_rpa_callback → file_ready / failed;
|
||||
无等待任务则 no-op;第二次调用该行已离开等待态,不再改(可重入)。
|
||||
【STEP 4 出站证据同步 2026-10-16】success 事实把最新可用出站归档按
|
||||
purpose=outbound 规则解析、record_kind='outbound' 落异动档(与入站
|
||||
handle_inbound_report STEP 4 对称;桥内自吞异常并自行 commit)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import FreightRpaOutboundUnitRun, TransferSourceJob
|
||||
from app.services.freight_rpa.reports.facts import ReportFact, require_report_kind
|
||||
|
||||
_FILE_READY = 'file_ready'
|
||||
_WAITING_RPA_CALLBACK = 'waiting_rpa_callback'
|
||||
_FAILED = 'failed'
|
||||
|
||||
|
||||
def _advance_waiting_source_job(
|
||||
*, source_code: str, file_no: str | None = None, file_sha256: str | None = None,
|
||||
callback_ok: bool = True, error_code: str | None = None, error_message: str | None = None,
|
||||
) -> TransferSourceJob | None:
|
||||
"""按来源推进最新等待回调的调拨来源任务(与入站桥同一等待态字段)。
|
||||
|
||||
核心逻辑:只改 status='waiting_rpa_callback' 的行;无匹配则不动作,
|
||||
避免回调迟到误推进其他阶段任务。success/有文件 → file_ready;否则 → failed。
|
||||
本函数只 flush 不 commit,提交归属 handle_outbound_report。
|
||||
|
||||
Args:
|
||||
source_code: 回调所属来源实例。
|
||||
file_no: 出站文件号(success 时)。
|
||||
file_sha256: 出站文件 sha256(success 时)。
|
||||
callback_ok / error_code / error_message: 回调终态。
|
||||
Returns:
|
||||
被推进的任务;无等待任务或已终态时返回 None。
|
||||
"""
|
||||
job = (
|
||||
TransferSourceJob.query
|
||||
.filter_by(source_code=source_code, status=_WAITING_RPA_CALLBACK)
|
||||
.order_by(TransferSourceJob.id.desc())
|
||||
.first()
|
||||
)
|
||||
if job is None:
|
||||
return None
|
||||
if callback_ok and file_no:
|
||||
job.status = _FILE_READY
|
||||
job.file_no = file_no
|
||||
job.file_sha256 = file_sha256
|
||||
job.error_code = None
|
||||
job.error_message = None
|
||||
job.finished_at = datetime.utcnow()
|
||||
else:
|
||||
job.status = _FAILED
|
||||
job.error_code = error_code or 'RPA_OUTBOUND_CALLBACK_FAILED'
|
||||
job.error_message = error_message or 'outbound rpa callback failed'
|
||||
job.finished_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
return job
|
||||
|
||||
|
||||
def handle_outbound_report(fact: ReportFact) -> None:
|
||||
"""report_kind 必须是 outbound。ok 且 file_id 有值时把等待中的 TransferSourceJob 推进到 file_ready;
|
||||
ok 为假时推进到 failed。没有 waiting_rpa_callback 行则 return。第二次调用时该行已离开等待态,不再改。
|
||||
|
||||
核心逻辑:
|
||||
[STEP 1] kind 门禁(fail-closed);[STEP 2] 推进等待中的来源任务(只改
|
||||
status='waiting_rpa_callback' 的行,无等待行返回 None);[STEP 3]
|
||||
推进结果必须在此提交;[STEP 4] success 事实触发出站证据同步
|
||||
(outbound_evidence_sync,record_kind='outbound',与入站 STEP 4 对称);
|
||||
[STEP 5] 精确定位本次回调收尾的执行单元并回写出站排程进度、归集终态。
|
||||
【不捕获异常】任何一步失败原样外抛供 Worker 重试(STEP 4 桥内自吞)。
|
||||
|
||||
Args:
|
||||
fact: 终态已提交后由归档入口构造的报表事实(report_kind/source_code/
|
||||
file_id/sha256/ok/error_code/error_message/unit_run_id)。
|
||||
Returns:
|
||||
None(推进/收口结果全部写库,不返回业务值)。
|
||||
Raises:
|
||||
ValidationError: report_kind 非 outbound(误注册/误分发,fail-closed)。
|
||||
"""
|
||||
# [STEP 1] kind 门禁:本函数只消费 outbound 事实。
|
||||
kind = require_report_kind(fact.report_kind)
|
||||
if kind != 'outbound':
|
||||
raise ValidationError(
|
||||
f"handle_outbound_report only accepts outbound facts, got: {kind!r}",
|
||||
code='SHIPPING.OUTBOUND_CALLBACK_INVALID',
|
||||
details={'report_kind': fact.report_kind},
|
||||
)
|
||||
|
||||
# [STEP 2] 推进等待中的调拨来源任务:ok 且 file_id 有值 → file_ready;
|
||||
# 否则 → failed。无等待行返回 None(调拨侧无行可改,直接结束推进分支)。
|
||||
if fact.ok and fact.file_id is not None:
|
||||
advanced = _advance_waiting_source_job(
|
||||
source_code=fact.source_code,
|
||||
file_no=str(fact.file_id),
|
||||
file_sha256=fact.sha256,
|
||||
callback_ok=True,
|
||||
)
|
||||
else:
|
||||
advanced = _advance_waiting_source_job(
|
||||
source_code=fact.source_code,
|
||||
callback_ok=False,
|
||||
error_code=fact.error_code,
|
||||
error_message=fact.error_message,
|
||||
)
|
||||
|
||||
# [STEP 3] 桥只 flush 不 commit:推进落库必须在此提交。
|
||||
if advanced is not None:
|
||||
db.session.commit()
|
||||
|
||||
# [STEP 4] 出站证据同步:success 事实(ok 且 file_id 有值)后把该来源最新
|
||||
# 可用出站归档按 purpose=outbound 规则解析、record_kind='outbound' 落异动档
|
||||
# (与入站 handle_inbound_report STEP 4 对称:按 ok 触发、不依赖等待任务存在;
|
||||
# 桥内自吞异常并自行 commit,本处不包 try——文件已提交,Worker 重试即可补齐)。
|
||||
if fact.ok and fact.file_id is not None:
|
||||
from app.services.in_transit_transfer.outbound_evidence_sync import (
|
||||
sync_and_commit_for_outbound_callback,
|
||||
)
|
||||
|
||||
sync_and_commit_for_outbound_callback(
|
||||
source_code=fact.source_code, now=datetime.utcnow(),
|
||||
)
|
||||
|
||||
# [STEP 5] 出站排程收口:按 fact.unit_run_id 精确定位本次回调收尾的执行单元。
|
||||
schedule_run_id: int | None = None
|
||||
if fact.unit_run_id is not None:
|
||||
unit = db.session.get(FreightRpaOutboundUnitRun, int(fact.unit_run_id))
|
||||
if unit is None:
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
raise NotFoundError(
|
||||
f"Outbound RPA unit not found: {fact.unit_run_id}",
|
||||
details={'unit_run_id': fact.unit_run_id},
|
||||
)
|
||||
schedule_run_id = unit.schedule_run_id
|
||||
if schedule_run_id:
|
||||
from app.services.schedule.freight_rpa_outbound_finalize import (
|
||||
finalize_outbound_schedule_run_if_complete,
|
||||
refresh_outbound_schedule_run_progress,
|
||||
)
|
||||
|
||||
refresh_outbound_schedule_run_progress(schedule_run_id)
|
||||
finalize_outbound_schedule_run_if_complete(schedule_run_id)
|
||||
@@ -0,0 +1,261 @@
|
||||
"""在途调拨出站 RPA 触发服务。
|
||||
|
||||
用途:为单个或多个来源触发出站 RPA 抓取(出站证据 = freight_rpa 出站 RPA 产物,
|
||||
复用货代出站 trigger 链路),不创建排程。按来源取站点、出站配置与登录连接
|
||||
(全部经 freight_rpa.reports.queries 只读入口),先落 RPA 单元运行行
|
||||
(awaiting_rpa,回调按 callback_id 查库可达),再装配出站 trigger unit 并
|
||||
调用 write_outbound_export_batch_trigger 原子写 trigger。
|
||||
依赖:write_outbound_export_batch_trigger(默认 writer,freight_rpa.outbound.trigger_io)、
|
||||
freight_rpa.reports.queries(get_site / get_outbound_config / get_rpa_login_profile /
|
||||
list_outbound_configured_source_codes——站点、配置与登录连接读取唯一权威)、db。
|
||||
逻辑:list_outbound_capable_source_codes 供排程 source_codes 留空时的缺省范围;
|
||||
一源一单元,query_parameters 原样下发;来源停用/出站配置缺失/登录连接缺失时
|
||||
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
|
||||
trigger_outbound_rpa_batch 把多来源合并为一个 batch trigger 文件:
|
||||
Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。
|
||||
trigger unit 载荷键集与 Worker 契约(freight_rpa.outbound.v1)逐键对齐入站。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.services.freight_rpa.outbound.trigger_io import (
|
||||
ACTION_OUTBOUND_EXPORT_BATCH,
|
||||
SCHEMA,
|
||||
write_outbound_export_batch_trigger,
|
||||
)
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
get_outbound_config,
|
||||
get_rpa_login_profile,
|
||||
get_site,
|
||||
list_outbound_configured_source_codes,
|
||||
)
|
||||
|
||||
RouteTriggerWriter = Callable[..., str | None]
|
||||
|
||||
|
||||
def _write_outbound_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None:
|
||||
"""适配出站 IO 的 meta 形参,对外保持与入站 writer 相同的 payload= 协议。"""
|
||||
return write_outbound_export_batch_trigger(run_no, units, meta=payload)
|
||||
|
||||
|
||||
def _build_trigger_unit(
|
||||
*, source_code: str, business_date: str, reason: str,
|
||||
) -> dict[str, Any]:
|
||||
"""装配单来源出站 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。
|
||||
|
||||
核心逻辑:一源一单元,query_parameters 原样下发;空条件表示 Worker 走页面默认。
|
||||
站点(get_site)/ 出站配置(get_outbound_config)/ 登录连接
|
||||
(get_rpa_login_profile)读取改经 freight_rpa.reports.queries 只读入口;装配出的
|
||||
unit 载荷键集与 Worker 契约逐键保持不变(快照含配置行主键与版本)。
|
||||
"""
|
||||
site = get_site(source_code)
|
||||
if site is None or not site.enabled:
|
||||
raise RuntimeError(f'source not enabled: {source_code}')
|
||||
config = get_outbound_config(source_code)
|
||||
if config is None:
|
||||
raise RuntimeError(f'outbound config missing: {source_code}')
|
||||
profile = get_rpa_login_profile(source_code)
|
||||
if profile is None or not profile.enabled:
|
||||
raise RuntimeError(f'outbound source profile unavailable: {source_code}')
|
||||
query_parameters = [
|
||||
dict(item) for item in (config.query_parameters_json or []) if isinstance(item, dict)
|
||||
]
|
||||
snapshot = {
|
||||
'config_id': config.config_id, 'config_version': config.config_version,
|
||||
'connector_type': site.connector_type,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': query_parameters,
|
||||
'warehouse_id': None, 'rpa_profile_id': profile.profile_id,
|
||||
}
|
||||
return {
|
||||
'source_id': site.source_id,
|
||||
'callback_id': f'outbound:{uuid.uuid4().hex}',
|
||||
'source_code': site.source_code,
|
||||
'connector_type': site.connector_type,
|
||||
'warehouse_id': None,
|
||||
'rpa_profile_id': profile.profile_id,
|
||||
'rpa_profile_code': profile.profile_code,
|
||||
'login_url': profile.login_url,
|
||||
'login_config': dict(profile.login_config or {}),
|
||||
'credential_envelope': {
|
||||
'username_ciphertext': profile.username_ciphertext,
|
||||
'password_ciphertext': profile.password_ciphertext,
|
||||
},
|
||||
'report_path_json': dict(snapshot.get('report_path_json') or {}),
|
||||
'query_parameters_json': list(query_parameters),
|
||||
'config_snapshot': snapshot,
|
||||
'business_date': business_date,
|
||||
'reason': reason,
|
||||
}
|
||||
|
||||
|
||||
def list_outbound_capable_source_codes() -> list[str]:
|
||||
"""列出可产出出站文件的启用来源实例(已配置出站报表的启用站点)。
|
||||
|
||||
用途:在途自动调拨排程 source_codes 留空时的缺省执行范围——出站文件
|
||||
只能来自已配置出站报表的站点,与货代出站 RPA 排程的站点口径一致。
|
||||
Returns:
|
||||
按 source_code 排序的来源编码列表;无匹配站点时为空列表。
|
||||
"""
|
||||
return list_outbound_configured_source_codes()
|
||||
|
||||
|
||||
def trigger_outbound_rpa(
|
||||
*,
|
||||
source_code: str,
|
||||
business_date: str,
|
||||
reason: str = 'transfer_retry_outbound',
|
||||
writer: RouteTriggerWriter | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""触发一次来源出站 RPA 抓取(先落单元行再写 trigger,保证回调可达)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
business_date: 业务日期。
|
||||
reason: 触发原因(写入 trigger)。
|
||||
writer: 触发写者;缺省复用 write_outbound_export_batch_trigger(payload= 协议)。
|
||||
Returns:
|
||||
{"ok": True, "callback_id": ..., "trigger_path": ...} 或
|
||||
{"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。
|
||||
"""
|
||||
try:
|
||||
unit_payload = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
|
||||
except RuntimeError as exc:
|
||||
return {"ok": False, "error_code": "RPA_OUTBOUND_CONFIG_MISSING", "error_message": str(exc)}
|
||||
|
||||
# [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库,
|
||||
# 不落行则回调必然 404(与排程路径 / 入站按需触发同一模式)。
|
||||
from app import db
|
||||
from app.models.freight_rpa_outbound_report import FreightRpaOutboundUnitRun as FreightRpaOutboundUnitRun
|
||||
|
||||
unit = FreightRpaOutboundUnitRun(
|
||||
# 按需触发无 ScheduleRun:schedule_run_id 保持 NULL(列可空;FK 禁止 0 占位)。
|
||||
source_id=unit_payload['source_id'],
|
||||
source_code=unit_payload['source_code'],
|
||||
connector_type=unit_payload['connector_type'],
|
||||
warehouse_id=unit_payload.get('warehouse_id'),
|
||||
callback_id=unit_payload['callback_id'],
|
||||
status='awaiting_rpa',
|
||||
config_snapshot_json=dict(unit_payload['config_snapshot']),
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.flush()
|
||||
unit_payload['unit_run_id'] = unit.id
|
||||
|
||||
# [STEP 2] 原子写 trigger;目录不可用则单元标 failed(fail-closed,不留永久 awaiting)。
|
||||
run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}"
|
||||
writer_fn = writer or _write_outbound_trigger
|
||||
path = writer_fn(run_no, [unit_payload], payload={
|
||||
'schema_version': SCHEMA,
|
||||
'action': ACTION_OUTBOUND_EXPORT_BATCH,
|
||||
'source_code': source_code,
|
||||
'business_date': business_date,
|
||||
'reason': reason,
|
||||
})
|
||||
if not path:
|
||||
unit.status = 'failed'
|
||||
unit.error_code = 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE'
|
||||
unit.error_message = 'outbound trigger directory unavailable'
|
||||
db.session.commit()
|
||||
return {"ok": False, "error_code": "RPA_OUTBOUND_TRIGGER_UNAVAILABLE"}
|
||||
|
||||
# [STEP 3] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
|
||||
unit.trigger_snapshot_json = unit_payload
|
||||
db.session.commit()
|
||||
return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path}
|
||||
|
||||
|
||||
def trigger_outbound_rpa_batch(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
business_date: str,
|
||||
reason: str = 'transfer_retry_outbound',
|
||||
writer: RouteTriggerWriter | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""批量触发多来源出站 RPA:全部有效来源合并写**一个** batch trigger 文件。
|
||||
|
||||
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个出站来源编码时调用;
|
||||
行级单来源重试仍走 trigger_outbound_rpa(一源一文件语义不变)。
|
||||
|
||||
核心逻辑:逐来源装配 unit(来源级隔离——配置缺失/停用跳过并记录,不炸整批);
|
||||
有效 units 先各落一行 RPA 单元运行行再一次性 write_outbound_export_batch_trigger
|
||||
原子落盘。Worker 对单文件按 profile 分组共享一次浏览器会话串行导出。
|
||||
入站 batch 的 parse_failed 本地重解析不在此复用——来源文件状态投影仅覆盖入站归档。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例编码列表(去重保序;空串自动剔除)。
|
||||
business_date: 业务日期。
|
||||
reason: 触发原因(写入 trigger payload)。
|
||||
writer: 触发写者;缺省复用 write_outbound_export_batch_trigger。
|
||||
|
||||
Returns:
|
||||
{"ok": True/False, "triggered": bool, "results": [...], "trigger_path"?/「error_code」?}。
|
||||
ok=本次请求产生了主效果(写盘成功);triggered=是否写了 batch trigger;
|
||||
results 逐来源携带真实结果。
|
||||
"""
|
||||
from app import db
|
||||
from app.models.freight_rpa_outbound_report import FreightRpaOutboundUnitRun as FreightRpaOutboundUnitRun
|
||||
|
||||
codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip()))
|
||||
results: list[dict[str, Any]] = []
|
||||
units: list[FreightRpaOutboundUnitRun] = []
|
||||
unit_payloads: list[dict[str, Any]] = []
|
||||
|
||||
# [STEP 1] 逐来源装配 unit;单源失败跳过不阻断整批。
|
||||
for code in codes:
|
||||
try:
|
||||
unit_payloads.append(_build_trigger_unit(source_code=code, business_date=business_date, reason=reason))
|
||||
except RuntimeError as exc:
|
||||
results.append({
|
||||
'source_code': code, 'ok': False,
|
||||
'error_code': 'RPA_OUTBOUND_CONFIG_MISSING', 'error_message': str(exc),
|
||||
})
|
||||
|
||||
if not unit_payloads:
|
||||
db.session.commit()
|
||||
return {"ok": False, "triggered": False, "error_code": "RPA_OUTBOUND_NO_TRIGGERABLE_SOURCE", "results": results}
|
||||
|
||||
# [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。
|
||||
for payload in unit_payloads:
|
||||
unit = FreightRpaOutboundUnitRun(
|
||||
source_id=payload['source_id'],
|
||||
source_code=payload['source_code'],
|
||||
connector_type=payload['connector_type'],
|
||||
warehouse_id=payload.get('warehouse_id'),
|
||||
callback_id=payload['callback_id'],
|
||||
status='awaiting_rpa',
|
||||
config_snapshot_json=dict(payload['config_snapshot']),
|
||||
)
|
||||
db.session.add(unit)
|
||||
units.append(unit)
|
||||
db.session.flush()
|
||||
for unit, payload in zip(units, unit_payloads):
|
||||
payload['unit_run_id'] = unit.id
|
||||
|
||||
# [STEP 3] 一个 batch trigger 原子落盘;目录不可用则本批单元全部标 failed(不留永久 awaiting)。
|
||||
run_no = f"TRIG-BATCH-{uuid.uuid4().hex[:8].upper()}"
|
||||
writer_fn = writer or _write_outbound_trigger
|
||||
path = writer_fn(run_no, unit_payloads, payload={
|
||||
'schema_version': SCHEMA,
|
||||
'action': ACTION_OUTBOUND_EXPORT_BATCH,
|
||||
'business_date': business_date,
|
||||
'reason': reason,
|
||||
'source_codes': [payload['source_code'] for payload in unit_payloads],
|
||||
})
|
||||
if not path:
|
||||
for unit in units:
|
||||
unit.status = 'failed'
|
||||
unit.error_code = 'RPA_OUTBOUND_TRIGGER_UNAVAILABLE'
|
||||
unit.error_message = 'outbound trigger directory unavailable'
|
||||
db.session.commit()
|
||||
return {"ok": False, "triggered": False, "error_code": "RPA_OUTBOUND_TRIGGER_UNAVAILABLE", "results": results}
|
||||
|
||||
# [STEP 4] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
|
||||
for unit, payload in zip(units, unit_payloads):
|
||||
unit.trigger_snapshot_json = payload
|
||||
results.append({'source_code': unit.source_code, 'ok': True})
|
||||
db.session.commit()
|
||||
return {"ok": True, "triggered": True, "trigger_path": path, "results": results}
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨严格数量门禁。
|
||||
|
||||
用途:实现"收料数量 == 外部系统 账面库存 才可执行"的精确匹配规则,
|
||||
用途:实现"异动数量 == 外部系统 账面库存 才可执行"的精确匹配规则,
|
||||
禁止部分调拨、数量容差与隐式截断。
|
||||
依赖:标准库 decimal。
|
||||
逻辑:所有比较基于 Decimal 精确语义;非法数量(0/负数/非数字)在解析层拒绝。
|
||||
@@ -18,11 +18,11 @@ MATCH_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
|
||||
|
||||
|
||||
class QuantityValidationError(ValueError):
|
||||
"""收料数量非法(0、负数、非数字)。"""
|
||||
"""入站数量非法(0、负数、非数字)。"""
|
||||
|
||||
|
||||
def validate_receipt_quantity(value: Any) -> Decimal:
|
||||
"""校验并归一化收料数量。
|
||||
def validate_inbound_quantity(value: Any) -> Decimal:
|
||||
"""校验并归一化入站数量。
|
||||
|
||||
Args:
|
||||
value: 数字或数字字符串。
|
||||
@@ -34,9 +34,9 @@ def validate_receipt_quantity(value: Any) -> Decimal:
|
||||
try:
|
||||
quantity = Decimal(str(value))
|
||||
except (InvalidOperation, ValueError) as exc:
|
||||
raise QuantityValidationError(f"invalid receipt quantity: {value!r}") from exc
|
||||
raise QuantityValidationError(f"invalid inbound quantity: {value!r}") from exc
|
||||
if quantity <= 0:
|
||||
raise QuantityValidationError(f"receipt quantity must be positive: {value!r}")
|
||||
raise QuantityValidationError(f"inbound quantity must be positive: {value!r}")
|
||||
return quantity
|
||||
|
||||
|
||||
@@ -45,17 +45,17 @@ def strict_quantities_equal(left: Any, right: Any) -> bool:
|
||||
return Decimal(str(left)) == Decimal(str(right))
|
||||
|
||||
|
||||
def classify_quantity_match(receipt_quantity: Any, external_quantity: Any | None) -> str:
|
||||
def classify_quantity_match(inbound_quantity: Any, external_quantity: Any | None) -> str:
|
||||
"""按严格相等规则分类数量匹配结果。
|
||||
|
||||
Args:
|
||||
receipt_quantity: 收料数量。
|
||||
inbound_quantity: 入站异动数量。
|
||||
external_quantity: 外部系统 账面库存;None 表示无库存。
|
||||
Returns:
|
||||
'executable' | 'blocked_quantity_mismatch' | 'blocked_inventory_not_found'。
|
||||
"""
|
||||
if external_quantity is None:
|
||||
return MATCH_INVENTORY_NOT_FOUND
|
||||
if strict_quantities_equal(receipt_quantity, external_quantity):
|
||||
if strict_quantities_equal(inbound_quantity, external_quantity):
|
||||
return MATCH_EXECUTABLE
|
||||
return MATCH_QUANTITY_MISMATCH
|
||||
@@ -1,69 +0,0 @@
|
||||
"""在途调拨收料归档文件的可用性门禁(单一事实来源)。
|
||||
|
||||
用途:把「一份 ShippingReceiptReportFile 是否可用于调拨链路」的判定收敛为本模块,
|
||||
供来源状态投影(source_file_status)、匹配取文件(movement_file_repository)、
|
||||
收料文件下载(api/in_transit_transfer)三处统一引用,防止口径漂移。
|
||||
依赖:models(ShippingReceiptReportFile)、date_policy(业务日 UTC 窗口换算)。
|
||||
逻辑:可用 = 未清理 且 当天(Asia/Shanghai 业务日)抓取 且 未过保留期;
|
||||
已失效(expired)= 可用核心的反相(未清理 且 [保留期已到 或 非当天抓取])。
|
||||
两函数同核推导,规则文本只存在一处。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import ColumnElement, and_, not_, or_
|
||||
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.services.in_transit_transfer.date_policy import business_date_utc_window
|
||||
|
||||
|
||||
def _fresh_and_retention_valid(now: datetime) -> ColumnElement:
|
||||
"""新鲜度 + 保留期核心条件(不含清理态,供可用/失效两函数共用)。"""
|
||||
window_start, window_end = business_date_utc_window(now)
|
||||
return and_(
|
||||
ShippingReceiptReportFile.created_at >= window_start,
|
||||
ShippingReceiptReportFile.created_at < window_end,
|
||||
or_(
|
||||
ShippingReceiptReportFile.archive_expires_at.is_(None),
|
||||
ShippingReceiptReportFile.archive_expires_at > now,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def usable_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
|
||||
"""返回「当前可用的收料归档文件」SQL 条件。
|
||||
|
||||
判定:未清理(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
|
||||
+ 未过保留期(archive_expires_at 为空视为长期有效)。匹配复用与下载
|
||||
只认可用文件;隔日/过期文件一律 fail-closed,交由上游触发重抓。
|
||||
|
||||
Args:
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
可直接并入 .filter() 的单个 SQLAlchemy 条件。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
return and_(
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
_fresh_and_retention_valid(now),
|
||||
)
|
||||
|
||||
|
||||
def expired_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
|
||||
"""返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。
|
||||
|
||||
判定:未清理 且 可用核心不成立(保留期已到 或 非当天业务日抓取)。
|
||||
命中即提示用户重试重抓,不报 ready,也不等待保留期清理任务落位。
|
||||
|
||||
Args:
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
可直接并入 .filter() 的单个 SQLAlchemy 条件。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
return and_(
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
not_(_fresh_and_retention_valid(now)),
|
||||
)
|
||||
@@ -1,22 +1,33 @@
|
||||
"""在途调拨人工重试服务(基于冻结文件仅重新查询 外部系统)。
|
||||
"""在途调拨人工重试服务(基于冻结快照仅重新查询 外部系统)。
|
||||
|
||||
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 外部系统;
|
||||
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
|
||||
依赖:models、capability_client、quantity、status、audit、matching_service.TransferDeps。
|
||||
依赖:models、capability_client、quantity、status、audit、matching_service.TransferDeps、
|
||||
scope_rules.parse_scope_rules、scope_rules.record_kinds_of。
|
||||
逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断;
|
||||
重查即续新鲜度——每次重检显式刷新行 updated_at(执行门禁行级 TTL 的续期机制);
|
||||
重查前置兜底对齐(STEP 0,同 run_matching):两个批量重查入口先 align_scope_rows
|
||||
补救落地同步失败/迟到的证据,再圈行重查(待处理池后门不得基于过期证据作答);
|
||||
【2026-10-14 对档对账(ADR 0001/规格 §9)】requery_items(匹配号入口)前置
|
||||
「对档重圈 → 与本匹配自有 items 对账」:档新增记录 → 补建 item(绑同一
|
||||
匹配);档证据变 → 刷新 item 证据并重置待查;档记录消失 → item 失效隔离
|
||||
(沿用 blocked_file_removed 语义退出主视图)。圈档复用匹配创建的同一函数
|
||||
(_circle_ledger_records:固定条件单点实现;记录类型取
|
||||
record_kinds_of(快照 scope_rules))+ 同一快照规则(scope_json),
|
||||
D17 占用互斥排除「其他匹配」的有效占用(本匹配自有 items 不构成占用);
|
||||
终态行(已执行/人工关闭/取消/在流)绝不触碰——已执行行不得被证据刷新
|
||||
复活(防同批档证据更新促成二次写 ERP)。
|
||||
原 align_scope_rows 文件兜底对齐已随出生翻转退役(重查不再对文件对账);
|
||||
库存查询按组织批量(2026-09-29):全部重查/恢复/单据重试入口统一经
|
||||
_recheck_items_batch——路由解析按 external_org 分组,一组一次
|
||||
capabilities.query_stock(与执行链写前复查同形态),行级评估 / Attempt /
|
||||
审计 / 新鲜度续期保持单行粒度;N 行重查 = 每组织 1 次外部调用,
|
||||
禁止回退逐行单查(N 行 N 次调用会打崩外部系统);
|
||||
file_removed 失效行不可重查:匹配号圈行路径由 scope 谓词排除,按 id 直取与
|
||||
路由解析叠加类型仓库定义(resolve_warehouse:fixed 覆盖映射档);
|
||||
file_removed 失效行不可重查:匹配号圈行路径由对账口径排除,按 id 直取与
|
||||
单行入口由资格门禁 _gate_retryable_item 兜底拒绝(拒绝逻辑单点闭环,消失
|
||||
证据不可用旧库存翻回可执行);
|
||||
交易单位唯一来源=ERP 库存行 stock_unit(img09):重查命中且数量一致但 ERP
|
||||
未给单位 → blocked_missing_unit(不落 ready,单位不得以文件值顶替)。
|
||||
未给单位 → blocked_missing_unit(不落 ready,单位不得以文件值顶替);
|
||||
批号查询目标经行所属匹配快照的转换规则派生(item_external_lot_no)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,20 +45,26 @@ from app.models import TransferAttempt, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.capability_client import StockTarget
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.evidence_sync import align_scope_rows
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
RESULT_EXTERNAL_QUERY_FAILED,
|
||||
RESULT_EXECUTABLE,
|
||||
RESULT_FILE_REMOVED,
|
||||
RESULT_MISSING_UNIT,
|
||||
RESULT_ROUTE_NOT_RESOLVED,
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
scope_item_query,
|
||||
_born_item_from_record,
|
||||
_circle_ledger_records,
|
||||
_dedupe_ledger_records_for_item_birth,
|
||||
_item_grain_of_ledger,
|
||||
_resolve_route_with_config,
|
||||
_SYNC_TERMINAL_STATUSES,
|
||||
item_external_lot_no,
|
||||
)
|
||||
from app.services.in_transit_transfer.movement_contract import external_lot_no
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.scope_rules import parse_scope_rules, record_kinds_of
|
||||
from app.services.in_transit_transfer.serializers import DOCUMENT_STATUS_GROUPS
|
||||
from app.services.in_transit_transfer.transfer_type import resolve_transfer_type
|
||||
|
||||
RETRY_KIND_EXTERNAL_RECHECK = "external_recheck"
|
||||
RETRY_KIND_RPA_REFETCH = "rpa_refetch"
|
||||
@@ -62,6 +79,38 @@ _RETRYABLE_STATUSES = {
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _route_for_item(deps: TransferDeps, item: TransferInvoiceItem) -> RouteMapping:
|
||||
"""行级路由解析:映射档解析 + 行所属匹配类型的仓库定义(mapped/fixed)叠加。
|
||||
|
||||
Args:
|
||||
deps: 注入依赖(route_resolver=映射档解析)。
|
||||
item: 重查行(matching_id 关联的匹配快照携带 transfer_type)。
|
||||
Returns:
|
||||
RouteMapping(fixed 角色按类型配置覆盖仓库/法人;无匹配或快照无类型码
|
||||
时透传映射档——存量兼容兜底)。
|
||||
Raises:
|
||||
RouteNotResolvedError / ValidationError: 映射档不可解析或类型配置脏数据
|
||||
(fail-closed,调用方按行级前置解析失败隔离)。
|
||||
"""
|
||||
config = None
|
||||
if item.matching_id is not None and item.matching is not None:
|
||||
scope = item.matching.scope_json if isinstance(item.matching.scope_json, dict) else {}
|
||||
type_code = scope.get("transfer_type")
|
||||
if type_code:
|
||||
# 存量重跑/重查不要求类型仍启用(「停用后存量不受影响」)。
|
||||
config = resolve_transfer_type(type_code, require_enabled=False)
|
||||
if config is None:
|
||||
return deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.movement_warehouse_code or "",
|
||||
)
|
||||
return _resolve_route_with_config(
|
||||
deps, config,
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.movement_warehouse_code or "",
|
||||
)
|
||||
|
||||
|
||||
def _gate_retryable_item(item_id: int) -> TransferInvoiceItem:
|
||||
"""单行重查资格门禁(单行与按 id 批量入口共用的拒绝单点)。
|
||||
|
||||
@@ -72,7 +121,7 @@ def _gate_retryable_item(item_id: int) -> TransferInvoiceItem:
|
||||
Raises:
|
||||
NotFoundError: item 不存在。
|
||||
ValidationError: result_unknown 只读 / 状态不可重试 / file_removed 行
|
||||
不可重查(消失证据不可恢复:证据行的源单已从最新收料文件中消失,
|
||||
不可重查(消失证据不可恢复:证据行的源单已从最新入站文件中消失,
|
||||
重查只会用外部系统旧库存把行翻回可执行,唯一出口=人工关闭 /
|
||||
等重新同步恢复该行)。
|
||||
"""
|
||||
@@ -139,7 +188,7 @@ def _degrade_recheck_row(item: TransferInvoiceItem, *, attempt: TransferAttempt,
|
||||
|
||||
|
||||
def _apply_recheck_outcome(item: TransferInvoiceItem, *, attempt: TransferAttempt,
|
||||
before_status: str, receipt_qty: Decimal, stock_row,
|
||||
before_status: str, inbound_qty: Decimal, stock_row,
|
||||
operation_id: str, request_id: str | None) -> str:
|
||||
"""行级评估收口:账面对照落状态/结果码/外部数量/单位,关闭 Attempt 并写审计。
|
||||
|
||||
@@ -147,14 +196,14 @@ def _apply_recheck_outcome(item: TransferInvoiceItem, *, attempt: TransferAttemp
|
||||
item: 重查行(Attempt 已创建并 flush)。
|
||||
attempt: 该行本次 external_query Attempt(running 态)。
|
||||
before_status: 重查前状态(审计 before)。
|
||||
receipt_qty: 行收料数量(严格相等判定的基准)。
|
||||
inbound_qty: 行异动数量(严格相等判定的基准)。
|
||||
stock_row: 批量查询结果中该行的账面行(StockRow);查无记录为 None。
|
||||
operation_id / request_id: 审计上下文(查询 operation_id 组内共享)。
|
||||
Returns:
|
||||
重查后的行状态。
|
||||
"""
|
||||
stock_qty = stock_row.quantity if stock_row is not None else None
|
||||
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
|
||||
if stock_qty is None or classify_quantity_match(inbound_qty, stock_qty) != RESULT_EXECUTABLE:
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = "blocked_inventory_not_found" if stock_qty is None else "blocked_quantity_mismatch"
|
||||
item.result_message = "external inventory not found" if stock_qty is None else "strict quantity mismatch"
|
||||
@@ -232,19 +281,17 @@ def _recheck_items_batch(
|
||||
行未被触碰、未建 Attempt;批量入口转为该行 ok=False,单行入口原样上抛
|
||||
保持历史 fail-closed 行为)。
|
||||
"""
|
||||
# [STEP 1] 行级前置解析(行级隔离):路由解析 + 收料数量解析,失败行原位
|
||||
# 跳过、不拖垮整批;行仓库字段刷新为本次解析值——查询与后续执行写路径必须
|
||||
# 用同一仓库值:行上旧值可能来自更早配置(路由已漂移),也可能为空(如
|
||||
# blocked_missing_unit 行在路由解析前被阻断)。
|
||||
# [STEP 1] 行级前置解析(行级隔离):路由解析(叠加行所属匹配类型的仓库
|
||||
# 定义,fixed 覆盖映射档)+ 异动数量解析,失败行原位跳过、不拖垮整批;行仓库
|
||||
# 字段刷新为本次解析值——查询与后续执行写路径必须用同一仓库值:行上旧值可能
|
||||
# 来自更早配置(路由已漂移),也可能为空(如 blocked_missing_unit 行在路由
|
||||
# 解析前被阻断)。
|
||||
resolved: list[tuple[TransferInvoiceItem, RouteMapping, Decimal]] = []
|
||||
row_errors: dict[int, Exception] = {}
|
||||
for item in items:
|
||||
try:
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
receipt_qty = Decimal(item.receipt_quantity)
|
||||
route = _route_for_item(deps, item)
|
||||
inbound_qty = Decimal(item.movement_quantity)
|
||||
except Exception as exc: # noqa: BLE001 —— 行级隔离:路由漂移/缺失/脏数量只影响该行
|
||||
row_errors[item.id] = exc
|
||||
logger.warning(
|
||||
@@ -255,7 +302,7 @@ def _recheck_items_batch(
|
||||
if (item.from_warehouse or "") != route.from_warehouse or (item.to_warehouse or "") != route.to_warehouse:
|
||||
item.from_warehouse = route.from_warehouse
|
||||
item.to_warehouse = route.to_warehouse
|
||||
resolved.append((item, route, receipt_qty))
|
||||
resolved.append((item, route, inbound_qty))
|
||||
|
||||
# [STEP 2] 按组织分组(同写前复查的 external_org 分组口径):同组行共享
|
||||
# 一次批量查询,N 行 = 每组织 1 次外部调用。
|
||||
@@ -271,7 +318,7 @@ def _recheck_items_batch(
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
attempts: dict[int, TransferAttempt] = {}
|
||||
before_statuses: dict[int, str] = {}
|
||||
for item, route, receipt_qty in entries:
|
||||
for item, route, inbound_qty in entries:
|
||||
item.attempt_no += 1
|
||||
before_statuses[item.id] = item.status
|
||||
attempts[item.id] = TransferAttempt(
|
||||
@@ -280,19 +327,20 @@ def _recheck_items_batch(
|
||||
request_snapshot_json={
|
||||
"invoice_no": item.invoice_no, "external_org": external_org,
|
||||
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
|
||||
"quantity": str(receipt_qty),
|
||||
"quantity": str(inbound_qty),
|
||||
},
|
||||
)
|
||||
db.session.add(attempts[item.id])
|
||||
db.session.flush()
|
||||
try:
|
||||
# [外部形态] 查询目标与回查同用 WTP→HOW 派生批号(movement_contract.external_lot_no)。
|
||||
# [外部形态] 查询目标与回查同用行所属匹配快照转换规则派生批号
|
||||
# (item_external_lot_no;行落库保持档原形)。
|
||||
stock = deps.capabilities.query_stock(
|
||||
operation_id=operation_id, external_org=external_org,
|
||||
targets=[StockTarget(
|
||||
material_no=item.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(item.lot_no),
|
||||
) for item, route, _receipt_qty in entries],
|
||||
lot_no=item_external_lot_no(item),
|
||||
) for item, route, _inbound_qty in entries],
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# [降级] 外部系统网关/绑定故障是组级事实:组内各行统一降级为
|
||||
@@ -303,22 +351,22 @@ def _recheck_items_batch(
|
||||
"transfer recheck org query failed (degrade rows): org=%s rows=%s error=%s",
|
||||
external_org, len(entries), detail,
|
||||
)
|
||||
for item, route, receipt_qty in entries:
|
||||
for item, route, inbound_qty in entries:
|
||||
statuses[item.id] = _degrade_recheck_row(
|
||||
item, attempt=attempts[item.id], before_status=before_statuses[item.id],
|
||||
detail=detail, operation_id=operation_id, request_id=request_id,
|
||||
)
|
||||
db.session.commit()
|
||||
continue
|
||||
for item, route, receipt_qty in entries:
|
||||
for item, route, inbound_qty in entries:
|
||||
# [外部形态] 回查键与查询目标同用派生批号(三元组精确匹配)。
|
||||
stock_row = stock.lookup_row(
|
||||
material_no=item.material_no, warehouse_code=route.from_warehouse,
|
||||
lot_no=external_lot_no(item.lot_no),
|
||||
lot_no=item_external_lot_no(item),
|
||||
)
|
||||
statuses[item.id] = _apply_recheck_outcome(
|
||||
item, attempt=attempts[item.id], before_status=before_statuses[item.id],
|
||||
receipt_qty=receipt_qty, stock_row=stock_row,
|
||||
inbound_qty=inbound_qty, stock_row=stock_row,
|
||||
operation_id=operation_id, request_id=request_id,
|
||||
)
|
||||
db.session.commit()
|
||||
@@ -380,18 +428,6 @@ def requery_items_by_ids(
|
||||
ids = [int(x) for x in (item_ids or []) if x is not None]
|
||||
if not ids:
|
||||
raise ValidationError("item_ids is required", code="TRANSFER.BATCH_ITEMS_REQUIRED")
|
||||
# [口径] 受影响来源=按 id 查回行的 source_code 去重(先查行→对齐→再重查)。
|
||||
source_rows = (
|
||||
db.session.query(TransferInvoiceItem.source_code)
|
||||
.filter(TransferInvoiceItem.id.in_(ids))
|
||||
.all()
|
||||
)
|
||||
affected_sources = sorted({(code or "").strip() for (code,) in source_rows})
|
||||
# [兜底对齐] 落地同步失败/迟到的静默补救:重查前先保证行对齐最新文件。
|
||||
# 对齐可能重写行集(证据变化重置回待查、消失行复现恢复),必须先于任何
|
||||
# 重查读取执行,否则待处理池后门会基于过期证据放行旧库存。
|
||||
align_scope_rows(source_codes=affected_sources, deps=deps,
|
||||
business_date=str(business_date_now()), now=datetime.utcnow())
|
||||
results_by_id: dict[int, dict] = {}
|
||||
eligible: list[TransferInvoiceItem] = []
|
||||
for item_id in ids:
|
||||
@@ -411,19 +447,179 @@ def requery_items_by_ids(
|
||||
return {"total": len(ids), "results": [results_by_id[item_id] for item_id in ids]}
|
||||
|
||||
|
||||
def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""批量重查 外部系统 库存:按匹配 scope 圈定全部/指定的可重查行,按组织批量查询并刷新。
|
||||
def _reconcile_items_with_ledger(
|
||||
matching, *, deps: TransferDeps, wanted_doc_nos: list[str] | None,
|
||||
) -> None:
|
||||
"""对档重圈并与本匹配自有 items 对账(出生翻转后重查的前置步骤,规格 §9)。
|
||||
|
||||
圈行口径与匹配卡实时视图同源(scope_item_query:来源+收料日期区间+调拨类型),
|
||||
行归属 matching_id 不参与——行归属解耦后行不随匹配迁移,视图能看到的历史行
|
||||
(matching_id 指向旧匹配)必须同样可被本次匹配的重查触达,否则出现「卡片提示
|
||||
重查、重查却查不到行」的死锁(2026-09-24 修复)。
|
||||
核心逻辑:[STEP 1] 按匹配快照规则(scope_rules + 来源 + 异动日期范围)圈定
|
||||
档记录——复用匹配创建的同一圈档函数 _circle_ledger_records(固定条件单点
|
||||
实现,杜绝谓词漂移)。记录类型取 record_kinds_of(已解析的快照 rules)
|
||||
(仅没有范围规则、也没有类型对象的调用点才显式只圈 inbound)。
|
||||
排除已执行封存、其他匹配的有效占用(D17;本匹配自有
|
||||
items 不构成占用)。[STEP 2] 三分类对账(**终态守卫:SUCCESS/DUPLICATE_
|
||||
SUCCESS/MANUALLY_CLOSED/CANCELLED/EXECUTING/RESULT_UNKNOWN 行绝不触碰——
|
||||
已执行行不得被证据刷新复活,否则同批档证据更新会促成二次写 ERP**):
|
||||
①档有行无(自有 items 未覆盖的圈中记录)→ 补建 item(绑同一匹配;
|
||||
类型配置缺失/路由不可解析时行级落 blocked(可解释、可重查),不影响
|
||||
其余行——口径与 _route_for_item 的逐行兜底对齐);
|
||||
②档证据变(数量/批号/仓库与 item 不一致)→ 刷新 item 证据并重置待查
|
||||
(旧库存是对旧数量查的,作废),展示字段照常刷新(仅非终态行);
|
||||
③自有 item 的档记录消失(防御:档缺席不删,仅异常清理场景)→ 失效隔离
|
||||
(blocked_file_removed,退出主视图,恢复走人工恢复;仅非终态行)。
|
||||
只 flush 不 commit(随调用方事务:requery_items 末尾 _recheck_items_batch
|
||||
的组粒度提交兜底持久化)。
|
||||
|
||||
Args:
|
||||
matching_no: 匹配编号(经 scope_json 圈定行集)。
|
||||
matching: 匹配 ORM 行(scope_json 快照 + 自有 items)。
|
||||
deps: 注入依赖(路由解析)。
|
||||
wanted_doc_nos: 可选单号过滤(invoice_nos 限定重查范围时同步约束补圈)。
|
||||
"""
|
||||
from app.core.errors import ValidationError as _ValidationError
|
||||
from app.services.in_transit_transfer.evidence_sync import SYNC_RESULT_PENDING
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import (
|
||||
get_by_code as get_type_config,
|
||||
)
|
||||
|
||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||
rules = parse_scope_rules(scope.get("scope_rules"))
|
||||
now = datetime.utcnow()
|
||||
|
||||
# [STEP 1] 快照规则圈档(共享圈档函数:与匹配创建同一固定条件实现)。
|
||||
sources = [str(code) for code in (scope.get("source_codes") or [])]
|
||||
records: list = []
|
||||
if sources:
|
||||
records = _dedupe_ledger_records_for_item_birth(
|
||||
_circle_ledger_records(
|
||||
source_codes=sources,
|
||||
rules=rules,
|
||||
movement_date_from=scope.get("movement_date_from"),
|
||||
movement_date_to=scope.get("movement_date_to"),
|
||||
record_kinds=record_kinds_of(rules),
|
||||
exclude_occupied_by_matching_id=matching.id,
|
||||
doc_nos=wanted_doc_nos,
|
||||
)
|
||||
)
|
||||
|
||||
# 类型配置(仓库定义):从快照类型码读现行配置(存量不要求启用)。
|
||||
# [逐行容错] 类型缺失/脏配置不炸整次重查:config=None 时补建行走行级阻断
|
||||
# (口径与 _route_for_item 的逐行兜底对齐;类型只有停用没有删除,正常不触发)。
|
||||
type_code = str(scope.get("transfer_type") or "")
|
||||
config = None
|
||||
if type_code:
|
||||
try:
|
||||
config = get_type_config(type_code)
|
||||
except _ValidationError:
|
||||
config = None
|
||||
|
||||
# [终态守卫·占用面] own_by_record 收全部自有行(含终态):档记录已被本匹配
|
||||
# 任一行(含已执行行)绑定时按「档有行有」处理——终态绑定永不补建第二个 item
|
||||
#(否则已执行记录将以新待查行复活 → 二次写 ERP)。同 grain 兄弟档亦视为已绑。
|
||||
own_by_record = {
|
||||
item.ledger_record_id: item
|
||||
for item in matching.items
|
||||
if item.ledger_record_id is not None
|
||||
}
|
||||
own_grains = {
|
||||
(str(item.source_code or ""), str(item.invoice_no or ""),
|
||||
str(item.material_no or ""), str(item.movement_date or ""))
|
||||
for item in matching.items
|
||||
}
|
||||
for record in records:
|
||||
item = own_by_record.get(record.id)
|
||||
if item is None:
|
||||
grain = _item_grain_of_ledger(record)
|
||||
if grain in own_grains:
|
||||
# 同 grain 已有自有 item(兄弟档 / 择优后的另一 ledger_record_id)。
|
||||
continue
|
||||
# [①补建] 档新增记录:绑同一匹配(D17:本匹配占用即成立)。
|
||||
route = None
|
||||
route_failed = False
|
||||
try:
|
||||
if config is None:
|
||||
raise _ValidationError(f"transfer type config missing: {type_code}")
|
||||
route = _resolve_route_with_config(
|
||||
deps, config,
|
||||
source_code=record.source_code, invoice_no=record.doc_no,
|
||||
warehouse_code=record.warehouse_code or "",
|
||||
)
|
||||
except Exception: # noqa: BLE001 —— 类型缺失/路由失败:行级阻断降级,不影响其余行
|
||||
route = None
|
||||
route_failed = True
|
||||
born = _born_item_from_record(
|
||||
record, matching_id=matching.id,
|
||||
route=route, now=now,
|
||||
)
|
||||
if route_failed:
|
||||
# [行级阻断] 可解释、可重查(配置/路由修复后重查即恢复)。
|
||||
born.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
born.result_code = RESULT_ROUTE_NOT_RESOLVED
|
||||
born.result_message = (
|
||||
f"transfer type config missing: {type_code}" if config is None
|
||||
else f"route not resolved for source {record.source_code}"
|
||||
)
|
||||
db.session.add(born)
|
||||
own_grains.add(grain)
|
||||
continue
|
||||
# [②证据对账] 只比对异动事实(数量/批号/仓库);名称/规格为展示字段。
|
||||
# [终态守卫·刷新面] 终态行(已执行/人工关闭/取消/在流)绝不触碰(含
|
||||
# updated_at)——旧 evidence_sync「终态行绝不触碰/不复活」冻结约束在
|
||||
# 翻转后的延续(防同批档证据更新促成二次写 ERP);非终态行照常对账。
|
||||
if item.status in _SYNC_TERMINAL_STATUSES:
|
||||
continue
|
||||
evidence_changed = (
|
||||
str(item.movement_quantity) != str(record.quantity or "")
|
||||
or (item.lot_no or "") != (record.lot_no or "")
|
||||
or (item.movement_warehouse_code or "") != (record.warehouse_code or "")
|
||||
)
|
||||
item.material_name = record.material_name or ""
|
||||
item.specification = record.specification or ""
|
||||
if evidence_changed:
|
||||
item.movement_quantity = str(record.quantity or "0")
|
||||
item.lot_no = record.lot_no or ""
|
||||
item.movement_warehouse_code = record.warehouse_code or ""
|
||||
# 重置待查:旧库存是对旧数量查的,作废;取数时刻同步置空。
|
||||
item.status = status_machine.TransferStatus.MATCHING.value
|
||||
item.result_code = SYNC_RESULT_PENDING
|
||||
item.result_message = None
|
||||
item.external_quantity = None
|
||||
item.inventory_checked_at = None
|
||||
item.updated_at = now
|
||||
|
||||
# [③失效隔离] 自有 item 的档记录不存在(档缺席不删,正常不触发;防御
|
||||
# 异常清理)→ 沿用 blocked_file_removed 语义退出主视图(仅非终态行;
|
||||
# 终态行的既定事实永不改写)。
|
||||
from app.models import TransferMovementLedger as _Ledger
|
||||
|
||||
record_ids = {record.id for record in records}
|
||||
for item in matching.items:
|
||||
if item.status in _SYNC_TERMINAL_STATUSES:
|
||||
continue
|
||||
if item.ledger_record_id is None or item.ledger_record_id in record_ids:
|
||||
continue
|
||||
if db.session.get(_Ledger, item.ledger_record_id) is None:
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = RESULT_FILE_REMOVED
|
||||
item.result_message = "ledger record removed"
|
||||
item.updated_at = now
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""批量重查 外部系统 库存:先对档对账(补建/刷新/隔离),再圈自有可重查行批量刷新。
|
||||
|
||||
【2026-10-14 对档对账(规格 §9)】原 scope_item_query 实时圈行退役——行由
|
||||
匹配创建时从档圈定且创建即绑定,重查改为:按匹配快照规则对档重圈 → 与本
|
||||
匹配自有 items 对账(档新增记录补建 / 档证据变刷新重置 / 档记录消失隔离)→
|
||||
自有可重查行按组织批量重查。重查只对账本匹配自己的 items,不受 D17 圈档
|
||||
互斥影响(自有占用不排除)。
|
||||
|
||||
Args:
|
||||
matching_no: 匹配编号(scope_json 快照供圈档规则/类型码)。
|
||||
deps: 注入依赖(capabilities = 外部系统网关客户端)。
|
||||
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该 scope 全部可重查行。
|
||||
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该匹配全部可重查行
|
||||
(对账补圈同受此约束,避免范围外补建)。
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
{"matching_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
|
||||
@@ -434,21 +630,16 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str
|
||||
matching = TransferMatching.query.filter_by(matching_no=matching_no).first()
|
||||
if matching is None:
|
||||
raise NotFoundError("matching not found", code="TRANSFER.MATCH_NOT_FOUND")
|
||||
# [口径一致] 受影响来源=scope_json 的 source_codes(与 scope_item_query 圈行同源,
|
||||
# 提取口径同 matching_service.scope_item_query:非 dict 视为空 scope)。
|
||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||
affected_sources = sorted({str(code) for code in (scope.get("source_codes") or [])})
|
||||
# [兜底对齐] 落地同步失败/迟到的静默补救:重查前先保证行对齐最新文件。
|
||||
# 对齐可能重写行集(证据变化重置回待查、消失行复现恢复),必须先于 scope
|
||||
# 圈行执行,否则重查会圈到过期行、基于过期证据放行旧库存。
|
||||
align_scope_rows(source_codes=affected_sources, deps=deps,
|
||||
business_date=str(business_date_now()), now=datetime.utcnow())
|
||||
# [口径统一] 圈行必须与匹配卡视图同谓词(scope:来源+日期区间+类型前缀)——
|
||||
# 行归属解耦后 matching_id 停留在首次创建值,按它圈行会漏掉全部存量行。
|
||||
# file_removed 行排除:消失证据不可重查恢复(唯一出口=人工关闭/出清)。
|
||||
wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()]
|
||||
|
||||
# [STEP A] 对档对账(补建/刷新/隔离,只 flush;持久化随后续组粒度提交)。
|
||||
_reconcile_items_with_ledger(matching, deps=deps, wanted_doc_nos=wanted or None)
|
||||
|
||||
# [STEP B] 自有可重查行(阻断/可执行)批量重查;file_removed 隔离行排除
|
||||
# (消失证据不可重查恢复,唯一出口=人工关闭/等对档修复)。
|
||||
query = (
|
||||
scope_item_query(matching)
|
||||
.filter(
|
||||
TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.matching_id == matching.id,
|
||||
TransferInvoiceItem.status.in_(_RETRYABLE_STATUSES),
|
||||
or_(
|
||||
TransferInvoiceItem.result_code.is_(None),
|
||||
@@ -456,7 +647,6 @@ def requery_items(*, matching_no: str, deps: TransferDeps, invoice_nos: list[str
|
||||
),
|
||||
)
|
||||
)
|
||||
wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()]
|
||||
if wanted:
|
||||
query = query.filter(TransferInvoiceItem.invoice_no.in_(wanted))
|
||||
items = query.order_by(TransferInvoiceItem.id).all()
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""
|
||||
services/in_transit_transfer/rpa_sinks.py
|
||||
|
||||
用途:入站 / 出站 RPA 回调与报表事实的组合根注册——把 /api/freight-rpa/inbound-*、
|
||||
outbound-* 接到 freight_rpa 归档入口与本包事实处理函数(调拨是唯一业务消费方)。
|
||||
依赖:freight_rpa.common.callback_sinks、freight_rpa.reports.dispatch、
|
||||
freight_rpa.inbound/outbound.report_archive、schedule.freight_rpa_*_finalize、
|
||||
inbound_report_handler / outbound_report_handler、models。
|
||||
逻辑:由 app.create_app 调用 register_inbound_sinks / register_outbound_sinks(幂等)。
|
||||
batch-ready:归档单元终态后立即尝试排程 finalize(文件返回= RPA/排程结束),
|
||||
再投递事实;事实处理(证据同步等)失败不得挡排程收口。不 import shipping_notice。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Callable
|
||||
|
||||
_LOG = logging.getLogger(__name__)
|
||||
|
||||
_INBOUND_UNIT_TERMINAL = frozenset({'success', 'empty', 'failed', 'cancelled'})
|
||||
_OUTBOUND_UNIT_TERMINAL = frozenset({'success', 'empty', 'failed', 'cancelled'})
|
||||
|
||||
|
||||
def _success_data_envelope(handler: Callable[[dict[str, Any]], dict[str, Any]]) -> Callable[..., dict[str, Any]]:
|
||||
"""旧 inbound/outbound 进度端点 envelope:{'success':True,'data':业务结果}。"""
|
||||
|
||||
def _sink(**payload: Any) -> dict[str, Any]:
|
||||
return {'success': True, 'data': handler(payload)}
|
||||
|
||||
return _sink
|
||||
|
||||
|
||||
def _try_finalize_inbound_schedule_after_unit(payload: dict[str, Any]) -> None:
|
||||
"""单元已落终态后按文件返回收口入站排程;解析/证据失败不得阻塞。
|
||||
|
||||
核心逻辑:用 callback_id 定位单元;仅当 status 已终态且挂了 schedule_run_id
|
||||
时 refresh + finalize_if_complete(幂等)。异常只记日志,不回滚已提交单元。
|
||||
"""
|
||||
callback_id = str(payload.get('callback_id') or '').strip()
|
||||
if not callback_id:
|
||||
return
|
||||
try:
|
||||
from app.models import FreightRpaInboundUnitRun
|
||||
from app.services.schedule.freight_rpa_inbound_finalize import (
|
||||
finalize_inbound_schedule_run_if_complete,
|
||||
refresh_inbound_schedule_run_progress,
|
||||
)
|
||||
|
||||
unit = FreightRpaInboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
|
||||
if unit is None or unit.schedule_run_id is None:
|
||||
return
|
||||
if str(unit.status or '') not in _INBOUND_UNIT_TERMINAL:
|
||||
return
|
||||
refresh_inbound_schedule_run_progress(int(unit.schedule_run_id))
|
||||
finalize_inbound_schedule_run_if_complete(int(unit.schedule_run_id))
|
||||
except Exception as exc: # noqa: BLE001 - 排程收口失败不得淹没归档结果
|
||||
_LOG.warning(
|
||||
'inbound schedule finalize after unit terminal failed callback_id=%s: %s',
|
||||
callback_id,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
|
||||
def _try_finalize_outbound_schedule_after_unit(payload: dict[str, Any]) -> None:
|
||||
"""单元已落终态后按文件返回收口出站排程;解析/证据失败不得阻塞。"""
|
||||
callback_id = str(payload.get('callback_id') or '').strip()
|
||||
if not callback_id:
|
||||
return
|
||||
try:
|
||||
from app.models import FreightRpaOutboundUnitRun
|
||||
from app.services.schedule.freight_rpa_outbound_finalize import (
|
||||
finalize_outbound_schedule_run_if_complete,
|
||||
refresh_outbound_schedule_run_progress,
|
||||
)
|
||||
|
||||
unit = FreightRpaOutboundUnitRun.query.filter_by(callback_id=callback_id).one_or_none()
|
||||
if unit is None or unit.schedule_run_id is None:
|
||||
return
|
||||
if str(unit.status or '') not in _OUTBOUND_UNIT_TERMINAL:
|
||||
return
|
||||
refresh_outbound_schedule_run_progress(int(unit.schedule_run_id))
|
||||
finalize_outbound_schedule_run_if_complete(int(unit.schedule_run_id))
|
||||
except Exception as exc: # noqa: BLE001 - 排程收口失败不得淹没归档结果
|
||||
_LOG.warning(
|
||||
'outbound schedule finalize after unit terminal failed callback_id=%s: %s',
|
||||
callback_id,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
|
||||
def _inbound_batch_ready_sink(**payload: Any) -> dict[str, Any]:
|
||||
"""入站 batch-ready:归档 →(单元终态后)排程收口 → 返回;事实投递异常仍尽量收口排程。"""
|
||||
from app.services.freight_rpa.inbound.report_archive import ingest_inbound_callback
|
||||
|
||||
try:
|
||||
data = ingest_inbound_callback(payload)
|
||||
return {'success': True, 'data': data}
|
||||
finally:
|
||||
# 单元终态已 commit 后,无论事实处理是否抛错,都按文件返回尝试排程 finalize。
|
||||
_try_finalize_inbound_schedule_after_unit(payload)
|
||||
|
||||
|
||||
def _outbound_batch_ready_sink(**payload: Any) -> dict[str, Any]:
|
||||
"""出站 batch-ready:归档 →(单元终态后)排程收口 → 返回。"""
|
||||
from app.services.freight_rpa.outbound.report_archive import ingest_outbound_callback
|
||||
|
||||
try:
|
||||
data = ingest_outbound_callback(payload)
|
||||
return {'success': True, 'data': data}
|
||||
finally:
|
||||
_try_finalize_outbound_schedule_after_unit(payload)
|
||||
|
||||
|
||||
def register_inbound_sinks() -> None:
|
||||
"""注册全部 inbound 进度 sink 与 inbound 事实处理函数(幂等)。
|
||||
|
||||
核心逻辑:inbound-batch-ready 走归档+文件返回即排程 finalize;unit/batch-progress 挂
|
||||
schedule.freight_rpa_inbound_finalize;事实处理函数挂 handle_inbound_report(证据/
|
||||
调拨推进;排程收口已在 batch-ready 侧完成,handler 内 finalize 仍幂等兜底)。
|
||||
"""
|
||||
from app.services.freight_rpa.common.callback_sinks import register_sink
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.in_transit_transfer.inbound_report_handler import handle_inbound_report
|
||||
from app.services.schedule import freight_rpa_inbound_finalize
|
||||
|
||||
register_sink('inbound-batch-ready', _inbound_batch_ready_sink)
|
||||
register_sink('inbound-unit-progress', _success_data_envelope(freight_rpa_inbound_finalize.mark_inbound_unit_processing))
|
||||
register_sink('inbound-batch-progress', _success_data_envelope(freight_rpa_inbound_finalize.report_inbound_batch_progress))
|
||||
register_report_handler('inbound', handle_inbound_report)
|
||||
|
||||
|
||||
def register_outbound_sinks() -> None:
|
||||
"""注册全部 outbound 进度 sink 与 outbound 事实处理函数(幂等)。
|
||||
|
||||
核心逻辑:outbound-batch-ready 走归档+文件返回即排程 finalize;unit/batch-progress 挂
|
||||
schedule.freight_rpa_outbound_finalize;事实处理函数挂 handle_outbound_report。
|
||||
"""
|
||||
from app.services.freight_rpa.common.callback_sinks import register_sink
|
||||
from app.services.freight_rpa.reports.dispatch import register_report_handler
|
||||
from app.services.in_transit_transfer.outbound_report_handler import handle_outbound_report
|
||||
from app.services.schedule import freight_rpa_outbound_finalize
|
||||
|
||||
register_sink('outbound-batch-ready', _outbound_batch_ready_sink)
|
||||
register_sink('outbound-unit-progress', _success_data_envelope(freight_rpa_outbound_finalize.mark_outbound_unit_processing))
|
||||
register_sink('outbound-batch-progress', _success_data_envelope(freight_rpa_outbound_finalize.report_outbound_batch_progress))
|
||||
register_report_handler('outbound', handle_outbound_report)
|
||||
@@ -0,0 +1,127 @@
|
||||
"""services/in_transit_transfer/scope_rules.py
|
||||
|
||||
用途:调拨类型范围规则引擎——受控字段白名单上的「字段+匹配方式+值列表」规则,
|
||||
规则间 AND、规则内多值 OR;内存谓词与 SQL 编译双形态共用同一解析结果,
|
||||
供匹配创建圈档、重查对账、管理页校验三处单一口径。
|
||||
依赖:app.core.errors.ValidationError;SQLAlchemy Select(编译形态)。
|
||||
逻辑:parse 校验词表/匹配方式/值非空 → ScopeRule 元组;evaluate 逐规则 AND、
|
||||
逐值 OR(prefix/contains 大小写不敏感);apply_scope_filters 生成等价 SQL;
|
||||
record_kinds_of 从 record_kind 范围规则推导证据流(入站/出站)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Mapping, Sequence
|
||||
|
||||
from sqlalchemy import Select, and_, or_, func
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
# 受控字段词表(封闭可扩展;新增字段须同步管理页下拉与 technical.md)。
|
||||
SCOPE_FIELDS: frozenset[str] = frozenset({
|
||||
"source_code", "doc_no", "warehouse_code", "storage_code", "lot_no",
|
||||
"movement_date", "record_kind", "in_out_flag", "order_type", "odm_id",
|
||||
"odm_name", "carton_id", "pallet_id", "material_code", "doc_nature",
|
||||
"movement_type", "reason_code", "partner_code",
|
||||
})
|
||||
|
||||
_MATCHES = ("prefix", "equals", "contains", "in")
|
||||
_RECORD_KINDS = ("inbound", "outbound")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScopeRule:
|
||||
"""单条范围规则:field 字段 / match 匹配方式 / values 值列表(规则内 OR)。"""
|
||||
|
||||
field: str
|
||||
match: str
|
||||
values: tuple[str, ...]
|
||||
|
||||
|
||||
def parse_scope_rules(raw: list[dict] | None) -> tuple[ScopeRule, ...]:
|
||||
"""校验并解析范围规则 JSON(管理页保存与匹配快照共用)。
|
||||
|
||||
Args:
|
||||
raw: [{"field", "match", "values"}];空列表/None 合法(=不限,由调用方决定是否放行)。
|
||||
Returns:
|
||||
ScopeRule 元组。
|
||||
Raises:
|
||||
ValidationError: 字段不在 SCOPE_FIELDS、match 非法、values 空/非字符串。
|
||||
"""
|
||||
rules: list[ScopeRule] = []
|
||||
for item in raw or []:
|
||||
field, match = str(item.get("field", "")), str(item.get("match", ""))
|
||||
values = item.get("values") or []
|
||||
if field not in SCOPE_FIELDS:
|
||||
raise ValidationError(f"unknown scope field: {field}", code="TRANSFER.SCOPE_RULE_INVALID", details={"field": field})
|
||||
if match not in _MATCHES or not values or not all(isinstance(v, str) and v.strip() for v in values):
|
||||
raise ValidationError(f"invalid scope rule: {field}/{match}", code="TRANSFER.SCOPE_RULE_INVALID", details={"field": field, "match": match})
|
||||
rules.append(ScopeRule(field=field, match=match, values=tuple(v.strip() for v in values)))
|
||||
return tuple(rules)
|
||||
|
||||
|
||||
def _hit(value: str | None, rule: ScopeRule) -> bool:
|
||||
text = str(value or "").strip().upper()
|
||||
if not text:
|
||||
return False
|
||||
if rule.match == "prefix":
|
||||
return text.startswith(tuple(v.upper() for v in rule.values))
|
||||
if rule.match == "equals":
|
||||
return text in {v.upper() for v in rule.values}
|
||||
if rule.match == "contains":
|
||||
return any(v.upper() in text for v in rule.values)
|
||||
return text in {v.upper() for v in rule.values} # in
|
||||
|
||||
|
||||
def record_kinds_of(rules: tuple[ScopeRule, ...]) -> tuple[str, ...]:
|
||||
"""从范围规则推导调拨类型需要的证据流(入站/出站)。
|
||||
|
||||
核心逻辑:筛 field=record_kind 的规则;无则默认双轨。多条规则时,各规则
|
||||
允许的 inbound/outbound 集合(与 evaluate 同口径 _hit)逐条取交集;结果按
|
||||
inbound→outbound 顺序输出,交集为空则返回空元组。
|
||||
|
||||
Args:
|
||||
rules: parse_scope_rules 产出的 ScopeRule 元组。
|
||||
Returns:
|
||||
仅含 inbound/outbound 的去重元组。
|
||||
"""
|
||||
kind_rules = [rule for rule in rules if rule.field == "record_kind"]
|
||||
if not kind_rules:
|
||||
return _RECORD_KINDS
|
||||
allowed: set[str] | None = None
|
||||
for rule in kind_rules:
|
||||
rule_allowed = {kind for kind in _RECORD_KINDS if _hit(kind, rule)}
|
||||
allowed = rule_allowed if allowed is None else allowed & rule_allowed
|
||||
if not allowed:
|
||||
return ()
|
||||
return tuple(kind for kind in _RECORD_KINDS if kind in allowed)
|
||||
|
||||
|
||||
def evaluate_scope(record: Mapping[str, Any], rules: Sequence[ScopeRule]) -> bool:
|
||||
"""内存求值:规则间 AND、规则内多值 OR(匹配/测试/小数据场景)。"""
|
||||
return all(_hit(record.get(rule.field), rule) for rule in rules)
|
||||
|
||||
|
||||
def apply_scope_filters(query: Select, model: type, rules: Sequence[ScopeRule]) -> Select:
|
||||
"""SQL 编译(与 evaluate_scope 同口径):圈档与重查对账共用,防谓词漂移。"""
|
||||
clauses = []
|
||||
for rule in rules:
|
||||
col = getattr(model, rule.field)
|
||||
upper = func.upper(col)
|
||||
if rule.match == "prefix":
|
||||
clauses.append(or_(*(upper.like(f"{v.upper()}%") for v in rule.values)))
|
||||
elif rule.match == "equals":
|
||||
clauses.append(upper.in_([v.upper() for v in rule.values]))
|
||||
elif rule.match == "contains":
|
||||
clauses.append(or_(*(upper.contains(v.upper()) for v in rule.values)))
|
||||
else:
|
||||
clauses.append(upper.in_([v.upper() for v in rule.values]))
|
||||
return query.filter(and_(*clauses)) if clauses else query
|
||||
|
||||
|
||||
def scope_rules_note(rules: Sequence[ScopeRule]) -> str:
|
||||
"""范围规则审计说明(写 scope_json 旁路人读字段)。"""
|
||||
parts = []
|
||||
for rule in rules:
|
||||
parts.append(f"{rule.field} {rule.match} {'|'.join(rule.values)}")
|
||||
return " AND ".join(parts)
|
||||
@@ -12,7 +12,10 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.in_transit_transfer.movement_contract import external_lot_no
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
item_external_lot_no,
|
||||
ledger_external_doc_no,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 单状态 → 展示分组映射(Task 17:首页「已执行」区块统计口径)
|
||||
@@ -41,11 +44,9 @@ def serialize_summary(summary) -> dict[str, Any]:
|
||||
"matching_id": summary.matching_id,
|
||||
"status": summary.status,
|
||||
"business_date": summary.business_date,
|
||||
"eligible_receipt_date_to": summary.eligible_receipt_date_to,
|
||||
"expires_at": summary.expires_at,
|
||||
"counts": {
|
||||
"file_invoice_count": summary.counts.file_invoice_count,
|
||||
"not_matured_count": summary.counts.not_matured_count,
|
||||
"matched_count": summary.counts.matched_count,
|
||||
"executable_count": summary.counts.executable_count,
|
||||
"blocked_count": summary.counts.blocked_count,
|
||||
@@ -73,8 +74,9 @@ def serialize_item(item) -> dict[str, Any]:
|
||||
"material_name": item.material_name,
|
||||
"specification": item.specification,
|
||||
"invoice_no": item.invoice_no,
|
||||
"external_doc_no": getattr(item, "external_doc_no", "") or "",
|
||||
"lot_no": item.lot_no,
|
||||
"receipt_date": item.receipt_date,
|
||||
"movement_date": item.movement_date,
|
||||
"from_warehouse": item.from_warehouse,
|
||||
"from_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"to_warehouse": item.to_warehouse,
|
||||
@@ -94,6 +96,8 @@ def serialize_item(item) -> dict[str, Any]:
|
||||
"checked_at": item.checked_at,
|
||||
"stale": item.stale,
|
||||
"file_current": item.file_current,
|
||||
# 出生匹配的调拨类型 code。可调拨明细跨类型混排时前端据此显示类别名称。
|
||||
"transfer_type": item.transfer_type,
|
||||
}
|
||||
|
||||
|
||||
@@ -137,7 +141,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
|
||||
items: 单挂接行集(TransferInvoiceItem 列表,调用方保证顺序)。
|
||||
|
||||
Returns:
|
||||
单投影 dict(8 键):{doc_no, receipt_date, from_warehouse, to_warehouse,
|
||||
单投影 dict(8 键):{doc_no, movement_date, from_warehouse, to_warehouse,
|
||||
status, erp_document_no, error_message, lines}。
|
||||
"""
|
||||
# 延迟引用 execution_service 的行聚合(模块级互相引用会循环导入;
|
||||
@@ -149,11 +153,11 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
|
||||
name_by_key: dict[tuple[str, str, str, str], str] = {}
|
||||
reason_by_key: dict[tuple[str, str, str, str], str] = {}
|
||||
for item in ordered:
|
||||
# [外部形态] join 键与 _build_order_lines 聚合键同形(批号 WTP→HOW 派生),
|
||||
# 否则 WTP 前缀行的品名/原因投影 lookup 会 miss。
|
||||
# [外部形态] join 键与 _build_order_lines 聚合键同形(批号经行所属匹配
|
||||
# 快照转换规则派生),否则 WTP 前缀行的品名/原因投影 lookup 会 miss。
|
||||
key = (
|
||||
str(item.material_no or "").strip(),
|
||||
external_lot_no(item.lot_no),
|
||||
item_external_lot_no(item),
|
||||
str(item.from_warehouse or "").strip(),
|
||||
str(item.to_warehouse or "").strip(),
|
||||
)
|
||||
@@ -166,7 +170,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
|
||||
reason_by_key[key] = message
|
||||
return {
|
||||
"doc_no": doc.doc_no,
|
||||
"receipt_date": doc.receipt_date,
|
||||
"movement_date": doc.movement_date,
|
||||
"from_warehouse": doc.from_warehouse,
|
||||
"to_warehouse": doc.to_warehouse,
|
||||
"status": doc.status,
|
||||
@@ -174,9 +178,10 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
|
||||
"error_message": doc.error_message,
|
||||
"lines": [
|
||||
{
|
||||
# 行级溯源收料通知号(2026-09-29 契约扩充,随 ERP 写入行同款口径
|
||||
# 行级溯源来源单号(2026-09-29 契约扩充,随 ERP 写入行同款口径
|
||||
# 透传):业务上一行恒对应一张 invoice,前端明细表首列展示。
|
||||
"invoice_no": line["invoice_no"],
|
||||
"external_doc_no": line.get("external_doc_no") or "",
|
||||
"material_no": line["material_no"],
|
||||
"material_name": name_by_key.get(
|
||||
(line["material_no"], line["lot_no"],
|
||||
@@ -212,7 +217,7 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]:
|
||||
"submit_timestamp": doc.submit_timestamp,
|
||||
"status": base["status"],
|
||||
"status_group": order_status_group(doc.status),
|
||||
"receipt_date": base["receipt_date"],
|
||||
"movement_date": base["movement_date"],
|
||||
"from_warehouse": base["from_warehouse"],
|
||||
"to_warehouse": base["to_warehouse"],
|
||||
"erp_document_no": base["erp_document_no"],
|
||||
@@ -222,15 +227,16 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]:
|
||||
"items": [
|
||||
{
|
||||
"invoice_no": item.invoice_no,
|
||||
"external_doc_no": ledger_external_doc_no(item),
|
||||
"material_no": item.material_no,
|
||||
"material_name": item.material_name,
|
||||
# 批号保持文件证据原形态(raw 原则);展示侧拨出批号由前端
|
||||
# deriveBatchNo 镜像转换(与匹配卡/可调拨明细/待办池同规则)。
|
||||
"lot_no": item.lot_no or "",
|
||||
"quantity": item.receipt_quantity,
|
||||
"quantity": item.movement_quantity,
|
||||
"unit": item.unit or "",
|
||||
}
|
||||
# 行序对齐统一规则第三键(2026-09-29):同单内收料日期/数据源恒同
|
||||
# 行序对齐统一规则第三键(2026-09-29):同单内异动日期/数据源恒同
|
||||
# (组键含两者),按 invoice_no 升序、id 兜底稳定排序。
|
||||
for item in sorted(items, key=lambda row: (str(row.invoice_no or ""), row.id))
|
||||
],
|
||||
|
||||
@@ -1,161 +1,549 @@
|
||||
"""在途调拨来源收料文件状态投影服务。
|
||||
"""在途调拨来源证据文件状态投影服务。
|
||||
|
||||
用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile),
|
||||
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 是否解析失败 /
|
||||
无文件待触发",供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
|
||||
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)、
|
||||
receipt_file_gate(可用/失效判定单一事实来源)。
|
||||
逻辑:按来源取该来源最新收料执行单元;命中可用门禁(当天业务日抓取且未过期,
|
||||
见 receipt_file_gate)→ ready,但文件已标记解析失败(parse_failed_at 非空)→
|
||||
parse_failed(不可当 ready,仍带 file_no/file_sha256 便于诊断);
|
||||
有进行中单元 → fetching;最新单元为失败终态 → failed;
|
||||
文件仍在但已失效 → expired;否则 → none。
|
||||
record_receipt_parse_failure / clear_receipt_parse_failure 维护解析失败三列
|
||||
(写入与清除均只 flush 不 commit,事务归属调用方)。
|
||||
用途:只读货代入站/出站链路已有事实(执行单元行 + freight_rpa 归档文件),
|
||||
按来源实例与记录类型投影"是否有 ready 文件 / 是否抓取中 / 是否失败 /
|
||||
是否解析失败 / 无文件待触发 / 出站未配置",供 /sources 接口与前端门禁使用。
|
||||
调拨不维护独立抓取状态表(低耦合)。
|
||||
依赖:freight_rpa.reports.queries(入站可用归档批量/单来源读取、失效来源存在性、
|
||||
get_outbound_config、解析失败标记只读写入口;入站归档文件模型不直连——
|
||||
阶段 B Task 4 边界);入站/出站执行单元行与出站归档文件、出站报表配置模型
|
||||
(出站证据轴 2026-10-22 起直连读取,不在边界禁列);
|
||||
date_policy.business_date_utc_window(出站文件新鲜度与入站可用条件同口径)。
|
||||
逻辑:resolve_source_file_status 按 record_kind 分流,缺省 inbound,既有调用方
|
||||
不传记录类型时返回值不变。入站顺序:可用文件 → ready,但 parse_failed_at
|
||||
非空 → parse_failed;进行中单元 → fetching;最新单元空数据 → no_data;
|
||||
最新单元失败终态 → failed;文件仍在但已失效 → expired;否则 → none。
|
||||
出站先查 get_outbound_config,缺失 → unconfigured;有配置则对出站文件表与
|
||||
FreightRpaOutboundUnitRun 走同一顺序。列表接口走
|
||||
resolve_source_file_statuses:同一顺序一次性投影全部来源,查询次数不随
|
||||
来源个数增长。record/clear_inbound_parse_failure 仍是入站解析失败标记的
|
||||
兼容薄壳(按主键委托 queries.mark/clear,只 flush 不 commit,事务归属调用方)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Any, Callable
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
||||
from app.services.in_transit_transfer.receipt_file_gate import (
|
||||
expired_receipt_file_condition,
|
||||
usable_receipt_file_condition,
|
||||
from sqlalchemy import and_, not_, or_
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
# 入站归档文件模型归 freight_rpa 域读写(阶段 B Task 4 边界),批量/单来源读取
|
||||
# 一律经 queries 只读函数;入站执行单元模型不在禁列(状态投影按 status 消费)。
|
||||
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun
|
||||
from app.models.freight_rpa_outbound_report import (
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
)
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
clear_inbound_parse_failure as _clear_parse_failure_by_id,
|
||||
expired_inbound_source_codes,
|
||||
get_outbound_config,
|
||||
has_expired_inbound_file,
|
||||
latest_usable_inbound_file,
|
||||
latest_usable_inbound_files_by_source,
|
||||
mark_inbound_parse_failure as _mark_parse_failure_by_id,
|
||||
)
|
||||
from app.services.in_transit_transfer.date_policy import business_date_utc_window
|
||||
|
||||
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
|
||||
FAILED_UNIT_STATUSES = ('failed', 'cancelled')
|
||||
# 空数据(no_receipt_data):抓取成功但当日无收料记录,属业务结果而非故障,
|
||||
# 独立投影 no_data 供前端如实展示(2026-10-08:曾误并入 failed 致无法分辨真失败)。
|
||||
# 空数据(RPA empty 回调契约值,shipping_notice 域术语保留):抓取成功但当日无记录,
|
||||
# 属业务结果而非故障,独立投影 no_data 供前端如实展示(2026-10-08:曾误并入 failed 致无法分辨真失败)。
|
||||
NO_DATA_UNIT_STATUSES = ('empty',)
|
||||
_RECORD_KINDS = ('inbound', 'outbound')
|
||||
|
||||
|
||||
def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
"""返回某来源的收料文件状态投影。
|
||||
@dataclass(frozen=True)
|
||||
class _FileFact:
|
||||
"""批量投影用的文件身份,字段与单来源文件视图中参与状态判断的部分一致。"""
|
||||
|
||||
失效判定(不依赖保留期清理任务落位,与匹配取文件/下载同口径,见
|
||||
receipt_file_gate):保留期已到 或 非当前业务日(Asia/Shanghai)抓取。
|
||||
file_id: int
|
||||
original_filename: str
|
||||
sha256: str
|
||||
parse_failed_at: datetime | None
|
||||
|
||||
Returns:
|
||||
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
|
||||
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'no_data', 'expired', 'none'};
|
||||
parse_failed 表示文件仍可用但解析失败:has_ready_file=False,
|
||||
仍带 file_no/file_sha256 便于诊断与前端提示。
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _UnitFact:
|
||||
"""批量投影用的执行单元,只保留状态判断需要的 status。"""
|
||||
|
||||
status: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _OutboundFileView:
|
||||
"""出站归档文件只读视图,字段与入站 InboundFileView 对齐,供同一投影顺序读取。"""
|
||||
|
||||
file_id: int
|
||||
source_code: str
|
||||
sha256: str
|
||||
storage_key: str
|
||||
original_filename: str
|
||||
created_at: datetime
|
||||
parse_failed_at: datetime | None = None
|
||||
|
||||
|
||||
def _outbound_fresh_and_retention_valid(now: datetime):
|
||||
"""出站归档的新鲜度 + 保留期条件,列与入站 _fresh_and_retention_valid 同口径。
|
||||
|
||||
核心逻辑:业务日窗口用 date_policy.business_date_utc_window(与 queries 内联
|
||||
数学一致);archive_expires_at 为空视为长期有效。
|
||||
"""
|
||||
window_start, window_end = business_date_utc_window(now)
|
||||
return and_(
|
||||
FreightRpaOutboundReportFile.created_at >= window_start,
|
||||
FreightRpaOutboundReportFile.created_at < window_end,
|
||||
or_(
|
||||
FreightRpaOutboundReportFile.archive_expires_at.is_(None),
|
||||
FreightRpaOutboundReportFile.archive_expires_at > now,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _outbound_file_view(report: FreightRpaOutboundReportFile) -> _OutboundFileView:
|
||||
"""把出站归档 ORM 行映射为冻结只读视图。"""
|
||||
return _OutboundFileView(
|
||||
file_id=report.id,
|
||||
source_code=report.unit_run.source_code,
|
||||
sha256=report.sha256,
|
||||
storage_key=report.storage_key,
|
||||
original_filename=report.original_filename,
|
||||
created_at=report.created_at,
|
||||
parse_failed_at=report.parse_failed_at,
|
||||
)
|
||||
|
||||
|
||||
def latest_usable_outbound_file(
|
||||
source_code: str,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> _OutboundFileView | None:
|
||||
"""返回某来源当前可用的出站归档只读视图,最新优先。
|
||||
|
||||
用途:出站证据流状态投影取文件身份;口径与 latest_usable_inbound_file 相同
|
||||
(未删除 + 当天业务日抓取 + 未过期),不读取对象存储字节。
|
||||
|
||||
核心逻辑:经出站执行单元行的 source_code 过滤,按 created_at/id 倒序取第一条。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(写在 FreightRpaOutboundUnitRun.source_code 上)。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
_OutboundFileView;无可用文件返回 None。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
report = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
FreightRpaOutboundReportFile.query
|
||||
.join(FreightRpaOutboundReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
usable_receipt_file_condition(),
|
||||
FreightRpaOutboundReportFile.unit_run.has(source_code=source_code),
|
||||
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
|
||||
_outbound_fresh_and_retention_valid(now),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
||||
.order_by(FreightRpaOutboundReportFile.created_at.desc(), FreightRpaOutboundReportFile.id.desc())
|
||||
.first()
|
||||
)
|
||||
if report is not None:
|
||||
# 解析失败分层:文件本身可用(当天抓取未过期未清理)但解析失败,
|
||||
# 不得当 ready 放行,单独投影 parse_failed 并保留文件身份供诊断。
|
||||
if report.parse_failed_at is not None:
|
||||
if report is None:
|
||||
return None
|
||||
return _outbound_file_view(report)
|
||||
|
||||
|
||||
def has_expired_outbound_file(source_code: str, *, now: datetime | None = None) -> bool:
|
||||
"""返回某来源是否存在未删除但已失效的出站归档(expired 投影依据)。
|
||||
|
||||
用途:出站状态投影在无可用文件、无进行中/终态单元之后,判断是否因隔日旧文件
|
||||
或保留期已到而提示重抓。只读不写。
|
||||
|
||||
核心逻辑:未删除且新鲜度+保留期不成立,与 has_expired_inbound_file 同核。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
存在失效但未清理的出站归档 → True;否则 False。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
expired = (
|
||||
FreightRpaOutboundReportFile.query
|
||||
.join(FreightRpaOutboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaOutboundReportFile.unit_run.has(source_code=source_code),
|
||||
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
|
||||
not_(_outbound_fresh_and_retention_valid(now)),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
return expired is not None
|
||||
|
||||
|
||||
def _empty_status(file_status: str) -> dict:
|
||||
"""没有可用文件身份时的投影字典。"""
|
||||
return {'file_status': file_status, 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
|
||||
def _status_from_facts(
|
||||
*,
|
||||
file_view: Any | None,
|
||||
active_unit: Any | None,
|
||||
latest_unit: Any | None,
|
||||
expired: bool,
|
||||
) -> dict:
|
||||
"""按既定优先级把已取到的文件与单元事实收成状态字典。
|
||||
|
||||
核心逻辑:可用文件(解析失败优先于 ready)→ 进行中单元 → 最新单元空数据 →
|
||||
最新单元失败终态 → 失效文件 → none。单来源与批量投影共用,避免两条路径
|
||||
各写一套优先级。
|
||||
|
||||
Args:
|
||||
file_view: 可用文件视图;须有 original_filename、file_id、parse_failed_at、sha256。
|
||||
没有可用文件时为 None。
|
||||
active_unit: 仍在进行的执行单元;没有时为 None。只要求对象存在。
|
||||
latest_unit: id 最大的执行单元;没有时为 None。须有 status。
|
||||
expired: 是否仍有未清理的失效归档。
|
||||
Returns:
|
||||
file_status 字典,键为 file_status / has_ready_file / file_no / file_sha256。
|
||||
"""
|
||||
if file_view is not None:
|
||||
file_no = file_view.original_filename or str(file_view.file_id)
|
||||
# 解析失败分层:文件本身可用但解析失败,不得当 ready,保留文件身份供诊断。
|
||||
if file_view.parse_failed_at is not None:
|
||||
return {
|
||||
'file_status': 'parse_failed',
|
||||
'has_ready_file': False,
|
||||
'file_no': report.original_filename or str(report.id),
|
||||
'file_sha256': report.sha256,
|
||||
'file_no': file_no,
|
||||
'file_sha256': file_view.sha256,
|
||||
}
|
||||
return {
|
||||
'file_status': 'ready',
|
||||
'has_ready_file': True,
|
||||
'file_no': report.original_filename or str(report.id),
|
||||
'file_sha256': report.sha256,
|
||||
'file_no': file_no,
|
||||
'file_sha256': file_view.sha256,
|
||||
}
|
||||
|
||||
active_unit = (
|
||||
ShippingReceiptRpaUnitRun.query
|
||||
.filter_by(source_code=source_code)
|
||||
.filter(ShippingReceiptRpaUnitRun.status.in_(RUNNING_UNIT_STATUSES))
|
||||
.order_by(ShippingReceiptRpaUnitRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
if active_unit is not None:
|
||||
return {'file_status': 'fetching', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
latest_unit = (
|
||||
ShippingReceiptRpaUnitRun.query
|
||||
.filter_by(source_code=source_code)
|
||||
.order_by(ShippingReceiptRpaUnitRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
return _empty_status('fetching')
|
||||
if latest_unit is not None and latest_unit.status in NO_DATA_UNIT_STATUSES:
|
||||
# 空数据:抓取成功但当日无收料记录——如实投影 no_data,不得与抓取失败混淆。
|
||||
return {'file_status': 'no_data', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
# 空数据:抓取成功但当日无记录——如实投影 no_data,不得与抓取失败混淆。
|
||||
return _empty_status('no_data')
|
||||
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
|
||||
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
# 文件仍在但已失效(保留期已到或隔日旧文件):不报 ready,单独投影 expired 提示重抓。
|
||||
expired_report = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
expired_receipt_file_condition(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if expired_report is not None:
|
||||
return {'file_status': 'expired', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
return _empty_status('failed')
|
||||
if expired:
|
||||
return _empty_status('expired')
|
||||
return _empty_status('none')
|
||||
|
||||
|
||||
def record_receipt_parse_failure(
|
||||
def _project_file_status(
|
||||
source_code: str,
|
||||
*,
|
||||
report: ShippingReceiptReportFile,
|
||||
error_code: str,
|
||||
error_message: str,
|
||||
now: datetime | None = None,
|
||||
) -> None:
|
||||
"""标记一份收料归档文件解析失败(写入 parse_failed_at / parse_error_code / parse_error_message)。
|
||||
latest_file: Callable[..., Any],
|
||||
unit_model: type,
|
||||
has_expired: Callable[..., bool],
|
||||
) -> dict:
|
||||
"""按入站既有顺序把文件视图与执行单元投影成文件状态。
|
||||
|
||||
【AI 触发时机】收料归档文件解析(schema/字段校验)失败需要把失败事实落到文件上、
|
||||
让来源状态投影为 parse_failed 阻止下游当作 ready 使用时调用;解析成功或重抓成功后
|
||||
改调 clear_receipt_parse_failure。
|
||||
|
||||
核心逻辑:[STEP 1] 写入失败时间(now 或当前 UTC)与截断后的错误码/错误信息;
|
||||
[STEP 2] db.session.flush() 使投影同事务内立即可见。只 flush 不 commit,
|
||||
事务提交时机归调用方(与解析流程共用同一事务,禁止在 service 层越权提交)。
|
||||
核心逻辑:有可用文件就不再查单元;没有进行中单元才看最新单元;最新单元
|
||||
已是空数据或失败终态就不再查失效文件。入站与出站共用,差异只在三个协作参数。
|
||||
|
||||
Args:
|
||||
report: 待标记的 ShippingReceiptReportFile(须已入库,主键可用)。
|
||||
error_code: 机器可读错误码,超 64 字符截断(对齐列宽 String(64))。
|
||||
error_message: 人类可读错误信息,超 2000 字符截断(Text 列防御性截断)。
|
||||
now: 可选失败时刻;缺省取当前 UTC(与全链路 utcnow 口径一致)。
|
||||
source_code: 来源实例编码。
|
||||
latest_file: 返回可用文件视图或 None;视图须有 original_filename、file_id、
|
||||
parse_failed_at、sha256。
|
||||
unit_model: 带 query/status/id/source_code 的执行单元模型。
|
||||
has_expired: 该来源是否仍有失效未清理文件。
|
||||
Returns:
|
||||
None。失败标记写在传入对象上并 flush,由调用方决定何时 commit 或回滚。
|
||||
file_status 字典,键为 file_status / has_ready_file / file_no / file_sha256。
|
||||
"""
|
||||
report.parse_failed_at = now or datetime.utcnow()
|
||||
report.parse_error_code = (error_code or '')[:64]
|
||||
report.parse_error_message = (error_message or '')[:2000]
|
||||
db.session.flush()
|
||||
file_view = latest_file(source_code)
|
||||
active_unit = None
|
||||
latest_unit = None
|
||||
expired = False
|
||||
if file_view is None:
|
||||
active_unit = (
|
||||
unit_model.query
|
||||
.filter_by(source_code=source_code)
|
||||
.filter(unit_model.status.in_(RUNNING_UNIT_STATUSES))
|
||||
.order_by(unit_model.id.desc())
|
||||
.first()
|
||||
)
|
||||
if active_unit is None:
|
||||
latest_unit = (
|
||||
unit_model.query
|
||||
.filter_by(source_code=source_code)
|
||||
.order_by(unit_model.id.desc())
|
||||
.first()
|
||||
)
|
||||
terminal = latest_unit is not None and latest_unit.status in (
|
||||
*NO_DATA_UNIT_STATUSES, *FAILED_UNIT_STATUSES,
|
||||
)
|
||||
if not terminal:
|
||||
expired = has_expired(source_code)
|
||||
return _status_from_facts(
|
||||
file_view=file_view,
|
||||
active_unit=active_unit,
|
||||
latest_unit=latest_unit,
|
||||
expired=expired,
|
||||
)
|
||||
|
||||
|
||||
def clear_receipt_parse_failure(*, report: ShippingReceiptReportFile) -> None:
|
||||
"""清除一份收料归档文件的解析失败标记(三列置空),投影恢复 ready。
|
||||
def _latest_files_by_source(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> dict[str, _FileFact]:
|
||||
"""一次取出这批来源各自最新的可用出站归档(入站批查已下沉 queries 层)。
|
||||
|
||||
核心逻辑:按来源主键过滤后按创建时间、文件主键倒序,每个来源只留第一条。
|
||||
只取状态判断用到的列,不加载执行单元上的 JSON 快照。
|
||||
|
||||
Args:
|
||||
file_model: 出站归档文件模型。
|
||||
unit_model: 对应的执行单元模型,用来按 source_id 过滤。
|
||||
source_ids: 要投影的来源主键。
|
||||
filters: 可用文件条件(未删除、当天业务日、未过保留期)。
|
||||
Returns:
|
||||
source_code 到文件事实的映射;没有可用文件的来源不出现。
|
||||
"""
|
||||
rows = (
|
||||
file_model.query
|
||||
.join(unit_model, file_model.unit_run_id == unit_model.id)
|
||||
.filter(unit_model.source_id.in_(source_ids), *filters)
|
||||
.with_entities(
|
||||
unit_model.source_code,
|
||||
file_model.id,
|
||||
file_model.original_filename,
|
||||
file_model.sha256,
|
||||
file_model.parse_failed_at,
|
||||
)
|
||||
.order_by(file_model.created_at.desc(), file_model.id.desc())
|
||||
.all()
|
||||
)
|
||||
picked: dict[str, _FileFact] = {}
|
||||
for source_code, file_id, filename, sha256, parse_failed_at in rows:
|
||||
if source_code in picked:
|
||||
continue
|
||||
picked[str(source_code)] = _FileFact(
|
||||
file_id=file_id,
|
||||
original_filename=filename,
|
||||
sha256=sha256,
|
||||
parse_failed_at=parse_failed_at,
|
||||
)
|
||||
return picked
|
||||
|
||||
|
||||
def _units_by_source(unit_model: type, source_ids: list[int]) -> tuple[dict[str, _UnitFact], dict[str, _UnitFact]]:
|
||||
"""一次取出这批来源的最新单元,以及仍在进行的最新单元。
|
||||
|
||||
核心逻辑:按 id 倒序扫描,每个来源遇到的第一行就是最新单元;状态属于进行中
|
||||
的第一行就是该来源仍在抓取的单元。较新的失败单元因此盖不住更早仍在进行的单元。
|
||||
|
||||
Args:
|
||||
unit_model: 入站或出站执行单元模型。
|
||||
source_ids: 要投影的来源主键。
|
||||
Returns:
|
||||
(最新单元, 进行中单元),键都是 source_code。没有单元时对应字典为空。
|
||||
"""
|
||||
rows = (
|
||||
unit_model.query
|
||||
.filter(unit_model.source_id.in_(source_ids))
|
||||
.with_entities(unit_model.source_code, unit_model.id, unit_model.status)
|
||||
.order_by(unit_model.id.desc())
|
||||
.all()
|
||||
)
|
||||
latest: dict[str, _UnitFact] = {}
|
||||
active: dict[str, _UnitFact] = {}
|
||||
for source_code, _unit_id, status in rows:
|
||||
code = str(source_code)
|
||||
if code not in latest:
|
||||
latest[code] = _UnitFact(status=status)
|
||||
if status in RUNNING_UNIT_STATUSES and code not in active:
|
||||
active[code] = _UnitFact(status=status)
|
||||
return latest, active
|
||||
|
||||
|
||||
def _expired_source_codes(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> set[str]:
|
||||
"""一次找出仍有失效未清理出站归档的来源编码(入站批查已下沉 queries 层)。
|
||||
|
||||
核心逻辑:只判断存在性,不取文件内容。失效条件由调用方传入,与单来源
|
||||
has_expired_* 使用同一套未删除且不满足新鲜度/保留期的口径。
|
||||
|
||||
Args:
|
||||
file_model: 出站归档文件模型。
|
||||
unit_model: 对应的执行单元模型。
|
||||
source_ids: 要投影的来源主键。
|
||||
filters: 失效文件条件。
|
||||
Returns:
|
||||
至少有一份失效未清理归档的 source_code 集合。
|
||||
"""
|
||||
rows = (
|
||||
file_model.query
|
||||
.join(unit_model, file_model.unit_run_id == unit_model.id)
|
||||
.filter(unit_model.source_id.in_(source_ids), *filters)
|
||||
.with_entities(unit_model.source_code)
|
||||
.distinct()
|
||||
.all()
|
||||
)
|
||||
return {str(row[0]) for row in rows}
|
||||
|
||||
|
||||
def resolve_source_file_statuses(sources: list[Any]) -> dict[str, dict[str, dict]]:
|
||||
"""批量投影一组来源的入站与出站证据文件状态。
|
||||
|
||||
用途:GET /sources 渲染来源选择卡。来源个数增加时仍只做固定几条查询,
|
||||
供页面同时展示调拨类型和数据源时不必按来源等待。
|
||||
|
||||
核心逻辑:出站配置、入站/出站的可用文件、执行单元、失效文件各查一次,
|
||||
再按与 resolve_source_file_status 相同的优先级收口。没有出站配置的来源
|
||||
直接记 unconfigured,不把入站状态抄到出站。
|
||||
|
||||
Args:
|
||||
sources: 已加载的来源行,须有 id 与 source_code。空列表不查库。
|
||||
Returns:
|
||||
{source_code: {"inbound": 状态字典, "outbound": 状态字典}}。
|
||||
状态字典键与 resolve_source_file_status 相同。
|
||||
"""
|
||||
if not sources:
|
||||
return {}
|
||||
now = datetime.utcnow()
|
||||
source_ids = [int(source.id) for source in sources]
|
||||
configured_outbound = {
|
||||
int(row[0])
|
||||
for row in (
|
||||
FreightRpaOutboundReportConfig.query
|
||||
.filter(FreightRpaOutboundReportConfig.source_id.in_(source_ids))
|
||||
.with_entities(FreightRpaOutboundReportConfig.source_id)
|
||||
.all()
|
||||
)
|
||||
}
|
||||
inbound_files = {
|
||||
code: _FileFact(
|
||||
file_id=view.file_id,
|
||||
original_filename=view.original_filename,
|
||||
sha256=view.sha256,
|
||||
parse_failed_at=view.parse_failed_at,
|
||||
)
|
||||
for code, view in latest_usable_inbound_files_by_source(source_ids, now=now).items()
|
||||
}
|
||||
inbound_latest, inbound_active = _units_by_source(FreightRpaInboundUnitRun, source_ids)
|
||||
inbound_expired = expired_inbound_source_codes(source_ids, now=now)
|
||||
outbound_files = _latest_files_by_source(
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
source_ids,
|
||||
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
|
||||
_outbound_fresh_and_retention_valid(now),
|
||||
)
|
||||
outbound_latest, outbound_active = _units_by_source(FreightRpaOutboundUnitRun, source_ids)
|
||||
outbound_expired = _expired_source_codes(
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
source_ids,
|
||||
FreightRpaOutboundReportFile.archive_deleted_at.is_(None),
|
||||
not_(_outbound_fresh_and_retention_valid(now)),
|
||||
)
|
||||
projected: dict[str, dict[str, dict]] = {}
|
||||
for source in sources:
|
||||
code = str(source.source_code)
|
||||
inbound = _status_from_facts(
|
||||
file_view=inbound_files.get(code),
|
||||
active_unit=inbound_active.get(code),
|
||||
latest_unit=inbound_latest.get(code),
|
||||
expired=code in inbound_expired,
|
||||
)
|
||||
if int(source.id) not in configured_outbound:
|
||||
outbound = _empty_status('unconfigured')
|
||||
else:
|
||||
outbound = _status_from_facts(
|
||||
file_view=outbound_files.get(code),
|
||||
active_unit=outbound_active.get(code),
|
||||
latest_unit=outbound_latest.get(code),
|
||||
expired=code in outbound_expired,
|
||||
)
|
||||
projected[code] = {'inbound': inbound, 'outbound': outbound}
|
||||
return projected
|
||||
|
||||
|
||||
def resolve_source_file_status(*, source_code: str, record_kind: str = 'inbound') -> dict:
|
||||
"""返回某来源在指定记录类型上的证据文件状态投影。
|
||||
|
||||
用途:来源列表与重试门禁按流入站或出站询问文件是否就绪。缺省 record_kind
|
||||
为 inbound,既有只传来源的调用返回值与改造前相同。
|
||||
|
||||
核心逻辑:record_kind 不是 inbound/outbound 时抛 ValidationError。出站先查
|
||||
get_outbound_config,没有配置行则 unconfigured,不再往下看文件或单元。
|
||||
有配置(以及全部入站)再按同一顺序投影。失效判定不依赖保留期清理任务:
|
||||
保留期已到,或非当前业务日(Asia/Shanghai)抓取。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
record_kind: inbound 或 outbound,默认 inbound。
|
||||
Returns:
|
||||
{"file_status", "has_ready_file", "file_no", "file_sha256"}。
|
||||
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'no_data',
|
||||
'expired', 'none', 'unconfigured'}。parse_failed 时 has_ready_file=False,
|
||||
仍带 file_no/file_sha256。unconfigured 仅出站且无出站报表配置时出现。
|
||||
Raises:
|
||||
ValidationError: record_kind 不是 inbound 或 outbound。
|
||||
"""
|
||||
if record_kind not in _RECORD_KINDS:
|
||||
raise ValidationError(
|
||||
f'unsupported record_kind: {record_kind}',
|
||||
details={'record_kind': record_kind},
|
||||
)
|
||||
if record_kind == 'outbound':
|
||||
if get_outbound_config(source_code) is None:
|
||||
return _empty_status('unconfigured')
|
||||
return _project_file_status(
|
||||
source_code,
|
||||
latest_file=latest_usable_outbound_file,
|
||||
unit_model=FreightRpaOutboundUnitRun,
|
||||
has_expired=has_expired_outbound_file,
|
||||
)
|
||||
return _project_file_status(
|
||||
source_code,
|
||||
latest_file=latest_usable_inbound_file,
|
||||
unit_model=FreightRpaInboundUnitRun,
|
||||
has_expired=has_expired_inbound_file,
|
||||
)
|
||||
|
||||
|
||||
def record_inbound_parse_failure(
|
||||
*,
|
||||
report: Any,
|
||||
error_code: str,
|
||||
error_message: str,
|
||||
) -> None:
|
||||
"""标记一份入站归档文件解析失败(写入 parse_failed_at / parse_error_code / parse_error_message)。
|
||||
|
||||
【AI 触发时机】入站归档文件解析(schema/字段校验)失败需要把失败事实落到文件上、
|
||||
让来源状态投影为 parse_failed 阻止下游当作 ready 使用时调用;解析成功或重抓成功后
|
||||
改调 clear_inbound_parse_failure。
|
||||
|
||||
【阶段 B Task 4 兼容薄壳】全量语义(失败时刻取当前 UTC、错误码按 64 字符/
|
||||
错误信息按 2000 字符截断、只 flush 不 commit——事务提交时机归属调用方)已
|
||||
收口 freight_rpa.reports.queries.mark_inbound_parse_failure(唯一实现);
|
||||
本壳只为既有调用方按归档文件对象传参的签名而保留——取对象主键委托真实现。
|
||||
|
||||
Args:
|
||||
report: 入站归档文件对象(仅取主键 .id;须已入库)。
|
||||
error_code: 机器可读错误码(真实现内按列宽截断)。
|
||||
error_message: 人类可读错误信息(真实现内做防御性截断)。
|
||||
Returns:
|
||||
None。失败标记随调用方事务落库。
|
||||
"""
|
||||
_mark_parse_failure_by_id(report.id, error_code=error_code, error_message=error_message)
|
||||
|
||||
|
||||
def clear_inbound_parse_failure(*, report: Any) -> None:
|
||||
"""清除一份入站归档文件的解析失败标记(三列置空),投影恢复 ready。
|
||||
|
||||
【AI 触发时机】同一文件重新解析成功、或人工确认可恢复后调用,使来源状态
|
||||
投影从 parse_failed 回到 ready;不要在文件已被清理/失效后调用(无意义)。
|
||||
|
||||
核心逻辑:[STEP 1] 将 parse_failed_at / parse_error_code / parse_error_message
|
||||
三列置 None(三者全空即未失败/已清除的约定态);[STEP 2] flush 使同事务内
|
||||
投影立即可见。只 flush 不 commit,事务提交时机归调用方。
|
||||
【阶段 B Task 4 兼容薄壳】语义收口同 record_inbound_parse_failure:取对象
|
||||
主键委托 freight_rpa.reports.queries.clear_inbound_parse_failure(置空三列
|
||||
后 flush,不 commit,事务归属调用方)。
|
||||
|
||||
Args:
|
||||
report: 待清除标记的 ShippingReceiptReportFile(须已入库,主键可用)。
|
||||
report: 入站归档文件对象(仅取主键 .id;须已入库)。
|
||||
Returns:
|
||||
None。清除写在传入对象上并 flush,由调用方决定何时 commit 或回滚。
|
||||
None。清除随调用方事务落库。
|
||||
"""
|
||||
report.parse_failed_at = None
|
||||
report.parse_error_code = None
|
||||
report.parse_error_message = None
|
||||
db.session.flush()
|
||||
_clear_parse_failure_by_id(report.id)
|
||||
@@ -1,15 +1,17 @@
|
||||
"""在途调拨状态机与转换门禁。
|
||||
|
||||
用途:定义提示词冻结的 13 个业务状态(TransferStatus)、Run 生命周期
|
||||
用途:定义提示词冻结的 12 个业务状态(TransferStatus)、Run 生命周期
|
||||
(TransferRunStatus)与通知状态(TransferNotificationStatus),
|
||||
并强制所有状态转换走服务端门禁。
|
||||
依赖:app.core.errors.AppError。
|
||||
逻辑:转换表声明即白名单,未声明的迁移一律抛 TransferStateError;
|
||||
result_unknown / manually_closed / success / duplicate_success /
|
||||
not_matured / cancelled 为无出边终态(唯二例外均为显式人工/生命周期语义:
|
||||
cancelled 为无出边终态(唯二例外均为显式人工/生命周期语义:
|
||||
DOCUMENT_RETRIGGER_TRANSITIONS 允许 result_unknown 单经人工 retrigger
|
||||
→ executing,D11 唯一出口;QUEUED Run 经 worker 领取 → executing);
|
||||
通知失败(notification_failed)是通知投递状态,绝不改写 外部系统 业务结果。
|
||||
【not_matured 状态已退役 2026-10-16】成熟概念删除(数据无成熟属性,
|
||||
日期边界由调用方入参给定);存量行经 tt16 迁移重映射为 cancelled。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,7 +25,7 @@ INVALID_STATE_TRANSITION_CODE = "TRANSFER.INVALID_STATE_TRANSITION"
|
||||
|
||||
|
||||
class TransferStatus(StrEnum):
|
||||
"""Invoice 项业务状态(含提示词冻结的全部 13 个状态)。"""
|
||||
"""Invoice 项业务状态(含提示词冻结的全部 12 个状态)。"""
|
||||
|
||||
FILE_PENDING = "file_pending"
|
||||
FILE_READY = "file_ready"
|
||||
@@ -33,7 +35,6 @@ class TransferStatus(StrEnum):
|
||||
SUCCESS = "success"
|
||||
DUPLICATE_SUCCESS = "duplicate_success"
|
||||
BLOCKED_RECOVERABLE = "blocked_recoverable"
|
||||
NOT_MATURED = "not_matured"
|
||||
RESULT_UNKNOWN = "result_unknown"
|
||||
MANUALLY_CLOSED = "manually_closed"
|
||||
CANCELLED = "cancelled"
|
||||
@@ -72,7 +73,6 @@ TERMINAL_TRANSFER_STATUSES: frozenset[str] = frozenset({
|
||||
TransferStatus.RESULT_UNKNOWN.value,
|
||||
TransferStatus.MANUALLY_CLOSED.value,
|
||||
TransferStatus.CANCELLED.value,
|
||||
TransferStatus.NOT_MATURED.value,
|
||||
TransferStatus.NOTIFICATION_FAILED.value,
|
||||
})
|
||||
|
||||
@@ -89,7 +89,6 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
TransferStatus.MATCHING.value: frozenset({
|
||||
TransferStatus.READY_TO_EXECUTE.value,
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
TransferStatus.NOT_MATURED.value,
|
||||
TransferStatus.CANCELLED.value,
|
||||
}),
|
||||
TransferStatus.READY_TO_EXECUTE.value: frozenset({
|
||||
@@ -114,7 +113,6 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
TransferStatus.MANUALLY_CLOSED.value,
|
||||
TransferStatus.CANCELLED.value,
|
||||
}),
|
||||
TransferStatus.NOT_MATURED.value: frozenset(),
|
||||
TransferStatus.SUCCESS.value: frozenset(),
|
||||
TransferStatus.DUPLICATE_SUCCESS.value: frozenset(),
|
||||
# [T10/R7 出边] result_unknown 行唯一出边 = 人工 retrigger 驱动 → executing
|
||||
|
||||
@@ -1,127 +1,84 @@
|
||||
"""在途调拨类型契约。
|
||||
"""在途调拨类型契约(配置化,ADR 0002)。
|
||||
|
||||
用途:定义调拨业务类型(在途仓至HUB仓 / HUB仓维修出 / HUB仓间调拨)及各类型
|
||||
的收料数据范围规则;类型 2/3 一期占位(fail-closed 拒绝匹配,规则先冻结)。
|
||||
依赖:app.core.errors.ValidationError、invoice_aggregator.AggregatedInvoice。
|
||||
逻辑:类型决定匹配纳入哪些收料单——类型 1 只保留 INVOICE 以 HOM/HOX/WTP 开头
|
||||
的单(大小写不敏感,范围外单与收料日期范围过滤同语义,静默排除不入明细);
|
||||
类型 2 规则已定(ODM ID=HoxinRMA)待收料文件解析层支持 odm_id 字段后启用;
|
||||
类型 3 规则待业务定义。范围判断统一走 invoice_in_scope 谓词(匹配过滤与
|
||||
scope 行圈定共用);调用方必须先 ensure_transfer_type_supported 再过滤。
|
||||
用途:匹配链路的类型门禁唯一入口——把 API/服务传入的类型编码解析为
|
||||
transfer_type_configs 配置 DTO(存在性/启停校验 fail-closed)。
|
||||
依赖:transfer_type_config_service(get_by_code,唯一读取口径)、app.core.errors。
|
||||
逻辑:【2026-10-14 配置化切换】类型不再硬编码枚举:合法值=配置表 code,
|
||||
数据范围/仓库定义/转换规则全部随配置(scope_rules / warehouse_config /
|
||||
transform_rules),匹配创建时快照进 scope_json。本模块只做「编码 → 配置
|
||||
DTO」的门禁解析:None/空 → REQUIRED;无此码(含空配置表)→ NOT_CONFIGURED;
|
||||
停用 → DISABLED(require_enabled=False 供存量匹配的重跑/重查使用——
|
||||
「停用后新匹配不可选,存量不受影响」,规格 §4.1)。
|
||||
旧枚举/前缀常量/谓词(TransferType / SUPPORTED_TRANSFER_TYPES /
|
||||
normalize_transfer_type / ensure_transfer_type_supported / invoice_in_scope /
|
||||
filter_invoices_for_type / transfer_type_scope_note)已随翻转退役:
|
||||
范围职责移交 scope_rules 引擎 + 匹配快照,批号转换移交 field_transforms。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import StrEnum
|
||||
from typing import Iterable
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.in_transit_transfer.invoice_aggregator import AggregatedInvoice
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import (
|
||||
TransferTypeConfigDTO,
|
||||
get_by_code,
|
||||
)
|
||||
|
||||
# 类型不支持(占位类型被调用)时的稳定错误码。
|
||||
TRANSFER_TYPE_NOT_SUPPORTED = "TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED"
|
||||
# 匹配创建未携带类型编码(必填缺失)的稳定错误码(规格 §11,四语言已配齐)。
|
||||
TRANSFER_TYPE_REQUIRED = "TRANSFER.TRANSFER_TYPE_REQUIRED"
|
||||
# 配置表为空或无此编码(fail-closed,D8 不做种子数据)。
|
||||
TRANSFER_TYPE_NOT_CONFIGURED = "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED"
|
||||
# 类型存在但已停用(停用后新匹配不可选)。
|
||||
TRANSFER_TYPE_DISABLED = "TRANSFER.TRANSFER_TYPE_DISABLED"
|
||||
|
||||
|
||||
class TransferType(StrEnum):
|
||||
"""调拨业务类型(值与前端/i18n、transfer_runs.transfer_type 列一致)。"""
|
||||
def resolve_transfer_type(code: str | None, *, require_enabled: bool = True) -> TransferTypeConfigDTO:
|
||||
"""把类型编码解析为配置 DTO(匹配链路的类型门禁唯一入口)。
|
||||
|
||||
IN_TRANSIT_TO_HUB = "in_transit_to_hub" # 在途仓至HUB仓
|
||||
HUB_REPAIR_OUT = "hub_repair_out" # HUB仓维修出(占位)
|
||||
HUB_TO_HUB = "hub_to_hub" # HUB仓间调拨(占位)
|
||||
|
||||
|
||||
# 一期已实现匹配/执行链路的类型;其余类型 fail-closed(占位,防止误生成 外部系统 单)。
|
||||
SUPPORTED_TRANSFER_TYPES: frozenset[TransferType] = frozenset({TransferType.IN_TRANSIT_TO_HUB})
|
||||
|
||||
# 类型 1(在途仓至HUB仓)数据范围:INVOICE 开头前缀(大小写不敏感)。
|
||||
IN_TRANSIT_TO_HUB_INVOICE_PREFIXES: tuple[str, ...] = ("HOM", "HOX", "WTP")
|
||||
|
||||
# 类型 2(HUB仓维修出)数据范围:ODM ID 精确值;待 movement 文件暴露 odm_id 后启用。
|
||||
HUB_REPAIR_OUT_ODM_ID = "HoxinRMA"
|
||||
|
||||
|
||||
def normalize_transfer_type(value: str | TransferType | None) -> TransferType:
|
||||
"""规范化调拨类型入参;缺省/空值回落到类型 1(存量调用方语义不变)。
|
||||
【AI 触发时机】匹配创建(run_matching / create_matching / API 必填校验)与
|
||||
存量匹配的重跑/重查需要类型配置(范围规则/仓库定义/转换规则)时,
|
||||
必须经本函数解析;禁止绕过配置直取编码或假设固定类型。
|
||||
|
||||
Args:
|
||||
value: 前端/API 传入的调拨类型值。
|
||||
code: 类型编码(transfer_type_configs.code,创建后不可变)。
|
||||
require_enabled: True(默认)=停用类型拒绝(新匹配路径);False=存量
|
||||
匹配的重跑/重查放行停用类型(「存量不受影响」语义)。
|
||||
Returns:
|
||||
TransferType 枚举。
|
||||
TransferTypeConfigDTO(scope_rules/warehouse_config/transform_rules 均为
|
||||
引擎解析后的受控对象)。
|
||||
Raises:
|
||||
ValidationError: 非法类型值(不在枚举内)。
|
||||
ValidationError: code 为 None/空白 → TRANSFER.TRANSFER_TYPE_REQUIRED;
|
||||
配置表无此码(含空表)→ TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED;
|
||||
停用且 require_enabled → TRANSFER.TRANSFER_TYPE_DISABLED。
|
||||
"""
|
||||
raw = str(value.value if isinstance(value, TransferType) else (value or "")).strip()
|
||||
if not raw:
|
||||
return TransferType.IN_TRANSIT_TO_HUB
|
||||
try:
|
||||
return TransferType(raw)
|
||||
except ValueError as exc:
|
||||
cleaned = str(code or "").strip()
|
||||
if not cleaned:
|
||||
raise ValidationError(
|
||||
f"unknown transfer type: {raw}",
|
||||
code="TRANSFER.TRANSFER_TYPE_INVALID",
|
||||
details={"transfer_type": raw},
|
||||
) from exc
|
||||
|
||||
|
||||
def ensure_transfer_type_supported(transfer_type: TransferType) -> None:
|
||||
"""占位类型 fail-closed:类型 2/3 处理链路未实现前禁止进入匹配。
|
||||
|
||||
Args:
|
||||
transfer_type: 已规范化的调拨类型。
|
||||
Raises:
|
||||
ValidationError: 类型未实现(TRANSFER_TYPE_NOT_SUPPORTED)。
|
||||
"""
|
||||
if transfer_type not in SUPPORTED_TRANSFER_TYPES:
|
||||
raise ValidationError(
|
||||
f"transfer type not supported yet: {transfer_type.value}",
|
||||
code=TRANSFER_TYPE_NOT_SUPPORTED,
|
||||
details={"transfer_type": transfer_type.value},
|
||||
"transfer_type is required",
|
||||
code=TRANSFER_TYPE_REQUIRED,
|
||||
http_status=422, # 规格 §11:匹配创建类型门禁统一 422
|
||||
)
|
||||
# 复用配置服务的唯一读取口径:脏配置在其读取侧已被引擎拦截(fail-closed)。
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import (
|
||||
TRANSFER_TYPE_NOT_CONFIGURED as _NOT_CONFIGURED,
|
||||
)
|
||||
|
||||
|
||||
def invoice_in_scope(invoice_no: str, transfer_type: TransferType | str | None) -> bool:
|
||||
"""判断 Invoice 单号是否落在调拨类型的收料数据范围内(单一判断口径)。
|
||||
|
||||
用途:匹配过滤(filter_invoices_for_type)与 scope 行圈定(matching_service
|
||||
的 scope_item_query)共用本谓词,避免"单过滤"与"行圈定"口径漂移。
|
||||
|
||||
Args:
|
||||
invoice_no: 收料单单号(大小写不敏感,前后空白忽略;空值恒 False)。
|
||||
transfer_type: 调拨类型(未规范化值允许,缺省/空回落类型 1)。
|
||||
Returns:
|
||||
True 表示该单在类型范围内(应纳入匹配/scope 查询);
|
||||
占位类型(规则未启用)恒 False。
|
||||
"""
|
||||
resolved = normalize_transfer_type(transfer_type)
|
||||
if resolved == TransferType.IN_TRANSIT_TO_HUB:
|
||||
prefixes = tuple(prefix.upper() for prefix in IN_TRANSIT_TO_HUB_INVOICE_PREFIXES)
|
||||
return str(invoice_no or "").strip().upper().startswith(prefixes)
|
||||
# 类型 2/3 的范围规则在启用时补齐(此前 ensure_transfer_type_supported 已拦截)。
|
||||
return False
|
||||
|
||||
|
||||
def filter_invoices_for_type(
|
||||
invoices: Iterable[AggregatedInvoice],
|
||||
transfer_type: TransferType,
|
||||
) -> list[AggregatedInvoice]:
|
||||
"""按类型的收料数据范围过滤汇总单(返回保留项,保持原顺序)。
|
||||
|
||||
Args:
|
||||
invoices: 已汇总的收料单。
|
||||
transfer_type: 已规范化且已确认支持的调拨类型。
|
||||
Returns:
|
||||
类型范围内的单列表(判断口径统一走 invoice_in_scope)。
|
||||
"""
|
||||
return [
|
||||
invoice for invoice in invoices
|
||||
if invoice_in_scope(invoice.invoice_no, transfer_type)
|
||||
]
|
||||
|
||||
|
||||
def transfer_type_scope_note(transfer_type: TransferType) -> str:
|
||||
"""类型的范围规则说明(写入 TransferMatching.scope_json 供审计追溯)。"""
|
||||
if transfer_type == TransferType.IN_TRANSIT_TO_HUB:
|
||||
return f"invoice_prefix:{'+'.join(IN_TRANSIT_TO_HUB_INVOICE_PREFIXES).lower()}"
|
||||
if transfer_type == TransferType.HUB_REPAIR_OUT:
|
||||
return f"odm_id:{HUB_REPAIR_OUT_ODM_ID}"
|
||||
return "pending_rule"
|
||||
try:
|
||||
config = get_by_code(cleaned)
|
||||
except ValidationError as exc:
|
||||
if exc.code == _NOT_CONFIGURED:
|
||||
# 归一为本模块稳定错误码(匹配链路与 API 复用同一码面)。
|
||||
raise ValidationError(
|
||||
f"transfer type not configured: {cleaned}",
|
||||
code=TRANSFER_TYPE_NOT_CONFIGURED,
|
||||
details={"transfer_type": cleaned},
|
||||
http_status=422, # 规格 §11:空配置/停用类型 → 422
|
||||
) from exc
|
||||
raise
|
||||
if require_enabled and not config.enabled:
|
||||
raise ValidationError(
|
||||
f"transfer type is disabled: {cleaned}",
|
||||
code=TRANSFER_TYPE_DISABLED,
|
||||
details={"transfer_type": cleaned},
|
||||
http_status=422, # 规格 §11:空配置/停用类型 → 422
|
||||
)
|
||||
return config
|
||||
@@ -0,0 +1,459 @@
|
||||
"""services/in_transit_transfer/transfer_type_config_service.py
|
||||
|
||||
用途:调拨类型配置域服务(ADR 0002)——transfer_type_configs 表的唯一 CRUD 入口:
|
||||
列表/启用列表/按码读取/创建/更新(code 创建后不可变,只有停用没有删除),
|
||||
以及 mapped/fixed 双模式仓库角色解析 resolve_warehouse(Task 11 路由接入、
|
||||
Task 5 管理 API 消费)。
|
||||
依赖:models.in_transit_transfer.TransferTypeConfig、app.db(db.session)、
|
||||
scope_rules.parse_scope_rules、field_transforms.parse_transform_rules、
|
||||
app.core.errors.ValidationError;RouteMapping 仅类型标注(TYPE_CHECKING)。
|
||||
逻辑:写路径先过三块配置 parse 门禁(范围规则/仓库定义/转换规则)→ 组装规范化
|
||||
JSON 后走 ORM 插入/更新(JSON 四列无 server_default,禁止原生 SQL 插入);
|
||||
读路径 DTO 组装同样全部走 parse——库内脏数据在读取侧也被拦截(fail-closed);
|
||||
resolve_warehouse 按 role 取 from/to 角色:mapped 透传 RouteMapping,
|
||||
fixed 覆盖仓库、external_org 非空才覆盖法人。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models.in_transit_transfer import TransferTypeConfig
|
||||
from app.services.in_transit_transfer.field_transforms import TransformRule, parse_transform_rules
|
||||
from app.services.in_transit_transfer.scope_rules import ScopeRule, parse_scope_rules
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.services.in_transit_transfer.matching_service import RouteMapping
|
||||
|
||||
# 稳定错误码(Task 5 同步四语言 errors.json;参数形态类失败走既有通用码)。
|
||||
TRANSFER_TYPE_NOT_CONFIGURED = "TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED"
|
||||
TRANSFER_TYPE_CODE_EXISTS = "TRANSFER.TRANSFER_TYPE_CODE_EXISTS"
|
||||
TRANSFER_TYPE_CODE_IMMUTABLE = "TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE"
|
||||
WAREHOUSE_CONFIG_INVALID = "TRANSFER.WAREHOUSE_CONFIG_INVALID"
|
||||
|
||||
# code 契约:小写字母开头,仅小写字母/数字/下划线,总长 2..64(与列宽一致)。
|
||||
CODE_PATTERN = re.compile(r"^[a-z][a-z0-9_]{1,63}$")
|
||||
|
||||
# 参数形态类校验失败复用既有通用码(不新增四语言条目,管理页表单层先行拦截)。
|
||||
_PARAM_INVALID = "VALIDATION.INVALID_PARAM"
|
||||
|
||||
_WAREHOUSE_MODES = ("mapped", "fixed")
|
||||
_WAREHOUSE_ROLE_KEYS = {"from": "from_role", "to": "to_role"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WarehouseRole:
|
||||
"""单角色仓库定义:mapped=沿用来源映射档;fixed=类型固定仓库(可覆盖法人)。"""
|
||||
|
||||
mode: str
|
||||
warehouse_code: str | None = None
|
||||
external_org: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WarehouseConfig:
|
||||
"""类型仓库定义:拨出(from)/拨入(to)两角色各自 mapped 或 fixed。"""
|
||||
|
||||
from_role: WarehouseRole
|
||||
to_role: WarehouseRole
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferTypeConfigDTO:
|
||||
"""调拨类型配置读取视图:三块配置均为引擎解析后的受控对象(非原始 JSON)。"""
|
||||
|
||||
code: str
|
||||
names: dict[str, Any]
|
||||
enabled: bool
|
||||
sort_order: int
|
||||
scope_rules: tuple[ScopeRule, ...]
|
||||
warehouse_config: WarehouseConfig
|
||||
transform_rules: tuple[TransformRule, ...]
|
||||
description: str | None
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
def _reject_param(message: str, **details: Any) -> ValidationError:
|
||||
"""参数形态类校验失败的统一出口(通用码 + 定位详情)。"""
|
||||
return ValidationError(message, code=_PARAM_INVALID, details=details)
|
||||
|
||||
|
||||
def _clean_str(value: Any) -> str | None:
|
||||
"""字符串规范化:非字符串 → None;空白串 → None;其余去首尾空白。"""
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
return value.strip() or None
|
||||
|
||||
|
||||
def _parse_warehouse_config(raw: dict | None) -> WarehouseConfig:
|
||||
"""校验并规范化仓库定义 JSON(保存与读取共用;非法 fail-closed)。
|
||||
|
||||
Args:
|
||||
raw: {"from": {...}, "to": {...}},角色项缺省视为 mapped(沿用映射档);
|
||||
mapped 项不消费固定仓库值(规范化为纯 {"mode": "mapped"})。
|
||||
Returns:
|
||||
规范化后的 WarehouseConfig。
|
||||
Raises:
|
||||
ValidationError: code=TRANSFER.WAREHOUSE_CONFIG_INVALID——mode 不在白名单、
|
||||
fixed 缺非空 warehouse_code、或结构非 dict。
|
||||
"""
|
||||
if raw is None:
|
||||
raw = {}
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError(
|
||||
"warehouse_config must be an object", code=WAREHOUSE_CONFIG_INVALID,
|
||||
)
|
||||
|
||||
def _role(role_key: str) -> WarehouseRole:
|
||||
entry = raw.get(role_key)
|
||||
if entry is None:
|
||||
return WarehouseRole(mode="mapped")
|
||||
if not isinstance(entry, dict):
|
||||
raise ValidationError(
|
||||
f"warehouse role {role_key} must be an object", code=WAREHOUSE_CONFIG_INVALID,
|
||||
details={"role": role_key},
|
||||
)
|
||||
mode = str(entry.get("mode", ""))
|
||||
if mode not in _WAREHOUSE_MODES:
|
||||
raise ValidationError(
|
||||
f"invalid warehouse mode: {mode}", code=WAREHOUSE_CONFIG_INVALID,
|
||||
details={"role": role_key, "mode": mode},
|
||||
)
|
||||
if mode != "fixed":
|
||||
return WarehouseRole(mode="mapped")
|
||||
warehouse_code = _clean_str(entry.get("warehouse_code"))
|
||||
if not warehouse_code:
|
||||
raise ValidationError(
|
||||
f"fixed warehouse role requires warehouse_code: {role_key}",
|
||||
code=WAREHOUSE_CONFIG_INVALID, details={"role": role_key},
|
||||
)
|
||||
return WarehouseRole(
|
||||
mode="fixed", warehouse_code=warehouse_code,
|
||||
external_org=_clean_str(entry.get("external_org")),
|
||||
)
|
||||
|
||||
return WarehouseConfig(from_role=_role("from"), to_role=_role("to"))
|
||||
|
||||
|
||||
def _warehouse_role_json(role: WarehouseRole) -> dict[str, Any]:
|
||||
"""WarehouseRole → 规范化 JSON 项(mapped 固化空值,保证读写对称)。"""
|
||||
return {"mode": role.mode, "warehouse_code": role.warehouse_code, "external_org": role.external_org}
|
||||
|
||||
|
||||
def _warehouse_config_json(config: WarehouseConfig) -> dict[str, Any]:
|
||||
"""WarehouseConfig → 入库 JSON(from/to 键与规格 §7 示例一致)。"""
|
||||
return {
|
||||
"from": _warehouse_role_json(config.from_role),
|
||||
"to": _warehouse_role_json(config.to_role),
|
||||
}
|
||||
|
||||
|
||||
def _to_dto(row: TransferTypeConfig) -> TransferTypeConfigDTO:
|
||||
"""ORM 行 → DTO;三块配置全部重走 parse,库内脏数据在读取侧被拦截。
|
||||
|
||||
Raises:
|
||||
ValidationError: 脏数据命中任一引擎白名单校验(SCOPE/WAREHOUSE/TRANSFORM)。
|
||||
"""
|
||||
return TransferTypeConfigDTO(
|
||||
code=row.code,
|
||||
names=dict(row.names_json or {}),
|
||||
enabled=bool(row.enabled),
|
||||
sort_order=int(row.sort_order or 0),
|
||||
scope_rules=parse_scope_rules(row.scope_rules_json),
|
||||
warehouse_config=_parse_warehouse_config(row.warehouse_config_json),
|
||||
transform_rules=parse_transform_rules(row.transform_rules_json),
|
||||
description=row.description,
|
||||
updated_at=row.updated_at,
|
||||
)
|
||||
|
||||
|
||||
def _query_by_code(code: str) -> TransferTypeConfig | None:
|
||||
"""按 code 精确查询(入参去首尾空白;不查 None/空串)。"""
|
||||
cleaned = str(code or "").strip()
|
||||
if not cleaned:
|
||||
return None
|
||||
return db.session.query(TransferTypeConfig).filter(TransferTypeConfig.code == cleaned).one_or_none()
|
||||
|
||||
|
||||
def _scope_rules_of(payload: dict) -> tuple[ScopeRule, ...]:
|
||||
"""解析 payload 中的范围规则(parse 门禁复用 Task 2 引擎,非法透传其错误码)。
|
||||
|
||||
Raises:
|
||||
ValidationError: TRANSFER.SCOPE_RULE_INVALID(规则字段/匹配方式/值非法)。
|
||||
"""
|
||||
return parse_scope_rules(payload.get("scope_rules"))
|
||||
|
||||
|
||||
def _enforce_scope_policy(payload: dict, rules: tuple[ScopeRule, ...]) -> None:
|
||||
"""空规则默认拒绝(防误圈全量);payload 显式确认(allow_empty_scope_rules)才放行。
|
||||
|
||||
[规格 §6] 是否允许「空=不限」由管理页显式确认——本服务默认要求至少一条。
|
||||
"""
|
||||
if rules or payload.get("allow_empty_scope_rules") is True:
|
||||
return
|
||||
raise _reject_param("scope_rules requires at least one rule unless explicitly confirmed")
|
||||
|
||||
|
||||
def _validated_names(payload: dict, *, required: bool) -> dict[str, Any] | None:
|
||||
"""校验 names:dict 且含非空 zh-CN(四语言名称的门禁底线)。
|
||||
|
||||
Args:
|
||||
payload: 创建/更新载荷。
|
||||
required: 创建恒为 True(names_json 必须含非空 zh-CN,缺 key 同拒);
|
||||
更新为 False(未提供保持原值,提供则同门禁校验)。
|
||||
Returns:
|
||||
names dict(更新未提供时 None,由调用方保持原值)。
|
||||
Raises:
|
||||
ValidationError: required 且缺 key、非 dict、缺 zh-CN 或 zh-CN 非非空字符串。
|
||||
"""
|
||||
if "names" not in payload:
|
||||
if required:
|
||||
raise _reject_param("names is required with non-empty zh-CN")
|
||||
return None
|
||||
names = payload.get("names")
|
||||
zh = names.get("zh-CN") if isinstance(names, dict) else None
|
||||
if not isinstance(zh, str) or not zh.strip():
|
||||
raise _reject_param("names requires non-empty zh-CN", names=names)
|
||||
return dict(names)
|
||||
|
||||
|
||||
def _coerce_sort_order(value: Any) -> int:
|
||||
"""sort_order 宽松转 int(JSON 数字/数字字符串),失败走参数校验码。"""
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise _reject_param(f"invalid sort_order: {value!r}", sort_order=value) from exc
|
||||
|
||||
|
||||
def list_configs() -> list[TransferTypeConfigDTO]:
|
||||
"""全量类型配置(含停用),按 sort_order 升序、code 次序稳定排序。
|
||||
|
||||
Returns:
|
||||
TransferTypeConfigDTO 列表(管理页列表用;含停用项)。
|
||||
Raises:
|
||||
ValidationError: 任一行的范围规则/仓库定义/转换规则为脏数据时,经 _to_dto
|
||||
抛对应引擎错误码(TRANSFER.SCOPE_RULE_INVALID /
|
||||
TRANSFER.WAREHOUSE_CONFIG_INVALID / TRANSFER.TRANSFORM_RULE_INVALID,
|
||||
fail-closed,不降级返回脏配置)。
|
||||
"""
|
||||
rows = (
|
||||
db.session.query(TransferTypeConfig)
|
||||
.order_by(TransferTypeConfig.sort_order.asc(), TransferTypeConfig.code.asc())
|
||||
.all()
|
||||
)
|
||||
return [_to_dto(row) for row in rows]
|
||||
|
||||
|
||||
def get_enabled() -> list[TransferTypeConfigDTO]:
|
||||
"""启用中的类型配置,按 sort_order 升序(chat 侧类型列表与 Task 5 公开接口用)。
|
||||
|
||||
Returns:
|
||||
仅 enabled 的 TransferTypeConfigDTO 列表。
|
||||
Raises:
|
||||
ValidationError: 脏数据同 list_configs——读取侧 parse fail-closed
|
||||
(对应引擎错误码,不降级返回脏配置)。
|
||||
"""
|
||||
rows = (
|
||||
db.session.query(TransferTypeConfig)
|
||||
.filter(TransferTypeConfig.enabled.is_(True))
|
||||
.order_by(TransferTypeConfig.sort_order.asc(), TransferTypeConfig.code.asc())
|
||||
.all()
|
||||
)
|
||||
return [_to_dto(row) for row in rows]
|
||||
|
||||
|
||||
def get_by_code(code: str) -> TransferTypeConfigDTO:
|
||||
"""按 code 读取单个类型配置。
|
||||
|
||||
Args:
|
||||
code: 类型编码(创建后不可变的业务主键)。
|
||||
Returns:
|
||||
TransferTypeConfigDTO。
|
||||
Raises:
|
||||
ValidationError: 不存在 → TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED(匹配链
|
||||
fail-closed 同码);脏配置 → 对应引擎错误码。
|
||||
"""
|
||||
row = _query_by_code(code)
|
||||
if row is None:
|
||||
raise ValidationError(
|
||||
f"transfer type not configured: {code}", code=TRANSFER_TYPE_NOT_CONFIGURED,
|
||||
details={"code": code},
|
||||
)
|
||||
return _to_dto(row)
|
||||
|
||||
|
||||
def create_config(payload: dict, operator_id: int | None = None) -> TransferTypeConfigDTO:
|
||||
"""创建类型配置(写入唯一入口;JSON 四列必须经 ORM 插入,无 server_default)。
|
||||
|
||||
Args:
|
||||
payload: {code, names, enabled?, sort_order?, scope_rules?, warehouse_config?,
|
||||
transform_rules?, description?, allow_empty_scope_rules?}。
|
||||
operator_id: 创建人 users.id(可空,系统初始化场景)。
|
||||
Returns:
|
||||
新建配置的 TransferTypeConfigDTO。
|
||||
Raises:
|
||||
ValidationError: code 重复 → TRANSFER.TRANSFER_TYPE_CODE_EXISTS;code 格式
|
||||
非法/缺 zh-CN/空 scope_rules 未显式确认 → 通用参数码;
|
||||
规则/仓库/转换非法 → 对应引擎错误码。
|
||||
"""
|
||||
if not isinstance(payload, dict):
|
||||
raise _reject_param("payload must be an object")
|
||||
|
||||
# [STEP 1] code 契约:格式先行(唯一性后置到 DB 前查重)。
|
||||
code = _clean_str(payload.get("code"))
|
||||
if not code or not CODE_PATTERN.match(code):
|
||||
raise _reject_param(f"invalid transfer type code: {code!r}", code=code)
|
||||
|
||||
# [STEP 2] names 必填且含非空 zh-CN(创建路径硬门禁,缺 key 同拒)。
|
||||
names = _validated_names(payload, required=True)
|
||||
|
||||
# [STEP 3] 三块配置 parse 门禁:范围规则(含空规则默认拒绝)、仓库定义、转换规则。
|
||||
scope_rules = _scope_rules_of(payload)
|
||||
_enforce_scope_policy(payload, scope_rules)
|
||||
warehouse_config = _parse_warehouse_config(payload.get("warehouse_config"))
|
||||
transform_rules = parse_transform_rules(payload.get("transform_rules"))
|
||||
|
||||
# [STEP 4] 唯一性预检(并发窗口由 uq_transfer_type_configs_code 兜底)。
|
||||
if _query_by_code(code) is not None:
|
||||
raise ValidationError(
|
||||
f"transfer type code already exists: {code}", code=TRANSFER_TYPE_CODE_EXISTS,
|
||||
details={"code": code},
|
||||
)
|
||||
|
||||
# [STEP 5] ORM 插入:JSON 列写入规范化结果(读回必可 parse,读写对称)。
|
||||
row = TransferTypeConfig(
|
||||
code=code,
|
||||
names_json=names,
|
||||
enabled=bool(payload.get("enabled", False)),
|
||||
sort_order=_coerce_sort_order(payload.get("sort_order", 0)),
|
||||
scope_rules_json=[
|
||||
{"field": r.field, "match": r.match, "values": list(r.values)} for r in scope_rules
|
||||
],
|
||||
warehouse_config_json=_warehouse_config_json(warehouse_config),
|
||||
transform_rules_json=[
|
||||
{"field": r.field, "op": r.op, "source": r.source, "target": r.target}
|
||||
for r in transform_rules
|
||||
],
|
||||
description=_clean_str(payload.get("description")),
|
||||
created_by=operator_id,
|
||||
updated_by=operator_id,
|
||||
)
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
return _to_dto(row)
|
||||
|
||||
|
||||
def update_config(code: str, payload: dict, operator_id: int | None = None) -> TransferTypeConfigDTO:
|
||||
"""更新类型配置(部分更新:payload 未提供的字段保持原值;code 不可变)。
|
||||
|
||||
原子校验:所有提供的键先全量 parse/校验,全部通过后才统一赋值提交——
|
||||
任一键非法时整单拒绝且行保持原值(不落半截变更,评审 Finding 2 契约)。
|
||||
|
||||
Args:
|
||||
code: 目标类型编码(路径参数)。
|
||||
payload: 待更新字段;含 code 且与目标不等 → 改名被拒。
|
||||
operator_id: 更新人 users.id(可空)。
|
||||
Returns:
|
||||
更新后的 TransferTypeConfigDTO。
|
||||
Raises:
|
||||
ValidationError: 不存在 → TRANSFER.TRANSFER_TYPE_NOT_CONFIGURED;改 code →
|
||||
TRANSFER.TRANSFER_TYPE_CODE_IMMUTABLE;字段校验失败同 create
|
||||
(引擎错误码或参数形态码),抛出时行未被修改。
|
||||
"""
|
||||
if not isinstance(payload, dict):
|
||||
raise _reject_param("payload must be an object")
|
||||
row = _query_by_code(code)
|
||||
if row is None:
|
||||
raise ValidationError(
|
||||
f"transfer type not configured: {code}", code=TRANSFER_TYPE_NOT_CONFIGURED,
|
||||
details={"code": code},
|
||||
)
|
||||
|
||||
# [STEP 1] code 不可变(transfer_runs.transfer_type 引用它,改名即断链)。
|
||||
payload_code = payload.get("code")
|
||||
if payload_code is not None and str(payload_code).strip() != row.code:
|
||||
raise ValidationError(
|
||||
f"transfer type code is immutable: {row.code}", code=TRANSFER_TYPE_CODE_IMMUTABLE,
|
||||
details={"code": row.code, "attempted": payload_code},
|
||||
)
|
||||
|
||||
# [STEP 2] 全量预校验(与 create 同构):所有可更新键先 parse/校验到 updates,
|
||||
# 任一非法即整体抛出——此阶段不触碰 ORM 行,杜绝半截变更残留 session
|
||||
# (评审 Finding 2:形如 {"description": 新值, "transform_rules": 非法}
|
||||
# 的载荷禁止先改 description 再抛错)。
|
||||
updates: dict[str, Any] = {}
|
||||
names = _validated_names(payload, required=False)
|
||||
if names is not None:
|
||||
updates["names_json"] = names
|
||||
if "scope_rules" in payload:
|
||||
scope_rules = _scope_rules_of(payload)
|
||||
_enforce_scope_policy(payload, scope_rules)
|
||||
updates["scope_rules_json"] = [
|
||||
{"field": r.field, "match": r.match, "values": list(r.values)} for r in scope_rules
|
||||
]
|
||||
if "warehouse_config" in payload:
|
||||
warehouse_config = _parse_warehouse_config(payload.get("warehouse_config"))
|
||||
updates["warehouse_config_json"] = _warehouse_config_json(warehouse_config)
|
||||
if "transform_rules" in payload:
|
||||
transform_rules = parse_transform_rules(payload.get("transform_rules"))
|
||||
updates["transform_rules_json"] = [
|
||||
{"field": r.field, "op": r.op, "source": r.source, "target": r.target}
|
||||
for r in transform_rules
|
||||
]
|
||||
if "enabled" in payload:
|
||||
updates["enabled"] = bool(payload.get("enabled"))
|
||||
if "sort_order" in payload:
|
||||
updates["sort_order"] = _coerce_sort_order(payload.get("sort_order"))
|
||||
if "description" in payload:
|
||||
updates["description"] = _clean_str(payload.get("description"))
|
||||
|
||||
# [STEP 3] 全部通过后统一赋值(键为本函数白名单字面量)+ updated_by,一次提交。
|
||||
for attr, value in updates.items():
|
||||
setattr(row, attr, value)
|
||||
row.updated_by = operator_id
|
||||
|
||||
db.session.commit()
|
||||
return _to_dto(row)
|
||||
|
||||
|
||||
def resolve_warehouse(
|
||||
route_mapped: "RouteMapping", config: WarehouseConfig, role: str,
|
||||
) -> tuple[str, str]:
|
||||
"""按角色解析运行期 (external_org, warehouse_code):mapped 透传、fixed 覆盖。
|
||||
|
||||
【AI 触发时机】匹配圈档/建单/库存查询需要「拨出仓、拨入仓、法人」三元组时,
|
||||
必须经本函数按类型配置解析;禁止绕过配置直取 RouteMapping 或硬编码仓库。
|
||||
|
||||
Args:
|
||||
route_mapped: 来源路由映射档解析结果(DefaultRouteResolver 产物)。
|
||||
config: 类型配置的仓库定义(WarehouseConfig)。
|
||||
role: "from"(拨出)或 "to"(拨入),其他值 fail-closed。
|
||||
Returns:
|
||||
(external_org, warehouse_code):mapped 双双透传映射档;fixed 取配置仓库,
|
||||
external_org 非空覆盖法人、为空沿用映射档。
|
||||
Raises:
|
||||
ValidationError: role 非法,或 fixed 角色缺 warehouse_code
|
||||
(TRANSFER.WAREHOUSE_CONFIG_INVALID;解析侧兜底防线)。
|
||||
"""
|
||||
if role == "from":
|
||||
role_config = config.from_role
|
||||
elif role == "to":
|
||||
role_config = config.to_role
|
||||
else:
|
||||
raise ValidationError(
|
||||
f"unknown warehouse role: {role}", code=WAREHOUSE_CONFIG_INVALID, details={"role": role},
|
||||
)
|
||||
if role_config.mode == "fixed":
|
||||
if not role_config.warehouse_code:
|
||||
raise ValidationError(
|
||||
f"fixed warehouse role requires warehouse_code: {role}",
|
||||
code=WAREHOUSE_CONFIG_INVALID, details={"role": role},
|
||||
)
|
||||
return (role_config.external_org or route_mapped.external_org, role_config.warehouse_code)
|
||||
warehouse = route_mapped.from_warehouse if role == "from" else route_mapped.to_warehouse
|
||||
return (route_mapped.external_org, warehouse)
|
||||
@@ -59,10 +59,9 @@ class WecomSummarySender:
|
||||
matched=counts.get("matched_count", 0),
|
||||
pending=counts.get("pending_stock_check_count", 0),
|
||||
),
|
||||
"可执行: {executable} 数量不符: {blocked} 未成熟: {not_matured}".format(
|
||||
"可执行: {executable} 数量不符: {blocked}".format(
|
||||
executable=counts.get("executable_count", 0),
|
||||
blocked=counts.get("blocked_count", 0),
|
||||
not_matured=counts.get("not_matured_count", 0),
|
||||
),
|
||||
])
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ backend/app/services/integrations/wecom/notify.py
|
||||
用途:企业微信消息通知适配(文本卡片、文件、事件消息)。
|
||||
依赖:requests、Flask current_app、User / WecomNotifyAudit 模型。
|
||||
逻辑:排程完成、权限申请、培训提醒等业务事件调用本模块发送企微消息并写审计。
|
||||
文本卡片标题默认加上「AI智能体」来源;密码重置和权限变更保持原标题。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -24,6 +25,17 @@ _TOKEN_CACHE = {
|
||||
'expires_at': None,
|
||||
}
|
||||
|
||||
# 企微 textcard 没有发送者栏,用来源前缀让收件人看出是 AI 智能体推送。
|
||||
_AGENT_SOURCE_PREFIX = 'AI智能体 · '
|
||||
_TEXT_CARD_TITLE_LIMIT = 120
|
||||
# 账号与权限通知不是智能体推送,标题不加来源。
|
||||
_NO_AGENT_SOURCE_EVENTS = frozenset({
|
||||
'password_reset',
|
||||
'permission_batch_updated',
|
||||
'permission_request_approved',
|
||||
'permission_request_rejected',
|
||||
})
|
||||
|
||||
|
||||
def _get_enabled_events() -> set[str]:
|
||||
raw = current_app.config.get('WECOM_NOTIFY_EVENTS', '')
|
||||
@@ -141,19 +153,54 @@ def send_wecom_file_message(wecom_userid: str, media_id: str) -> dict:
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _with_agent_source_title(title: str, *, enabled: bool = True) -> str:
|
||||
"""
|
||||
给企微 textcard 标题加上「AI智能体」来源,并限制在 120 字以内。
|
||||
|
||||
核心逻辑:前缀放在最前,超长时截断业务标题,避免来源被切掉。
|
||||
已带相同前缀时不重复添加。enabled 为 False 时只做长度截断。
|
||||
Args:
|
||||
title: 业务侧传入的卡片标题。
|
||||
enabled: 为 False 时保持原标题,用于密码重置和权限变更。
|
||||
Returns:
|
||||
实际发给企业微信的标题。
|
||||
"""
|
||||
text = (title or '').strip()
|
||||
if not enabled:
|
||||
return text[:_TEXT_CARD_TITLE_LIMIT]
|
||||
if text.startswith(_AGENT_SOURCE_PREFIX):
|
||||
return text[:_TEXT_CARD_TITLE_LIMIT]
|
||||
return f'{_AGENT_SOURCE_PREFIX}{text}'[:_TEXT_CARD_TITLE_LIMIT]
|
||||
|
||||
|
||||
def send_wecom_textcard_message(
|
||||
wecom_userid: str,
|
||||
title: str,
|
||||
description: str,
|
||||
jump_url: str,
|
||||
*,
|
||||
with_agent_source: bool = True,
|
||||
) -> dict:
|
||||
"""
|
||||
发送企业微信文本卡片。
|
||||
|
||||
核心逻辑:默认在标题前加上「AI智能体」来源。审计记录仍保存调用方传入的业务标题。
|
||||
Args:
|
||||
wecom_userid: 企业微信 userid。
|
||||
title: 业务标题。
|
||||
description: 卡片正文。
|
||||
jump_url: 点击跳转地址。
|
||||
with_agent_source: 为 False 时标题不加来源。
|
||||
Returns:
|
||||
企业微信 message/send 的 JSON 响应。
|
||||
"""
|
||||
token = _get_access_token()
|
||||
payload = {
|
||||
'touser': wecom_userid,
|
||||
'msgtype': 'textcard',
|
||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||
'textcard': {
|
||||
'title': title[:120],
|
||||
'title': _with_agent_source_title(title, enabled=with_agent_source),
|
||||
'description': (description or '')[:1024],
|
||||
'url': jump_url or _get_notify_base_url() or 'https://work.weixin.qq.com',
|
||||
'btntxt': '查看详情',
|
||||
@@ -200,6 +247,7 @@ def send_wecom_event_message(
|
||||
|
||||
核心逻辑:默认使用 `user.wecom_userid`;合同付款第二、三轮可传入 OA HrmResource.id
|
||||
作为 wecom_userid,因为该 id 同时是企业微信 userid。
|
||||
标题在发送时加上「AI智能体」来源;密码重置和权限变更不加。审计 title 保持业务标题。
|
||||
Args:
|
||||
event_type: 通知事件开关名。
|
||||
user: 审计关联的系统用户,可为收件人在 HXOPS 中的映射账号。
|
||||
@@ -239,7 +287,13 @@ def send_wecom_event_message(
|
||||
else:
|
||||
final_jump_url = _build_jump_url(jump_path, trace_id, jump_params)
|
||||
audit.jump_url = final_jump_url
|
||||
data = send_wecom_textcard_message(target_userid, title, content, final_jump_url)
|
||||
data = send_wecom_textcard_message(
|
||||
target_userid,
|
||||
title,
|
||||
content,
|
||||
final_jump_url,
|
||||
with_agent_source=event_type not in _NO_AGENT_SOURCE_EVENTS,
|
||||
)
|
||||
if data.get('errcode') == 0:
|
||||
audit.status = 'sent'
|
||||
return {'ok': True, 'trace_id': trace_id}
|
||||
|
||||
@@ -3,8 +3,8 @@ backend/app/services/lean_training_service.py
|
||||
|
||||
用途:精益管理培训的周任务、员工提交、看板和提醒规则服务。
|
||||
依赖:TrainingConfig/Resource、精益培训模型、User、统一 ValidationError。
|
||||
逻辑:管理端冻结每周视频列表、每周推送数量与受训对象;学员端"本期视频"口径为本任务首次推送的
|
||||
视频(已推送前缀扣除其它更早期任务已推送部分,推过的视频不重复展示、不要求重学);
|
||||
逻辑:管理端冻结每周视频列表、每周推送数量与受训对象;受训角色按用户已挂的全部权限组匹配。
|
||||
学员端「本期视频」口径为本任务首次推送的视频(已推送前缀扣除其它更早期任务已推送部分,推过的视频不重复展示、不要求重学);
|
||||
员工仅对本期视频提交观看事实与学习感悟,服务端按 50 字门槛判定完成,管理看板只读取已授权范围。
|
||||
"""
|
||||
|
||||
@@ -23,10 +23,12 @@ from app.models import (
|
||||
Agent,
|
||||
LeanTrainingCompletion,
|
||||
LeanTrainingWeeklyTask,
|
||||
PermissionRole,
|
||||
TrainingConfig,
|
||||
TrainingConfigResource,
|
||||
User,
|
||||
)
|
||||
from app.models.permission_role import user_permission_roles
|
||||
from app.services.integrations.minio import minio_service
|
||||
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, to_utc_naive, utc_now_naive
|
||||
|
||||
@@ -252,20 +254,38 @@ def _normalize_target_user_ids(value: Any) -> list[int]:
|
||||
|
||||
|
||||
def target_user_ids_for_task(task: LeanTrainingWeeklyTask) -> set[int]:
|
||||
"""返回周任务的在职受训对象,角色和用户指定对象按并集处理。"""
|
||||
"""返回周任务的在职受训对象。指定用户,以及主角色或任一已挂角色命中的人,按并集处理。"""
|
||||
predicates = []
|
||||
if task.target_user_ids:
|
||||
predicates.append(User.id.in_(list(task.target_user_ids)))
|
||||
if task.target_roles:
|
||||
predicates.append(User.role.in_(list(task.target_roles)))
|
||||
role_codes = list(task.target_roles)
|
||||
member_ids = (
|
||||
select(user_permission_roles.c.user_id)
|
||||
.join(PermissionRole, PermissionRole.id == user_permission_roles.c.role_id)
|
||||
.where(PermissionRole.code.in_(role_codes))
|
||||
)
|
||||
predicates.append(or_(User.role.in_(role_codes), User.id.in_(member_ids)))
|
||||
if not predicates:
|
||||
return set()
|
||||
return set(db.session.execute(select(User.id).where(User.status == "active", or_(*predicates))).scalars())
|
||||
|
||||
|
||||
def is_task_targeted_to_user(task: LeanTrainingWeeklyTask, user: User) -> bool:
|
||||
"""判断员工是否属于周任务对象,角色匹配或显式指定任一成立即可学习。"""
|
||||
return user.status == "active" and (user.id in set(task.target_user_ids or []) or user.role in set(task.target_roles or []))
|
||||
"""判断员工是否属于周任务对象。任一已挂角色命中,或显式指定用户,即可学习。"""
|
||||
if user.status != "active":
|
||||
return False
|
||||
if user.id in set(task.target_user_ids or []):
|
||||
return True
|
||||
codes = set(task.target_roles or [])
|
||||
if not codes:
|
||||
return False
|
||||
from app.services.permission_roles.service import list_assigned_roles, roles_configured
|
||||
|
||||
assigned = {str(user.role or "")}
|
||||
if roles_configured():
|
||||
assigned.update(role.code for role in list_assigned_roles(user))
|
||||
return bool(assigned & codes)
|
||||
|
||||
|
||||
def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool = False, own_pushed_ids: list[int] | None = None) -> dict[str, Any]:
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
services/permission_roles/service.py
|
||||
|
||||
用途:权限组 CRUD、成员预览/确认调整、把角色包同步到 users.role 与 user_agent_permissions。
|
||||
依赖:PermissionRole、User、Agent、catalog。
|
||||
用途:权限组 CRUD、成员预览/确认调整、把多个角色包的并集同步到用户授权。
|
||||
依赖:PermissionRole、user_permission_roles、User、Agent、catalog。
|
||||
逻辑:由 api/admin/permission_roles 调用;用户创建/改角色时 sync_user_grants_from_role。
|
||||
一个用户可挂多个业务角色,应用入口与能力取并集;平台管理员不与其他角色叠加。
|
||||
拿掉最后一个业务角色时回到默认权限组。users.role 只记主角色。
|
||||
排程种子/告警用 first_platform_admin_user 按 is_platform_admin join,不写死 role='admin'。
|
||||
未种子角色表时保持旧的按人勾选,避免单测全量改夹具。
|
||||
"""
|
||||
@@ -14,12 +16,13 @@ import re
|
||||
from datetime import datetime
|
||||
from typing import Any, Iterable
|
||||
|
||||
from sqlalchemy import delete, insert, select
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.models.permission_role import PermissionRole
|
||||
from app.models.permission_role import PermissionRole, user_permission_roles
|
||||
from app.services.permission_roles.catalog import (
|
||||
FEATURE_CATALOG,
|
||||
KNOWN_FEATURE_KEYS,
|
||||
@@ -75,6 +78,187 @@ def list_role_name_map() -> dict[str, str]:
|
||||
return {row.code: row.name for row in rows}
|
||||
|
||||
|
||||
def list_assigned_roles(user: User, sess: Any | None = None) -> list[PermissionRole]:
|
||||
"""
|
||||
读取用户已挂的权限组。
|
||||
|
||||
核心逻辑:有成员表行时以成员表为准;还没回填时回退 users.role,兼容只写 role 的旧数据和测试。
|
||||
"""
|
||||
session = _orm_session(sess)
|
||||
if user is None or getattr(user, 'id', None) is None or not _permission_roles_exist(session):
|
||||
return []
|
||||
linked = (
|
||||
session.query(PermissionRole)
|
||||
.join(user_permission_roles, user_permission_roles.c.role_id == PermissionRole.id)
|
||||
.filter(user_permission_roles.c.user_id == user.id)
|
||||
.order_by(PermissionRole.sort_order.asc(), PermissionRole.id.asc())
|
||||
.all()
|
||||
)
|
||||
if linked:
|
||||
return linked
|
||||
code = str(getattr(user, 'role', '') or '').strip()
|
||||
if not code:
|
||||
return []
|
||||
fallback = session.query(PermissionRole).filter(PermissionRole.code == code).one_or_none()
|
||||
return [fallback] if fallback else []
|
||||
|
||||
|
||||
def roles_by_user_ids(user_ids: list[int]) -> dict[int, list[PermissionRole]]:
|
||||
"""批量读取成员关系,避免用户列表逐人查询。"""
|
||||
if not user_ids or not roles_configured():
|
||||
return {}
|
||||
rows = (
|
||||
db.session.query(user_permission_roles.c.user_id, PermissionRole)
|
||||
.join(PermissionRole, PermissionRole.id == user_permission_roles.c.role_id)
|
||||
.filter(user_permission_roles.c.user_id.in_(user_ids))
|
||||
.order_by(PermissionRole.sort_order.asc(), PermissionRole.id.asc())
|
||||
.all()
|
||||
)
|
||||
grouped: dict[int, list[PermissionRole]] = {}
|
||||
for user_id, role in rows:
|
||||
grouped.setdefault(int(user_id), []).append(role)
|
||||
return grouped
|
||||
|
||||
|
||||
def _primary_role(roles: list[PermissionRole]) -> PermissionRole | None:
|
||||
"""主角色:平台管理员优先,否则取非默认角色里排序最前的一个。"""
|
||||
if not roles:
|
||||
return None
|
||||
admins = [role for role in roles if role.is_platform_admin]
|
||||
pool = admins or [role for role in roles if not role.is_default] or roles
|
||||
return sorted(pool, key=lambda role: (role.sort_order, role.id or 0))[0]
|
||||
|
||||
|
||||
def _role_label(roles: list[PermissionRole], role_names: dict[str, str], fallback: str) -> str:
|
||||
"""多个角色显示名用顿号拼接;没有成员行时回退主角色名。"""
|
||||
if roles:
|
||||
return '、'.join(role.name for role in roles)
|
||||
return role_names.get(fallback) or fallback
|
||||
|
||||
|
||||
def describe_user_roles(
|
||||
user: User,
|
||||
assigned: list[PermissionRole] | None = None,
|
||||
role_names: dict[str, str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
用户当前的主角色与全部角色。
|
||||
|
||||
Args:
|
||||
assigned: 已批量查出的角色;None 时再查成员表。空列表表示调用方确认没有成员行。
|
||||
"""
|
||||
names = role_names if role_names is not None else list_role_name_map()
|
||||
if assigned is None and roles_configured():
|
||||
roles = list_assigned_roles(user)
|
||||
else:
|
||||
roles = list(assigned or [])
|
||||
primary = _primary_role(roles)
|
||||
fallback = str(user.role or '')
|
||||
return {
|
||||
'role': primary.code if primary else fallback,
|
||||
'role_name': _role_label(roles, names, fallback),
|
||||
'role_codes': [role.code for role in roles] or ([fallback] if fallback else []),
|
||||
}
|
||||
|
||||
|
||||
def role_auth_payload(user: User) -> dict[str, Any]:
|
||||
"""
|
||||
登录态里的角色展示。
|
||||
|
||||
Returns:
|
||||
role_name: 全部角色名,顿号拼接。
|
||||
role_codes: 全部角色 code;未配置权限组时只有 users.role。
|
||||
"""
|
||||
described = describe_user_roles(user)
|
||||
return {
|
||||
'role_name': described['role_name'],
|
||||
'role_codes': described['role_codes'],
|
||||
}
|
||||
|
||||
|
||||
def _has_membership_rows(user: User) -> bool:
|
||||
"""该用户是否已有成员表行。"""
|
||||
if user.id is None:
|
||||
return False
|
||||
found = db.session.execute(
|
||||
select(user_permission_roles.c.user_id)
|
||||
.where(user_permission_roles.c.user_id == user.id)
|
||||
.limit(1)
|
||||
).first()
|
||||
return found is not None
|
||||
|
||||
|
||||
def replace_user_roles(user: User, roles: list[PermissionRole]) -> list[PermissionRole]:
|
||||
"""
|
||||
用给定权限组替换成员关系,并回写 users.role 主角色。
|
||||
|
||||
核心逻辑:出现平台管理员时只保留该角色。空列表回落到默认权限组。
|
||||
"""
|
||||
if user.id is None:
|
||||
db.session.flush()
|
||||
unique: list[PermissionRole] = []
|
||||
seen: set[int] = set()
|
||||
for role in roles:
|
||||
if role is None or role.id in seen:
|
||||
continue
|
||||
seen.add(role.id)
|
||||
unique.append(role)
|
||||
admins = [role for role in unique if role.is_platform_admin]
|
||||
if admins:
|
||||
unique = [sorted(admins, key=lambda role: (role.sort_order, role.id or 0))[0]]
|
||||
elif not unique:
|
||||
default = get_default_role()
|
||||
unique = [default] if default else []
|
||||
db.session.execute(
|
||||
delete(user_permission_roles).where(user_permission_roles.c.user_id == user.id)
|
||||
)
|
||||
if unique:
|
||||
db.session.execute(
|
||||
insert(user_permission_roles),
|
||||
[{'user_id': user.id, 'role_id': role.id} for role in unique],
|
||||
)
|
||||
primary = _primary_role(unique)
|
||||
user.role = primary.code if primary else default_role_code()
|
||||
user._is_platform_admin_cached = None
|
||||
db.session.flush()
|
||||
return unique
|
||||
|
||||
|
||||
def roles_after_grant(current: list[PermissionRole], incoming: PermissionRole) -> list[PermissionRole]:
|
||||
"""
|
||||
追加一个角色后的成员集合。
|
||||
|
||||
核心逻辑:业务角色会拿掉默认角色,避免「普通用户」人数把已有专属角色的人再计一次;
|
||||
其他业务角色保留。追加默认角色时不拿掉已有业务角色。平台管理员独占。
|
||||
"""
|
||||
if incoming.is_platform_admin:
|
||||
return [incoming]
|
||||
if incoming.is_default:
|
||||
if any(role.id == incoming.id for role in current):
|
||||
return list(current)
|
||||
return [*current, incoming]
|
||||
kept = [
|
||||
role for role in current
|
||||
if not role.is_default and not role.is_platform_admin and role.id != incoming.id
|
||||
]
|
||||
return [*kept, incoming]
|
||||
|
||||
|
||||
def roles_after_revoke(current: list[PermissionRole], incoming: PermissionRole) -> list[PermissionRole]:
|
||||
"""
|
||||
移出一个角色后的成员集合。
|
||||
|
||||
核心逻辑:还剩别的角色就只移出这一个。一个都不剩时回到默认权限组。
|
||||
默认角色是唯一角色时保持不变。
|
||||
"""
|
||||
kept = [role for role in current if role.id != incoming.id]
|
||||
if not kept:
|
||||
default = get_default_role()
|
||||
if default is not None:
|
||||
return [default]
|
||||
return kept
|
||||
|
||||
|
||||
def _orm_session(sess: Any | None):
|
||||
"""排程种子 after_commit 可能传入独立 Session,查询必须落在同一会话。"""
|
||||
return sess if sess is not None else db.session
|
||||
@@ -158,7 +342,7 @@ def user_is_platform_admin(user: User | None, sess: Any | None = None) -> bool:
|
||||
"""
|
||||
判断用户是否属于 is_platform_admin 权限组。
|
||||
|
||||
核心逻辑:已种子时按 users.role join permission_roles;否则回退 role=admin。
|
||||
核心逻辑:已种子时看全部已挂角色里是否有平台管理组;否则回退 role=admin。
|
||||
同一 User 实例在一次请求内缓存结果,避免货代工作台重复查询。
|
||||
|
||||
Args:
|
||||
@@ -172,22 +356,20 @@ def user_is_platform_admin(user: User | None, sess: Any | None = None) -> bool:
|
||||
return False
|
||||
session = _orm_session(sess)
|
||||
role_code = str(getattr(user, 'role', '') or '').strip()
|
||||
assigned = list_assigned_roles(user, session) if _permission_roles_exist(session) else []
|
||||
cache_key = (role_code, tuple(role.code for role in assigned))
|
||||
cached = getattr(user, '_is_platform_admin_cached', None)
|
||||
if isinstance(cached, tuple) and len(cached) == 2 and cached[0] == role_code:
|
||||
if isinstance(cached, tuple) and len(cached) == 2 and cached[0] == cache_key:
|
||||
return bool(cached[1])
|
||||
if not role_code:
|
||||
user._is_platform_admin_cached = (role_code, False)
|
||||
return False
|
||||
if _permission_roles_exist(session):
|
||||
role = (
|
||||
session.query(PermissionRole)
|
||||
.filter(PermissionRole.code == role_code)
|
||||
.one_or_none()
|
||||
)
|
||||
result = bool(role and role.is_platform_admin)
|
||||
if assigned:
|
||||
result = any(role.is_platform_admin for role in assigned)
|
||||
elif not role_code:
|
||||
result = False
|
||||
elif _permission_roles_exist(session):
|
||||
result = False
|
||||
else:
|
||||
result = role_code == PLATFORM_ADMIN_CODE
|
||||
user._is_platform_admin_cached = (role_code, result)
|
||||
user._is_platform_admin_cached = (cache_key, result)
|
||||
return result
|
||||
|
||||
|
||||
@@ -211,46 +393,92 @@ def _normalize_feature_map(raw: Any) -> dict[str, bool]:
|
||||
|
||||
def effective_feature_permissions(user: User) -> dict[str, bool] | None:
|
||||
"""
|
||||
若已配置权限组,返回该用户角色包的有效功能权限;否则 None 表示走 User 旧默认值。
|
||||
若已配置权限组,返回该用户全部角色的有效功能权限;否则 None 表示走 User 旧默认值。
|
||||
|
||||
核心逻辑:任一业务角色打开的能力即生效。平台管理员仍默认全开,再用该组上的显式值覆盖。
|
||||
"""
|
||||
if not roles_configured():
|
||||
return None
|
||||
role = get_role_by_code(user.role)
|
||||
stored = _normalize_feature_map(role.feature_permissions if role else {})
|
||||
if role and role.is_platform_admin:
|
||||
roles = list_assigned_roles(user)
|
||||
admin = next((role for role in roles if role.is_platform_admin), None)
|
||||
if admin is not None:
|
||||
result = {key: True for key in KNOWN_FEATURE_KEYS}
|
||||
result.update(stored)
|
||||
result.update(_normalize_feature_map(admin.feature_permissions))
|
||||
return result
|
||||
result = {key: False for key in KNOWN_FEATURE_KEYS}
|
||||
result.update(stored)
|
||||
for role in roles:
|
||||
for key, enabled in _normalize_feature_map(role.feature_permissions).items():
|
||||
if enabled:
|
||||
result[key] = True
|
||||
return result
|
||||
|
||||
|
||||
def sync_user_grants_from_role(user: User) -> None:
|
||||
"""
|
||||
按用户当前 role 重写 Agent 授权与个人功能覆盖。
|
||||
按用户已挂的全部角色重算 Agent 授权与个人功能覆盖。
|
||||
|
||||
核心逻辑:管理员不写 user_agent_permissions(入口隐式全开);
|
||||
其他角色用权限组勾选的 Agent 全量替换;个人 feature_permissions 清空,改由角色包计算。
|
||||
核心逻辑:还没有成员行时先按 users.role 写入一行。管理员不写 user_agent_permissions(入口隐式全开);
|
||||
其他角色把各权限组勾选的 Agent 取并集。个人 feature_permissions 清空,改由角色包计算。
|
||||
未配置权限组时不改。
|
||||
"""
|
||||
if not roles_configured():
|
||||
return
|
||||
role = get_role_by_code(user.role)
|
||||
if role is None:
|
||||
if user.id is None:
|
||||
db.session.flush()
|
||||
roles = list_assigned_roles(user)
|
||||
if not roles:
|
||||
fallback = get_default_role()
|
||||
if fallback is None:
|
||||
return
|
||||
user.role = fallback.code
|
||||
role = fallback
|
||||
roles = [fallback]
|
||||
if not _has_membership_rows(user):
|
||||
roles = replace_user_roles(user, roles)
|
||||
admins = [role for role in roles if role.is_platform_admin]
|
||||
user.feature_permissions = {}
|
||||
if role.is_platform_admin:
|
||||
user._is_platform_admin_cached = None
|
||||
if admins:
|
||||
if len(roles) != 1:
|
||||
replace_user_roles(user, [admins[0]])
|
||||
return
|
||||
user.agents = list(role.agents)
|
||||
primary = _primary_role(roles)
|
||||
if primary is not None and user.role != primary.code:
|
||||
user.role = primary.code
|
||||
seen: dict[int, Agent] = {}
|
||||
for role in roles:
|
||||
for agent in role.agents:
|
||||
seen[agent.id] = agent
|
||||
user.agents = list(seen.values())
|
||||
|
||||
|
||||
def _users_for_role(role: PermissionRole, *, active_only: bool = False) -> list[User]:
|
||||
"""
|
||||
某权限组的成员。
|
||||
|
||||
核心逻辑:成员表里挂了该角色的人,加上尚未回填、users.role 仍等于该 code 的人。
|
||||
"""
|
||||
linked_ids = select(user_permission_roles.c.user_id).where(
|
||||
user_permission_roles.c.role_id == role.id
|
||||
)
|
||||
any_membership = select(user_permission_roles.c.user_id)
|
||||
linked = db.session.query(User).filter(User.id.in_(linked_ids))
|
||||
unlinked = db.session.query(User).filter(
|
||||
User.role == role.code,
|
||||
~User.id.in_(any_membership),
|
||||
)
|
||||
if active_only:
|
||||
linked = linked.filter(User.status == 'active')
|
||||
unlinked = unlinked.filter(User.status == 'active')
|
||||
found: dict[int, User] = {}
|
||||
for user in [*linked.all(), *unlinked.all()]:
|
||||
found[user.id] = user
|
||||
return list(found.values())
|
||||
|
||||
|
||||
def _count_members(code: str) -> int:
|
||||
return db.session.query(User).filter(User.role == code).count()
|
||||
role = get_role_by_code(code)
|
||||
if role is None:
|
||||
return db.session.query(User).filter(User.role == code).count()
|
||||
return len(_users_for_role(role))
|
||||
|
||||
|
||||
def _serialize_role(role: PermissionRole, *, with_agents: bool = True) -> dict[str, Any]:
|
||||
@@ -437,9 +665,9 @@ def create_role(data: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
def update_role(code: str, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
保存权限组。仅当应用勾选或能力开关变化时,才同步该组用户的应用授权。
|
||||
保存权限组。仅当应用勾选或能力开关变化时,才按并集重算该组用户的应用授权。
|
||||
|
||||
管理员不可改应用入口勾选。只改名称/说明不重写成员权限。
|
||||
管理员不可改应用入口勾选。只改名称/说明不重写成员权限。其他人身上的其他角色保留。
|
||||
"""
|
||||
role = get_role_by_code(code)
|
||||
if not role:
|
||||
@@ -447,7 +675,7 @@ def update_role(code: str, data: dict[str, Any]) -> dict[str, Any]:
|
||||
allow_agents = not role.is_platform_admin
|
||||
grants_changed = _grants_changed(role, data, allow_agents=allow_agents)
|
||||
_apply_package(role, data, allow_agents=allow_agents)
|
||||
users = db.session.query(User).filter(User.role == role.code).all() if grants_changed else []
|
||||
users = _users_for_role(role) if grants_changed else []
|
||||
for user in users:
|
||||
sync_user_grants_from_role(user)
|
||||
db.session.commit()
|
||||
@@ -470,28 +698,67 @@ def delete_role(code: str) -> dict[str, Any]:
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def _person_payload(user: User, role_names: dict[str, str]) -> dict[str, Any]:
|
||||
def _person_payload(
|
||||
user: User,
|
||||
role_names: dict[str, str],
|
||||
assigned: list[PermissionRole] | None = None,
|
||||
*,
|
||||
retained_role_names: list[str] | None = None,
|
||||
returns_to_default: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""选人与确认框共用的人员行。role 是主角色,role_codes 是全部角色。"""
|
||||
roles = list_assigned_roles(user) if assigned is None else assigned
|
||||
primary = _primary_role(roles)
|
||||
fallback = str(user.role or '')
|
||||
return {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'department': user.department,
|
||||
'role': user.role,
|
||||
'role_name': role_names.get(user.role) or user.role,
|
||||
'role': primary.code if primary else fallback,
|
||||
'role_name': _role_label(roles, role_names, fallback),
|
||||
'role_codes': [role.code for role in roles] or ([fallback] if fallback else []),
|
||||
'retained_role_names': list(retained_role_names or []),
|
||||
'returns_to_default': returns_to_default,
|
||||
'wecom_bound': bool(user.wecom_userid),
|
||||
}
|
||||
|
||||
|
||||
def assign_role_codes(user: User, codes: list[str]) -> None:
|
||||
"""
|
||||
按 code 列表替换该用户的全部角色并重算授权。
|
||||
|
||||
核心逻辑:空列表回落到默认权限组。平台管理员 code 会清掉其他角色。
|
||||
"""
|
||||
roles: list[PermissionRole] = []
|
||||
for code in codes:
|
||||
role = get_role_by_code(code)
|
||||
if role is not None:
|
||||
roles.append(role)
|
||||
replace_user_roles(user, roles)
|
||||
sync_user_grants_from_role(user)
|
||||
|
||||
|
||||
def list_picker_people() -> list[dict[str, Any]]:
|
||||
"""选人弹窗候选人:启用用户且排除平台管理员。"""
|
||||
role_names = list_role_name_map()
|
||||
query = db.session.query(User).filter(User.status == 'active')
|
||||
admin_codes = platform_admin_role_codes()
|
||||
if admin_codes:
|
||||
query = query.filter(User.role.notin_(admin_codes))
|
||||
admin_ids = (
|
||||
select(user_permission_roles.c.user_id)
|
||||
.join(PermissionRole, PermissionRole.id == user_permission_roles.c.role_id)
|
||||
.where(PermissionRole.is_platform_admin.is_(True))
|
||||
)
|
||||
query = query.filter(User.role.notin_(admin_codes), ~User.id.in_(admin_ids))
|
||||
users = query.order_by(User.id.asc()).all()
|
||||
return [_person_payload(user, role_names) for user in users]
|
||||
assigned = roles_by_user_ids([user.id for user in users])
|
||||
payloads = []
|
||||
for user in users:
|
||||
roles = assigned.get(user.id) or list_assigned_roles(user)
|
||||
payloads.append(_person_payload(user, role_names, roles))
|
||||
return payloads
|
||||
|
||||
|
||||
def _normalize_selected_ids(raw: Any) -> list[int]:
|
||||
@@ -511,7 +778,10 @@ def _normalize_selected_ids(raw: Any) -> list[int]:
|
||||
|
||||
def preview_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
||||
"""
|
||||
计算勾选草稿相对当前成员的增减,供确认框展示来源角色。
|
||||
计算勾选草稿相对当前成员的增减。
|
||||
|
||||
核心逻辑:加入是追加本角色,不拿走其他业务角色。移出只拿掉本角色;
|
||||
一个业务角色都不剩时回到默认权限组。默认角色若已是唯一角色,取消勾选不算变更。
|
||||
"""
|
||||
role = get_role_by_code(code)
|
||||
if not role:
|
||||
@@ -520,35 +790,59 @@ def preview_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
||||
raise ForbiddenError('Platform admin members cannot be changed here', code='ROLE.ADMIN_LOCKED')
|
||||
default_code = default_role_code()
|
||||
selected = set(_normalize_selected_ids(selected_ids))
|
||||
current_members = (
|
||||
db.session.query(User)
|
||||
.filter(User.role == role.code)
|
||||
.filter(User.status == 'active')
|
||||
.all()
|
||||
)
|
||||
current_members = _users_for_role(role, active_only=True)
|
||||
current_ids = {user.id for user in current_members}
|
||||
added_ids = [item for item in selected if item not in current_ids]
|
||||
removed_ids = [item for item in current_ids if item not in selected]
|
||||
if role.code == default_code:
|
||||
removed_ids = []
|
||||
users_by_id = {
|
||||
user.id: user
|
||||
for user in db.session.query(User).filter(User.id.in_(added_ids + removed_ids)).all()
|
||||
} if added_ids or removed_ids else {}
|
||||
role_names = list_role_name_map()
|
||||
assigned_map = roles_by_user_ids(added_ids + removed_ids)
|
||||
|
||||
def _rows(ids: list[int]) -> list[dict[str, Any]]:
|
||||
rows = []
|
||||
for user_id in ids:
|
||||
user = users_by_id.get(user_id)
|
||||
if not user or user_is_platform_admin(user):
|
||||
continue
|
||||
rows.append(_person_payload(user, role_names))
|
||||
return rows
|
||||
def _assigned(person: User) -> list[PermissionRole]:
|
||||
rows = assigned_map.get(person.id)
|
||||
if rows:
|
||||
return rows
|
||||
return list_assigned_roles(person)
|
||||
|
||||
added = _rows(added_ids)
|
||||
removed = _rows(removed_ids)
|
||||
stolen = [row for row in added if row['role'] not in {default_code, role.code}]
|
||||
added = []
|
||||
for user_id in added_ids:
|
||||
user = users_by_id.get(user_id)
|
||||
if not user or user_is_platform_admin(user):
|
||||
continue
|
||||
current = _assigned(user)
|
||||
nxt = roles_after_grant(current, role)
|
||||
if role.is_default:
|
||||
retained = [item.name for item in nxt if item.id != role.id]
|
||||
else:
|
||||
retained = [item.name for item in nxt if item.id != role.id and not item.is_default]
|
||||
added.append(_person_payload(
|
||||
user,
|
||||
role_names,
|
||||
current,
|
||||
retained_role_names=retained,
|
||||
))
|
||||
removed = []
|
||||
for user_id in removed_ids:
|
||||
user = users_by_id.get(user_id)
|
||||
if not user or user_is_platform_admin(user):
|
||||
continue
|
||||
current = _assigned(user)
|
||||
nxt = roles_after_revoke(current, role)
|
||||
if {item.id for item in nxt} == {item.id for item in current}:
|
||||
continue
|
||||
returns = bool(nxt) and all(item.is_default for item in nxt)
|
||||
retained = [] if returns else [item.name for item in nxt]
|
||||
removed.append(_person_payload(
|
||||
user,
|
||||
role_names,
|
||||
current,
|
||||
retained_role_names=retained,
|
||||
returns_to_default=returns,
|
||||
))
|
||||
stolen = [row for row in added if row['retained_role_names']]
|
||||
return {
|
||||
'role_code': role.code,
|
||||
'role_name': role.name,
|
||||
@@ -562,26 +856,28 @@ def preview_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
||||
|
||||
def apply_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
||||
"""
|
||||
确认后写回成员:勾选的人改入本角色;取消勾选的人回到默认角色。
|
||||
排除管理员;默认角色忽略移出。
|
||||
确认后写回成员:勾选的人追加本角色;取消勾选的人只移出本角色。
|
||||
|
||||
核心逻辑:其他业务角色保留。移出后没有任何角色时回到默认权限组。排除管理员。
|
||||
"""
|
||||
preview = preview_role_members(code, selected_ids)
|
||||
role = get_role_by_code(code)
|
||||
default_code = preview['default_role_code']
|
||||
skipped_admin = 0
|
||||
for row in preview['added']:
|
||||
user = db.session.get(User, row['id'])
|
||||
if not user or user_is_platform_admin(user):
|
||||
skipped_admin += 1
|
||||
continue
|
||||
user.role = role.code
|
||||
current = list_assigned_roles(user)
|
||||
replace_user_roles(user, roles_after_grant(current, role))
|
||||
sync_user_grants_from_role(user)
|
||||
for row in preview['removed']:
|
||||
user = db.session.get(User, row['id'])
|
||||
if not user or user_is_platform_admin(user):
|
||||
skipped_admin += 1
|
||||
continue
|
||||
user.role = default_code
|
||||
current = list_assigned_roles(user)
|
||||
replace_user_roles(user, roles_after_revoke(current, role))
|
||||
sync_user_grants_from_role(user)
|
||||
db.session.commit()
|
||||
return {
|
||||
@@ -614,13 +910,24 @@ def assert_role_assignable(code: str | None, *, allow_admin: bool) -> str:
|
||||
|
||||
def ensure_not_last_admin(user: User, new_role: str) -> None:
|
||||
"""禁止撤掉最后一名启用中的平台管理员。"""
|
||||
ensure_role_codes_keep_admin(user, [new_role])
|
||||
|
||||
|
||||
def ensure_role_codes_keep_admin(user: User, codes: list[str]) -> None:
|
||||
"""
|
||||
禁止把最后一名启用中的平台管理员改成不含管理组的角色集合。
|
||||
|
||||
Args:
|
||||
codes: 即将写入的角色 code。空列表视为卸下管理身份。
|
||||
"""
|
||||
if not user_is_platform_admin(user):
|
||||
return
|
||||
incoming = get_role_by_code(new_role)
|
||||
if incoming and incoming.is_platform_admin:
|
||||
return
|
||||
if not roles_configured() and new_role == PLATFORM_ADMIN_CODE:
|
||||
return
|
||||
for code in codes:
|
||||
incoming = get_role_by_code(code) if roles_configured() else None
|
||||
if incoming and incoming.is_platform_admin:
|
||||
return
|
||||
if not roles_configured() and str(code or '') == PLATFORM_ADMIN_CODE:
|
||||
return
|
||||
others = platform_admin_users_query().filter(User.id != user.id).first()
|
||||
if others is None:
|
||||
raise ValidationError('Cannot demote the last platform admin', code='ROLE.LAST_ADMIN')
|
||||
|
||||
@@ -343,11 +343,13 @@ def _register_headers_from_config() -> None:
|
||||
for name, cfg in get_all_schedule_sql_configs().items():
|
||||
if cfg.alias_order and cfg.header_labels:
|
||||
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import register_inventory_rpa_excel_headers
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import register_receipt_rpa_excel_headers
|
||||
from app.services.schedule.freight_rpa_onhand_finalize import register_inventory_rpa_excel_headers
|
||||
from app.services.schedule.freight_rpa_inbound_finalize import register_inbound_rpa_excel_headers
|
||||
from app.services.schedule.freight_rpa_outbound_finalize import register_outbound_rpa_excel_headers
|
||||
|
||||
register_inventory_rpa_excel_headers()
|
||||
register_receipt_rpa_excel_headers()
|
||||
register_inbound_rpa_excel_headers()
|
||||
register_outbound_rpa_excel_headers()
|
||||
|
||||
|
||||
def reload_config() -> dict[str, Any]:
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
"""收料原样归档三年到期对象清理。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
|
||||
"""仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。"""
|
||||
limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000))
|
||||
now = datetime.utcnow()
|
||||
rows = ShippingReceiptReportFile.query.filter(
|
||||
ShippingReceiptReportFile.archive_expires_at.is_not(None),
|
||||
ShippingReceiptReportFile.archive_expires_at <= now,
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
).order_by(ShippingReceiptReportFile.id).limit(limit).all()
|
||||
success = failed = 0
|
||||
errors: list[str] = []
|
||||
for report_file in rows:
|
||||
try:
|
||||
file_asset_storage.delete_object(report_file.storage_key)
|
||||
report_file.archive_deleted_at = now
|
||||
report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()}
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_archive_deleted', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
|
||||
unit_id=report_file.unit_run_id, result='success',
|
||||
before={'status': 'archived'}, after={'status': 'archive_deleted'},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
success += 1
|
||||
except Exception as exc:
|
||||
errors.append(f'{report_file.id}: {exc}')
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_archive_delete_attempted', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
|
||||
unit_id=report_file.unit_run_id, result='failure',
|
||||
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
failed += 1
|
||||
db.session.commit()
|
||||
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'receipt_retention', 'status': 'completed'}]
|
||||
Loaded 100 of 986 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user