Merge branch 'dev' into picture-feedback

This commit is contained in:
HTEWJ\26070045 committed 2026-10-29 11:04:59 +08:00
commit 34ad40778b
180 files changed
+13262 -5333

No files matched your search

+58 -10
View File
@@ -46,26 +46,56 @@ from app.path_utils import resolve_backend_relative_path
from app.services.file_assets.storage import file_asset_storage
def _released_line_indexes_for_task(order_task_id: int) -> set[int]:
"""按正式 OT 身份读取已审计短缺放行的行号集合(复核 Case 的 confirmed_task_id 恒为 OT id)。"""
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
rows = (
ShippingOrderReviewLineDecision.query
.join(
ShippingOrderReviewCase,
ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id,
)
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(order_task_id),
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
ShippingOrderReviewLineDecision.line_index.isnot(None),
)
.all()
)
return {int(row.line_index) for row in rows}
def _notice_source_code(task: ShippingNotice) -> str | None:
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。
匹配事实的 task_id 挂在正式 OT 上:传 Notice 时取 order_task_id,
传 OT 本身时取 id(整单 ODM 候选投影会在物化前以 OT 调用)。
已审计短缺放行行(release_onhand_shortage)的 match_result 恒为 not_found
(如预约键 0 命中的料号兜底行),其事实源码与 matched 行同票参与唯一性
裁决;只按 matched 过滤会让「整单放行」的单永远解析不到库存源
(回归 OT-20261027-4BD4CEFF)。
"""
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
if task_id is None:
return None
task_id = int(task_id)
released_line_indexes = _released_line_indexes_for_task(task_id)
codes = [
str(row[0]).strip().upper()
for row in db.session.query(ShippingNoticeLineOnhandMatch.source_code).filter(
for row in db.session.query(
ShippingNoticeLineOnhandMatch.source_code,
ShippingNoticeLineOnhandMatch.match_result,
ShippingNoticeLineOnhandMatch.line_index,
).filter(
ShippingNoticeLineOnhandMatch.task_id == task_id,
ShippingNoticeLineOnhandMatch.is_current.is_(True),
ShippingNoticeLineOnhandMatch.match_result == 'matched',
ShippingNoticeLineOnhandMatch.source_code.isnot(None),
).distinct().all()
if row[0]
).all()
if row[0] and (row[1] == 'matched' or (row[2] is not None and int(row[2]) in released_line_indexes))
]
codes = list(dict.fromkeys(codes))
return codes[0] if len(codes) == 1 else None
@@ -87,19 +117,31 @@ def _notice_chosen_odm(task: ShippingNotice) -> str | None:
def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
"""从 Notice 行级匹配读取本次导出的唯一库存文件。"""
"""从 Notice 行级匹配读取本次导出的唯一库存文件。
已审计短缺放行行(not_found 事实)的证据快照与 matched 行同票:整单放行时
库存证据文件仍必须落 Artifact 审计,否则证据流断链(回归 OT-20261027-4BD4CEFF)。
"""
task_id = getattr(task, 'order_task_id', None)
if task_id is None:
return None
task_id = int(task_id)
released_line_indexes = _released_line_indexes_for_task(task_id)
ids = [
int(row[0]) for row in db.session.query(ShippingNoticeLineOnhandMatch.onhand_snapshot_id).filter(
int(row[0]) for row in db.session.query(
ShippingNoticeLineOnhandMatch.onhand_snapshot_id,
ShippingNoticeLineOnhandMatch.match_result,
ShippingNoticeLineOnhandMatch.line_index,
).filter(
ShippingNoticeLineOnhandMatch.task_id == task_id,
ShippingNoticeLineOnhandMatch.is_current.is_(True),
ShippingNoticeLineOnhandMatch.match_result == 'matched',
ShippingNoticeLineOnhandMatch.onhand_snapshot_id.isnot(None),
).distinct().all()
).all()
if row[0] is not None and (
row[1] == 'matched' or (row[2] is not None and int(row[2]) in released_line_indexes)
)
]
ids = list(dict.fromkeys(ids))
return ids[0] if len(ids) == 1 else None
@@ -799,8 +841,14 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
# [STEP 1] 短缺放行的人工字段仅从该行的活动决定审计快照读取,
# 只能补模板行级库存字段,不能污染快照或任务级库存输入。
# [身份口径] 复核 Case.confirmed_task_id 恒为正式 OT id;本函数入参可能是
# 换绑后的 Notice,必须经 order_task_id 回链 OT,否则放行/结案决定恒查空,
# 放行行进不了导出资格、结案行漏剔除(与 _facts_order_task 同款键位纪律)。
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
order_task_id_for_decisions = int(
getattr(source_notice, 'order_task_id', None) or source_notice.id
)
release_overrides_by_source_line: dict[int, dict[str, Any]] = {}
released_source_line_indexes: set[int] = set()
if source_notice.id is not None:
@@ -808,7 +856,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
ShippingOrderReviewLineDecision.query
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
ShippingOrderReviewCase.confirmed_task_id == order_task_id_for_decisions,
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
)
@@ -835,7 +883,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
ShippingOrderReviewLineDecision.query
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
ShippingOrderReviewCase.confirmed_task_id == order_task_id_for_decisions,
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
)
@@ -2520,7 +2520,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
# 三态结果:success / failed / unknown。result 显式给定则优先,否则由 success 布尔推导。
raw_result = str(payload.get('result') or '').strip().lower()
if raw_result in {'success', 'failed', 'unknown'}:
if raw_result in {'success', 'failed', 'unknown', 'allocating'}:
result_status = raw_result
else:
result_status = 'success' if success else 'failed'
@@ -2614,6 +2614,25 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
position=POSITION_UPLOADED if has_verified_upload_success(task) else None,
)
if completed.status == 'running' and completed.error_code == 'CRANE_ALLOCATING':
set_task_step_progress(
task,
stage="freight_uploading",
step_title="上传货代",
status="running",
message='货代已接收文件,正在分配,稍后自动回查一次',
progress_percent=90,
detail='Processing + Allocating the Shipping Order',
)
log_task_event(task, 'upload_rpa_allocating', {'artifact_id': completed.artifact_id, 'attempt_id': completed.id})
db.session.commit()
return tool_response(
status='running',
task=task,
message='货代已接收文件,正在分配',
data=serialize_task_for_tool(task),
)
if completed.status == 'unknown':
# unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。
set_task_step_progress(
@@ -414,7 +414,11 @@ def _shortage_release_required_fields(
source_code=resolved_source_code, enabled=True,
).first()
template = getattr(source, 'excel_template', None) if source is not None else None
profile = getattr(source, 'parsing_profile', None) if source is not None else None
# [s18 改名] 解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系
# (与 freight_rpa.parsing_profile.require_source_profile 同口径);
# 站点行 getattr 读法会静默得 None,曾致短缺放行(自动+人工)全部失败。
release_config = getattr(source, 'onhand_report_config', None) if source is not None else None
profile = release_config.parsing_profile if release_config is not None else None
if template is None or profile is None:
raise ConflictError(
'Inventory source export template is unavailable',
@@ -1951,16 +1951,19 @@ def list_freight_notice_groups_for_task(
.first()
)
from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status
projected_upload_status = project_notice_upload_status(notice)
hide_allocating_error = projected_upload_status == 'allocating'
items.append({
'business_no': business_no,
'po_number': po_number,
# Notice 面契约:成功统一为 uploaded,禁止下发 Attempt 原词 succeeded。
'upload_status': project_notice_upload_status(notice),
'upload_status': projected_upload_status,
'upload_mode': upload_mode,
'upload_attempt': upload_attempt,
'upload_error_code': getattr(latest_attempt, 'error_code', None),
'upload_error_code': None if hide_allocating_error else getattr(latest_attempt, 'error_code', None),
# 逐单失败原因:优先取最近一次上传的错误正文,回退到任务级 error_message。
'upload_error_message': (getattr(latest_attempt, 'error_message', None) or '')[:500] or None,
# 分配中的内部错误码不是失败原因,不能把这一行显示成需人工。
'upload_error_message': None if hide_allocating_error else ((getattr(latest_attempt, 'error_message', None) or '')[:500] or None),
'export_file_name': getattr(artifact, 'file_name', None),
'available_actions': available_actions,
'lines': _notice_line_summary_for_task(notice),
@@ -75,6 +75,14 @@ def start_rpa_attempt(task: ShippingNotice, *, artifact_id: int | None = None, i
return existing
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first():
raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')
allocating = ShippingUploadAttempt.query.filter_by(
artifact_id=artifact.id, status='running', error_code='CRANE_ALLOCATING',
).first()
if allocating is not None:
raise ConflictError(
'Crane has accepted the file and is still allocating; refresh status instead of uploading again',
code='SHIPPING.UPLOAD_CRANE_ALLOCATING',
)
# 业务决定:结果未知(timed_out/unknown)不再阻断重新下发 RPA。该状态表示“无法判断上传是否成功/失败”,
# 为避免用户卡死、无法继续尝试,允许再次触发;若上次实际上传成功,重复触发可能产生重复单,
# 需由用户在 CRANE 侧核查(错误文案已提示)。幂等 key 去重仍保留。
@@ -123,7 +131,7 @@ def project_notice_upload_status(task: ShippingNotice | Any) -> str | None:
task: 正式 Notice,或可解析到 Notice 的 OT。
Returns:
uploaded | uploading | pending | failed | unknown | 其它透传小写 | None。
uploaded | allocating | uploading | pending | failed | unknown | 其它透传小写 | None。
"""
attempt = latest_upload_attempt(task)
if attempt is not None:
@@ -131,6 +139,8 @@ def project_notice_upload_status(task: ShippingNotice | Any) -> str | None:
# Attempt 层当前写入成功态只有 succeeded(callback result=success 已在 complete_attempt 内翻译)。
if status == 'succeeded':
return 'uploaded'
if status == 'running' and str(getattr(attempt, 'error_code', None) or '') == 'CRANE_ALLOCATING':
return 'allocating'
if status in _UPLOAD_IN_FLIGHT_TOKENS:
return 'uploading'
if status == 'pending':
@@ -221,9 +231,9 @@ def _normalize_callback_result(result: str | None, success: bool) -> str:
"""
if result is not None:
normalized = str(result or '').strip().lower()
if normalized not in {'success', 'failed', 'unknown'}:
if normalized not in {'success', 'failed', 'unknown', 'allocating'}:
raise ValidationError(
'result must be success, failed or unknown',
'result must be success, failed, unknown or allocating',
code='SHIPPING.UPLOAD_RESULT_INVALID',
)
return normalized
@@ -243,7 +253,7 @@ def complete_attempt(
callback_id: 回调幂等键(唯一)。
freight_ref_no: 成功时货代回执号。
error_message: 失败/未知时的脱敏错误信息。
result: 三态结果 success / failed / unknown;三态与布尔推导见 _normalize_callback_result。
result: success / failed / unknown / allocating。allocating 表示 Crane 已接收且仍在分配。
Returns:
ShippingUploadAttempt: 已更新状态的 Attob。
@@ -266,10 +276,16 @@ def complete_attempt(
if artifact.status in {'superseded', 'invalidated'}:
raise ConflictError('Superseded artifact cannot accept callback', code='SHIPPING.ARTIFACT_ALREADY_SUPERSEDED')
if attempt.status == 'succeeded' or artifact.status == 'uploaded':
if str(result or '').strip().lower() == 'allocating':
return attempt
raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE')
if attempt.status not in {'pending', 'running', 'timed_out', 'unknown'}:
raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE')
result_status = _normalize_callback_result(result, success)
if result_status == 'allocating':
from app.services.freight_rpa.upload.crane_recheck import remember_crane_allocating
return remember_crane_allocating(attempt, artifact, callback)
attempt.callback_id = callback
attempt.finished_at = datetime.utcnow()
task = db.session.get(ShippingNotice, artifact.task_id)
@@ -1,11 +1,10 @@
"""
services/shipping_notice/upload_config_validation.py
用途:对连接级“发货 Excel 自动上传”配置做后端严格白名单校验,产出受限 JSON。
依赖:app.core.errors.ValidationError;仅标准库,不引入第三方。
逻辑:配置由管理端表单编辑,但后端只接受本模块允许的字段、枚举与安全边界;
禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作落库。
upload_config 是“这次上传到底用了什么”的快照来源,不做版本管理(见技术文档)。
用途:系统连接只保存「是否启用发货 Excel 自动上传」。
依赖:app.core.errors.ValidationError;标准库 hashlib/json。
逻辑:页面路径、选择器和成功文案由连接器代码固定,管理端提交的这些字段一律丢弃。
upload_config 快照只保留 enabled,供本次上传审计。
"""
from __future__ import annotations
@@ -16,192 +15,34 @@ from typing import Any
from app.core.errors import ValidationError
# 连接类型与各平台已审核域名(主机名白名单,后缀匹配以覆盖同域子站)。
ALLOWED_CONNECTOR_TYPES = frozenset({'dbs', 'crane'})
ALLOWED_PLATFORM_DOMAINS: dict[str, tuple[str, ...]] = {
'dbs': ('dbschenker.com',),
'crane': ('craneww.com',),
}
ALLOWED_SUBMIT_MODES = frozenset({'auto_after_file', 'click_submit'})
ALLOWED_RESULT_MODES = frozenset({'page_notice', 'history_record'})
# 字段白名单:禁止把额外键(模板、Cookie、脚本)混入配置。
ALLOWED_KEYS = frozenset({
'enabled', 'entry_url', 'file_input_selector',
'submit_mode', 'submit_selector',
'result_mode', 'result_selector', 'success_texts', 'timeout_seconds',
})
MAX_ENTRY_URL_LENGTH = 500
MAX_SELECTOR_LENGTH = 200
MAX_SUCCESS_TEXTS = 10
MAX_SUCCESS_TEXT_LENGTH = 200
MIN_TIMEOUT_SECONDS = 1
MAX_TIMEOUT_SECONDS = 600
DEFAULT_TIMEOUT_SECONDS = 120
# 复用的字符黑名单:任何脚本/表达式/注入语义都拒绝。
_BLOCKED_SELECTOR_MARKERS = (
'javascript:', '<script', 'expression(', 'onclick=', 'onload=', 'onerror=',
'onmouseover=', 'onmouseout=', 'onfocus=', 'onblur=', 'onchange=', 'oninput=',
)
_BLOCKED_SELECTOR_CHARS = ('(', ')', '{', '}', ';', '<', '>', '`', '\\', '\n', '\r')
def _reject(message: str, *, field: str) -> None:
raise ValidationError(message, code='SHIPPING.UPLOAD_CONFIG_INVALID', details={'field': field})
def _normalize_text(value: Any) -> str:
return str(value or '').strip()
def _validate_entry_url(connector_type: str, value: Any, *, required: bool = True) -> str | None:
"""校验上传入口为 HTTPS 且主机名属于已审核平台域名。"""
url = _normalize_text(value)
if not url:
if required:
_reject('entry_url is required', field='entry_url')
return None
if len(url) > MAX_ENTRY_URL_LENGTH:
_reject('entry_url is too long', field='entry_url')
if not url.lower().startswith('https://'):
_reject('entry_url must be HTTPS', field='entry_url')
# 简单主机名解析:仅定位 host:port 部分,禁止 userinfo/query 进入主机判断。
scheme_rest = url[8:]
authority = scheme_rest.split('/', 1)[0].split('?', 1)[0].split('#', 1)[0]
host = authority.split('@')[-1].split(':')[0].strip().lower()
if not host:
_reject('entry_url host is invalid', field='entry_url')
allowed = ALLOWED_PLATFORM_DOMAINS.get(connector_type, ())
if not any(host == domain or host.endswith('.' + domain) for domain in allowed):
_reject(
f'entry_url host not allowed for {connector_type}',
field='entry_url',
)
return url
def _validate_css_selector(value: Any, *, field: str, required: bool) -> str | None:
"""校验普通 CSS selector:限制长度、拒绝脚本及表达式语义。"""
selector = _normalize_text(value)
if not selector:
if required:
_reject(f'{field} is required', field=field)
return None
if len(selector) > MAX_SELECTOR_LENGTH:
_reject(f'{field} is too long', field=field)
lowered = selector.lower()
for marker in _BLOCKED_SELECTOR_MARKERS:
if marker in lowered:
_reject(f'{field} contains script semantics', field=field)
for char in _BLOCKED_SELECTOR_CHARS:
if char in selector:
_reject(f'{field} contains an invalid character', field=field)
return selector
def _validate_success_texts(value: Any) -> list[str]:
if value in (None, ''):
return []
if not isinstance(value, list):
_reject('success_texts must be a list', field='success_texts')
if len(value) > MAX_SUCCESS_TEXTS:
_reject('success_texts is too long', field='success_texts')
result: list[str] = []
for item in value:
text = _normalize_text(item)
if not text or len(text) > MAX_SUCCESS_TEXT_LENGTH:
_reject('success_texts contains an invalid item', field='success_texts')
if text not in result:
result.append(text)
return result
def validate_upload_config(connector_type: str, raw: Any) -> dict[str, Any] | None:
"""白名单校验连接级上传配置,返回规范化 JSON;raw 为空/None 表示未配置(返回 None)。
"""只保留 enabled。页面参数即使随旧表单提交也不落库。
Args:
connector_type: 连接类型,仅允许 dbs / crane。
raw: 管理端提交的原始上传配置对象。
raw: 管理端提交的上传配置。None 或空串表示未配置。
Returns:
dict | None: 规范化受限 JSON;未配置时返回 None。
dict | None: ``{"enabled": bool}``;未配置时返回 None。
Raises:
ValidationError: 含未知字段/非法枚举/不安全 selector/非 HTTPS 或非法域名/
enabled=true 但缺少上传或结果判定所需字段。
ValidationError: 连接类型非法或上传配置不是对象。
"""
normalized_connector = _normalize_text(connector_type).lower()
normalized_connector = str(connector_type or '').strip().lower()
if normalized_connector not in ALLOWED_CONNECTOR_TYPES:
_reject('connector_type must be dbs or crane', field='connector_type')
if raw in (None, ''):
return None
if not isinstance(raw, dict):
_reject('upload_config must be an object', field='upload_config_json')
unknown = set(raw) - ALLOWED_KEYS
if unknown:
_reject(f'upload_config contains unsupported fields: {sorted(unknown)}', field='upload_config_json')
enabled = raw.get('enabled') is True
config: dict[str, Any] = {
'enabled': enabled,
'entry_url': _validate_entry_url(normalized_connector, raw.get('entry_url'), required=enabled),
'file_input_selector': _validate_css_selector(
raw.get('file_input_selector'), field='file_input_selector', required=enabled,
),
'submit_mode': _normalize_text(raw.get('submit_mode')),
'submit_selector': _validate_css_selector(
raw.get('submit_selector'), field='submit_selector', required=False,
),
'result_mode': _normalize_text(raw.get('result_mode')),
'result_selector': _validate_css_selector(
raw.get('result_selector'), field='result_selector', required=False,
),
'success_texts': _validate_success_texts(raw.get('success_texts')),
'timeout_seconds': raw.get('timeout_seconds', DEFAULT_TIMEOUT_SECONDS),
}
if config['submit_mode'] not in ALLOWED_SUBMIT_MODES:
_reject('submit_mode must be auto_after_file or click_submit', field='submit_mode')
if config['result_mode'] not in ALLOWED_RESULT_MODES:
_reject('result_mode must be page_notice or history_record', field='result_mode')
if config['submit_mode'] == 'auto_after_file':
# auto_after_file 由页面在选文件后自动提交,不应同时配置提交按钮选择器。
config['submit_selector'] = None
try:
timeout = int(config['timeout_seconds'])
except (TypeError, ValueError):
_reject('timeout_seconds must be an integer', field='timeout_seconds')
if timeout < MIN_TIMEOUT_SECONDS or timeout > MAX_TIMEOUT_SECONDS:
_reject(
f'timeout_seconds must be within [{MIN_TIMEOUT_SECONDS}, {MAX_TIMEOUT_SECONDS}]',
field='timeout_seconds',
)
config['timeout_seconds'] = timeout
if enabled:
# 完成一次上传所需的公共字段由上述必填校验覆盖;此处补齐连接差异。
if not config['file_input_selector']:
_reject('enabled upload requires file_input_selector', field='file_input_selector')
if config['submit_mode'] == 'click_submit' and not config['submit_selector']:
_reject('enabled click_submit upload requires submit_selector', field='submit_selector')
# 结果判定:dbs(DSV) 使用代码内置的受控成功流(History 绿状态/页面证据),
# 不强制 admin 填写结果字段;crane 必须由 admin 补全提交/结果判定字段后才可启用。
if normalized_connector == 'crane':
if config['result_mode'] == 'page_notice':
if not config['result_selector'] or not config['success_texts']:
_reject(
'enabled crane page_notice upload requires result_selector and success_texts',
field='result_selector',
)
elif config['result_mode'] == 'history_record' and not config['result_selector']:
_reject('enabled crane history_record upload requires result_selector', field='result_selector')
# 未启用时仍保存规范化的受限 JSON,方便 admin 预填后续补全。
return config
return {'enabled': raw.get('enabled') is True}
def compute_upload_config_hash(config: dict[str, Any] | None) -> str | None: