feat(shipping-notice): 人工重取库存前置候选刷新并放开行级库存源下拉

- 人工重试库存准备前置幂等重判:任务级整单重路由、行级定向重评目标行,复用裁决与冻结链路,零新动作码零契约变更
- 新版候选集 supersede 时内置失效旧库存事实,导出归档与查询服务同步适配
- 行级「库存源」下拉抽纯函数合并选项:歧义行候选置顶 + 全部已启用源去重兜底,任一已启用源可人工指定
- 库存源门禁归一 Notice→OT 身份解析;任务中心抽屉与表格接入行级重取入口
- 同步四语言文案、技术文档与实施计划
This commit is contained in:
hugo committed 2026-10-13 15:04:40 +08:00
1 parent e38e5a63fe
commit ea94fb28db
35 files changed
+2675 -83

No files matched your search

+106 -11
View File
@@ -186,6 +186,7 @@ def workspace_shipping_tasks():
lifecycle_status=lifecycle_status,
page=page,
page_size=page_size,
is_admin=bool(user.is_platform_admin()),
))
@@ -394,14 +395,38 @@ def workspace_batch_restore_shipping_tasks():
@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST'])
def workspace_shipping_export_archive():
"""按显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。"""
"""按显式任务号下载当前用户可下载(创建者或管理员)的 ready 发货 Excel ZIP。"""
user = _require_user()
data = request.get_json(silent=True) or {}
task_nos = data.get('task_nos')
if task_nos is not None and not isinstance(task_nos, list):
raise ValidationError('task_nos must be a list', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
from app.services.shipping_notice.export_archive import build_export_archive
stream, filename, _manifest = build_export_archive(user_id=user.id, task_nos=task_nos or [])
from app.services.shipping_notice.fulfillment_audit import record_access_audit
stream, filename, manifest = build_export_archive(
user_id=user.id,
task_nos=task_nos or [],
is_admin=bool(user.is_platform_admin()),
)
# 与 business_no 批量导出同一审计口径:按票落 record_access_audit(自行提交)。
for entry in manifest.get('entries') or []:
aggregate_no = str(entry.get('business_no') or '').strip()
task_no = str(entry.get('task_no') or '').strip()
if not aggregate_no and not task_no:
continue
record_access_audit(
action='download_task_excel',
aggregate_type='shipping_task',
aggregate_id=task_no or aggregate_no,
actor_id=user.id,
task_no=task_no or None,
reason_code='excel_downloaded',
metadata={
'export': 'batch_zip',
'batch_status': str(entry.get('status') or ''),
},
)
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
response.call_on_close(stream.close)
return response
@@ -455,7 +480,11 @@ def workspace_confirm_shipping_customer(task_no: str):
details={'field': 'customer_id'},
) from exc
updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id)
return _ok(serialize_task_detail(updated))
return _ok(serialize_task_detail(
updated,
viewer_user_id=user.id,
is_admin=bool(user.is_platform_admin()),
))
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
@@ -499,7 +528,7 @@ def workspace_create_shipping_task_from_notice():
db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
orchestrator_started = start_task_orchestrator(task_id)
return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task, viewer_user_id=user.id) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
def workspace_replace_shipping_task_notice(task_no: str):
@@ -657,7 +686,12 @@ def workspace_shipping_task_ui_state(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
return _ok(build_task_ui_state(task, include_stage_context=True))
return _ok(build_task_ui_state(
task,
include_stage_context=True,
viewer_user_id=user.id,
viewer_is_admin=bool(user.is_platform_admin()),
))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
def workspace_shipping_task_chat_actions(task_no: str):
@@ -1032,6 +1066,38 @@ def _load_business_notice_for_user(*, business_no: str, user_id: int) -> Shippin
return task
def _load_business_notice_readable_for_user(
*,
business_no: str,
user_id: int,
is_admin: bool,
) -> ShippingNotice:
"""
按精确发货通知单号加载当前用户可下载的 Notice(创建者或管理员)。
核心逻辑:下载是只读动作,授权走 can_download_task_export 统一谓词口径
(可下载=可见),不经过写路径的履约归属断言;管理员可下载其可见的正式
Notice,且每次下载均由端点写入 record_access_audit。
Args:
business_no: 对外发货通知单号。
user_id: 当前服务端会话用户主键。
is_admin: 是否平台管理员。
Returns:
可下载的 ShippingNotice。
Raises:
NotFoundError: 编号不存在、非正式 Notice 或用户不可见。
"""
normalized = str(business_no or '').strip().upper()
from app.services.shipping_notice.query_service import get_task_visible_to_user
task = get_task_visible_to_user(normalized, user_id, is_admin=is_admin)
if not isinstance(task, ShippingNotice) or str(task.business_no or '').strip().upper() != normalized:
raise NotFoundError('Shipping notice not found')
return task
def _start_notice_rpa_upload(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]:
"""按 business_no 发起单张通知的货代 RPA 上传或重试。"""
task = _load_business_notice_for_user(business_no=business_no, user_id=user_id)
@@ -1138,9 +1204,13 @@ def workspace_batch_start_shipping_notice_rpa_upload():
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/export', methods=['GET'])
def workspace_shipping_notice_export(business_no: str):
"""按发货通知单号下载该通知唯一的正式 Excel,并保留下载审计。"""
"""按发货通知单号下载该通知唯一的正式 Excel(创建者或管理员),并保留下载审计。"""
user = _require_user()
task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id))
task = _load_business_notice_readable_for_user(
business_no=business_no,
user_id=int(user.id),
is_admin=bool(user.is_platform_admin()),
)
err_msg = task_export_error_message(task)
if err_msg:
raise NotFoundError(err_msg)
@@ -1162,7 +1232,7 @@ def workspace_shipping_notice_export(business_no: str):
@workspace_shipping_notice_bp.route('/shipping-notices/batch/export', methods=['POST'])
def workspace_shipping_notice_export_archive():
"""按多个 business_no 下载各自唯一 Excel 的 ZIP;任一越权或缺文件均整体拒绝。"""
"""按多个 business_no 下载各自唯一 Excel 的 ZIP(创建者或管理员);任一越权或缺文件均整体拒绝。"""
user = _require_user()
data = request.get_json(silent=True) or {}
raw_values = data.get('business_nos')
@@ -1174,8 +1244,32 @@ def workspace_shipping_notice_export_archive():
if not business_nos or len(business_nos) > 100:
raise ValidationError('business_nos must contain 1 to 100 business numbers')
from app.services.shipping_notice.export_archive import build_export_archive
from app.services.shipping_notice.fulfillment_audit import record_access_audit
stream, filename, _manifest = build_export_archive(user_id=int(user.id), business_nos=business_nos)
stream, filename, manifest = build_export_archive(
user_id=int(user.id),
business_nos=business_nos,
is_admin=bool(user.is_platform_admin()),
)
# 批量导出与单票下载同一审计口径:按票落 record_access_audit(自行提交),
# manifest.business_no 是 aggregate 事实源;missing/checksum 票据也留痕。
for entry in manifest.get('entries') or []:
aggregate_no = str(entry.get('business_no') or '').strip()
task_no = str(entry.get('task_no') or '').strip()
if not aggregate_no and not task_no:
continue
record_access_audit(
action='download_notice_excel',
aggregate_type='shipping_notice',
aggregate_id=aggregate_no or task_no,
actor_id=user.id,
task_no=task_no or None,
reason_code='excel_downloaded',
metadata={
'export': 'batch_zip',
'batch_status': str(entry.get('status') or ''),
},
)
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
response.call_on_close(stream.close)
return response
@@ -1183,9 +1277,10 @@ def workspace_shipping_notice_export_archive():
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
def workspace_shipping_task_export(task_no: str):
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
"""下载当前用户可下载任务的出货 Excel(创建者或管理员);写入统一访问审计。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
from app.services.shipping_notice.query_service import get_task_visible_to_user
task = get_task_visible_to_user(task_no, user.id, is_admin=bool(user.is_platform_admin()))
task = _require_formal_notice(task)
err_msg = task_export_error_message(task)
if err_msg:
@@ -169,7 +169,7 @@ class ShippingQueryShortageDetailsAction:
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
yield TurnEvent(event="step.started", data={"step_id": "query_shortage_details", "label": "查询缺口明细..."})
detail = serialize_task_detail(task)
detail = serialize_task_detail(task, viewer_user_id=int(ctx.user_id))
content = format_shortage_details_message(detail if isinstance(detail, dict) else {})
yield from stream_text_events(content, payload={"task_no": task.task_no})
yield TurnEvent(event="step.completed", data={"step_id": "query_shortage_details"})
@@ -18,7 +18,10 @@ from zipfile import ZIP_DEFLATED, ZipFile
from app.core.errors import NotFoundError, ValidationError
from app.models import ShippingExportArtifact, ShippingNotice
from app.services.shipping_notice.query_service import get_task_for_user, resolve_task_export_download
from app.services.shipping_notice.query_service import (
get_task_visible_to_user,
resolve_task_export_download,
)
MAX_ARCHIVE_TASKS = 100
@@ -28,15 +31,17 @@ def _select_tasks(
user_id: int,
task_refs: list[str] | None,
selection_name: str,
is_admin: bool = False,
require_business_no: bool = False,
) -> tuple[list[ShippingNotice], str]:
"""按显式 task_no 或 business_no 选择当前用户通知,禁止部分越权成功。"""
"""按显式 task_no 或 business_no 选择当前用户可下载通知,禁止部分越权成功。"""
normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_refs or []) if str(item or '').strip()))
if not normalized_tasks:
raise ValidationError(f'{selection_name} is required', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
tasks = []
for task_no in normalized_tasks:
task = get_task_for_user(task_no, user_id)
# 下载授权与单票导出同一谓词:创建者或管理员(可下载=可见)。
task = get_task_visible_to_user(task_no, user_id, is_admin=is_admin)
# 导出归档是正式 Notice 边界;OT 尚未生成正式单据时不可进入 Artifact 查询。
if not isinstance(task, ShippingNotice) or (
require_business_no and str(getattr(task, 'business_no', '') or '').strip().upper() != task_no.upper()
@@ -90,10 +95,17 @@ def build_export_archive(
user_id: int,
task_nos: list[str] | None = None,
business_nos: list[str] | None = None,
is_admin: bool = False,
) -> tuple[BinaryIO, str, dict]:
"""
生成 ZIP 和 manifest;缺失/损坏票据保留在 manifest,但不阻止其余有效文件下载。
Args:
user_id: 当前下载用户;与 ``is_admin`` 共同构成下载授权谓词口径。
task_nos: 按 SN 技术号选择(与 business_nos 二选一)。
business_nos: 按发货通知单号选择(与 task_nos 二选一)。
is_admin: 是否平台管理员;管理员可打包其可见的正式 Notice。
Returns:
(定位到开头的 ZIP 字节流, 下载文件名, manifest 字典)。
"""
@@ -105,6 +117,7 @@ def build_export_archive(
user_id=user_id,
task_refs=selection_values,
selection_name=selection_name,
is_admin=is_admin,
require_business_no=business_nos is not None,
)
artifacts = _ready_artifacts(tasks)
@@ -115,11 +128,16 @@ def build_export_archive(
included = 0
with ZipFile(stream, mode='w', compression=ZIP_DEFLATED) as archive:
for task in tasks:
# business_no 供端点按票写入访问审计(与单票下载同一 aggregate 口径)。
entry_base = {
'task_no': task.task_no,
'business_no': str(getattr(task, 'business_no', '') or ''),
}
task_artifacts = artifacts.get(int(task.id), []) if task.id is not None else []
if not task_artifacts:
entries.append({'task_no': task.task_no, 'status': 'missing_artifact', 'artifact_no': None, 'file_name': None})
entries.append({**entry_base, 'status': 'missing_artifact', 'artifact_no': None, 'file_name': None})
for artifact in task_artifacts:
entry = {'task_no': task.task_no, 'status': 'missing_file', 'artifact_no': artifact.artifact_no, 'file_name': None}
entry = {**entry_base, 'status': 'missing_file', 'artifact_no': artifact.artifact_no, 'file_name': None}
entry['artifact_no'] = artifact.artifact_no
path = Path(artifact.file_path)
if not path.is_file():
@@ -716,6 +716,255 @@ def freeze_manual_line_source_selection(
return result, all(bool(item['candidate_inventory_source_codes']) for item in line_projections)
def active_candidate_set_is_manually_pinned(
task: ShippingNotice,
*,
session: Session | None = None,
) -> bool:
"""
判断活动候选集是否含人工选源(「人工指定即定论」的统一判定入口)。
Args:
task: 当前 ShippingOrderTask。
session: 可选 Session。
Returns:
bool: True 表示人工已裁决候选源,自动重路由必须跳过。
"""
sess = session or db.session
active_set = (
sess.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
if getattr(task, 'active_inventory_candidate_set_id', None) is not None
else None
)
if active_set is None:
return False
if getattr(active_set, 'frozen_by_id', None) is not None:
return True
return any(
str(getattr(source, 'candidate_origin', '') or '').strip().lower() == 'manual_override'
for source in (active_set.sources or [])
)
def refresh_candidates_from_current_routing(
task: ShippingNotice,
*,
execution_id: int | None = None,
session: Session | None = None,
) -> bool:
"""
任务级:按当前库存源主数据与路由规则重跑裁决并重冻结候选集;返回是否产生新版本候选集。
【AI 触发时机】:仅「重新获取库存(RPA)」的任务级人工重取路径作为前置步骤调用;
禁止在轮询(poll)、自动首投路径调用——刷新是显式人工动作的伴随效果,不是隐式自动行为。
核心逻辑:
[守卫 1] 仅多候选未定源可刷新(task_frozen_inventory_source_codes > 1);源已定单
不得自动改源,换源走 override_line_inventory_source 行级覆写。
[守卫 2] 活动候选集含人工选源(frozen_by_id / candidate_origin='manual_override')
时跳过:人工指定即定论,禁止重路由洗掉人工裁决。
[STEP 1] 记录当前活动 set_id。
[STEP 2] adjudicate_and_apply_inventory_source(execution_id=...) 重裁决 + 幂等冻结
(freeze 服务 input_fingerprint 未变则复用旧集,零副作用;重裁决为 unresolved 时
apply 不落任何事实,活动集保持不变,同样视为无变化)。
[STEP 3] 活动集变化时冻结服务已内置旧版本下游失效(_invalidate_task_candidate_outputs:
匹配事实/准备 Attempt/RPA Attempt 等),此处仅补写任务事件供审计追溯。
Args:
task: 当前 ShippingOrderTask(须已冻结候选集)。
execution_id: 当前 ProcessExecution id;透传冻结服务,避免重冻结撤销活动执行链。
session: 可选 Session。
Returns:
bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。
"""
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
sess = session or db.session
if len(task_frozen_inventory_source_codes(task)) <= 1:
return False
if active_candidate_set_is_manually_pinned(task, session=sess):
return False
before = get_active_candidate_set(task)
before_set_id = int(before.id) if before is not None else None
adjudicate_and_apply_inventory_source(task, execution_id=execution_id)
sess.flush()
after = get_active_candidate_set(task)
after_set_id = int(after.id) if after is not None else None
if before_set_id == after_set_id:
return False
from app.services.shipping_notice.tool_common import log_task_event
log_task_event(
task,
'inventory_candidates_refreshed',
{
'scope': 'task',
'previous_set_id': before_set_id,
'new_set_id': after_set_id,
'source_codes': task_frozen_inventory_source_codes(task),
},
source='system',
)
return True
def refresh_line_candidates_from_current_routing(
task: ShippingNotice,
*,
line_no: int,
execution_id: int | None = None,
session: Session | None = None,
) -> bool:
"""
行级:按当前库存源主数据与路由规则重评单个订单行的候选源并重冻结候选集;返回是否产生新版本。
【AI 触发时机】:仅「重新获取库存(RPA)」的行级重抓(retry_inventory_preparation 携带
line_scope)作为前置步骤调用;禁止在轮询/自动首投路径调用。
核心逻辑:
[守卫 1] 目标行当前候选 >1(未定源)才重评;单源行已定,改源走行级覆写。
[守卫 2] 活动候选集含人工选源时跳过(与任务级刷新同一条红线:人工指定即定论)。
[STEP 1] 行级规则重评:_task_routing_lines(task) 按 line_no-1 取目标行(越界返回 False),
evaluate_inventory_source_rules(task=task, line=...) 得到规则原始候选,经
get_database_inventory_source 过滤停用源(对齐 _result_to_adjudication 语义);
仅接受 resolved/ambiguous 结论,unresolved 保持旧行为不刷新。
[STEP 2] 以活动集全量行为骨架构建 line_projections:目标行替换为新候选,其余行原样继承
(保留既有行候选,不做整单重路由)。
[STEP 3] freeze_candidates_for_task(candidates_frozen 裁决)幂等冻结;created_new 即新版
候选集(supersede 旧集时内置下游失效),写行级刷新任务事件并返回 True。
Args:
task: 当前 ShippingOrderTask(须已冻结候选集)。
line_no: 目标订单项次(1 基,对应冻结快照 line_no)。
execution_id: 当前 ProcessExecution id;透传冻结服务,避免重冻结撤销活动执行链。
session: 可选 Session。
Returns:
bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。
"""
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
)
from app.services.shipping_notice.inventory_source_rules import (
_task_routing_lines,
compute_routing_fingerprint,
evaluate_inventory_source_rules,
extract_routing_context,
)
sess = session or db.session
active_set = get_active_candidate_set(task)
if active_set is None:
return False
if active_candidate_set_is_manually_pinned(task, session=sess):
return False
existing_lines = {
int(row.line_no): row
for row in (active_set.lines or [])
if getattr(row, 'line_no', None) is not None
}
target = existing_lines.get(int(line_no))
if target is None:
return False
current_codes = [
str(code).strip().upper()
for code in (target.source_codes_json or [])
if str(code or '').strip()
]
if len(current_codes) <= 1:
return False
routing_lines = _task_routing_lines(task)
position = int(line_no) - 1
if position < 0 or position >= len(routing_lines):
return False
line_result = evaluate_inventory_source_rules(task=task, line=routing_lines[position])
line_status = str(getattr(line_result, 'status', '') or '').strip().lower()
if line_status not in {'resolved', 'ambiguous'}:
return False
new_codes: list[str] = []
for raw in (getattr(line_result, 'source_codes', None) or []):
code = str(raw or '').strip().upper()
if code and code not in new_codes and get_database_inventory_source(code) is not None:
new_codes.append(code)
if not new_codes:
return False
line_projections: list[dict[str, Any]] = []
union_codes: list[str] = []
for row_line_no in sorted(existing_lines):
row = existing_lines[row_line_no]
codes = (
new_codes
if row_line_no == int(line_no)
else [
str(code).strip().upper()
for code in (row.source_codes_json or [])
if str(code or '').strip()
]
)
for code in codes:
if code not in union_codes:
union_codes.append(code)
line_projections.append({
'line_no': row_line_no,
'source_line_no': str(getattr(row, 'source_line_no', '') or '') or None,
'part_number': getattr(row, 'part_number', None),
'reservation_id': getattr(row, 'reservation_id', None),
'candidate_inventory_source_codes': codes,
})
if not union_codes:
return False
context = extract_routing_context(task)
adjudication = InventorySourceAdjudication(
status='candidates_frozen',
method='line_refresh_reroute',
source_code=None,
connector_type=None,
warehouse_id=None,
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(context),
candidates=[{'source_code': code} for code in union_codes],
evidence=[{
'line_candidates_refresh': {
'line_no': int(line_no),
'previous_codes': current_codes,
'new_codes': new_codes,
},
}],
reason='line_refresh_reroute',
)
freeze_result = freeze_candidates_for_task(
task,
adjudication=adjudication,
line_projections=line_projections,
execution_id=execution_id,
session=sess,
)
if not freeze_result.created_new:
return False
from app.services.shipping_notice.tool_common import log_task_event
log_task_event(
task,
'inventory_candidates_refreshed',
{
'scope': 'line',
'line_no': int(line_no),
'previous_codes': current_codes,
'new_codes': new_codes,
'new_set_id': int(freeze_result.candidate_set_id),
},
source='system',
)
return True
def freeze_wave_notice_routing(
notice: ShippingNotice,
*,
@@ -21,6 +21,7 @@ from app.models import (
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingInventoryFile,
ShippingNotice,
ShippingOrderTask,
ShippingNoticeLineInventoryMatch,
ShippingTaskInventoryRpaAttempt,
@@ -82,8 +83,35 @@ def _candidate_set_filter(
return list(rows)
def resolve_inventory_fact_task(task: Any) -> Any:
"""
将库存事实读取对象归一为正式 OT。
核心逻辑:候选集/库存 Link 全部挂在 OT 上,而货代上传等入口按 business_no
加载 ShippingNotice——Notice 没有 active_inventory_candidate_set_id 字段,
直接查询会 fail-closed 成「库存源尚未确定」(历史缺陷:RPA 上传被恒拦截,
自动推进的 freight_upload_rpa 门禁也因此秒切人工)。OT 原样返回;Notice 沿
order_task_id 解析,缺绑定或 OT 不存在时原样返回,由上层无候选集语义继续
fail-closed。
Args:
task: ShippingOrderTask 或 ShippingNotice。
Returns:
归一后的 OT(或无法解析时的原对象)。
"""
if isinstance(task, ShippingNotice):
order_task_id = getattr(task, 'order_task_id', None)
if order_task_id is None:
return task
order_task = _session().get(ShippingOrderTask, int(order_task_id))
if order_task is not None:
return order_task
return task
def get_active_candidate_set(
task: ShippingOrderTask,
task: ShippingOrderTask | ShippingNotice,
*,
session: Session | None = None,
) -> ShippingInventoryCandidateSet | None:
@@ -92,7 +120,9 @@ def get_active_candidate_set(
核心逻辑:严格依赖 ShippingOrderTask.active_inventory_candidate_set_id;
指针为空、坏链、跨 Task、非 frozen 均返回 None,由上层映射阻断。
传入 ShippingNotice 时先归一为其 order_task(见 resolve_inventory_fact_task)。
"""
task = resolve_inventory_fact_task(task)
candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None)
if candidate_set_id is None:
return None
@@ -277,9 +277,14 @@ def assert_inventory_source_gate(
def task_inventory_identity(task: ShippingOrderTask) -> dict[str, str | None]:
"""返回库存执行身份;固定仓来自配置,动态仓仅来自已验证库存 Link。"""
"""返回库存执行身份;固定仓来自配置,动态仓仅来自已验证库存 Link。
传入 ShippingNotice 时先归一为其 order_task(库存 Link 挂在 OT 上)。
"""
from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
task = resolve_inventory_fact_task(task)
source_codes = task_frozen_inventory_source_codes(task)
source_code = source_codes[0] if len(source_codes) == 1 else None
source = get_database_inventory_source(source_code) if source_code else None
@@ -294,13 +299,19 @@ def resolve_inventory_source_warehouse_id(
*,
source: dict[str, Any] | None,
) -> str | None:
"""解析库存执行仓库:固定仓读 Source 配置,动态仓只读有效库存 Link。"""
"""解析库存执行仓库:固定仓读 Source 配置,动态仓只读有效库存 Link。
传入 ShippingNotice 时先归一为其 order_task(库存 Link 挂在 OT 上)。
"""
if not source:
return None
mode = str(source.get('warehouse_resolution_mode') or '').strip().lower()
if mode == 'fixed':
return str(source.get('fixed_warehouse_id') or '').strip().upper() or None
from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task
task = resolve_inventory_fact_task(task)
task_id = getattr(task, 'id', None)
source_code = str(source.get('source_code') or '').strip().upper()
if not task_id or not source_code:
@@ -5,6 +5,9 @@ services/shipping_notice/line_inventory_match_persistence.py
依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。
逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库;
新快照新增行并切换 is_current;不覆盖历史快照事实。
行级 inventory_snapshot_id 按匹配结果自带的 inventory_file_no 归因到「命中文件」;
仅行结果未回填文件号(如 not_found)时才回退任务级锚点快照——多源池下锚点文件
≠命中文件,混用会导致 Excel 仓库列写成锚点仓(历史缺陷:AWSCV 单写成 CMH01)。
匹配器下发的料号兜底总量 part_available_qty(Task 1)随行事实字符串化落列,
供后续投影层与自动放行服务读取。
"""
@@ -111,12 +114,14 @@ def persist_line_inventory_match_facts(
from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts
snap_id = active_inventory_runtime_facts(task).get('inventory_file_id')
# 匹配器结果可能未回填 inventory_file_no,但当前快照本身已是行匹配的
# 正式文件身份。持久化必须补齐,避免“有快照却无行级下载证据”。
# 任务级锚点快照仅作行结果缺文件号时的回退身份;命中文件归因在行循环内逐行解析。
snapshot_file_no = None
if snap_id is not None:
snapshot = ShippingInventoryFile.query.get(int(snap_id))
snapshot_file_no = str(getattr(snapshot, 'inventory_file_no', '') or '').strip() or None
# 命中文件号 → 文件 ID 缓存;文件号查不到文件时缓存 None,本行回退锚点快照
# (命中证据仍以 matched_file_no 为准,不把锚点伪装成命中文件)。
file_id_by_no: dict[str, int | None] = {}
line_results = [
item for item in list(match_payload.get('line_results') or []) if isinstance(item, dict)
@@ -156,6 +161,23 @@ def persist_line_inventory_match_facts(
continue
snapshot_line_id = int(snapshot_line.id)
# [STEP] 行级文件归因:匹配结果自带 inventory_file_no 时解析命中文件 ID;
# 未回填(如 not_found)或文件号无法解析时回退任务级锚点快照。
# 禁止把锚点文件身份盖到命中了其他源文件的行上(历史缺陷根因)。
line_file_no = str(result.get('inventory_file_no') or '').strip() or None
line_snap_id = snap_id
if line_file_no is not None:
if line_file_no not in file_id_by_no:
hit_file = (
ShippingInventoryFile.query
.filter_by(inventory_file_no=line_file_no)
.first()
)
file_id_by_no[line_file_no] = int(hit_file.id) if hit_file is not None else None
resolved_file_id = file_id_by_no[line_file_no]
if resolved_file_id is not None:
line_snap_id = resolved_file_id
match_result, inventory_status = map_disposition_to_match_codes(
disposition=str(result.get('disposition') or res.get('disposition') or ''),
part_number=result.get('part_number') or res.get('part_number'),
@@ -172,8 +194,8 @@ def persist_line_inventory_match_facts(
else []
)
# [STEP] BE-5:无库存快照时禁止 ready/not_found(不得规范为 0)
if snap_id is None and (
# [STEP] BE-5:本行无任何库存文件身份时禁止 ready/not_found(不得规范为 0)
if line_snap_id is None and (
inventory_status == 'ready'
or match_result in {'matched', 'not_found'}
):
@@ -195,20 +217,20 @@ def persist_line_inventory_match_facts(
)
unit_value = str(unit_raw or '').strip()[:32] or None
# [STEP] 同 OT+行+快照:更新;否则新建并撤销旧 current
# [STEP] 同 OT+行+命中文件:更新;否则新建并撤销旧 current
existing = None
if snap_id is not None:
if line_snap_id is not None:
existing = (
ShippingNoticeLineInventoryMatch.query
.filter_by(
task_id=int(task.id),
snapshot_line_id=snapshot_line_id,
line_no=line_no,
inventory_snapshot_id=int(snap_id),
inventory_snapshot_id=int(line_snap_id),
)
.first()
)
if existing is None and snap_id is None:
if existing is None and line_snap_id is None:
existing = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True)
@@ -253,7 +275,7 @@ def persist_line_inventory_match_facts(
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
'inventory_file_no': file_no,
'inventory_row_ref': result.get('inventory_row_ref'),
'snapshot_missing': snap_id is None,
'snapshot_missing': line_snap_id is None,
'evidence_ref_plain': evidence_plain if evidence_ref else None,
}
row = ShippingNoticeLineInventoryMatch(
@@ -273,7 +295,7 @@ def persist_line_inventory_match_facts(
else None
),
candidate_line_id=int(candidate_line.id) if candidate_line is not None else None,
inventory_snapshot_id=int(snap_id) if snap_id is not None else None,
inventory_snapshot_id=int(line_snap_id) if line_snap_id is not None else None,
match_result=match_result,
inventory_status=inventory_status,
required_qty=str(required) if required is not None else None,
@@ -304,7 +326,7 @@ def persist_line_inventory_match_facts(
'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None,
'allowed_source_codes_snapshot': list(allowed_source_codes),
'inventory_file_no': file_no,
'inventory_snapshot_id': int(snap_id) if snap_id is not None else None,
'inventory_snapshot_id': int(line_snap_id) if line_snap_id is not None else None,
'inventory_row_ref': result.get('inventory_row_ref'),
'match_result': match_result,
}).encode('utf-8')
@@ -342,7 +364,7 @@ def persist_line_inventory_match_facts(
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
'inventory_file_no': file_no,
'inventory_row_ref': result.get('inventory_row_ref'),
'snapshot_missing': snap_id is None,
'snapshot_missing': line_snap_id is None,
'evidence_ref_plain': evidence_plain if evidence_ref else None,
}
existing.match_result = match_result
@@ -385,7 +407,7 @@ def persist_line_inventory_match_facts(
'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None,
'allowed_source_codes_snapshot': list(allowed_source_codes),
'inventory_file_no': file_no,
'inventory_snapshot_id': int(snap_id) if snap_id is not None else None,
'inventory_snapshot_id': int(line_snap_id) if line_snap_id is not None else None,
'inventory_row_ref': result.get('inventory_row_ref'),
'match_result': match_result,
}).encode('utf-8')
@@ -938,6 +938,42 @@ def _handle_retry_inventory_preparation(
freeze_mode='manual',
)
db.session.flush()
# [STEP 0B] 人工重取前的候选源刷新(幂等):任务级 retry_inventory_preparation 先按当前
# 主数据/路由规则整单重判候选集;行级重抓(line_scope 非空)仅重评目标行候选。
# 两者均无变化零副作用;有变化则新版候选集随 supersede 自带旧事实失效,再走下方
# 既有失效与重取链——补源场景由此闭环:管理端启用新源后点「重新获取库存(RPA)」
# 即可让新源进入取数与匹配范围,无需重建订单。
# 轮询/自动首投(外层条件已排除)与 Excel 已生成(源锁定,D7 边界)不刷新;
# 已定源(任务级整单/行级目标行候选 ≤1)与人工钉源不刷新(helper 内守卫,改源走
# override_line_inventory_source)。
# 行键失效(line_scope_key/snapshot_line_id 解析不到行)时 _resolve_line_inventory_scope
# 返回 None,按既有降级语义走任务级刷新(升级前行为一致)。
if str(payload.get('action_code') or '').strip() == 'retry_inventory_preparation':
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
if latest_export_artifact(task) is None:
from app.services.shipping_notice.inventory_candidate_freeze_service import (
refresh_candidates_from_current_routing,
refresh_line_candidates_from_current_routing,
)
if line_scope is None:
refresh_candidates_from_current_routing(task, execution_id=int(execution.id))
elif refresh_line_candidates_from_current_routing(
task, line_no=int(line_scope['line_no']), execution_id=int(execution.id),
):
# 刷新产生新候选集后旧 scope 已过期:按同参重解析行作用域,让本次失效与
# RPA 取数直接使用新冻结码;重解析为 None(如行键已失效)则保守沿用旧值。
refreshed_scope = _resolve_line_inventory_scope(
task,
line_scope_key=(
payload.get('line_scope_key')
if payload.get('line_scope_key') is not None
else payload.get('snapshot_line_id')
),
)
if refreshed_scope is not None:
line_scope = refreshed_scope
if payload.get('action_code') in {
'retry_inventory_preparation',
'retry_inventory_from_preparation',
@@ -1564,13 +1564,22 @@ def _enrich_task_center_fields(
data["created_by"] = task.user_id
if viewer_user_id is not None:
data["can_handle"] = task_can_handle(task, int(viewer_user_id), is_admin=is_admin)
# 下载能力与导出端点同一谓词;SUMMARY/DETAIL 均下发,供抽屉/批量勾选消费。
data["can_download_export"] = can_download_task_export(
task, user_id=int(viewer_user_id), is_admin=is_admin,
)
data["recent_event"] = _latest_task_event_summary(task)
data["artifact_summary"] = _artifact_summary_for_task(task)
data['notice_line_summary'] = _notice_line_summary_for_task(task)
# [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。
from app.services.shipping_notice.ui_state import build_task_ui_state
ui_state = build_task_ui_state(task, include_stage_context=include_stage_context)
ui_state = build_task_ui_state(
task,
include_stage_context=include_stage_context,
viewer_user_id=viewer_user_id,
viewer_is_admin=is_admin,
)
data["ui_state"] = ui_state
# [PERF] 优先复用 ui_state.process_gate(build_task_ui_state 已查 Execution);
# 无 Gate 时回退 position/user_mode,避免再跑一次 resolve_task_ui_state。
@@ -1730,12 +1739,15 @@ def list_tasks_page_for_user(
page: int = 1,
page_size: int = 20,
lifecycle_status: str | None = None,
is_admin: bool = False,
) -> dict[str, Any]:
"""
分页列出当前用户可见的发货任务摘要。
工作台任务量增长后必须由数据库分页,不能先拉取固定上限再在浏览器切页;
`items` 仅表示当前页,`total` 用于计算稳定的页码与空页回退。
``is_admin`` 只影响 SUMMARY 的能力字段(can_handle / can_download_export),
不扩大列表可见范围(仍为本人 + 无主 Notice)。
"""
normalized_page = max(1, int(page))
normalized_page_size = max(1, min(int(page_size), 100))
@@ -1795,7 +1807,7 @@ def list_tasks_page_for_user(
rows = [row for row in rows if row is not None]
return {
"items": [
serialize_task_summary(item, viewer_user_id=user_id)
serialize_task_summary(item, viewer_user_id=user_id, is_admin=is_admin)
for item in rows
],
"page": normalized_page,
@@ -1849,6 +1861,35 @@ def get_task_visible_to_user(
return task
def can_download_task_export(
task: ShippingOrderTask | ShippingNotice | None,
*,
user_id: int,
is_admin: bool = False,
) -> bool:
"""
导出下载的唯一授权谓词:创建者或平台管理员(与导出端点同一口径)。
核心逻辑:单票/批量 Excel 下载端点与 UI 的 download_excel 动作、
can_download_export 字段都必须消费本谓词,禁止各处另行推导归属;
管理员放开下载(可下载=可见)后,每次下载仍须写入 record_access_audit。
无主任务(user_id IS NULL)仅管理员可下载。
Args:
task: 已加载的任务实体(可为 None)。
user_id: 当前查看/下载用户。
is_admin: 是否平台管理员。
Returns:
当前用户是否允许下载该任务的正式 Excel。
"""
if task is None:
return False
if is_admin:
return True
return task.user_id is not None and int(task.user_id) == int(user_id)
def list_freight_notice_groups_for_task(
task: ShippingNotice,
*,
@@ -61,7 +61,11 @@ from app.services.shipping_notice.lifecycle_projection import (
LIFECYCLE_STAGES,
project_lifecycle,
)
from app.services.shipping_notice.query_service import resolve_task_export_download, serialize_task_summary
from app.services.shipping_notice.query_service import (
can_download_task_export,
resolve_task_export_download,
serialize_task_summary,
)
from app.services.shipping_notice.state_machine import (
UserMode,
)
@@ -1162,6 +1166,8 @@ def build_task_ui_state(
task: ShippingNotice,
*,
include_stage_context: bool = False,
viewer_user_id: int | None = None,
viewer_is_admin: bool = False,
) -> dict[str, Any]:
"""
构建单票任务 UI State。
@@ -1170,6 +1176,14 @@ def build_task_ui_state(
禁止 Chat、通知卡与任务中心分别推导状态;
可点击用户动作只由 Gate 与已验证 Artifact 授权产生。
Gate 摘要只查一次,再派生 position/user_mode,禁止再走 resolve_task_ui_state 二次查库。
Args:
task: 源任务实体。
include_stage_context: 是否附带 stage_context(工作面只读事实)。
viewer_user_id: 当前查看者;给定时时 download_excel 动作按导出统一谓词
(can_download_task_export:创建者或管理员)门禁下发;为 None 时维持
聊天链路旧口径(仅按 Artifact 授权,聊天会话与创建者同源)。
viewer_is_admin: 查看者是否平台管理员(配合 viewer_user_id 使用)。
"""
from app.services.shipping_notice.state_machine import (
_review_status_fallback_ui_state,
@@ -1210,7 +1224,12 @@ def build_task_ui_state(
# [AUTHORITY] Gate 负责当前可写恢复动作;Excel 下载是已产出文件的只读动作,
# 两者不能相互覆盖。即使当前 Gate 阻断并清空旧动作,也只在
# Artifact 已通过 resolve_task_export_download 校验时补入下载授权。
if resolve_task_export_download(task) is not None:
# 下载动作与导出端点消费同一谓词:viewer 已知时按创建者/管理员门禁,
# 避免非创建者"看得到点不动";viewer 未知(聊天链路)维持 Artifact 口径。
if resolve_task_export_download(task) is not None and (
viewer_user_id is None
or can_download_task_export(task, user_id=int(viewer_user_id), is_admin=viewer_is_admin)
):
download_action = _unified_action({
'id': 'download_excel',
'label': '下载 Excel',