feat(shipping_notice): 支持客户 ODM 白名单与整单 ODM 选择收敛导出

- 客户主数据新增 odm_ids 白名单字段(含 Alembic 迁移),表单与管理端支持维护
- 导出库存命中行按客户白名单与整单 ODM 裁决收敛,新增 notice_odm_choice_service
- 工作台新增 odm-options / odm-choice 接口,投影行级候选并持久化用户选择
- 修复复核工作台跨 Run 切换时接收解析上下文残留
- 同步四语言 i18n、测试用例、funclist 与 shipping-notice 技术文档
This commit is contained in:
hugo committed 2026-09-16 19:50:12 +08:00
1 parent a032354cb9
commit d396371020
51 files changed
+2717 -109

No files matched your search

+1
View File
@@ -63,6 +63,7 @@ frontend/package-lock.json
*.swp
*.swo
.cursorrules
.zcode
# Runtime files
.run/
@@ -481,6 +481,45 @@ def workspace_shipping_task_detail(task_no: str):
))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/odm-options', methods=['GET'])
def workspace_shipping_task_odm_options(task_no: str):
"""返回整单 ODM ID 候选与当前选择(工作台整单裁决路径,只读)。"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
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=is_admin)
if not task:
raise NotFoundError('Not found')
return _ok(notice_odm_options(task))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/odm-choice', methods=['POST'])
def workspace_set_shipping_task_odm_choice(task_no: str):
"""保存整单 ODM ID 用户选择;重复提交覆盖旧选择,成功后前端可重试生成 Excel。"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.notice_odm_choice_service import set_notice_odm_choice
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=is_admin)
if not task:
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
try:
snapshot_line_id = int(data.get('snapshot_line_id') or 0)
except (TypeError, ValueError):
snapshot_line_id = 0
result = set_notice_odm_choice(
task,
snapshot_line_id=snapshot_line_id,
odm_id=str(data.get('odm_id') or ''),
)
db.session.commit()
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/audit-timeline', methods=['GET'])
def workspace_list_shipping_task_audit_timeline(task_no: str):
"""业务用户 Task 审计时间线(统一 ShippingAuditEvent,无敏感快照)。"""
+2
View File
@@ -45,6 +45,8 @@ class ShippingCustomer(Base):
index=True,
)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# 客户可用的 ODM ID 清单;为空表示不限定。生成发货 Excel 时用于收敛库存命中行。
odm_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
@@ -126,6 +126,8 @@ class ShippingNoticeLineInventoryMatch(Base):
onupdate=datetime.utcnow,
nullable=False,
)
# 整单 ODM ID 用户选择;写在当前匹配事实行上,随重匹配轮次自然失效。
chosen_odm_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# T6: 行级实际源证据(决策 E1 硬约束)——用于幂等保护与跨源匹配审计。
matched_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
matched_row_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
@@ -37,6 +37,47 @@ from app.services.shipping_notice.customer_normalization import (
CUSTOMER_STATUSES = frozenset({'active', 'inactive', 'merged'})
IDENTIFIER_STATUSES = frozenset({'pending', 'approved', 'disabled'})
_ODM_ID_MAX_ITEMS = 100
_ODM_ID_MAX_LENGTH = 64
def _normalize_odm_ids(value: Any) -> list[str] | None:
"""
规范化客户 ODM ID 清单:逐项 trim、去空、去重(保持原顺序)。
Args:
value: 前端提交的清单(字符串列表);None 表示未提交,空列表表示清空。
Returns:
规范化后的清单;None 仅当输入为 None。
Raises:
ValidationError: 条目超长或清单超量。
"""
if value is None:
return None
if not isinstance(value, list):
raise ValidationError(
'ODM ID list must be an array of strings',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
)
normalized: list[str] = []
for item in value:
text = str(item or '').strip()
if not text:
continue
if len(text) > _ODM_ID_MAX_LENGTH:
raise ValidationError(
'ODM ID is too long',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
details={'odm_id': text},
)
if text not in normalized:
normalized.append(text)
if len(normalized) > _ODM_ID_MAX_ITEMS:
raise ValidationError(
'Too many ODM IDs',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
)
return normalized
def _record_lifecycle_event(
@@ -142,6 +183,7 @@ def serialize_customer(
'status': record.status,
'merged_into_customer_id': record.merged_into_customer_id,
'remark': record.remark,
'odm_ids': list(record.odm_ids or []) if record.odm_ids is not None else None,
'created_by_id': record.created_by_id,
'updated_by_id': record.updated_by_id,
'created_at': record.created_at.isoformat() if record.created_at else None,
@@ -318,6 +360,7 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
short_code=short_code,
status=status,
remark=clean_text(data.get('remark')) or None,
odm_ids=_normalize_odm_ids(data.get('odm_ids')) if 'odm_ids' in data else None,
created_by_id=actor_id,
updated_by_id=actor_id,
)
@@ -385,11 +428,13 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
'short_code': record.short_code,
'status': record.status,
'remark': record.remark,
'odm_ids': list(record.odm_ids or []) if record.odm_ids is not None else None,
}
next_name = before['standard_name']
next_short_code = before['short_code']
next_status = before['status']
next_remark = before['remark']
next_odm_ids = before['odm_ids']
if 'standard_name' in data:
name = clean_text(data.get('standard_name'))
if not name:
@@ -404,11 +449,14 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
if 'remark' in data:
next_remark = clean_text(data.get('remark')) or None
if 'odm_ids' in data:
next_odm_ids = _normalize_odm_ids(data.get('odm_ids'))
after = {
'standard_name': next_name,
'short_code': next_short_code,
'status': next_status,
'remark': next_remark,
'odm_ids': next_odm_ids,
}
changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]}
if changes:
@@ -418,6 +466,7 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
record.short_code = next_short_code
record.status = next_status
record.remark = next_remark
record.odm_ids = next_odm_ids
record.updated_by_id = actor_id
_record_lifecycle_event(
record,
@@ -56,6 +56,7 @@ from app.services.shipping_notice.order_schema.field_rules import normalize_orde
from app.services.shipping_notice.reservation_region import (
apply_reservation_region_candidates,
reservation_region_candidates_from_layout,
resolve_candidate_line_numbers,
)
@@ -551,6 +552,10 @@ def _candidate_for_sample(
header_field_id=str((reservation_fields.get('header') or {}).get('field_id') or '') or None,
line_field_id=str((reservation_fields.get('line') or {}).get('field_id') or '') or None,
line_count=len(rows),
# 盲测与正式解析共用 LN 值定位,防止预览与正式路由行归属不一致。
line_numbers=resolve_candidate_line_numbers([
row.get('customer_po_line_no') if isinstance(row, dict) else None for row in rows
]),
)
if applied.header_value and reservation_fields.get('header'):
header = reservation_fields['header']
+277 -54
View File
@@ -5,6 +5,8 @@ services/shipping_notice/export.py
依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。
逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板;
导出前按本单 match_keys(通常 reservation+part)裁剪库存候选再匹配,避免全量快照进匹配;
整单 ODM 裁决依次应用:客户 odm_ids 范围 → 用户选择(OT.chosen_odm_id)→
唯一可行交集自动收敛;模板消费 odm 字段时生效;
Header 的 system_fact:warehouse_id 取本 Notice 唯一行库位(PVMI 契约);多库位冲突失败;
在最终导出行集上按通知明细项次写入模板;内部遍历序号不属于业务字段。
订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。
@@ -45,8 +47,12 @@ from app.services.file_assets.storage import file_asset_storage
def _notice_source_code(task: ShippingNotice) -> str | None:
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。"""
task_id = getattr(task, 'order_task_id', None)
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。
匹配事实的 task_id 挂在正式 OT 上:传 Notice 时取 order_task_id,
传 OT 本身时取 id(整单 ODM 候选投影会在物化前以 OT 调用)。
"""
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)
@@ -63,6 +69,23 @@ def _notice_source_code(task: ShippingNotice) -> str | None:
return codes[0] if len(codes) == 1 else None
def _notice_chosen_odm(task: ShippingNotice) -> str | None:
"""读取当前行级匹配事实上的整单 ODM 用户选择(notice_odm_choice_service 落库)。"""
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
if task_id is None:
return None
values = [
str(row[0]).strip()
for row in db.session.query(ShippingNoticeLineInventoryMatch.chosen_odm_id).filter(
ShippingNoticeLineInventoryMatch.task_id == int(task_id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.chosen_odm_id.isnot(None),
).distinct().all()
if row[0]
]
return values[0] if values else None
def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
"""从 Notice 行级匹配读取本次导出的唯一库存文件。"""
task_id = getattr(task, 'order_task_id', None)
@@ -426,29 +449,7 @@ def _match_inventory_lines(
return []
if not match_keys:
raise ValueError('库存解析模板缺少订单与库存匹配键')
from app.models import ShippingInventoryField
ids = {
int(item.get('inventory_field_id'))
for item in match_keys
if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit()
}
catalog = {
str(item.id): str(item.id)
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(ids)).all()
}
normalized_keys: list[dict[str, str]] = []
for item in match_keys:
if not isinstance(item, dict):
raise ValueError('库存解析模板匹配键无效')
field_id = str(item.get('inventory_field_id') or '').strip()
inventory_field = catalog.get(field_id)
if not inventory_field:
raise ValueError('库存解析模板引用的库存字段已不可用')
normalized_keys.append({
'order_field_id': str(item.get('order_field_id') or ''),
'inventory_field': inventory_field,
})
normalized_keys = _normalize_match_keys(match_keys)
result: list[dict[str, Any]] = []
for position, order_line in enumerate(order_lines, start=1):
expected = [
@@ -586,34 +587,176 @@ def _input_checksum(
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
def generate_shipment_excel(
task: ShippingNotice,
) -> tuple[str, str, ShippingExportArtifact]:
"""
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
def _resolve_odm_inventory_field_id() -> int | None:
"""返回 odm_id 库存字段目录 ID;目录未配置或已停用时返回 None(整单 ODM 裁决整体跳过)。"""
field = ShippingInventoryField.query.filter_by(field_code='odm_id', status='active').first()
return int(field.id) if field is not None else None
Returns:
(绝对文件路径, 下载文件名, 待随任务事务提交的 Artifact)。
def _normalize_match_keys(match_keys: list[dict[str, Any]]) -> list[dict[str, str]]:
"""
校验并规范化库存解析模板匹配键为 {order_field_id, inventory_field} 列表。
Raises:
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
AppError: 没有可导出的满足/已审计放行行,或输入事实不完整。
ValueError: 匹配键缺失、无效或引用的库存字段已不可用。
"""
from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
ids = {
int(item.get('inventory_field_id'))
for item in match_keys
if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit()
}
catalog = {
str(item.id): str(item.id)
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(ids)).all()
}
normalized_keys: list[dict[str, str]] = []
for item in match_keys:
if not isinstance(item, dict):
raise ValueError('库存解析模板匹配键无效')
field_id = str(item.get('inventory_field_id') or '').strip()
inventory_field = catalog.get(field_id)
if not inventory_field:
raise ValueError('库存解析模板引用的库存字段已不可用')
normalized_keys.append({
'order_field_id': str(item.get('order_field_id') or ''),
'inventory_field': inventory_field,
})
return normalized_keys
# OT 在库存门禁通过后才物化为正式 Notice;之后导出链路只接受 Notice。
from app.models import ShippingOrderTask
if isinstance(task, ShippingOrderTask):
from app.services.shipping_notice.shipping_notice_creation_service import (
create_shipping_notice_after_inventory_gate,
def _per_line_odm_sets(
order_lines: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
normalized_keys: list[dict[str, str]],
odm_key: str,
) -> list[set[str]]:
"""逐导出行收集命中库存行的 odm 值集合;缺匹配键行与未命中行返回空集。"""
sets: list[set[str]] = []
for order_line in order_lines:
expected = [
(_match_text(order_line.get(item['order_field_id'])), item['inventory_field'])
for item in normalized_keys
]
if any(not value for value, _field in expected):
sets.append(set())
continue
matched = {
_match_text(row.get(odm_key))
for row in inventory_lines
if all(_match_text(row.get(field)) == value for value, field in expected)
}
matched.discard('')
sets.append(matched)
return sets
def _intersect_odm_sets(sets: list[set[str]]) -> set[str]:
"""各行命中 odm 集合的交集;未命中行(空集)不参与约束,全部为空返回空集。"""
active = [item for item in sets if item]
if not active:
return set()
return set.intersection(*active)
def _adjudicate_notice_odm(
*,
line_values: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
match_keys: list[dict[str, Any]],
odm_field_id: int | None,
snapshot: ShippingOrderSnapshot,
chosen_odm_raw: str | None,
) -> dict[str, Any]:
"""
整单(Notice)级 ODM 收敛裁决;模板不消费 odm 字段时直接跳过。
逻辑:客户 ODM ID 范围非空先过滤;用户选择(OT.chosen_odm_id)次之;
无范围且无选择时,各导出行命中 odm 交集唯一则自动收敛(唯一可行解,无需人工)。
多值并存时不过滤,由逐行折叠按现有契约阻断,并由工作台下发候选供用户选择。
Returns:
{'inventory_lines': 收敛后的库存行, 'feasible_odm_ids': 排序候选,
'whitelist_applied': 是否应用了客户范围, 'chosen_odm_id': 用户选择(展示值)}
Raises:
ValueError: 范围排除全部命中,或用户选择在当前库存中已不存在。
"""
result = {
'inventory_lines': inventory_lines,
'feasible_odm_ids': [],
'per_line_odm_ids': [],
'whitelist_applied': False,
'chosen_odm_id': None,
}
if odm_field_id is None:
return result
odm_key = str(odm_field_id)
# 归一化值 → 原始展示值:候选/已选回显保留库存行原样大小写。
odm_display: dict[str, str] = {}
for row in inventory_lines:
raw = str(row.get(odm_key) or '').strip()
if raw:
odm_display.setdefault(_match_text(raw), raw)
customer = db.session.get(ShippingCustomer, int(snapshot.customer_id)) if snapshot.customer_id else None
customer_odm_ids = [
_match_text(value) for value in (customer.odm_ids or []) if _match_text(value)
] if customer is not None else []
chosen_odm = _match_text(chosen_odm_raw) if str(chosen_odm_raw or '').strip() else None
result['chosen_odm_id'] = odm_display.get(chosen_odm, str(chosen_odm_raw).strip()) if chosen_odm else None
normalized_keys = _normalize_match_keys(match_keys)
pre_odm_sets = _per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)
if customer_odm_ids:
result['whitelist_applied'] = True
scope = set(customer_odm_ids)
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in scope]
# 范围把原本有命中的行全部排除时,必须给出指向客户数据的可行动错误,
# 避免回落成误导性的「没有匹配的库存记录」。
if any(pre_odm_sets) and not any(_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)):
raise ValueError('订单行命中的库存记录 ODM ID 不在客户数据维护的 ODM ID 范围内,请检查客户数据或库存文件')
# 逐行候选取「客户范围过滤后、选择收敛前」的集合:用户在任何一行改选,候选都来自同一口径。
scoped_sets = (
_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)
if customer_odm_ids else pre_odm_sets
)
if chosen_odm:
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) == chosen_odm]
if any(pre_odm_sets) and not any(_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key)):
raise ValueError('发货通知已选择的 ODM ID 在当前库存中不存在,请重新选择')
elif not customer_odm_ids:
# 无范围、无选择:交集唯一即唯一可行解,自动收敛;多值留给折叠阻断 + 人工选择。
feasible = _intersect_odm_sets(pre_odm_sets)
if len(feasible) == 1:
inventory_lines = [row for row in inventory_lines if _match_text(row.get(odm_key)) in feasible]
result['inventory_lines'] = inventory_lines
result['per_line_odm_ids'] = [
sorted(odm_display.get(value, value) for value in line_set)
for line_set in scoped_sets
]
result['feasible_odm_ids'] = sorted(
odm_display.get(value, value)
for value in _intersect_odm_sets(
_per_line_odm_sets(line_values, inventory_lines, normalized_keys, odm_key),
)
task = create_shipping_notice_after_inventory_gate(task)
if not task_is_active(task):
raise ValueError('已作废或归档的任务不能生成发货 Excel')
assert_task_not_supersession_blocked(task)
assert_notice_has_no_export_artifact(task)
)
return result
def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
"""
汇集发货 Excel 导出匹配所需的只读输入;不物化、不写库。
【AI 触发时机】:generate_shipment_excel 的行匹配准备,以及工作台整单 ODM
候选投影(notice_odm_choice_service)复用,保证两者消费同一份匹配事实。
Returns:
source/template/snapshot/header_values/line_values/inventory_lines/
match_keys/line_inventory_fields/header_inventory_fields/verification/
selected_snapshot_line_ids/release_overrides_by_line/released_export_line_indexes。
"""
from app.services.shipping_notice.reservation_service import (
current_available_snapshot_line_ids,
)
# [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。
source_code = str(_notice_source_code(task) or '').strip().upper()
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
@@ -637,11 +780,6 @@ def generate_shipment_excel(
if snapshot is None:
raise ValueError('任务没有可用于导出的冻结订单快照')
header_values, all_line_values = order_field_id_values(task)
export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date()
from app.services.shipping_notice.reservation_service import (
current_available_snapshot_line_ids,
reserve_available_for_artifact,
)
profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {}
match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else []
line_inventory_fields = _inventory_fields_by_mode(mappings, 'line')
@@ -696,6 +834,7 @@ def generate_shipment_excel(
continue
row = dict(values)
row['__order_line_index'] = source_index
row['__snapshot_line_id'] = int(line.id)
line_values.append(row)
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
@@ -703,8 +842,6 @@ def generate_shipment_excel(
# 裁成候选子集,再做模板字段匹配——禁止上万行全量快照进入逐行匹配。
inventory_lines = resolve_inventory_lines_for_execution(source_notice)
if (line_inventory_fields or header_inventory_fields) and match_keys and line_values:
from app.models import ShippingInventoryField
match_field_ids = {
int(item.get('inventory_field_id'))
for item in match_keys
@@ -742,6 +879,90 @@ def generate_shipment_excel(
and not isinstance(row.get('__order_line_index'), bool)
and int(row['__order_line_index']) in released_source_line_indexes
}
return {
'source': source,
'template': template,
'snapshot': snapshot,
'mappings': mappings,
'source_notice': source_notice,
'header_values': header_values,
'line_values': line_values,
'inventory_lines': inventory_lines,
'match_keys': match_keys,
'line_inventory_fields': line_inventory_fields,
'header_inventory_fields': header_inventory_fields,
'verification': verification,
'released_snapshot_line_ids': released_snapshot_line_ids,
'selected_snapshot_line_ids': selected_snapshot_line_ids,
'release_overrides_by_line': release_overrides_by_line,
'released_export_line_indexes': released_export_line_indexes,
}
def generate_shipment_excel(
task: ShippingNotice,
) -> tuple[str, str, ShippingExportArtifact]:
"""
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
Args:
chosen_odm_id: 整单 ODM ID 用户选择(本次生成的请求参数,不落库);
多 ODM 冲突时由工作台下发候选后随 Gate 动作传入,仅当其在当前库存命中时生效。
Returns:
(绝对文件路径, 下载文件名, 待随任务事务提交的 Artifact)。
Raises:
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
AppError: 没有可导出的满足/已审计放行行,或输入事实不完整。
"""
from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
# OT 在库存门禁通过后才物化为正式 Notice;之后导出链路只接受 Notice。
from app.models import ShippingOrderTask
if isinstance(task, ShippingOrderTask):
from app.services.shipping_notice.shipping_notice_creation_service import (
create_shipping_notice_after_inventory_gate,
)
task = create_shipping_notice_after_inventory_gate(task)
if not task_is_active(task):
raise ValueError('已作废或归档的任务不能生成发货 Excel')
assert_task_not_supersession_blocked(task)
assert_notice_has_no_export_artifact(task)
inputs = prepare_export_match_inputs(task)
source = inputs['source']
template = inputs['template']
snapshot = inputs['snapshot']
mappings = inputs['mappings']
source_notice = inputs['source_notice']
header_values = inputs['header_values']
line_values = inputs['line_values']
match_keys = inputs['match_keys']
line_inventory_fields = inputs['line_inventory_fields']
header_inventory_fields = inputs['header_inventory_fields']
inventory_lines = inputs['inventory_lines']
verification = inputs['verification']
released_snapshot_line_ids = inputs['released_snapshot_line_ids']
selected_snapshot_line_ids = inputs['selected_snapshot_line_ids']
release_overrides_by_line = inputs['release_overrides_by_line']
released_export_line_indexes = inputs['released_export_line_indexes']
export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date()
# [STEP 3.5] 整单 ODM 裁决:客户 ODM ID 范围 → 用户选择 → 唯一可行交集自动收敛。
odm_field_id = (
_resolve_odm_inventory_field_id()
if (line_inventory_fields or header_inventory_fields) else None
)
adjudication = _adjudicate_notice_odm(
line_values=line_values,
inventory_lines=inventory_lines,
match_keys=match_keys,
odm_field_id=odm_field_id,
snapshot=snapshot,
chosen_odm_raw=_notice_chosen_odm(task),
)
inventory_lines = adjudication['inventory_lines']
matched_inventory_lines = _match_inventory_lines(
line_values,
inventory_lines,
@@ -854,6 +1075,8 @@ def generate_shipment_excel(
)
db.session.add(artifact)
db.session.flush()
from app.services.shipping_notice.reservation_service import reserve_available_for_artifact
reserve_available_for_artifact(
source_notice,
artifact=artifact,
@@ -0,0 +1,177 @@
"""
services/shipping_notice/notice_odm_choice_service.py
用途:发货通知整单(Notice)级 ODM ID 的逐行候选投影与用户选择持久化。
依赖:export(prepare_export_match_inputs/_adjudicate_notice_odm)、ShippingNoticeLineInventoryMatch、AppError。
逻辑:候选 = 各导出行命中 odm(先经客户 odm_ids 范围过滤)的交集,与导出收敛共用同一
事实源(prepare_export_match_inputs);选择写在当前行级匹配事实行
(shipping_notice_line_inventory_matches.chosen_odm_id)上,按「同一库存快照文件」
圈同步范围——改任一行,同文件全部 is_current 行统一变更(Header 契约是整单一个值);
重匹配产生新匹配轮次后旧选择自然失效。实际收敛由导出裁决执行,本服务只投影与落库。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import AppError
from app.models import ShippingCustomer, ShippingNoticeLineInventoryMatch
_ODM_CHOICE_INVALID_CODE = 'SHIPPING.NOTICE_ODM_CHOICE_INVALID'
def _adjudication_task_id(task) -> int | None:
"""返回裁决挂接的 OT 主键:Notice 取 order_task_id,OT 取自身 id。"""
return getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
def notice_odm_options(task) -> dict[str, Any]:
"""
投影整单 ODM 逐行候选与当前用户选择;只读,不物化 Notice、不写库。
【AI 触发时机】:工作台通知准备面板需要展示「一个预约单号多个 ODM ID」的
行级候选与已选值时调用;禁止用它替代导出收敛——实际过滤由导出裁决执行。
Returns:
{odm_field_id, lines: [{snapshot_line_id, odm_values, chosen_odm_id}],
customer_odm_ids, whitelist_applied};模板不消费 odm 字段时 lines 为空列表。
"""
from app.services.shipping_notice.export import (
_adjudicate_notice_odm,
_notice_chosen_odm,
_resolve_odm_inventory_field_id,
prepare_export_match_inputs,
)
empty: dict[str, Any] = {
'odm_field_id': None,
'lines': [],
'customer_odm_ids': [],
'whitelist_applied': False,
}
# OT / Notice 都可直接投影(导出取数兼容两者);导出时再按正式链路裁决。
try:
inputs = prepare_export_match_inputs(task)
except (ValueError, AppError):
return empty
odm_field_id = (
_resolve_odm_inventory_field_id()
if (inputs['line_inventory_fields'] or inputs['header_inventory_fields']) else None
)
if odm_field_id is None:
return empty
snapshot = inputs['snapshot']
customer = db.session.get(ShippingCustomer, int(snapshot.customer_id)) if snapshot.customer_id else None
customer_odm_ids = (
[str(value or '').strip() for value in (customer.odm_ids or []) if str(value or '').strip()]
if customer is not None else []
)
try:
adjudication = _adjudicate_notice_odm(
line_values=inputs['line_values'],
inventory_lines=inputs['inventory_lines'],
match_keys=inputs['match_keys'],
odm_field_id=odm_field_id,
snapshot=snapshot,
chosen_odm_raw=_notice_chosen_odm(task),
)
except ValueError:
# 范围排除全部命中 / 选择已失效:候选投影为空,用户需先修客户数据或重选。
return {
'odm_field_id': odm_field_id,
'lines': [],
'customer_odm_ids': customer_odm_ids,
'whitelist_applied': True,
}
lines_payload = []
for row, odm_values in zip(inputs['line_values'], adjudication['per_line_odm_ids'], strict=True):
lines_payload.append({
'snapshot_line_id': row.get('__snapshot_line_id'),
'odm_values': list(odm_values),
'chosen_odm_id': adjudication['chosen_odm_id'],
})
return {
'odm_field_id': odm_field_id,
'lines': lines_payload,
'customer_odm_ids': customer_odm_ids,
'whitelist_applied': adjudication['whitelist_applied'],
}
def set_notice_odm_choice(task, *, snapshot_line_id: int, odm_id: str) -> dict[str, Any]:
"""
保存整单 ODM ID 用户选择:更新目标行的当前匹配事实,并同步同一快照文件的行。
同步范围 = 与目标行 `inventory_snapshot_id` 相同的全部 is_current 匹配行
(Header 契约是整单一个值,同文件行必须一致);校验取同步范围内各行候选的交集,
保证选择不会把其他行变成无匹配。
Args:
task: 正式 Notice 或其 OT。
snapshot_line_id: 用户编辑的冻结订单行 ID(工作台行主键)。
odm_id: 用户选定的 ODM ID。
Returns:
{task_id, odm_id, synced_line_count, odm_values}。
Raises:
AppError: 无当前匹配事实、行不存在,或所选值不在同步范围可行候选内
(SHIPPING.NOTICE_ODM_CHOICE_INVALID)。
"""
normalized = str(odm_id or '').strip()
options = notice_odm_options(task)
task_id = _adjudication_task_id(task)
if not task_id:
raise AppError(
code=_ODM_CHOICE_INVALID_CODE,
message='Shipping task is required before recording ODM choice',
http_status=409,
)
target_row = (
ShippingNoticeLineInventoryMatch.query
.filter_by(
task_id=int(task_id),
snapshot_line_id=int(snapshot_line_id or 0),
is_current=True,
)
.first()
)
if target_row is None:
raise AppError(
code=_ODM_CHOICE_INVALID_CODE,
message='No current inventory match fact for the given line',
http_status=409,
details={'snapshot_line_id': snapshot_line_id},
)
# 同步范围:与目标行关联同一快照文件的全部当前匹配行。
scope_rows = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task_id), is_current=True)
.filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id == target_row.inventory_snapshot_id)
.all()
) if target_row.inventory_snapshot_id is not None else [target_row]
lines_by_sid = {
str(item.get('snapshot_line_id')): item for item in options.get('lines') or []
}
scope_candidates: list[set[str]] = []
for row in scope_rows:
entry = lines_by_sid.get(str(row.snapshot_line_id))
if entry is not None:
scope_candidates.append({str(v).strip().casefold() for v in entry.get('odm_values') or []})
feasible: set[str] = set.intersection(*scope_candidates) if scope_candidates else set()
if not normalized or normalized.strip().casefold() not in feasible:
raise AppError(
code=_ODM_CHOICE_INVALID_CODE,
message='Selected ODM ID is not among the feasible values',
http_status=409,
details={'odm_id': normalized, 'odm_values': sorted(feasible)},
)
# 同步落库:同一快照文件的全部当前匹配行写同一选择(前后端同步语义的落库侧)。
for row in scope_rows:
row.chosen_odm_id = normalized
db.session.flush()
return {
'task_id': int(task_id),
'odm_id': normalized,
'synced_line_count': len(scope_rows),
'odm_values': sorted(feasible),
}
@@ -64,6 +64,7 @@ from app.services.shipping_notice.order_profile_value_adapter import get_value_a
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
from app.services.shipping_notice.reservation_region import (
apply_reservation_region_candidates,
resolve_candidate_line_numbers,
)
@@ -2090,14 +2091,18 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
)
decision['parsed_table_count'] = 1
decision['route_type'] = 'profile_deterministic'
# 模板确定性取值已成功,复核只针对业务归属(Reservation 专区/行校验)。
# 必须以 deterministic 携带原因码交 STP 裁 needs_review,让已解析订单
# 继续落 provisional Candidate 供复核台编辑;review_required 会被
# Worker 当作"无可信取值"丢弃,复核草稿将退化为空白手工单。
if any(order.get('reservation_region_status') == 'needs_review' for order in orders):
decision['fallback_reason_codes'] = ['reservation_region_needs_review']
return _apply_stp_route_adjudication(
decision, execution_mode='review_required', orders=orders,
decision, execution_mode='deterministic', orders=orders,
)
if decision.get('fallback_reason_codes'):
return _apply_stp_route_adjudication(
decision, execution_mode='review_required', orders=orders,
decision, execution_mode='deterministic', orders=orders,
)
decision['fallback_reason_codes'] = []
return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders)
@@ -2357,11 +2362,31 @@ def _build_approved_profile_order_result(
if candidates:
header_target = reservation_scope.get('header')
line_target = reservation_scope.get('line')
# Reservation 注释的 L#n 引用单据印刷行号(LN 列),必须按 customer_po_line_no
# 值定位逻辑行;LN 非连续(部分行已拆单)时按位置写入会错配并误报越界。
line_numbers: list[int | None] | None = None
if line_target:
ln_field_id = next(
(str(item.get('field_id') or '') for item in fields
if str(item.get('field_code') or '') == 'customer_po_line_no'),
None,
)
if ln_field_id:
line_numbers = resolve_candidate_line_numbers([
next(
(observation.get('value') for field in group.get('fields') or []
if str(field.get('field_id') or '') == ln_field_id
for observation in field.get('observations') or []),
None,
)
for group in line_groups
])
applied = apply_reservation_region_candidates(
candidates=candidates,
header_field_id=str(header_target.get('field_id') or '') if header_target else None,
line_field_id=str(line_target.get('field_id') or '') if line_target else None,
line_count=len(line_groups),
line_numbers=line_numbers,
)
if applied.header_value and header_target:
header_evidence = next((item for item in candidates if item.get('scope') == 'header'), {})
@@ -2379,9 +2404,10 @@ def _build_approved_profile_order_result(
]
if line_target:
for line_no, value in applied.line_values.items():
# line_no 已是逻辑行序号;候选里携带的是印刷行号,证据只按值回查。
line_evidence = next((
item for item in candidates
if item.get('scope') == 'line' and item.get('line_no') == line_no and item.get('value') == value
if item.get('scope') == 'line' and item.get('value') == value
), {})
line_groups[line_no - 1].setdefault('fields', []).append({'field_id': str(line_target.get('field_id') or ''), 'observations': [{
'value': value, 'document_id': int(unit.document_id),
@@ -2390,7 +2416,8 @@ def _build_approved_profile_order_result(
line_id = str(line_target.get('field_id') or '')
line_code = str(line_target.get('field_code') or '')
for missing in source_missing_fields['lines']:
if isinstance(missing, dict) and int(missing.get('line_index') or -1) == line_no - 1:
# 不能用 `or -1` 兜底:line_index 0 是合法值,会被 falsy 判断跳过。
if isinstance(missing, dict) and missing.get('line_index') == line_no - 1:
missing['field_ids'] = [field_id for field_id in missing['field_ids'] if field_id != line_id]
missing['field_codes'] = [field_code for field_code in missing['field_codes'] if field_code != line_code]
source_missing_fields['lines'] = [
@@ -1065,6 +1065,54 @@ def _queue_current_gate_hint(case: ShippingOrderReviewCase) -> dict[str, Any] |
return None
# 队列当前 Gate 活跃口径:在 _queue_current_gate_hint 活跃集合上补 queued/failed_terminal,
# 供 needs_attention 兜底取 Gate,避免终态失败的单被漏判。
_QUEUE_CURRENT_GATE_STATUSES = frozenset({
'pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal',
})
# 需要人工介入的 Gate 状态;waiting_external/running/pending/queued 属系统在办,不算需人工。
_QUEUE_ATTENTION_GATE_STATUSES = frozenset({'blocked_manual', 'blocked_retryable', 'failed_terminal'})
def _queue_gate_needs_attention(case: ShippingOrderReviewCase) -> bool:
"""
判定 Case 当前正式门禁是否需要人工介入;供队列摘要下发 needs_attention。
只读会话级批量缓存(_load_review_case_summary_batch 已预取 Execution/Gate),
零额外 SQL;当前 Gate 取 execution.current_gate_code 对应 Gate,缺失时按
sequence_no 取第一个活跃 Gate。调用方禁止据此之外再自行推断阻塞。
Args:
case: 当前复核 Case。
Returns:
当前 Gate 状态 ∈ {blocked_manual, blocked_retryable, failed_terminal} 时 True;
无 Execution / 无活跃 Gate 时 False。
"""
cache = db.session.info.get('shipping_conversation_projection_read_cache')
if not isinstance(cache, dict) or getattr(case, 'id', None) is None:
return False
execution = (cache.get('execution_by_case_id') or {}).get(int(case.id))
if execution is None:
return False
gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower()
gates = (cache.get('gates_by_execution_id') or {}).get(int(execution.id), []) or []
current = None
if gate_code:
for gate in gates:
if str(getattr(gate, 'gate_code', '') or '').strip().lower() == gate_code:
current = gate
break
if current is None:
for gate in gates:
if str(getattr(gate, 'status', '') or '').strip().lower() in _QUEUE_CURRENT_GATE_STATUSES:
current = gate
break
if current is None:
return False
return str(getattr(current, 'status', '') or '').strip().lower() in _QUEUE_ATTENTION_GATE_STATUSES
def _serialize_review_case_summary(
case: ShippingOrderReviewCase,
*,
@@ -1157,6 +1205,7 @@ def _serialize_review_case_summary(
'status': case.status,
'draft_version': int(draft.draft_version) if draft is not None else None,
'issue_count': len(draft.issue_summary_json or []) if draft is not None else 0,
'needs_attention': _queue_gate_needs_attention(case),
# Intake 解析失败没有 Candidate,恢复必须从当前阶段卡调用原 SNI retry API。
# 其它 Intake 状态(尤其 parsing/cancelled)不得由前端显示或猜测重试。
'available_actions': (
@@ -1377,6 +1426,28 @@ def _load_review_case_summary_batch(
}
def _queue_summary_bucket(item: dict[str, Any]) -> str:
"""
队列计数桶归类;优先级与前端队列图标一致:需人工 > 终态完成 > 进行中。
桶是"处置去向"粗归类,与五态图标非一一映射(non_order 计入 completed,
图标为中性别灰○);needs_attention(门禁阻塞)恒优先于 completed,
避免阻塞单被计数成"完成"。
Args:
item: 队列 item 投影(含 status / needs_attention / lifecycle_stage)。
Returns:
'needs_action' | 'completed' | 'processing'。
"""
status = str(item.get('status') or '')
if status in ('unreviewed', 'draft', 'ready', 'quality_issue') or item.get('needs_attention'):
return 'needs_action'
if status in ('non_order', 'closed', 'completed') or str(item.get('lifecycle_stage') or '') == 'upload_complete':
return 'completed'
return 'processing'
def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str, Any]:
"""返回会话级文件当前队列;Run/Case 历史均不参与主队列平铺。"""
if not runs:
@@ -1444,10 +1515,11 @@ def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str,
db.session.info.pop('shipping_conversation_projection_read_cache', None)
else:
db.session.info['shipping_conversation_projection_read_cache'] = previous_cache
buckets = [_queue_summary_bucket(item) for item in items]
counts = {
'total': len(items),
'needs_action': sum(1 for item in items if item['status'] in ('unreviewed', 'draft', 'ready')),
'processing': sum(1 for item in items if item['status'] in ('confirming', 'reparse_pending')),
'completed': sum(1 for item in items if item['status'] in ('confirmed', 'non_order', 'quality_issue')),
'needs_action': buckets.count('needs_action'),
'processing': buckets.count('processing'),
'completed': buckets.count('completed'),
}
return {'conversation_id': conversation_id, 'summary': counts, 'items': items}
@@ -210,6 +210,17 @@ def project_reservation_onto_validation_evidence(
header_field_id=str((reservation_scope.get('header') or {}).get('field_id') or '') or None,
line_field_id=str((reservation_scope.get('line') or {}).get('field_id') or '') or None,
line_count=len(projected['lines']),
line_numbers=resolve_candidate_line_numbers([
next(
(
field.get('normalized_value') or field.get('raw_value')
for field in line.get('fields') or []
if isinstance(field, dict) and str(field.get('field_code') or '') == 'customer_po_line_no'
),
None,
)
for line in projected['lines']
]),
)
header_target = reservation_scope.get('header')
if applied.header_value and header_target:
@@ -247,20 +258,51 @@ def project_reservation_onto_validation_evidence(
return projected
def resolve_candidate_line_numbers(values: list[object]) -> list[int | None] | None:
"""把按逻辑行顺序给出的 Customer PO 行号(LN 列)取值整理为候选定位表。
核心逻辑:Reservation 注释里的 ``L#n`` 引用的是单据上印刷的行号,必须按 LN 值
定位逻辑行;LN 非连续(如部分行已拆单)时按位置写入会错配并误报越界。
任一行解析出有效行号才返回定位表;完全没有行号取值时返回 None,
由调用方保持历史位置序行为以兼容无 LN 字段的旧 Schema。
"""
numbers: list[int | None] = []
has_number = False
for value in values:
try:
number = int(str(value).strip())
except (TypeError, ValueError):
number = None
else:
has_number = True
numbers.append(number)
return numbers if has_number else None
def apply_reservation_region_candidates(
*, candidates: list[dict[str, object]], header_field_id: str | None,
line_field_id: str | None, line_count: int,
line_numbers: list[int | None] | None = None,
) -> ReservationRegionApplication:
"""按固定契约将专用区域候选归属到订单头和逻辑明细行。
无行号 Reservation 是整单事实,最多接受一个不同值;带行号的值仅在
Schema 启用明细 Reservation 字段时写入对应逻辑行。冲突、越界行号或
多个不同整单值必须转人工复核,不能静默猜测。
``line_numbers`` 为各逻辑行的 Customer PO 行号(LN 列,1 起始);提供时候选
``line_no`` 按 LN 值定位逻辑行,被引用行号不存在则记 ``line_out_of_range``。
未提供时保持历史位置序写入,仅兼容无 LN 字段的旧 Schema。
"""
_ = header_field_id
header_values: list[str] = []
line_values_by_no: dict[int, list[str]] = {}
reasons: list[str] = []
line_target_by_number: dict[int, int] = {}
if line_numbers is not None:
for index, number in enumerate(line_numbers):
if isinstance(number, int) and number > 0:
line_target_by_number.setdefault(number, index + 1)
for item in candidates:
if not isinstance(item, dict):
continue
@@ -277,6 +319,8 @@ def apply_reservation_region_candidates(
except (TypeError, ValueError):
reasons.append('line_out_of_range')
continue
if line_numbers is not None:
line_no = line_target_by_number.get(line_no, 0)
if line_no < 1 or line_no > line_count:
reasons.append('line_out_of_range')
continue
@@ -1001,6 +1001,30 @@ def _build_stage_context(
if str(item.get('source_code') or '').strip()
]
# [STEP] 整单 ODM 裁决投影:一个预约单号多个 ODM ID 时,逐行下发候选与已选
# (同一快照文件的行同步使用同一值);投影失败不阻断工作台渲染,仅退化为无 ODM 入口。
try:
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
odm_projection = notice_odm_options(task)
except Exception:
odm_projection = {}
odm_lines_by_sid = {
str(item.get('snapshot_line_id')): item for item in odm_projection.get('lines') or []
}
for prep_line in preparation_lines:
entry = odm_lines_by_sid.get(str(prep_line.get('snapshot_line_id')))
if entry is None:
continue
prep_line['odm_values'] = list(entry.get('odm_values') or [])
prep_line['chosen_odm_id'] = entry.get('chosen_odm_id')
prep_line['odm_conflict'] = len(entry.get('odm_values') or []) > 1
odm_options_payload = {
'conflict': any(bool(item.get('odm_conflict')) for item in preparation_lines),
'customer_odm_ids': list(odm_projection.get('customer_odm_ids') or []),
'whitelist_applied': bool(odm_projection.get('whitelist_applied')),
}
artifact = None
attempts = []
if getattr(task, 'id', None):
@@ -1052,6 +1076,8 @@ def _build_stage_context(
],
'resolved_source_codes': list(facts.get('resolved_ok_source_codes') or []),
'source_options': source_options,
# 整单 ODM 裁决:conflict=True 时前端展示候选下拉,选择后可重试生成 Excel。
'odm_options': odm_options_payload,
'inventory_file': {
'available': downloadable_inventory is not None,
'file_name': downloadable_inventory[1] if downloadable_inventory is not None else None,
@@ -0,0 +1,54 @@
"""customer odm scope: add odm_ids to shipping_customers
Revision ID: aa11bb22cc33
Revises: fb26bc033d27
Create Date: 2026-09-16 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "aa11bb22cc33"
down_revision = "fb26bc033d27"
branch_labels = None
depends_on = None
def _add_column(insp, table: str, column: sa.Column) -> None:
if table not in set(insp.get_table_names()):
return
columns = {col["name"] for col in insp.get_columns(table)}
if column.name not in columns:
with op.batch_alter_table(table, schema=None) as batch_op:
batch_op.add_column(column)
def _drop_column(insp, table: str, name: str) -> None:
if table not in set(insp.get_table_names()):
return
columns = {col["name"] for col in insp.get_columns(table)}
if name in columns:
with op.batch_alter_table(table, schema=None) as batch_op:
batch_op.drop_column(name)
def upgrade():
insp = sa.inspect(op.get_bind())
_add_column(
insp,
"shipping_customers",
sa.Column("odm_ids", sa.JSON(), nullable=True),
)
_add_column(
insp,
"shipping_notice_line_inventory_matches",
sa.Column("chosen_odm_id", sa.String(length=64), nullable=True),
)
def downgrade():
insp = sa.inspect(op.get_bind())
_drop_column(insp, "shipping_notice_line_inventory_matches", "chosen_odm_id")
_drop_column(insp, "shipping_customers", "odm_ids")
@@ -29,6 +29,14 @@ RESERVATION_DEFINITION = {
],
}
LN_RESERVATION_DEFINITION = {
'reservation_id_region': {'region': {'x0': .1, 'y0': .1, 'x1': .9, 'y1': .2}, 'page_no': 1},
'fields': DEFINITION['fields'] + [
{'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line', 'required': True},
{'field_id': 'ln', 'field_code': 'customer_po_line_no', 'scope': 'line'},
],
}
def _row(po: str, part: str) -> dict:
return {'status': 'parsed', 'issues': [], 'fields': [
@@ -38,6 +46,12 @@ def _row(po: str, part: str) -> dict:
]}
def _ln_row(po: str, part: str, ln: str) -> dict:
row = _row(po, part)
row['fields'].append({'field_id': 'ln', 'value': ln, 'quote': ln})
return row
def _page_glyphs(*lines: str) -> list[dict]:
"""构造跨页 Reservation 路由回归所需的最小坐标文字。"""
glyphs = []
@@ -152,6 +166,63 @@ def test_approved_pdf_marks_conflicting_reservation_region_for_review():
assert (orders or [])[0]['reservation_region_status'] == 'needs_review'
def test_approved_pdf_maps_reservation_by_printed_ln_when_ln_non_contiguous():
"""PO_6075309 回归:LN=1/2/4/5 非连续时 L#n 必须按 LN 值落行,整单不转复核。
关键断言:L#4/L#5 分别写入 LN=4/LN=5 行(旧位置序会把 L#4 错配到 LN=5 并把
L#5 误报 line_out_of_range);行级 reservation 已全部归属后 source_missing_fields
不得残留 line_index 0 的假缺失(``or -1`` falsy bug)。
"""
orders, reason = _build_approved_profile_order_result(
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
definition=LN_RESERVATION_DEFINITION,
table={'rows': [
_ln_row('PO-1', 'P-1', '1'), _ln_row('PO-1', 'P-2', '2'),
_ln_row('PO-1', 'P-4', '4'), _ln_row('PO-1', 'P-5', '5'),
]},
reservation_region_candidates=[
{'value': '1000159370', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation L#1: 1000159370'},
{'value': '1000159366', 'scope': 'line', 'line_no': 2, 'raw_text': 'Reservation L#2: 1000159366'},
{'value': '1000159379', 'scope': 'line', 'line_no': 4, 'raw_text': 'Reservation L#4: 1000159379'},
{'value': '1000159236', 'scope': 'line', 'line_no': 5, 'raw_text': 'Reservation L#5: 1000159236'},
],
)
assert reason is None
order = (orders or [])[0]
assert order.get('reservation_region_status') != 'needs_review'
assert 'source_missing_fields' not in order
expected_by_ln = {'1': '1000159370', '2': '1000159366', '4': '1000159379', '5': '1000159236'}
for line in order['lines']:
ln = next(item['observations'][0]['value'] for item in line['fields'] if item['field_id'] == 'ln')
assert any(
item['field_id'] == 'line-reservation' and item['observations'][0]['value'] == expected_by_ln[ln]
for item in line['fields']
)
def test_approved_pdf_keeps_reservation_review_when_referenced_ln_row_is_missing():
"""被引用的印刷行号在解析行中不存在时必须转复核,不得按位置静默写入。"""
orders, reason = _build_approved_profile_order_result(
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
definition=LN_RESERVATION_DEFINITION,
table={'rows': [_ln_row('PO-1', 'P-1', '1'), _ln_row('PO-1', 'P-2', '2')]},
reservation_region_candidates=[
{'value': '1000159236', 'scope': 'line', 'line_no': 5, 'raw_text': 'Reservation L#5: 1000159236'},
],
)
assert reason is None
order = (orders or [])[0]
assert order['reservation_region_status'] == 'needs_review'
assert order['reservation_region_review_reasons'] == ['line_out_of_range']
# LN=1/LN=2 行无对应候选,reservation 保持缺失供人工补录。
assert all(
not any(item['field_id'] == 'line-reservation' for item in line['fields'])
for line in order['lines']
)
def test_enabled_reservation_region_reads_vendor_comments_across_pages():
"""已标注专区时,正式路由不能使用旧 page_no/region,必须跨页按文本锚点读取。"""
result = _reservation_region_candidates(
@@ -896,3 +896,260 @@ def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch
with pytest.raises(RuntimeError, match='commit failed'):
_commit_generated_export(str(path))
assert not path.exists()
def _build_multi_odm_notice(
*, tmp_path, odm_values=None, customer_odm_ids=None, choice_odm=None, line_specs=None,
):
"""
构造「订单行命中多个 ODM ID」的整单导出场景;须在 app_context 内调用。
Args:
odm_values: 单订单行场景下库存行命中的 ODM 值列表。
line_specs: 多订单行场景 [{'part': 料号, 'odm_values': [...]}];提供时忽略 odm_values。
customer_odm_ids: 客户数据的 ODM ID 范围(None = 不限定)。
choice_odm: 整单用户选择(写入 OT.chosen_odm_id)
Returns:
(notice, customer)。
"""
from tests.conftest import confirm_test_customer_resolution
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
db.session.add(schema); db.session.flush()
part = _lookup_standard_fields('part_number')['part_number']
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
db.session.add(version); db.session.flush()
draft = excel_template.create_draft(_workbook_upload(), {
'template_code': 'ODMSCOPE', 'display_name': 'OdmScope',
'definition': {'filename_pattern': '{task_no}.xlsx', 'mappings': [
{'sheet': 'Detail', 'row_mode': 'header', 'start_row': 2, 'target_column': 1, 'source_kind': 'inventory_field', 'source_key': _inventory_field_id('odm_id'), 'formatter': 'text'},
]},
}, actor_id=None)
published = excel_template.publish(draft['id'], actor_id=None)
parsing = ShippingInventoryParsingProfile(
profile_code='ODMSCOPE', display_name='OdmScope', version=1, status='published', file_format='xlsx',
definition_json={'field_mapping': {_inventory_field_id('part_number'): 'Part No.', _inventory_field_id('odm_id'): 'ODM ID'}, 'match_keys': [{'order_field_id': part.id, 'inventory_field_id': _inventory_field_id('part_number')}]},
)
login = ShippingRpaProfile(
profile_code='ODMSCOPE', display_name='OdmScope', connector_type='dbs', login_url='https://invalid',
login_config_json={'auth_mode': 'password'},
)
db.session.add_all([parsing, login]); db.session.flush()
db.session.add(ShippingInventorySource(
source_code='ODMSCOPE', display_name='OdmScope', connector_type='dbs', rpa_profile_id=login.id,
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
))
customer = ShippingCustomer(
standard_name='ODM范围客户', short_code='ODMSC', status='active',
odm_ids=list(customer_odm_ids) if customer_odm_ids is not None else None,
)
db.session.add(customer); db.session.flush()
ot = ShippingOrderTask(task_no='OT-ODMSCOPE', user_id=1, status='ready', current_step='customer_review')
db.session.add(ot); db.session.flush()
extraction = ShippingOrderExtraction(
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted',
)
db.session.add(extraction); db.session.flush()
specs = line_specs or [{'part': 'PN-A', 'odm_values': odm_values}]
snapshot_lines = []
for index, spec in enumerate(specs, start=1):
order_line = ShippingOrderLine(extraction_id=extraction.id, position=index, line_no=index)
db.session.add(order_line); db.session.flush()
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=order_line.id, field_id=part.id,
decision_status='accepted', resolved_value_json=spec['part'],
)
db.session.add(decision); db.session.flush()
db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=order_line.id, field_id=part.id,
value_text=spec['part'], decision_id=decision.id,
))
snapshot_lines.append((index, part.id, spec['part'], 1, f'100000000{index}'))
confirm_test_customer_resolution(ot, customer=customer, extraction=extraction)
inventory_rows = []
for spec in specs:
for odm in spec['odm_values']:
inventory_rows.append({_inventory_field_id('part_number'): spec['part'], _inventory_field_id('odm_id'): odm})
inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-ODMSCOPE', user_id=None, source_file_name='odm-scope.xlsx',
storage_path=str(tmp_path / 'odm-scope.xlsx'),
inventory_lines_json=inventory_rows,
line_count=len(inventory_rows), share_mode='task_only', warehouse_id='DUB', source_code='ODMSCOPE',
snapshot_status='ready',
)
db.session.add(inventory_file); db.session.flush()
snapshot = _freeze_export_snapshot(
ot, extraction, version,
lines=snapshot_lines,
customer_id=customer.id, inventory_file_id=inventory_file.id,
)
notice = _materialize_export_notice(
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='ODMSCOPE', notice_no='TASK-ODMSCOPE',
)
if choice_odm is not None:
for match in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(ot.id), is_current=True).all():
match.chosen_odm_id = choice_odm
db.session.flush()
return notice, customer
def test_export_narrows_odm_by_customer_range(app, tmp_path):
"""客户 ODM ID 范围非空时,导出只取范围内库存行;范围命中唯一值写入表头。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['odm-2'],
)
path, _filename_value, _artifact = generate_shipment_excel(task)
workbook = load_workbook(path, data_only=True)
try:
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
finally:
workbook.close()
def test_export_odm_range_excluding_all_raises_specific_error(app, tmp_path):
"""客户范围把全部命中排除时,必须报指向客户数据的可行动错误而非「没有匹配」。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['ODM-9'],
)
with pytest.raises(ValueError, match='不在客户数据维护的 ODM ID 范围'):
generate_shipment_excel(task)
def test_export_applies_notice_odm_choice(app, tmp_path):
"""整单用户选择优先于多值冲突;选择经 casefold 归一后命中库存行。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], choice_odm='odm-2',
)
path, _filename_value, _artifact = generate_shipment_excel(task)
workbook = load_workbook(path, data_only=True)
try:
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
finally:
workbook.close()
def test_export_auto_narrows_unique_feasible_odm_without_manual_choice(app, tmp_path):
"""无范围、无选择时,整单唯一可行 ODM(各行命中交集恰一个)自动收敛。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, line_specs=[
{'part': 'PN-A', 'odm_values': ['ODM-1', 'ODM-2']},
{'part': 'PN-B', 'odm_values': ['ODM-2']},
])
path, _filename_value, _artifact = generate_shipment_excel(task)
workbook = load_workbook(path, data_only=True)
try:
assert workbook['Detail'].cell(2, 1).value == 'ODM-2'
finally:
workbook.close()
def test_export_keeps_conflict_when_odm_scope_cannot_decide(app, tmp_path):
"""无范围、无选择且多值并存时维持折叠冲突阻断,等待用户整单选择。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'])
with pytest.raises(ValueError, match='库存字段“ODM 编号”'):
generate_shipment_excel(task)
def test_notice_odm_options_and_choice_roundtrip(app, tmp_path):
"""整单候选按客户范围逐行投影;合法选择落库并回显,非法选择有明确错误。"""
from app.core.errors import AppError
from app.services.shipping_notice.notice_odm_choice_service import (
notice_odm_options,
set_notice_odm_choice,
)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, customer = _build_multi_odm_notice(
tmp_path=tmp_path, odm_values=['ODM-1', 'ODM-2'], customer_odm_ids=['ODM-2', 'ODM-3'],
)
options = notice_odm_options(task)
# [断言] 逐行候选是客户范围过滤后的集合,且保留库存行原始大小写。
assert options['whitelist_applied'] is True
assert options['customer_odm_ids'] == ['ODM-2', 'ODM-3']
assert len(options['lines']) == 1
assert options['lines'][0]['odm_values'] == ['ODM-2']
assert options['lines'][0]['chosen_odm_id'] is None
snapshot_line_id = options['lines'][0]['snapshot_line_id']
result = set_notice_odm_choice(task, snapshot_line_id=snapshot_line_id, odm_id='ODM-2')
assert result['odm_id'] == 'ODM-2'
matches = ShippingNoticeLineInventoryMatch.query.filter_by(
task_id=int(task.order_task_id), is_current=True,
).all()
assert matches and {m.chosen_odm_id for m in matches} == {'ODM-2'}
options = notice_odm_options(task)
assert options['lines'][0]['chosen_odm_id'] == 'ODM-2'
with pytest.raises(AppError) as exc:
set_notice_odm_choice(task, snapshot_line_id=snapshot_line_id, odm_id='ODM-9')
assert getattr(exc.value, 'code', '') == 'SHIPPING.NOTICE_ODM_CHOICE_INVALID'
def test_notice_odm_choice_syncs_same_snapshot_file_lines(app, tmp_path):
"""同一快照文件的行:改任一行 ODM ID,其余行同步落库同一选择。"""
from app.services.shipping_notice.notice_odm_choice_service import (
notice_odm_options,
set_notice_odm_choice,
)
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, line_specs=[
{'part': 'PN-A', 'odm_values': ['ODM-1', 'ODM-2']},
{'part': 'PN-B', 'odm_values': ['ODM-2', 'ODM-3']},
])
options = notice_odm_options(task)
# [断言] 每行有自己的候选;同文件两行的可行集=交集。
by_sid = {str(item['snapshot_line_id']): item for item in options['lines']}
assert len(by_sid) == 2
assert options['lines'][0]['odm_values'] == ['ODM-1', 'ODM-2']
target_sid = options['lines'][0]['snapshot_line_id']
result = set_notice_odm_choice(
task, snapshot_line_id=target_sid, odm_id='ODM-2',
)
# [断言] 同步范围=同一快照文件:两行当前匹配行写同一选择。
assert result['synced_line_count'] == 2
matches = ShippingNoticeLineInventoryMatch.query.filter_by(
task_id=int(task.order_task_id), is_current=True,
).all()
assert len(matches) == 2
assert {m.chosen_odm_id for m in matches} == {'ODM-2'}
options = notice_odm_options(task)
assert all(item['chosen_odm_id'] == 'ODM-2' for item in options['lines'])
def test_notice_odm_options_empty_when_template_ignores_odm(app, tmp_path):
"""模板不消费 odm 字段时投影为空候选,不产生任何选择入口。"""
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
task, _customer = _build_multi_odm_notice(tmp_path=tmp_path, odm_values=['ODM-1'])
options = notice_odm_options(task)
assert options['odm_field_id'] is not None
assert options['lines'] and options['lines'][0]['odm_values'] == ['ODM-1']
@@ -212,6 +212,35 @@ def test_reservation_region_requires_review_when_numbered_value_has_no_line_targ
assert applied.review_reasons == ('line_field_unavailable',)
def test_reservation_region_matches_line_by_printed_ln_number_not_position():
"""LN 非连续(部分行已拆单)时必须按 LN 值定位逻辑行,禁止位置错配或误报越界。"""
applied = apply_reservation_region_candidates(
candidates=extract_reservation_from_region_text(
"Reservation L#1: 1000159370\nReservation L#2: 1000159366\n"
"Reservation L#4: 1000159379\nReservation L#5: 1000159236"
),
header_field_id='header-reservation', line_field_id='line-reservation',
line_count=4, line_numbers=[1, 2, 4, 5],
)
assert applied.needs_review is False
# 键是逻辑行序号:L#4→第 3 行(LN=4)、L#5→第 4 行(LN=5)。
assert applied.line_values == {1: '1000159370', 2: '1000159366', 3: '1000159379', 4: '1000159236'}
def test_reservation_region_flags_review_when_referenced_ln_number_is_absent():
"""被引用的印刷行号在解析行中不存在时必须转复核,不得静默按位置写入。"""
applied = apply_reservation_region_candidates(
candidates=extract_reservation_from_region_text("Reservation L#5: 1000159236"),
header_field_id='header-reservation', line_field_id='line-reservation',
line_count=2, line_numbers=[1, 2],
)
assert applied.line_values == {}
assert applied.needs_review is True
assert applied.review_reasons == ('line_out_of_range',)
def test_reservation_gate_blocks_empty_and_malformed_order_lines():
"""空订单或畸形行都不能被视为 Reservation 门禁通过。"""
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
@@ -2962,3 +2962,254 @@ def test_run_lineage_root_walk_loads_parent_runs_without_frozen_snapshot_columns
for statement in point_loads:
assert 'input_snapshot_json' not in statement
assert 'result_json' not in statement
def test_review_queue_flags_blocked_gate_cases_as_needs_attention(app):
"""门禁 blocked_manual(如库存缺口)的已建任务单,队列必须下发 needs_attention=True。"""
from app.models import ShippingProcessExecution, ShippingProcessGate
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-NEEDS-ATTN')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-NEEDS-ATTN',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-needs-attn',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-ATTN',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
task = ShippingOrderTask(
task_no='OT-REVIEW-QUEUE-NEEDS-ATTN',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
status='processing',
stage='inventory_preparation',
)
db.session.add(task)
db.session.flush()
execution = ShippingProcessExecution(
execution_no='SPE-REVIEW-QUEUE-NEEDS-ATTN',
task_id=task.id,
review_case_id=case.id,
status='active',
current_gate_code='inventory_sufficiency',
)
db.session.add(execution)
db.session.flush()
db.session.add(ShippingProcessGate(
execution_id=execution.id,
gate_code='inventory_sufficiency',
sequence_no=16,
status='blocked_manual',
))
task.active_process_execution_id = execution.id
case.status = 'confirmed'
case.confirmed_task_id = task.id
db.session.commit()
queue = serialize_review_queue([run])
# 关键断言:库存缺口类门禁阻塞必须在队列可见,不再只依赖当前单的完整详情。
assert queue['items'][0]['needs_attention'] is True
assert queue['items'][0]['lifecycle_stage'] == 'fulfillment_prep'
# 关键断言:needs_attention 抬升 summary needs_action 桶,不得被计成完成/在办。
assert queue['summary'] == {'total': 1, 'needs_action': 1, 'processing': 0, 'completed': 0}
def test_review_queue_waiting_external_gate_is_not_needs_attention(app):
"""RPA 外部等待(waiting_external)属于系统在办,不得标记 needs_attention。"""
from app.models import ShippingProcessExecution, ShippingProcessGate
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-WAIT-EXT')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-WAIT-EXT',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-wait-ext',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-WAIT',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
task = ShippingOrderTask(
task_no='OT-REVIEW-QUEUE-WAIT-EXT',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
status='processing',
stage='freight_uploading',
)
db.session.add(task)
db.session.flush()
execution = ShippingProcessExecution(
execution_no='SPE-REVIEW-QUEUE-WAIT-EXT',
task_id=task.id,
review_case_id=case.id,
status='waiting_external',
current_gate_code='freight_upload_rpa',
)
db.session.add(execution)
db.session.flush()
db.session.add(ShippingProcessGate(
execution_id=execution.id,
gate_code='freight_upload_rpa',
sequence_no=18,
status='waiting_external',
))
task.active_process_execution_id = execution.id
case.status = 'confirmed'
case.confirmed_task_id = task.id
db.session.commit()
item = serialize_review_queue([run])['items'][0]
# 关键断言:外部等待是在办不是待办,图标应走进行中而非需人工。
assert item['needs_attention'] is False
def test_review_queue_without_execution_is_not_needs_attention(app):
"""已建任务但尚无 Execution(或缓存未命中)时,needs_attention 必须为 False。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-NO-EXEC')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-NO-EXEC',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-no-exec',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-NOEXEC',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
task = ShippingOrderTask(
task_no='OT-REVIEW-QUEUE-NO-EXEC',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
status='processing',
stage='inventory_preparation',
)
db.session.add(task)
db.session.flush()
case.status = 'confirmed'
case.confirmed_task_id = task.id
db.session.commit()
item = serialize_review_queue([run])['items'][0]
# 关键断言:无门禁事实时不臆造需人工标志。
assert item['needs_attention'] is False
def test_review_queue_summary_counts_terminal_stage_as_completed(app):
"""OT.stage=completed(通知完成)的已建任务单计入 completed,不再计入 processing。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-DONE')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-SUM-DONE',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-sum-done',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-SUMDONE',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
task = ShippingOrderTask(
task_no='OT-REVIEW-QUEUE-SUM-DONE',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
status='processing',
stage='completed',
)
db.session.add(task)
db.session.flush()
case.status = 'confirmed'
case.confirmed_task_id = task.id
db.session.commit()
summary = serialize_review_queue([run])['summary']
# 关键断言:summary 与五态图标同口径——confirmed+终态=completed 而非 processing。
assert summary['total'] == 1
assert summary['completed'] == 1
assert summary['processing'] == 0
assert summary['needs_action'] == 0
def test_review_queue_summary_counts_quality_issue_as_needs_action(app):
"""quality_issue(文件质量异常)从 completed 改归 needs_action,与黄⚠图标一致。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-QI')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-SUM-QI',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-sum-qi',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-SUMQI',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
case.status = 'quality_issue'
db.session.commit()
summary = serialize_review_queue([run])['summary']
# 关键断言:质量异常是待办不是完成。
assert summary['needs_action'] == 1
assert summary['completed'] == 0
assert summary['processing'] == 0
def test_review_queue_summary_counts_plain_confirmed_as_processing(app):
"""已建任务、无阻塞、非终态的 confirmed 单计入 processing(对应转圈图标)。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-PROC')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-SUM-PROC',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-sum-proc',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-SUMPROC',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
task = ShippingOrderTask(
task_no='OT-REVIEW-QUEUE-SUM-PROC',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
status='processing',
stage='inventory_preparation',
)
db.session.add(task)
db.session.flush()
case.status = 'confirmed'
case.confirmed_task_id = task.id
db.session.commit()
summary = serialize_review_queue([run])['summary']
# 关键断言:已创建任务是在办不是完成。
assert summary['processing'] == 1
assert summary['completed'] == 0
assert summary['needs_action'] == 0
+182 -3
View File
@@ -699,7 +699,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
**阶段 1 历史结论(2026-07-21)**:Run 锁定版本的完整 `definition_json` 已成为确定性订单表格解析的唯一业务配置来源。解析器只使用已启用字段的 `field_code + display_name + aliases` 编译冻结表头契约,不再维护业务别名常量,不读取当前 published 版本,也不在缺少契约时猜测表头。保存草稿和发布版本都会拒绝标准化后跨字段别名碰撞,并拒绝把 Allocation ID、Parent Allocation ID、Commodity Group ID、Supplier Code、UUID、Internal ID 配置为 Reservation ID 表头。同一字段命中多列时不静默选首列,而是记录 `deterministic_table_issues` 并进入复核。后端不再扫描任意单元格猜 Reservation ID,不把文档级 Reservation 广播到所有明细行,也不会为 Schema 未启用的 UOM、币种、金额等字段注入默认值或派生值。冻结的 retired 版本继续按自身别名解析,上传预处理若在任务边界选择当前 published Schema,也只生成提示,不替代正式 Run 的冻结真值。
**Reservation ID 专用证据区域(2026-08-25)**:管理员在同一模板画布圈选唯一的 `reservation_id_region`(区域坐标与页码),不配置 JSON、来源映射、拆分规则或 Header/Line 归属。后端只从该区域内带 `Reservation` 语义的 5/10 位数字提取候选:无行号的值写入 `header.reservation_id`,并由既有有效值规则作为所有未覆盖明细的默认 Reservation;`Line N` / `for line N` 的值仅写入第 N 个逻辑明细并覆盖默认值。多个不同整单值、同一行不同值、越界行号或 Schema 未启用行字段时转 Review;普通数量、客户号等无 Reservation 标签数字一律忽略。区域页可不同于明细页,正式解析、画布预览和盲测共用同一解析/归属契约;XFA 拆分规则仍仅负责 datasets 结构取值,不能代替本能力。
**Reservation ID 专用证据区域(2026-08-25)**:管理员在同一模板画布圈选唯一的 `reservation_id_region`(区域坐标与页码),不配置 JSON、来源映射、拆分规则或 Header/Line 归属。后端只从该区域内带 `Reservation` 语义的 5/10 位数字提取候选:无行号的值写入 `header.reservation_id`,并由既有有效值规则作为所有未覆盖明细的默认 Reservation;`Line N` / `for line N` / `L#N` 的值按 Customer PO 行号(`customer_po_line_no`,LN 列)定位对应逻辑明细并覆盖默认值(**2026-09-16 修订**:此前按"第 N 个逻辑明细"位置写入,LN 非连续——如部分行已拆到其他 PO——时会错配行归属并把存在的行号误报越界;解析行缺少 LN 取值时才回退位置序以兼容无 LN 字段的旧 Schema)。多个不同整单值、同一行不同值、被引用行号不存在或 Schema 未启用行字段时转 Review;普通数量、客户号等无 Reservation 标签数字一律忽略。区域页可不同于明细页,正式解析、画布预览和盲测共用同一解析/归属契约;XFA 拆分规则仍仅负责 datasets 结构取值,不能代替本能力。**带复核原因的确定性订单必须保留(2026-09-16)**:Reservation 专区/行校验触发 `needs_review` 时以 `deterministic` 携带原因码交 STP 裁决,已解析订单继续落 provisional Candidate 供复核台编辑;不得以 `review_required` 丢弃取值导致复核草稿空白。
**阶段 1 历史 Dify 配置**:此段不再适用订单抽取。当前无需为订单抽取配置画布、Prompt、Start/End 变量、Code 节点或 `execution_manifest`;Schema 别名只在 HXOPS 管理端维护。
@@ -2032,7 +2032,7 @@ pip --version
cd C:\HxopsRpaTest
python -m pip install --upgrade pip
python -m pip install playwright openpyxl pyyaml
python -m pip install playwright openpyxl pyyaml cryptography
python -m playwright install chromium
```
@@ -2868,6 +2868,166 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui
- 生产 Windows RPA 脚本
- 上传成功 / 失败回执样例
### 1.9 收料报表 RPA 共享部署(Windows RPA + Ubuntu 后端)
> 本节是收料报表 RPA(独立 Windows Worker)的部署手册,章节结构与 `1.5` 库存导出 RPA 对应。安全提示与 `1.5` 相同:示例中的 IP、账号、密码、API Key 均为占位符,请在各环境本地替换为实际值,**禁止将真实密码/密钥写入仓库或提交到 Git**。
> 前置条件:已按 `1.5.2` 至 `1.5.10` 完成同一台 Windows RPA 主机、`hxops-rpa-test-data` / `hxops-rpa-prod-data` SMB 共享、Ubuntu 挂载与后端容器挂载。收料**不新建共享、不新建挂载**,只在既有共享下增加专用子目录、独立 Worker 与独立回调。
> Worker 脚本层速查另见 [scripts/rpa/README.md](../../../scripts/rpa/README.md) 顶部「收料 RPA(独立 Worker)」;本节是部署权威来源。
#### 1.9.1 与库存 RPA 的边界和目录规划
**与库存 RPA 完全一致、直接复用(不重复执行)**:
- Windows RPA 主机、Python 3.12、Playwright Chromium、`hxops_share` 共享账号、两个 SMB 共享与 Ubuntu 挂载(`1.5.2`–`1.5.8`)。
- DPAPI Secret 文件(`1.5.10` 的 `new_rpa_worker_secret.ps1`,字段为 `ToolApiKey` + `CredentialKey`):收料启动脚本读取**同一格式、同一文件**,无需新建收料 Secret。
- Worker `-ApiBase` 口径与 `1.5.10` 相同:Docker Compose 部署填前端 nginx 网关地址(如 `http://<host>:8890`),以 `{base}/api/...` 可达为准。
**收料专用、不得与库存混用**:
| 项 | 库存 RPA | 收料 RPA |
| --- | --- | --- |
| Worker | `scripts\rpa\inventory\inventory_rpa_worker.py` | `scripts\rpa\receipt\receipt_rpa_worker.py` |
| 启动脚本 | `inventory\start_inventory_worker.ps1` | `receipt\start_receipt_worker.ps1` |
| trigger 目录 | `data\inventory_triggers` | `data\freight_receipt_rpa\receipt_triggers` |
| drop 目录 | `data\inventory_drop` | `data\freight_receipt_rpa\receipt_drop` |
| 回调端点 | `/api/shipping-notice/rpa/inventory-batch-ready` | `/api/shipping-notice/rpa/receipt-batch-ready` |
| 心跳与哨兵 | 必需,触发前在线检查 fail-fast | **无**:收料 Worker 不发心跳、不写 `.hxops_rpa_shared_mount` |
| 结果归属 | 库存快照/库存匹配 | MinIO 原样归档 + 企微投递,绝不进入库存链路 |
路径对应关系(测试环境;正式环境把 `Test` / `test-data` 换成 `Prod` / `prod-data`):
```text
Windows RPA:C:\HxopsRpaTest\data\freight_receipt_rpa\receipt_triggers
Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers
Windows RPA:C:\HxopsRpaTest\data\freight_receipt_rpa\receipt_drop
Ubuntu 后端:/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_drop
```
浏览器 Profile:收料 Worker 在 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR`(收料启动脚本默认指向 `<WorkerRoot>\data\shipping_notice\freight_rpa\browser_profile`)下,为每个 `connector + profile + login_url` 分组创建 `receipt_*` 临时目录,组处理完立即删除;不保留跨排程登录会话。与库存 Worker 的 `run_*` 一次性 Profile、`{connector}__{profile}_session` 长期会话目录互不影响。
#### 1.9.2 Windows RPA 主机:部署收料 Worker
在既有 test/prod WorkerRoot 下追加收料专用目录:
```powershell
foreach ($root in @("C:\HxopsRpaTest", "C:\HxopsRpaProd")) {
New-Item -ItemType Directory -Force "$root\data\freight_receipt_rpa\receipt_triggers"
New-Item -ItemType Directory -Force "$root\data\freight_receipt_rpa\receipt_drop"
New-Item -ItemType Directory -Force "$root\data\freight_receipt_rpa\logs"
}
```
`receipt_rpa_worker.py` 启动时按「所在目录必须同时存在 `connectors/`、`common/`、`inventory/`、`receipt/` 子目录」定位 RPA 根目录,因此必须复制**整个** `scripts\rpa`(首次部署 `1.5.2` 已覆盖;升级时同样整目录同步,保持 Worker、driver 与公共模块同一版本),不能只复制 `receipt\` 子目录。
依赖与 `1.5.4` 相同,另需 `cryptography`(解密 RPA Profile 加密凭据;库存 Worker 同样依赖,新增部署时两个 Worker 一起补齐):
```powershell
cd C:\HxopsRpaTest
python -m pip install playwright openpyxl pyyaml cryptography
python -m playwright install chromium
```
Secret 复用 `1.5.10` 创建的 `C:\HxopsRpaSecrets\test.xml` / `prod.xml`。手工启动 test(首次验证用可见窗口;加 `-Mock` 可在不访问货代网站的情况下验证 trigger 消费、回调、归档与企微投递全链路;正式常驻建议验证后再加 `-Headless`):
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
"C:\HxopsRpaTest\scripts\rpa\receipt\start_receipt_worker.ps1" `
-Environment test `
-ApiBase "http://<test后端地址>:<端口>" `
-WorkerRoot "C:\HxopsRpaTest" `
-SecretFile "C:\HxopsRpaSecrets\test.xml"
```
启动成功会输出 `[freight_receipt_rpa_worker] started trigger_dir=... drop_dir=...`,随后轮询 `receipt_triggers` 下完整的 `.json` 触发文件。执行策略拦截、`Unblock-File`、UTF-8 BOM 要求均与 `1.5.10` 相同(`start_receipt_worker.ps1` 同样必须保持 UTF-8 BOM,从仓库原样复制)。
后台常驻沿用 `1.5.10` 的「`AtLogOn + Interactive`、每环境独立任务」模式,仅把动作换成收料启动脚本。收料 Worker 不写 `worker.log`,日志输出到控制台;计划任务建议用 `cmd.exe` 包装做文件重定向:
```powershell
$TestApiBase = "http://<test后端地址>:<端口>"
$ReceiptAction = New-ScheduledTaskAction `
-Execute "cmd.exe" `
-Argument "/c powershell.exe -NoProfile -ExecutionPolicy Bypass -File ""C:\HxopsRpaTest\scripts\rpa\receipt\start_receipt_worker.ps1"" -Environment test -ApiBase ""$TestApiBase"" -WorkerRoot ""C:\HxopsRpaTest"" -SecretFile ""C:\HxopsRpaSecrets\test.xml"" >> ""C:\HxopsRpaTest\data\freight_receipt_rpa\logs\receipt_worker.log"" 2>&1" `
-WorkingDirectory "C:\HxopsRpaTest"
# $Trigger / $Principal / $Settings 与 1.5.10 的库存任务完全一致:
# AtLogOn + Interactive;RestartCount 10、RestartInterval 1 分钟、ExecutionTimeLimit 0、MultipleInstances IgnoreNew。
Register-ScheduledTask -TaskName "HXOPS Receipt RPA Worker TEST" -Action $ReceiptAction -Trigger $Trigger -Principal $Principal -Settings $Settings
```
任务名建议 `HXOPS Receipt RPA Worker TEST` / `HXOPS Receipt RPA Worker PROD`,与库存任务并存;收料与库存 Worker 可同机、同一交互式用户会话同时运行,日常启停命令与 `1.5.10` 相同(替换任务名即可)。
#### 1.9.3 Ubuntu 后端:环境变量、排程与归档
`.env.test` 在 `1.5.9` 基础上追加(正式环境把路径换成 `/mnt/hxops-rpa-prod-data/...`):
```env
# 收料 RPA 共享目录(与 Windows Worker 的 data\freight_receipt_rpa 属同一 SMB 共享的子路径)
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_drop
# 收料排程等待回调超时(秒);超时回收为 RPA.RECEIPT_CALLBACK_TIMEOUT,不自动重试
SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS=900
```
> ⚠️ **最容易漏的一步**:不配置这两个目录变量时,后端默认写容器本地 `backend/data/shipping_notice/freight_receipt_rpa/*`,Windows 共享盘永远看不到 trigger,单元会一直等到超时回收。
容器 bind mount **无需新增**:收料目录位于既有 `/mnt/hxops-rpa-*data` 共享的子路径下,`hxops-backend`、`hxops-schedule-worker` 按 `1.5.9` 挂载后即已覆盖;修改 `.env` 后按惯例重建相关容器。
归档与通知依赖:
- 收料文件在回调时**原样上传 MinIO**(`shipping/receipt-reports/{年}/{月}/{单元}/{sha256}.xlsx`),保留三年;MinIO 不可用时该单元回调失败,不落成功态。
- 到期对象由平台排程任务 **货代收料归档到期清理**(`freight-receipt-rpa-retention`)删除,建议在排程管理配置每日一次;它只删除过期对象,不删除运行、文件事实与审计记录。
- 企微逐文件推送与汇总发给排程任务配置的接收人(`notify_user_ids` + `notify_enabled`),接收人必须已完成企微绑定,否则投递记 `WECOM_USER_UNBOUND` 失败。
排程创建:管理端「排程管理」新增平台任务 **货代收料 RPA**(`freight-receipt-rpa`),可选参数 `source_codes` 留空则执行全部已启用收料配置,按需配置 Cron 与接收人。收料排程与库存排程相互独立(站点、Cron、接收人分别选择)。收料触发前**没有**库存那套 Worker 在线 fail-fast 检查:Worker 停止只会让单元等待到 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS` 超时回收,因此上线后应按 `1.9.4` 验收并保留 `receipt_worker.log` 巡检。
#### 1.9.4 端到端验证
1. 管理端「货代管理 → 库存站点」抽屉为目标站点启用收料配置:DBS 必须配置 Warehouse(每个 Warehouse 展开一个单元);Crane 固定 `Inbound Details`,拒绝 Warehouse 与查询条件。
2. 链路演练(不依赖真实货代网站):以 `-Mock` 启动收料 Worker → 排程管理手工执行一次「货代收料 RPA」→ 确认回调、MinIO 归档、企微投递全链路成功后停止 Mock Worker。
3. 真实链路:启动真实收料 Worker 并触发排程,依次确认:
- `ls /mnt/hxops-rpa-test-data/freight_receipt_rpa/receipt_triggers` 出现 `receipt_export_batch_{run_no}.json`;
- Worker 领取后文件进入同目录 `processing/`,全部单元处理完进入 `processed/`(契约级失败进 `failed/`);
- `receipt_drop` 出现 `receipt_{callback_id}_{时间戳}.xlsx`;
- 回调 `/api/shipping-notice/rpa/receipt-batch-ready` 成功,单元 `success`,MinIO 出现归档对象;
- 接收人企微收到文件消息与汇总,工作台「收料文件」可查看并下载。
4. 失败路径:制造一个失败单元(如停用对应 RPA Profile),确认排程终态 `failed` / `partial_failed`、管理端失败单元可查、带原因重试生成新单元且以 `retry_of_id` 关联旧单元;通知重发不触发重新导出。
5. 隔离确认:收料文件不出现在 `inventory_drop`,不产生任何 `ShippingInventoryFile` / 库存快照 / 库存匹配记录。
#### 1.9.5 常见问题
- trigger 长时间无人消费:收料 Worker 未启动;两端 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR` 不一致;或后端未配置变量、写到了容器本地默认路径(见 `1.9.3` 的告警)。
- 回调 401/403:Worker `X-Integration-Key` 与该环境 `SHIPPING_NOTICE_TOOL_API_KEY` 不一致,或 `-ApiBase` 未按 `1.5.10` 的网关口径填写。
- 回调报 `SHIPPING.RECEIPT_CALLBACK_FILE_INVALID`:`file_path` 不在收料 drop 根内、非 `.xlsx`、空文件或超过 `FILE_ASSET_MAX_SIZE_MB`;多为收料/库存目录串用所致。
- 单元长期 `awaiting_rpa`、排程停在 `awaiting_receipt_rpa_callback`:Worker 停止或崩溃;超过 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS` 由回收逻辑置 `RPA.RECEIPT_CALLBACK_TIMEOUT`,**不自动重试**,需管理员带原因重试或等下一轮 Cron。
- DBS/Crane 登录或导出失败:先在 Windows 手工登录确认 MFA/SSO/代理;Crane 无论 Profile 首页保存为何,Worker 均强制进入 `#/inbound-details-query` 用页面默认条件执行;确认 Profile 已启用且 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 两端一致(否则无法解密凭据)。
- `receipt_drop` 磁盘占用增长:归档完成后本地文件不再被后端读取,收料 Worker **不做本地清理**;按运维周期人工清理,建议保留最近几天便于排障。
- 其余排障顺序与 `1.5.12` 一致:先看 Worker 控制台 / `receipt_worker.log`,再看两端目录与共享挂载,最后看后端日志与收料审计事件。
#### 1.9.6 收料 RPA 三环境速查
| 运行位置 | 后端目录/环境 | Worker 目录与环境 | 说明 |
| --- | --- | --- | --- |
| Windows 本地联调 | 本地后端;默认 `backend/data/shipping_notice/freight_receipt_rpa/*` | 当前项目 `scripts/rpa/receipt/`;`dev` | 不连 test/prod、不用 test/prod Key;`-Mock` 可全链路演练 |
| Linux 测试服务器 | `/mnt/hxops-rpa-test-data/freight_receipt_rpa/*`;`.env.test` | `C:\HxopsRpaTest\data\freight_receipt_rpa`;`test` | 与库存测试共用同一 SMB 共享与挂载 |
| Linux 正式服务器 | `/mnt/hxops-rpa-prod-data/freight_receipt_rpa/*`;`.env.prod` | `C:\HxopsRpaProd\data\freight_receipt_rpa`;`prod` | 测试真实链路验收通过后再开启正式排程 |
Windows 本地联调(项目根目录 PowerShell;本地后端默认目录与 Worker 指向一致,无需配置目录变量):
```powershell
# 窗口一:启动本地后端(同 2.1 的库存本地联调)。
# 窗口二:直接运行收料 Worker(不经启动脚本,免 Secret 文件;MOCK=true 时生成模拟 xlsx,
# 走完整 trigger 消费 → 回调 → 归档 → 企微链路)。
$env:HXOPS_API_BASE = "http://127.0.0.1:5052"
$env:SHIPPING_NOTICE_TOOL_API_KEY = "<与本地后端一致>"
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "true"
$receiptRoot = Join-Path (Get-Location).Path "backend\data\shipping_notice\freight_receipt_rpa"
$env:SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $receiptRoot "receipt_triggers"
$env:SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $receiptRoot "receipt_drop"
python scripts/rpa/receipt/receipt_rpa_worker.py
```
真实本地导出(`MOCK=false`)还需受控注入 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 并设置 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR`;排程下发的真实 trigger 均含加密凭据,Mock 消费真实 trigger 时同样需要该密钥。也可改用启动脚本 `.\scripts\rpa\receipt\start_receipt_worker.ps1 -Environment test -ApiBase "http://127.0.0.1:5052" ...`(需先按 `1.5.10` 生成本地 Secret 文件)。
***
## 2. Dify 手工配置边界
@@ -3491,7 +3651,7 @@ DBS 每个 Warehouse 单独导出且不填报表日期;Crane 固定 `Inbound D
### 可靠性、补偿与审计边界
- trigger 采用“同目录临时文件写完、`fsync` 后 `os.replace` 原子发布”方式;收料 Worker 只能 claim 完整的 `.json`,不得读取半写入 trigger。
- `awaiting_receipt_rpa` 运行受 `SHIPPING_NOTICE_RPA_RECEIPT_CALLBACK_TIMEOUT_SECONDS`(默认值由部署配置决定)限制。超时回收将仍 pending/running 的单元标记为 `failed/RPA.RECEIPT_CALLBACK_TIMEOUT`,结束排程并写前后快照审计;**不自动重试、不自动重发**,后续 Cron 或管理员人工补偿可继续执行。
- `awaiting_receipt_rpa` 运行受 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 `900`,可由部署配置覆盖)限制。超时回收将仍 pending/running 的单元标记为 `failed/RPA.RECEIPT_CALLBACK_TIMEOUT`,结束排程并写前后快照审计;**不自动重试、不自动重发**,后续 Cron 或管理员人工补偿可继续执行。
- Worker 启动及常规扫描均回收超时运行,避免服务或 Worker 重启后运行永久占用排程状态。
- 空结果、Worker 失败、归档成功、对象删除失败、企微文件/汇总投递成功或失败、管理员查看失败单元、人工重试和重发均写追加式 `ShippingAuditEvent`。审计包含操作人/时间/对象、结果、脱敏原因或错误码、变更前后状态;不得写入密码、Cookie、令牌、对象存储定位或浏览器会话。
- 管理员失败单元查询仅返回运行诊断所需的站点、Warehouse、状态、错误码/脱敏错误和时间;接收人不拥有该查询、配置、重试或重发权限。
@@ -3607,3 +3767,22 @@ inventory_preparation Gate
- 一期规划中的「快照重冻结 + `order_data_version` 递增」由既有 `update_notice_*` ⇒ `_commit_notice_edit` ⇒ `_apply_notice_edit_change_effects` 链路承担(编辑落库后依赖 `change_effect` 失效下游);`order_data_version` 由乐观锁 `_assert_order_data_version` 保护,避免重复冻结引入二次状态机。
- 波次通知「按自身行重跑路由」(D8)已实现(见一期章节):不再继承首通知源,`freeze_wave_notice_routing` 按波次自身行冻结候选集;本二期不新增二次波次状态机,与一期波次路由冻结复用同一套链路。
## 客户数据 ODM ID 范围与整单 ODM 裁决(2026-09)
- 「客户主数据」页面与文案统一更名为「客户数据」;`ShippingCustomer` 新增可空 `odm_ids`(JSON 字符串清单),由客户数据页维护(每行一个,留空表示不限定)。
- 生成发货 Excel 的整单 ODM 裁决(模板 Header 消费 `odm_id` 字段时生效,`export._adjudicate_notice_odm`):
1. 客户 `odm_ids` 非空 → 先全局过滤库存命中行,仅保留范围内的 ODM;把原有命中全部排除时报「订单行命中的库存记录 ODM ID 不在客户数据维护的 ODM ID 范围内」。
2. 用户选择(`shipping_notice_line_inventory_matches.chosen_odm_id`,task 全部 `is_current` 行统一值)→ 过滤为所选 ODM;在当前库存中不存在时报「已选择的 ODM ID 在当前库存中不存在」。
3. 无范围、无选择且各行命中 ODM 交集唯一 → 自动收敛到唯一可行值;交集多个 → 维持折叠冲突阻断,由工作台下发候选。
- 工作台「通知准备」面板为**行内 ODM 下拉**(任一行候选多于一个且未生成 Excel 时展示列):候选为该行经客户范围过滤后的命中值(保留原大小写);确认后 `POST /shipping-tasks/<task_no>/odm-choice`(body: `snapshot_line_id` + `odm_id`)落库并自动重试 `regenerate_excel_artifact`。
- **同快照文件同步**:选择按 `inventory_snapshot_id` 圈同步——改任一行,同一快照文件的全部 `is_current` 匹配行写同一 `chosen_odm_id`(前后端同步:后端落库即同步,前端刷新后各行回显同一值);校验取同步范围内各行候选的交集,保证选择不会把其他行变成无匹配。
- 选择不落 Notice/OT:Notice 在生成失败事务中会回滚,行级匹配事实表才是导出读取库存源/文件的既有事实源;重匹配产生新匹配轮次后旧选择自然失效。Header 契约是整单一个值,若业务需要不同行走不同 ODM(跨快照文件),应拆分通知单。
- 迁移:`aa11bb22cc33_customer_odm_scope`(`shipping_customers.odm_ids` + `shipping_notice_line_inventory_matches.chosen_odm_id`,均幂等守卫)。
## 订单队列五态图标与 needs_attention(2026-09)
- 队列接口(`serialize_review_queue` / `serialize_review_run` 共用的 `_serialize_review_case_summary`)每个 item 新增 `needs_attention: bool`:复用批量预取的 Execution/Gate 会话缓存(零额外 SQL),当前 Gate(优先 `execution.current_gate_code`,缺失按 `sequence_no` 取第一个活跃 Gate)状态 ∈ {`blocked_manual`, `blocked_retryable`, `failed_terminal`} 时为 True;`waiting_external`/`running`/`pending`/`queued` 属系统在办。前端禁止自行推断阻塞。
- 左侧文件队列图标五态口径(`ReviewDocumentNavigation.vue` 的 `navIconKind`,优先级命中即停):失败 ✗ → 需人工 ⚠(`issue_count>0` 或 `needs_attention`,以及 `draft`/`ready`/`unreviewed`/`quality_issue`/`pending_review`/`waiting_review`)→ 终态绿勾 ✓(`lifecycle_stage=upload_complete` 或 `closed`/`completed`)→ 系统在办蓝转圈(`confirmed`/`confirming`/`processing`/`reparse_pending`/`queued`)→ 中性灰圈(`non_order`/`cancelled`/`superseded`)→ 兜底转圈。绿勾不再被「已创建任务」等中间态占用;选中态仅由行高亮表达。
- 队列 `summary` 三桶与图标同口径(`_queue_summary_bucket`):`quality_issue` 归 needs_action;`confirmed` 归 processing;仅终态归 completed。前端当前未消费三桶,属契约纠偏。
- 已知边界(fail-safe):队列 `lifecycle_stage` 为轻量投影,极端场景会偏早(兜回 `intake_parse`),后果是完成单暂不亮绿勾;反向(未完成亮绿勾)不可能——`upload_complete` 仅由已持久化 `OT.stage=completed` 驱动。
+2
View File
@@ -93,6 +93,7 @@
| --- | --- | --- |
| **统一 ShippingProcessingProjection(15 阶段)+ 正式任务编辑** | 阶段 0–6 已验收 | 库存源硬门禁;复核台原地 formal_task;Schema `task_edit_policy`/`change_effect`;正式编辑审计矩阵;Dify NONE。验收:`unified-progress-formal-edit-stage0~6` + `final-acceptance` + `dify-config`。 |
| 订单生命周期工作台状态展示统一(v2) | 已实现 | 五阶段下方横幅移除;右栏「当前任务」卡为唯一状态宿主:状态行=user_status 短标签(Run 级 lifecycle_status 受控兑底映射)+ 状态块内嵌动态说明(`RUN_STATUS_FALLBACK_MAP`/`REDUNDANT_DETAIL_REASON_CODES` 双常量裁决,诊断信息不隐藏);无 Case 瞬态保留单行白名单轻提示;聊天页/任务中心同源接入零视觉变化。设计:[2026-08-31 状态展示统一设计](superpowers/specs/2026-08-31-shipping-review-status-display-unification-design.md) |
| 订单队列五态图标与门禁阻塞标志 | 已实现 | 队列 item 新增 `needs_attention`(复用批量 Gate 缓存零额外 SQL,blocked_manual/blocked_retryable/failed_terminal 为真);左侧文件队列图标收敛为 需人工⚠/进行中🔄/终态✓/失败✗/中性○ 五态,绿勾仅限通知完成终态;队列 summary 三桶同口径。设计:[2026-09-16 队列图标语义设计](superpowers/specs/2026-09-16-review-queue-icon-semantics-design.md) |
| 发货通知技术手册 | 已文档化 | 见 [docs/features/shipping-notice/technical.md](features/shipping-notice/technical.md) |
| 发货通知业务说明 | 已文档化 | 见 [docs/features/shipping-notice/business.md](features/shipping-notice/business.md) |
| 业务去重与任务版本(Phase 3) | 已实现 | Intake 业务指纹/重复决策、修订版本链、强制新建权限与审计;见技术手册第三节摘要 |
@@ -179,6 +180,7 @@
| **行级人工选源动作 select_line_inventory_source(一期)** | 已实现 | Gate 业务动作(属 `inventory_matching`):校验行冲突、源 ∈ 候选、源启用、通知未生成 Excel(否则 `SHIPPING.LINE_SOURCE_LOCKED`);写候选行覆写 + 仅该行重匹配 + 审计 `review_line_source_selected`。 |
| **通知准备行源下拉与锁定渲染(一期)** | 已实现 | `ui_state.preparation` 下发 `source_locked` / `lines[].source_ambiguous` / `source_candidates`;前端歧义行渲染库存源下拉 + 首选高亮 + 确认,`source_locked` 行只读徽标;阶段自动跳转一次性 toast + 清理 `reparse` 死守卫;四语言文案。 |
| **波次库存源按自身行重路由(D8)** | 已实现 | `post_ot_fulfillment_wave_service` 创建波次通知不再继承首通知任务级源字段(`inventory_source_*`/`routing_fingerprint`/`snapshot_id`),仅继承订单级路由上下文(目的地/仓提示);新增 `inventory_candidate_freeze_service.freeze_wave_notice_routing` 按波次自身行评估路由并冻结候选集,随后走同一套自动探测/匹配/反写。测试:`test_shipping_wave_rerouting.py`。 |
| **客户数据 ODM ID 范围与整单 ODM 裁决** | 已实现 | 客户数据(原客户主数据)维护可空 `odm_ids` 清单;生成 Excel 时按客户范围过滤库存命中行,范围后仍多值时工作台整单选择(写入行级匹配事实 `chosen_odm_id`)并自动重试;交集唯一自动收敛。 |
| **确认后订单编辑窗谓词(二期 T10)** | 已实现 | `order_edit_window_service.editable_scope`(header=订单任一通知无 Excel 且无活动 Attempt;行=所属通知无 Excel 且无活动 Attempt,未入波次行不受首单 Excel 限制)+ `order_has_active_attempt`;`ui_state` 下发 `edit_window`;测试通过。设计 §3.1。 |
| **Excel 前保存守卫 + 失效分类重跑(二期 T11/T12)** | 已实现 | 正式字段编辑路径(`task_workflow.update_notice_*`)新增活动 Attempt 守卫(`SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`);失效重跑沿用 Schema `change_effect`:路由字段→`rerun_inventory_source_resolution`、行字段→`rerun_inventory_matching`、导出→`regenerate_excel`、需重解析→`require_revision`;审计含 `applied_effects` 失效动作链。设计 §3.2/§3.3。 |
| **编辑窗前端渲染(二期 T13)** | 已实现 | `ShippingTaskUiState.edit_window` 类型 + `formalHeaderEditable()`/`formalLineEditable(lineKey)`;头字段编辑块按 `edit_window.header` 门控、歧义行源下拉确认按行锁定;四语言 `errors.json` 补 `SHIPPING.EDIT_WINDOW_FIELD_LOCKED/SYSTEM_BUSY`;`npm run build` 通过。 |
@@ -0,0 +1,667 @@
# 订单队列图标语义重映射 + needs_attention 标志 实现计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 队列行内图标收敛为五态语义(需人工⚠/进行中🔄/终态✓/失败✗/中性○),后端队列下发 `needs_attention` 门禁阻塞标志,summary 计数同口径对齐。
**Architecture:** 后端在既有批量 Gate 缓存上新增只读判定函数(零额外 SQL),`_serialize_review_case_summary` 增量输出字段;前端单组件重写 `navIconKind` 优先级链并新增 LoaderCircle 分支。无迁移、无接口破坏性变更。
**Tech Stack:** Flask + SQLAlchemy 2.0(后端);Vue 3 `<script setup>` + lucide-vue-next + vitest(前端);pytest(后端测试)。
**Spec:** `docs/superpowers/specs/2026-09-16-review-queue-icon-semantics-design.md`
## Global Constraints
- 🚫 **禁止自动 commit**(用户强规则,覆盖本 skill 模板的提交步骤):每个任务只落盘 + 跑验证,最后统一停在"完成、未提交"状态;仅当用户当轮明确说提交时才 `git add <具体文件>` + commit。
- 外科手术式改动:只改本计划列出的文件与位置;不顺手改注释/格式/相邻代码。
- 无数据库迁移;无新增第三方依赖;不改既有字段语义(`status`/`issue_count`/`lifecycle_stage` 原样保留)。
- 验证基线:改动文件对应测试通过 + `cd frontend && npm run build` 通过(Task 4 统一回归)。
- 注释遵循 AGENTS.md §5:新增函数带含 Args/Returns 的 docstring;逻辑变化同步更新受影响注释。
---
### Task 1: 后端 `needs_attention` 字段
**Files:**
- Modify: `backend/app/services/shipping_notice/order_review_projection.py`(在 `_queue_current_gate_hint` 之后、`_serialize_review_case_summary` 之前插入辅助函数;在 `_serialize_review_case_summary` 返回 dict 增加一行)
- Test: `backend/tests/test_shipping_order_review_service.py`(文件末尾追加 3 个测试)
**Interfaces:**
- Consumes: 会话级缓存 `shipping_conversation_projection_read_cache` 中的 `execution_by_case_id` / `gates_by_execution_id`(`_load_review_case_summary_batch` 已预取,`:1333-1355`)。
- Produces: 队列 item 新增 `'needs_attention': bool`(`serialize_review_queue` 与 `serialize_review_run` 的 items 均携带);模块级函数 `_queue_gate_needs_attention(case: ShippingOrderReviewCase) -> bool`,Task 2 依赖该字段。
- [ ] **Step 1: 追加失败测试**
在 `backend/tests/test_shipping_order_review_service.py` 文件末尾追加(fixture 写法仿照同文件 `test_review_queue_falls_back_to_process_gate_when_ot_stage_is_legacy_step`,`:351-406`):
```python
def test_review_queue_flags_blocked_gate_cases_as_needs_attention(app):
"""门禁 blocked_manual(如库存缺口)的已建任务单,队列必须下发 needs_attention=True。"""
from app.models import ShippingProcessExecution, ShippingProcessGate
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-NEEDS-ATTN')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-NEEDS-ATTN',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-needs-attn',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-ATTN',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
task = ShippingOrderTask(
task_no='OT-REVIEW-QUEUE-NEEDS-ATTN',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
status='processing',
stage='inventory_preparation',
)
db.session.add(task)
db.session.flush()
execution = ShippingProcessExecution(
execution_no='SPE-REVIEW-QUEUE-NEEDS-ATTN',
task_id=task.id,
review_case_id=case.id,
status='active',
current_gate_code='inventory_sufficiency',
)
db.session.add(execution)
db.session.flush()
db.session.add(ShippingProcessGate(
execution_id=execution.id,
gate_code='inventory_sufficiency',
sequence_no=16,
status='blocked_manual',
))
task.active_process_execution_id = execution.id
case.status = 'confirmed'
case.confirmed_task_id = task.id
db.session.commit()
item = serialize_review_queue([run])['items'][0]
# 关键断言:库存缺口类门禁阻塞必须在队列可见,不再只依赖当前单的完整详情。
assert item['needs_attention'] is True
assert item['lifecycle_stage'] == 'fulfillment_prep'
def test_review_queue_waiting_external_gate_is_not_needs_attention(app):
"""RPA 外部等待(waiting_external)属于系统在办,不得标记 needs_attention。"""
from app.models import ShippingProcessExecution, ShippingProcessGate
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-WAIT-EXT')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-WAIT-EXT',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-wait-ext',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-WAIT',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
task = ShippingOrderTask(
task_no='OT-REVIEW-QUEUE-WAIT-EXT',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
status='processing',
stage='freight_uploading',
)
db.session.add(task)
db.session.flush()
execution = ShippingProcessExecution(
execution_no='SPE-REVIEW-QUEUE-WAIT-EXT',
task_id=task.id,
review_case_id=case.id,
status='waiting_external',
current_gate_code='freight_upload_rpa',
)
db.session.add(execution)
db.session.flush()
db.session.add(ShippingProcessGate(
execution_id=execution.id,
gate_code='freight_upload_rpa',
sequence_no=18,
status='waiting_external',
))
task.active_process_execution_id = execution.id
case.status = 'confirmed'
case.confirmed_task_id = task.id
db.session.commit()
item = serialize_review_queue([run])['items'][0]
# 关键断言:外部等待是在办不是待办,图标应走进行中而非需人工。
assert item['needs_attention'] is False
def test_review_queue_without_execution_is_not_needs_attention(app):
"""已建任务但尚无 Execution(或缓存未命中)时,needs_attention 必须为 False。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-NO-EXEC')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-NO-EXEC',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-no-exec',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-NOEXEC',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
task = ShippingOrderTask(
task_no='OT-REVIEW-QUEUE-NO-EXEC',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
status='processing',
stage='inventory_preparation',
)
db.session.add(task)
db.session.flush()
case.status = 'confirmed'
case.confirmed_task_id = task.id
db.session.commit()
item = serialize_review_queue([run])['items'][0]
# 关键断言:无门禁事实时不臆造需人工标志。
assert item['needs_attention'] is False
```
若文件顶部 import 缺少 `ShippingOrderCandidate` / `ShippingOrderTask` / `ensure_review_case_for_unit` / `db`,按同文件既有测试的 import 方式补齐(它们已在既有测试中使用,通常已在顶部导入)。
- [ ] **Step 2: 运行验证测试失败**
Run: `cd backend && source venv/bin/activate && python -m pytest tests/test_shipping_order_review_service.py::test_review_queue_flags_blocked_gate_cases_as_needs_attention -v`
Expected: FAIL,`KeyError: 'needs_attention'`
- [ ] **Step 3: 实现辅助函数与字段**
3a. 在 `order_review_projection.py` 的 `_queue_current_gate_hint` 函数结束(`:1065` 的 `return None`)与 `_serialize_review_case_summary`(`:1068`)之间插入:
```python
# 队列当前 Gate 活跃口径:在 _queue_current_gate_hint 活跃集合上补 queued/failed_terminal,
# 供 needs_attention 兜底取 Gate,避免终态失败的单被漏判。
_QUEUE_CURRENT_GATE_STATUSES = frozenset({
'pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal',
})
# 需要人工介入的 Gate 状态;waiting_external/running/pending/queued 属系统在办,不算需人工。
_QUEUE_ATTENTION_GATE_STATUSES = frozenset({'blocked_manual', 'blocked_retryable', 'failed_terminal'})
def _queue_gate_needs_attention(case: ShippingOrderReviewCase) -> bool:
"""
判定 Case 当前正式门禁是否需要人工介入;供队列摘要下发 needs_attention。
只读会话级批量缓存(_load_review_case_summary_batch 已预取 Execution/Gate),
零额外 SQL;当前 Gate 取 execution.current_gate_code 对应 Gate,缺失时按
sequence_no 取第一个活跃 Gate。调用方禁止据此之外再自行推断阻塞。
Args:
case: 当前复核 Case。
Returns:
当前 Gate 状态 ∈ {blocked_manual, blocked_retryable, failed_terminal} 时 True;
无 Execution / 无活跃 Gate 时 False。
"""
cache = db.session.info.get('shipping_conversation_projection_read_cache')
if not isinstance(cache, dict) or getattr(case, 'id', None) is None:
return False
execution = (cache.get('execution_by_case_id') or {}).get(int(case.id))
if execution is None:
return False
gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower()
gates = (cache.get('gates_by_execution_id') or {}).get(int(execution.id), []) or []
current = None
if gate_code:
for gate in gates:
if str(getattr(gate, 'gate_code', '') or '').strip().lower() == gate_code:
current = gate
break
if current is None:
for gate in gates:
if str(getattr(gate, 'status', '') or '').strip().lower() in _QUEUE_CURRENT_GATE_STATUSES:
current = gate
break
if current is None:
return False
return str(getattr(current, 'status', '') or '').strip().lower() in _QUEUE_ATTENTION_GATE_STATUSES
```
3b. 在 `_serialize_review_case_summary` 返回 dict 中,`'issue_count': len(draft.issue_summary_json or []) if draft is not None else 0,`(`:1159`)之后插入一行:
```python
'needs_attention': _queue_gate_needs_attention(case),
```
- [ ] **Step 4: 运行新测试通过**
Run: `cd backend && source venv/bin/activate && python -m pytest tests/test_shipping_order_review_service.py -v -k "needs_attention"`
Expected: 3 passed
- [ ] **Step 5: 跑整个测试文件防回归**
Run: `cd backend && source venv/bin/activate && python -m pytest tests/test_shipping_order_review_service.py -v`
Expected: 全部 passed(既有测试只断言 `lifecycle_stage`,不受新字段影响)
---
### Task 2: 后端 summary 计数对齐
**Files:**
- Modify: `backend/app/services/shipping_notice/order_review_projection.py`(`serialize_review_queue` 前插入归类函数;替换 `:1447-1452` 的 counts 块)
- Test: `backend/tests/test_shipping_order_review_service.py`(追加 2 个测试)
**Interfaces:**
- Consumes: Task 1 的 item 字段 `needs_attention`。
- Produces: 模块级函数 `_queue_summary_bucket(item: dict[str, Any]) -> str`(返回 `'needs_action' | 'processing' | 'completed'`);`serialize_review_queue` 返回的 `summary` 三桶新口径。
- [ ] **Step 1: 追加失败测试**
```python
def test_review_queue_summary_counts_terminal_stage_as_completed(app):
"""OT.stage=completed(通知完成)的已建任务单计入 completed,不再计入 processing。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-DONE')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-SUM-DONE',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-sum-done',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-SUMDONE',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
task = ShippingOrderTask(
task_no='OT-REVIEW-QUEUE-SUM-DONE',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
status='processing',
stage='completed',
)
db.session.add(task)
db.session.flush()
case.status = 'confirmed'
case.confirmed_task_id = task.id
db.session.commit()
summary = serialize_review_queue([run])['summary']
# 关键断言:summary 与五态图标同口径——confirmed+终态=completed 而非 processing。
assert summary['total'] == 1
assert summary['completed'] == 1
assert summary['processing'] == 0
assert summary['needs_action'] == 0
def test_review_queue_summary_counts_quality_issue_as_needs_action(app):
"""quality_issue(文件质量异常)从 completed 改归 needs_action,与黄⚠图标一致。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-QI')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-SUM-QI',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-sum-qi',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-SUMQI',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
case.status = 'quality_issue'
db.session.commit()
summary = serialize_review_queue([run])['summary']
# 关键断言:质量异常是待办不是完成。
assert summary['needs_action'] == 1
assert summary['completed'] == 0
assert summary['processing'] == 0
def test_review_queue_summary_counts_plain_confirmed_as_processing(app):
"""已建任务、无阻塞、非终态的 confirmed 单计入 processing(对应转圈图标)。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-SUM-PROC')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-SUM-PROC',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-sum-proc',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-SUMPROC',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
task = ShippingOrderTask(
task_no='OT-REVIEW-QUEUE-SUM-PROC',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
status='processing',
stage='inventory_preparation',
)
db.session.add(task)
db.session.flush()
case.status = 'confirmed'
case.confirmed_task_id = task.id
db.session.commit()
summary = serialize_review_queue([run])['summary']
# 关键断言:已创建任务是在办不是完成。
assert summary['processing'] == 1
assert summary['completed'] == 0
assert summary['needs_action'] == 0
```
- [ ] **Step 2: 运行验证测试失败**
Run: `cd backend && source venv/bin/activate && python -m pytest tests/test_shipping_order_review_service.py -v -k "summary_counts"`
Expected: 3 FAILED(terminal 单被计入 processing;quality_issue 被计入 completed;plain confirmed 被计入 completed)
- [ ] **Step 3: 实现归类函数并替换 counts**
3a. 在 `serialize_review_queue`(`:1380`)定义之前插入:
```python
def _queue_summary_bucket(item: dict[str, Any]) -> str:
"""
队列计数桶归类;优先级与前端队列图标一致:需人工 > 终态完成 > 进行中。
桶是"处置去向"粗归类,与五态图标非一一映射(non_order 计入 completed,
图标为中性别灰○);needs_attention(门禁阻塞)恒优先于 completed,
避免阻塞单被计数成"完成"。
Args:
item: 队列 item 投影(含 status / needs_attention / lifecycle_stage)。
Returns:
'needs_action' | 'completed' | 'processing'。
"""
status = str(item.get('status') or '')
if status in ('unreviewed', 'draft', 'ready', 'quality_issue') or item.get('needs_attention'):
return 'needs_action'
if status in ('non_order', 'closed', 'completed') or str(item.get('lifecycle_stage') or '') == 'upload_complete':
return 'completed'
return 'processing'
```
3b. 将 `serialize_review_queue` 末尾的 counts 块(原 `:1447-1452`):
```python
counts = {
'total': len(items),
'needs_action': sum(1 for item in items if item['status'] in ('unreviewed', 'draft', 'ready')),
'processing': sum(1 for item in items if item['status'] in ('confirming', 'reparse_pending')),
'completed': sum(1 for item in items if item['status'] in ('confirmed', 'non_order', 'quality_issue')),
}
```
替换为:
```python
buckets = [_queue_summary_bucket(item) for item in items]
counts = {
'total': len(items),
'needs_action': buckets.count('needs_action'),
'processing': buckets.count('processing'),
'completed': buckets.count('completed'),
}
```
- [ ] **Step 4: 运行新测试通过**
Run: `cd backend && source venv/bin/activate && python -m pytest tests/test_shipping_order_review_service.py -v -k "summary_counts or needs_attention"`
Expected: 6 passed
- [ ] **Step 5: 跑整个测试文件防回归**
Run: `cd backend && source venv/bin/activate && python -m pytest tests/test_shipping_order_review_service.py -v`
Expected: 全部 passed(已核实 `summary` 三桶除本文件外无其他消费方;`test_shipping_conversation_processing_api.py` 等文件的 `needs_action` 属另一投影 `ShippingProcessingProjection`,不受影响)
---
### Task 3: 前端类型 + 图标映射重写
**Files:**
- Modify: `frontend/src/features/chat/types/shipping.api.types.ts`(`ShippingOrderReviewCaseSummary`,`:2322` 的 `issue_count` 之后)
- Modify: `frontend/src/features/chat/components/shipping-review/ReviewDocumentNavigation.vue`
- Test: `frontend/src/features/chat/components/shipping-review/ReviewDocumentNavigation.spec.ts`
**Interfaces:**
- Consumes: 队列 item 的 `needs_attention?: boolean`(Task 1 下发;旧后端缺省按 false)。
- Produces: `navIconKind(item): 'alert' | 'done' | 'failed' | 'processing' | 'idle'`(删除 `'active'`);`ReviewDocumentNavItem` 新增 `needs_attention?: boolean | null`。
- [ ] **Step 1: 追加失败测试**
在 `ReviewDocumentNavigation.spec.ts` 的最后一个 `describe` 之后追加:
```ts
describe('ReviewDocumentNavigation queue row status icons', () => {
/**
* 以指定字段挂载单行侧栏队列,返回该行按钮包装器。
*/
function mountRow(item: Partial<ReviewDocumentNavItem>) {
return mount(ReviewDocumentNavigation, {
props: {
items: [{ case_no: 'C-1', file_name: 'f1.pdf', status: 'draft', ...item }],
activeCaseNo: 'C-1',
navAriaLabel: 'nav',
forceMode: 'sidebar',
},
global: { plugins: i18n },
}).get('[data-testid="review-doc-nav-C-1"]');
}
it('renders confirmed cases as in-progress spinner instead of done check', () => {
const row = mountRow({ status: 'confirmed' });
// 关键断言:已创建任务是系统在办中间态,必须转圈而非绿勾。
expect(row.find('svg.animate-spin').exists()).toBe(true);
expect(row.find('svg.text-emerald-500').exists()).toBe(false);
});
it('renders ready-to-confirm cases as amber attention icon', () => {
const row = mountRow({ status: 'ready' });
// 关键断言:可确认是等人操作,属于待办而非完成。
expect(row.find('svg.text-amber-500').exists()).toBe(true);
});
it('renders backend gate-blocked cases as amber attention icon', () => {
const row = mountRow({ status: 'confirmed', needs_attention: true });
// 关键断言:needs_attention 是后端门禁裁决,优先于中间态转圈。
expect(row.find('svg.text-amber-500').exists()).toBe(true);
expect(row.find('svg.animate-spin').exists()).toBe(false);
});
it('reserves the green check for terminal upload_complete', () => {
const row = mountRow({ status: 'confirmed', lifecycle_stage: 'upload_complete' });
expect(row.find('svg.text-emerald-500').exists()).toBe(true);
expect(row.find('svg.animate-spin').exists()).toBe(false);
});
it('renders failed and neutral states as before', () => {
expect(mountRow({ status: 'failed' }).find('svg.text-rose-500').exists()).toBe(true);
const idle = mountRow({ status: 'non_order' });
expect(idle.find('svg.text-muted').exists()).toBe(true);
expect(idle.find('svg.animate-spin').exists()).toBe(false);
});
it('keeps the truthful state icon on the selected row', () => {
const row = mountRow({ status: 'draft' });
// 关键断言:选中态由行高亮表达,图标不再被 active 覆盖成灰圈。
expect(row.find('svg.text-amber-500').exists()).toBe(true);
});
it('treats missing needs_attention as false for old queue payloads', () => {
const row = mountRow({ status: 'confirmed', needs_attention: undefined });
expect(row.find('svg.animate-spin').exists()).toBe(true);
});
});
```
- [ ] **Step 2: 运行验证测试失败**
Run: `cd frontend && npx vitest run src/features/chat/components/shipping-review/ReviewDocumentNavigation.spec.ts`
Expected: 新增用例 FAIL(confirmed 画绿勾、选中草稿被灰圈覆盖、`needs_attention` 未消费);既有用例仍 PASS
- [ ] **Step 3: 修改类型 `shipping.api.types.ts`**
在 `ShippingOrderReviewCaseSummary` 的 `issue_count: number;`(`:2322`)之后插入:
```ts
/** 队列后端按当前门禁裁决:blocked_manual/blocked_retryable/failed_terminal 为 true;前端禁止自行推断阻塞。 */
needs_attention?: boolean;
```
- [ ] **Step 4: 重写组件映射与模板**
4a. `ReviewDocumentNavigation.vue` import 块(`:9-17`)加入 `LoaderCircle`(保持字母序):
```ts
import {
Check,
ChevronLeft,
ChevronRight,
Circle,
LoaderCircle,
Search,
TriangleAlert,
X,
} from 'lucide-vue-next';
```
4b. `ReviewDocumentNavItem` 类型(`:21-31`):`issue_count` 之后新增字段,并同步 `lifecycle_stage` 注释:
```ts
issue_count?: number;
/** 队列接口按当前门禁裁决的"需人工"标志(blocked_manual/blocked_retryable/failed_terminal);前端禁止自行推断阻塞。 */
needs_attention?: boolean | null;
po_number?: string | null;
customer_name?: string | null;
stage_label?: string | null;
/** 队列接口下发的生命周期码;用于阶段文字展示与终态(upload_complete)绿勾判定,不参与阶段裁决。 */
lifecycle_stage?: ReviewLifecycleStageCode | null;
```
4c. 整体替换 `navIconKind` 函数(`:120-133`):
```ts
/**
* 队列状态图标语义,按优先级命中即停:
* 失败 → 需人工(草稿问题数 / needs_attention 门禁阻塞)→ 终态绿勾
* → 等人状态 ⚠ → 系统在办转圈 → 中性灰圈 → 兜底转圈。
* 绿勾只属于终态(upload_complete / closed / completed);选中态由行高亮表达,
* 本函数不感知选中,图标永远如实反映状态。
*/
function navIconKind(item: ReviewDocumentNavItem): 'alert' | 'done' | 'failed' | 'processing' | 'idle' {
const status = String(item.status || '').toLowerCase();
if (status === 'failed' || status === 'error') return 'failed';
if ((item.issue_count && item.issue_count > 0) || item.needs_attention === true) return 'alert';
if (item.lifecycle_stage === 'upload_complete' || status === 'completed' || status === 'closed') return 'done';
if (['draft', 'ready', 'unreviewed', 'quality_issue', 'pending_review', 'waiting_review'].includes(status)) return 'alert';
if (['confirmed', 'confirming', 'processing', 'reparse_pending', 'queued'].includes(status)) return 'processing';
if (['non_order', 'cancelled', 'superseded'].includes(status)) return 'idle';
return 'processing';
}
```
4d. `matchesStatusFilter`(`:142`)的 processing 分支改为:
```ts
if (statusFilter.value === 'processing') return kind === 'processing';
```
4e. tabs 模板分支(`:216-225` 的 `<X>` 块之后、`<Circle>` 之前)插入:
```html
<LoaderCircle
v-else-if="navIconKind(item) === 'processing'"
class="h-3.5 w-3.5 shrink-0 animate-spin text-brand-600"
aria-hidden="true"
/>
```
4f. sidebar 模板分支(`:328-331` 的 `<X>` 块之后、`<Circle>` 之前)插入(该分支图标不带 aria-hidden,保持一致):
```html
<LoaderCircle
v-else-if="navIconKind(item) === 'processing'"
class="mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin text-brand-600"
/>
```
- [ ] **Step 5: 运行新测试通过**
Run: `cd frontend && npx vitest run src/features/chat/components/shipping-review/ReviewDocumentNavigation.spec.ts`
Expected: 全部 passed(含既有 8 个用例)
- [ ] **Step 6: 构建验证**
Run: `cd frontend && npm run build`
Expected: 构建通过,无 vue-tsc 类型错误
---
### Task 4: 文档同步 + 全量回归
**Files:**
- Modify: `docs/features/shipping-notice/technical.md`(文件末尾追加章节)
- Modify: `docs/funclist.md`(`:95` 工作台条目所在表格追加一行)
**Interfaces:**
- Consumes: Task 1–3 的最终实现。
- Produces: 与代码一致的权威文档(AGENTS.md §9 要求同一 PR 内同步)。
- [ ] **Step 1: technical.md 末尾追加**
在 `docs/features/shipping-notice/technical.md` 文件末尾(「客户数据 ODM ID 范围与整单 ODM 裁决(2026-09)」章节之后)追加:
```markdown
## 订单队列五态图标与 needs_attention(2026-09)
- 队列接口(`serialize_review_queue` / `serialize_review_run` 共用的 `_serialize_review_case_summary`)每个 item 新增 `needs_attention: bool`:复用批量预取的 Execution/Gate 会话缓存(零额外 SQL),当前 Gate(优先 `execution.current_gate_code`,缺失按 `sequence_no` 取第一个活跃 Gate)状态 ∈ {`blocked_manual`, `blocked_retryable`, `failed_terminal`} 时为 True;`waiting_external`/`running`/`pending`/`queued` 属系统在办。前端禁止自行推断阻塞。
- 左侧文件队列图标五态口径(`ReviewDocumentNavigation.vue` 的 `navIconKind`,优先级命中即停):失败 ✗ → 需人工 ⚠(`issue_count>0` 或 `needs_attention`,以及 `draft`/`ready`/`unreviewed`/`quality_issue`)→ 终态绿勾 ✓(`lifecycle_stage=upload_complete` 或 `closed`/`completed`)→ 系统在办蓝转圈(`confirmed`/`confirming`/`processing`/`reparse_pending`/`queued`)→ 中性灰圈(`non_order`/`cancelled`/`superseded`)→ 兜底转圈。绿勾不再被「已创建任务」等中间态占用;选中态仅由行高亮表达。
- 队列 `summary` 三桶与图标同口径(`_queue_summary_bucket`):`quality_issue` 归 needs_action;`confirmed` 归 processing;仅终态归 completed。前端当前未消费三桶,属契约纠偏。
- 已知边界(fail-safe):队列 `lifecycle_stage` 为轻量投影,极端场景会偏早(兜回 `intake_parse`),后果是完成单暂不亮绿勾;反向(未完成亮绿勾)不可能——`upload_complete` 仅由已持久化 `OT.stage=completed` 驱动。
```
- [ ] **Step 2: funclist.md 追加条目**
在 `docs/funclist.md:95`(「订单生命周期工作台状态展示统一(v2)」行)之后同表追加一行:
```markdown
| 订单队列五态图标与门禁阻塞标志 | 已实现 | 队列 item 新增 `needs_attention`(复用批量 Gate 缓存零额外 SQL,blocked_manual/blocked_retryable/failed_terminal 为真);左侧文件队列图标收敛为 需人工⚠/进行中🔄/终态✓/失败✗/中性○ 五态,绿勾仅限通知完成终态;队列 summary 三桶同口径。设计:[2026-09-16 队列图标语义设计](superpowers/specs/2026-09-16-review-queue-icon-semantics-design.md) |
```
- [ ] **Step 3: 全量回归**
Run: `cd backend && source venv/bin/activate && python -m pytest tests/test_shipping_order_review_service.py -v`
Expected: 全部 passed
Run: `cd frontend && npx vitest run src/features/chat/components/shipping-review/ReviewDocumentNavigation.spec.ts && npm run build`
Expected: 测试全过、构建通过
- [ ] **Step 4: 停在"完成、未提交"**
向用户汇报改动文件清单与验证结果;**不执行任何 git add/commit**,等用户指示。
@@ -0,0 +1,120 @@
# 订单队列图标语义重映射 + 门禁阻塞标志 设计文档
- 日期:2026-09-16
- 分支:hugo-shipping-notice
- 状态:待评审
## 1. 背景与问题
订单生命周期工作台左侧"本批订单队列"(`ReviewDocumentNavigation.vue`)的行内状态图标存在语义错位:
1. **绿勾被中间态占用**:图标映射把 Case 状态 `confirmed`(已创建任务)、`ready`(可确认)判为 `done` 画绿勾,但它们分别处于"系统/RPA 进行中"和"等待人工确认",并非终态。用户看到"通知准备/货代上传 · 已创建任务"亮绿勾,误读为"该阶段已完成"。`ready`(可确认)明明等人操作却画绿勾,是第二个语义错误。
2. **选中项图标被覆盖**:`navIconKind()` 首行"当前选中返回 `active`"使选中草稿单的 ⚠️ 被灰圈覆盖,图标不再如实反映状态(选中态已有蓝色边框+底色表达)。
3. **"进行中"与"中性"不可区分**:`processing`/`reparse_pending`/`confirmed` 与 `non_order`/`superseded` 都渲染灰圈。
4. **库存缺口阻塞在队列不可见**:`issue_count` 只统计草稿复核问题(`order_review_projection.py:1159`),通知准备阶段的库存缺口记录在 Process Gate(`blocked_manual` 等)上,队列序列化刻意不读阻断信息(`blocking_reason=None`,性能约束),队列无字段携带"被库存缺口卡住需人工"。
同页面顶部阶段条的视觉语言是 ✓=已完成、蓝点/转圈=进行中、🔒=阻塞;队列图标必须与之同义。
## 2. 目标 / 非目标
**目标**
- 队列行内图标收敛为行业通用的五态语义:需人工(黄⚠)/ 进行中(蓝转圈)/ 已完成(绿✓,仅终态)/ 失败(红✗)/ 中性(灰○)。
- 选中项只靠行高亮表达,图标永远如实反映状态。
- 后端队列 item 新增 `needs_attention` 标志,利用已批量预取的 Gate 缓存判定(零额外 SQL),使"库存缺口等门禁阻塞需人工"在队列可见。
- 队列 `summary` 计数与新语义对齐(现状把 `confirmed`/`quality_issue` 计入 completed,与新图标矛盾;前端已核实无消费方,仅测试引用)。
**非目标**
- 不改 Gate/Execution 写路径、状态机与任何动作授权。
- 不改队列接口既有字段语义(`issue_count`、`status`、`lifecycle_stage` 原样保留)。
- 不新增 i18n 文案(图标为 aria-hidden 装饰元素,状态文字已有)。
- 不改收起模式(数字轨)与窄屏抽屉(无图标)。
## 3. 设计原则
1. 一个图标只回答一个问题:"这单现在什么状态、要不要我处理"。
2. 图标永远如实反映状态;选中态由行高亮(既有蓝色边框+底色)表达。
3. 绿勾只属于终态;宁可少亮绿勾(用户多看一眼),不可错亮绿勾(漏单)。
4. 同页面同一图形必须同义(与顶部阶段条对齐)。
## 4. 前端:图标映射重写
文件:`frontend/src/features/chat/components/shipping-review/ReviewDocumentNavigation.vue`
`navIconKind()` 按以下优先级自上而下判定,命中即停。输入:`status`、`issue_count`、`needs_attention`、`lifecycle_stage`。
| 优先级 | 条件 | 图标 | 含义 |
| --- | --- | --- | --- |
| 1 | `status` ∈ {`failed`, `error`} | 红 ✗(X) | 失败 |
| 2 | `issue_count > 0` **或** `needs_attention === true` | 黄 ⚠️(TriangleAlert) | 需人工处理(草稿问题 / 门禁阻塞如库存缺口) |
| 3 | 终态:`lifecycle_stage === 'upload_complete'` 或 `status` ∈ {`completed`, `closed`} | 绿 ✓(Check) | 整单完成(通知完成) |
| 4 | 需人工状态:`status` ∈ {`draft`, `ready`, `unreviewed`, `quality_issue`, `pending_review`, `waiting_review`} | 黄 ⚠️(TriangleAlert) | 等人操作 |
| 5 | 进行中:`status` ∈ {`confirmed`, `processing`, `reparse_pending`, `queued`, `confirming`} | 蓝 🔄(LoaderCircle + animate-spin) | 系统/RPA 在办 |
| 6 | 中性:`status` ∈ {`non_order`, `cancelled`, `superseded`} | 灰 ○(Circle) | 不适用/已废弃 |
| 7 | 兜底(含 `unknown`) | 蓝 🔄(LoaderCircle + animate-spin) | 未知按仍在流转处理 |
- 删除 `active` 返回值与选中优先分支;返回值联合类型收敛为 `'alert' | 'done' | 'failed' | 'processing' | 'idle'`。
- `matchesStatusFilter()`:`processing` 过滤改判 `kind === 'processing'`(删 `|| kind === 'active'`)。
- 模板 tabs 分支与 sidebar 分支的图标链各插入 `LoaderCircle`(`h-3.5 w-3.5` + `animate-spin` + `text-brand-600`,与 `ReviewLifecycleStageNavigation.vue:85` 顶部阶段条进行中样式一致);沿用既有重复写法,不抽子组件。
- 视觉:⚠️ amber-500、✓ emerald-500、✗ rose-500、○ muted,全部不变。
- 注释同步(AGENTS.md §5.3):`navIconKind` docstring 写明优先级链与"绿勾=终态"约束;`lifecycle_stage` 字段注释更新为"用于阶段文字展示与终态(upload_complete)绿勾判定,不参与阶段裁决";`ReviewDocumentNavItem` 类型新增 `needs_attention?: boolean | null` 并注明来源为队列接口。
- 类型:`frontend/src/features/chat/types/shipping.api.types.ts` 的 `ShippingOrderReviewCaseSummary` 新增 `needs_attention?: boolean`(后端可选下发,缺省视为 false)。
对照截图的可见变化:6 个"通知准备/货代上传 · 已创建任务"绿勾 → 蓝转圈;"可确认"绿勾 → 黄⚠;仅"通知完成"终态亮绿勾。
## 5. 后端:needs_attention 标志
文件:`backend/app/services/shipping_notice/order_review_projection.py`
1. **现状复用**:`_load_review_case_summary_batch` 已批量预取 `executions_by_case_id` / `gates_by_execution_id` 并写入会话缓存(`:1333-1355`、`:1213-1215`),`_queue_current_gate_hint` 已从中取当前 Gate 码。本改动不新增任何 SQL。
2. **当前 Gate 判定**:优先 `execution.current_gate_code` 对应 Gate;缺失时按 `sequence_no` 取第一个状态 ∈ {`pending`, `queued`, `running`, `blocked_retryable`, `blocked_manual`, `waiting_external`, `failed_terminal`} 的 Gate(在 `_queue_current_gate_hint` 活跃口径上补 `queued` 与 `failed_terminal`,避免终态失败的单被漏判)。
3. **`needs_attention` 裁决**:当前 Gate `status` ∈ {`blocked_manual`, `blocked_retryable`, `failed_terminal`} → `true`;无 Execution / 无活跃 Gate → `false`。`waiting_external`(RPA 外部等待)、`running`/`pending`/`queued` 视为在办,不算需人工。
4. **输出**:`_serialize_review_case_summary` 返回 dict 新增 `'needs_attention': bool`;`serialize_review_run` 与 `serialize_review_queue` 两个队列数据源自动携带(共用同一序列化函数)。仅对 `case.confirmed_task_id` 存在的 Case 有意义,但字段恒输出(布尔,不缺键)。
5. **docstring**:函数注释写明裁决口径与"禁止前端自行推断阻塞"的约束。
## 6. 后端:summary 计数对齐
`serialize_review_queue` 的 counts(`order_review_projection.py:1447-1452`)重算,与 item 口径一致:
- `needs_action`:`status` ∈ {`unreviewed`, `draft`, `ready`, `quality_issue`} 或 `needs_attention` 为真。
- `completed`:终态——`status` ∈ {`non_order`, `closed`, `completed`} 或 `lifecycle_stage === 'upload_complete'`。
- `processing`:其余(`confirmed`/`confirming`/`reparse_pending` 等进行中)。
依据:前端已核实无任何组件消费 `queue.summary` 的三个计数(仅 `items` 与 `total` 语义被使用),后端仅 `backend/tests/test_shipping_order_review_service.py` 引用,风险可控。若不改,summary 的 completed 会与 item 的 needs_attention 图标互相矛盾,成为下一个"为什么"。
注意:summary 三个桶是"队列处置去向"粗粒度归类,与五态图标不是一一映射(如 `non_order` 计入 completed,但图标为中性别灰 ○);桶口径只需与"要不要再看这单"一致,不要求与图形一致。
## 7. 已知边界(明示,非缺陷)
- **阶段偏早(fail-safe)**:队列 `lifecycle_stage` 是轻量投影,极端场景(OT.stage 脏值且 Gate 缓存缺失)会兜回 `intake_parse`(`order_review_projection.py:1105`、`:1133`);异步回调成功但 OT.stage 未落库的瞬间也会短暂偏早。方向安全:完成单不亮绿勾只亮转圈,用户多看一眼;反向(未完成亮绿勾)不可能——`upload_complete` 仅由已持久化 `OT.stage == 'completed'` 驱动,队列不采信异步回执(`lifecycle_projection.py:138-146`)。
- **`ready` 归黄⚠ 的口径变化**:`ready`(可确认)从绿勾改为黄⚠。若产品上希望"可确认"用独立图标(如待办蓝框),另行迭代,本版不引入第六种图形。
## 8. 测试计划
**后端**(`backend/tests/test_shipping_order_review_service.py`)
- `confirmed` Case + 当前 Gate `blocked_manual`(库存缺口场景)→ item `needs_attention=true`,summary `needs_action` 含该单。
- 当前 Gate `waiting_external` → `needs_attention=false`。
- 无 Execution 的 `confirmed` Case → `needs_attention=false`。
- summary 计数:`quality_issue` 归 needs_action、`confirmed` 归 processing、`upload_complete` 归 completed。
- 关键断言按 `docs/test_plan_matrix.md` §1 附意图注释。
**前端**(`frontend/src/features/chat/components/shipping-review/ReviewDocumentNavigation.spec.ts`)
- 映射表逐行:`confirmed`→转圈、`ready`→⚠、`draft`→⚠、`upload_complete`→✓、`failed`→✗、`non_order`→○、`needs_attention=true`+`confirmed`→⚠。
- 选中项:选中 `draft` 单,图标仍为 ⚠(行高亮独立表达选中)。
- `needs_attention` 缺省(旧后端响应)→ 按 false 处理,不报错。
**构建**:`cd frontend && npm run build` 必须通过;后端跑相关 pytest 文件。
## 9. 文档同步(与代码同一提交/PR)
- `docs/features/shipping-notice/technical.md`:队列投影小节补 `needs_attention` 字段与五态图标口径。
- `docs/funclist.md`:涉及的功能条目措辞同步(如已有队列状态展示条目)。
## 10. 改动量与风险
- 后端 1 个文件(+辅助函数、+字段、+计数重算)+ 1 个测试文件;无迁移、无新依赖、无接口破坏性变更(纯增量字段)。
- 前端 2 个文件(组件 + 类型)+ 1 个测试文件。
- 主要风险:summary 计数语义变化(已核实无前端消费方);图标语义变化对用户习惯的影响(正是本次目的)。
@@ -64,7 +64,7 @@ export const workspaceRoutes: RouteRecordRaw[] = [
path: 'shipping-notice/customers',
name: 'workspace-shipping-customers',
component: () => import('@/features/shipping-notice/customers/ShippingCustomersPage.vue'),
meta: { title: '货代客户主数据', requiresAdmin: true },
meta: { title: '货代客户数据', requiresAdmin: true },
},
{
path: 'shipping-notice/my-tasks',
@@ -166,6 +166,16 @@ export const getWorkspaceShippingFreightNoticeGroups = (taskNo: string) =>
{ priority: 'low' },
);
/** 整单 ODM 裁决:保存行级选择(同快照文件行后端同步),随后可重试生成 Excel。 */
export const setWorkspaceShippingTaskOdmChoice = (
taskNo: string,
payload: { snapshot_line_id: string | number; odm_id: string },
) =>
requestJson<{ task_id: number; odm_id: string; synced_line_count: number; odm_values: string[] }>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/odm-choice`,
jsonPost(payload),
);
/**
* 分页拉取任务工作台统一审计时间线(ShippingAuditEvent 单源)。
*/
@@ -173,3 +173,64 @@ describe('ReviewDocumentNavigation', () => {
narrow.unmount();
});
});
describe('ReviewDocumentNavigation queue row status icons', () => {
/**
* 以指定字段挂载单行侧栏队列,返回该行按钮包装器。
*/
function mountRow(item: Partial<ReviewDocumentNavItem>) {
return mount(ReviewDocumentNavigation, {
props: {
items: [{ case_no: 'C-1', file_name: 'f1.pdf', status: 'draft', ...item }],
activeCaseNo: 'C-1',
navAriaLabel: 'nav',
forceMode: 'sidebar',
},
global: { plugins: [i18n] },
}).get('[data-testid="review-doc-nav-C-1"]');
}
it('renders confirmed cases as in-progress spinner instead of done check', () => {
const row = mountRow({ status: 'confirmed' });
// 关键断言:已创建任务是系统在办中间态,必须转圈而非绿勾。
expect(row.find('svg.animate-spin').exists()).toBe(true);
expect(row.find('svg.text-emerald-500').exists()).toBe(false);
});
it('renders ready-to-confirm cases as amber attention icon', () => {
const row = mountRow({ status: 'ready' });
// 关键断言:可确认是等人操作,属于待办而非完成。
expect(row.find('svg.text-amber-500').exists()).toBe(true);
});
it('renders backend gate-blocked cases as amber attention icon', () => {
const row = mountRow({ status: 'confirmed', needs_attention: true });
// 关键断言:needs_attention 是后端门禁裁决,优先于中间态转圈。
expect(row.find('svg.text-amber-500').exists()).toBe(true);
expect(row.find('svg.animate-spin').exists()).toBe(false);
});
it('reserves the green check for terminal upload_complete', () => {
const row = mountRow({ status: 'confirmed', lifecycle_stage: 'upload_complete' });
expect(row.find('svg.text-emerald-500').exists()).toBe(true);
expect(row.find('svg.animate-spin').exists()).toBe(false);
});
it('renders failed and neutral states as before', () => {
expect(mountRow({ status: 'failed' }).find('svg.text-rose-500').exists()).toBe(true);
const idle = mountRow({ status: 'non_order' });
expect(idle.find('svg.text-muted').exists()).toBe(true);
expect(idle.find('svg.animate-spin').exists()).toBe(false);
});
it('keeps the truthful state icon on the selected row', () => {
const row = mountRow({ status: 'draft' });
// 关键断言:选中态由行高亮表达,图标不再被 active 覆盖成灰圈。
expect(row.find('svg.text-amber-500').exists()).toBe(true);
});
it('treats missing needs_attention as false for old queue payloads', () => {
const row = mountRow({ status: 'confirmed', needs_attention: undefined });
expect(row.find('svg.animate-spin').exists()).toBe(true);
});
});
@@ -11,6 +11,7 @@ import {
ChevronLeft,
ChevronRight,
Circle,
LoaderCircle,
Search,
TriangleAlert,
X,
@@ -23,10 +24,12 @@ export type ReviewDocumentNavItem = {
file_name?: string | null;
status: string;
issue_count?: number;
/** 队列接口按当前门禁裁决的"需人工"标志(blocked_manual/blocked_retryable/failed_terminal);前端禁止自行推断阻塞。 */
needs_attention?: boolean | null;
po_number?: string | null;
customer_name?: string | null;
stage_label?: string | null;
/** 队列接口下发的生命周期码;仅用于本地化展示,不参与阶段裁决。 */
/** 队列接口下发的生命周期码;用于阶段文字展示与终态(upload_complete)绿勾判定,不参与阶段裁决。 */
lifecycle_stage?: ReviewLifecycleStageCode | null;
};
@@ -118,17 +121,20 @@ function lifecycleStageLabel(item: ReviewDocumentNavItem): string | null {
}
/**
* 导航状态图标语义。
* 队列状态图标语义,按优先级命中即停:
* 失败 → 需人工(草稿问题数 / needs_attention 门禁阻塞)→ 终态绿勾
* → 等人状态 ⚠ → 系统在办转圈 → 中性灰圈 → 兜底转圈。
* 绿勾只属于终态(upload_complete / closed / completed);选中态由行高亮表达,
* 本函数不感知选中,图标永远如实反映状态。
*/
function navIconKind(item: ReviewDocumentNavItem): 'active' | 'alert' | 'processing' | 'done' | 'failed' | 'idle' {
if (props.activeCaseNo === item.case_no) return 'active';
function navIconKind(item: ReviewDocumentNavItem): 'alert' | 'done' | 'failed' | 'processing' | 'idle' {
const status = String(item.status || '').toLowerCase();
if (item.issue_count && item.issue_count > 0) return 'alert';
if (status === 'failed' || status === 'error') return 'failed';
if (status === 'confirmed' || status === 'completed' || status === 'ready' || status === 'closed') return 'done';
if (status === 'processing' || status === 'reparse_pending' || status === 'queued') return 'processing';
if (status === 'non_order' || status === 'cancelled' || status === 'superseded') return 'idle';
if (status === 'draft' || status === 'pending_review' || status === 'waiting_review') return 'alert';
if ((item.issue_count && item.issue_count > 0) || item.needs_attention === true) return 'alert';
if (item.lifecycle_stage === 'upload_complete' || status === 'completed' || status === 'closed') return 'done';
if (['draft', 'ready', 'unreviewed', 'quality_issue', 'pending_review', 'waiting_review'].includes(status)) return 'alert';
if (['confirmed', 'confirming', 'processing', 'reparse_pending', 'queued'].includes(status)) return 'processing';
if (['non_order', 'cancelled', 'superseded'].includes(status)) return 'idle';
return 'processing';
}
@@ -139,7 +145,7 @@ function matchesStatusFilter(item: ReviewDocumentNavItem): boolean {
if (statusFilter.value === 'all') return true;
const kind = navIconKind(item);
if (statusFilter.value === 'needs_action') return kind === 'alert';
if (statusFilter.value === 'processing') return kind === 'processing' || kind === 'active';
if (statusFilter.value === 'processing') return kind === 'processing';
if (statusFilter.value === 'done') return kind === 'done';
if (statusFilter.value === 'failed') return kind === 'failed';
return true;
@@ -218,6 +224,11 @@ function onSelect(caseNo: string) {
class="h-3.5 w-3.5 shrink-0 text-rose-500"
aria-hidden="true"
/>
<LoaderCircle
v-else-if="navIconKind(item) === 'processing'"
class="h-3.5 w-3.5 shrink-0 animate-spin text-brand-600"
aria-hidden="true"
/>
<Circle
v-else
class="h-3 w-3 shrink-0 text-muted"
@@ -329,6 +340,10 @@ function onSelect(caseNo: string) {
v-else-if="navIconKind(item) === 'failed'"
class="mt-0.5 h-3.5 w-3.5 shrink-0 text-rose-500"
/>
<LoaderCircle
v-else-if="navIconKind(item) === 'processing'"
class="mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin text-brand-600"
/>
<Circle
v-else
class="mt-0.5 h-3 w-3 shrink-0 text-muted"
@@ -771,6 +771,48 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(false);
});
it('beginCrossRunSwitch drops the previous file intake context and rejects its stale success', async () => {
// 关键断言:跨 Run 切文件(如 PO_6075309 → PO_6075316)切换即清空接收解析上下文,
// 迟到的旧 Case 上下文成功响应也不得把旧附件名/邮件正文写回新文件工作面。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.ensureIntakeParseContextLoaded('CASE-1');
expect(review.intakeParseContext.value?.attachment.filename).toBe('order.pdf');
let resolveStale: ((value: Record<string, unknown>) => void) | null = null;
api.getIntakeParseContext.mockImplementationOnce(
() => new Promise((resolve) => { resolveStale = resolve; }),
);
const pendingStale = review.ensureIntakeParseContextLoaded('CASE-1');
review.beginCrossRunSwitch('CASE-2');
expect(review.intakeParseContext.value).toBeNull();
expect(review.intakeParseLoading.value).toBe(false);
expect(review.intakeParseLoadFailed.value).toBe(false);
resolveStale?.({
case_no: 'CASE-1',
attachment: { document_id: 1, filename: 'order.pdf', mime_type: 'application/pdf', preview_kind: 'pdf' },
email: null,
});
await pendingStale;
expect(review.intakeParseContext.value).toBeNull();
});
it('load fast path drops the stale intake context when the target Case changes', async () => {
// 关键断言:稳定工作台直达 load 换 Case(重解析落位/重试等入口)同样撤销旧上下文。
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1');
await review.ensureIntakeParseContextLoaded('CASE-1');
expect(review.intakeParseContext.value?.case_no).toBe('CASE-1');
api.getCase.mockResolvedValue(buildCase({ case_no: 'CASE-2', document: { id: 2, file_name: 'second.pdf' } }));
await review.load('RUN-1', 'CASE-2');
expect(review.activeCase.value?.case_no).toBe('CASE-2');
expect(review.intakeParseContext.value).toBeNull();
expect(review.intakeParseLoading.value).toBe(false);
});
it('discards stale selectCase responses when switching PDFs quickly', async () => {
// 关键断言:A 后发先至不得覆盖后选的 B;切换时先清空瞬态。
let resolveA: ((value: ShippingOrderReviewCase) => void) | null = null;
@@ -1096,6 +1096,13 @@ export function useShippingOrderReview(options: {
// 已有稳定工作台且路由明确目标 PDF 时,目标详情是用户切换的关键路径;
// Run/Queue 只负责后续更新导航和阶段摘要,不能用其慢投影阻塞当前文件显示。
if (hasStableWorkbench && preferredCaseNo) {
// 稳定工作台直达 load 换 Case 时(如重解析落位/重试),同样必须撤销旧文件的
// 接收解析上下文;新上下文由视图层 Case 变化 watcher 按目标 Case 重载。
if (String(preferredCaseNo || '').trim() !== String(activeCase.value?.case_no || '').trim()) {
intakeParseContext.value = null;
intakeParseLoading.value = false;
intakeParseLoadFailed.value = false;
}
const [caseSnapshot, caseEvidence] = await Promise.all([
getWorkspaceShippingOrderReviewCase(preferredCaseNo),
getWorkspaceShippingOrderReviewEvidence(preferredCaseNo),
@@ -1189,6 +1196,8 @@ export function useShippingOrderReview(options: {
* 核心逻辑:保留 activeCase/工作台壳(避免大骨架闪动),但清空 user_task_no,
* 让 shippingProcessingProjection 立即丢弃上一份 PDF 的右卡/库存态;目标 Case
* 仍由随后的 load(preferredCaseNo) 目标优先路径写入。
* 接收解析上下文必须与预览一并撤销:Run 变更即 Case 变更,旧文件的附件名/邮件正文
* 不得残留在新文件工作面(新上下文由视图层 Case 变化 watcher 重载)。
* @param caseNo - 目标复核 Case 编号
*/
const beginCrossRunSwitch = (caseNo: string) => {
@@ -1212,6 +1221,9 @@ export function useShippingOrderReview(options: {
};
}
clearPreview();
intakeParseContext.value = null;
intakeParseLoading.value = false;
intakeParseLoadFailed.value = false;
};
/**
@@ -1498,6 +1498,15 @@ export interface ShippingTaskUiState {
}>;
/** 人工覆写库存源(方案 3·放开):全部已启用源,供行级下拉人工指定。 */
source_options?: Array<{ source_code?: string | null; display_name?: string | null }>;
/**
* 整单 ODM 裁决摘要:conflict=true 表示范围限定后仍有多行存在多值,
* 由行内 odm 下发候选,用户改任一行后同一快照文件的其他行同步。
*/
odm_options?: {
conflict?: boolean;
customer_odm_ids?: Array<string>;
whitelist_applied?: boolean;
};
/** 阶段能力(Task 2 下发);prep 工作台能力工具条消费,scope=task 级。 */
capabilities?: ShippingStageCapability[];
/** 仅当前任务活动关联的库存快照才可下载。 */
@@ -1523,6 +1532,10 @@ export interface ShippingTaskUiState {
/** 多文件冲突行(D5):候选源列表供行内下拉,选定后走 override_line_inventory_source。 */
source_ambiguous?: boolean;
source_candidates?: Array<string>;
/** 整单 ODM 裁决:本行候选(经客户范围过滤);同快照文件行同步同一 chosen 值。 */
odm_values?: Array<string>;
chosen_odm_id?: string | null;
odm_conflict?: boolean;
}>;
artifact?: { file_name?: string | null; status?: string | null } | null;
} | null;
@@ -2307,6 +2320,8 @@ export interface ShippingOrderReviewCaseSummary {
intake_parse_authorized?: boolean;
draft_version?: number | null;
issue_count: number;
/** 队列后端按当前门禁裁决:blocked_manual/blocked_retryable/failed_terminal 为 true;前端禁止自行推断阻塞。 */
needs_attention?: boolean;
available_actions: string[];
/** 仅 parse_failed 时由后端下发,供当前阶段卡调用原 Intake retry API。 */
intake_no?: string | null;
@@ -38,6 +38,7 @@ import {
retryShippingNoticeIntake,
decideWorkspaceShippingOrderReviewLineFulfillment,
waveWorkspaceShippingOrderReviewLineFulfillment,
setWorkspaceShippingTaskOdmChoice,
viewWorkspaceShippingOrderReviewHighlightDiagnostic,
} from '../api/shipping.api';
import type {
@@ -2643,6 +2644,38 @@ async function submitOverrideSource(line: { snapshot_line_id?: number | null; li
}
}
/** 整单 ODM 裁决列可见性:任一行候选多于一个时展示(候选已经客户范围过滤)。 */
const formalPreparationOdmColumnVisible = computed(() =>
(formalPreparationContext.value?.lines || []).some((line) => (line.odm_values?.length || 0) > 1),
);
const lineOdmSelections = ref<Record<string, string>>({});
const lineOdmBusy = ref(false);
/**
* 提交行级 ODM 选择:后端把同一快照文件的全部当前匹配行同步为同一值,
* 刷新详情后其他行回显同步结果,并在门禁仍授权时自动重试生成 Excel。
*/
async function submitLineOdmChoice(line: { snapshot_line_id?: number | null }) {
const selectionKey = String(line.snapshot_line_id ?? '');
const odmId = String(lineOdmSelections.value[selectionKey] || '').trim();
const taskNo = String(confirmedNoticeTaskNo.value || '').trim();
if (!odmId || !taskNo || lineOdmBusy.value) return;
lineOdmBusy.value = true;
try {
await setWorkspaceShippingTaskOdmChoice(taskNo, { snapshot_line_id: selectionKey, odm_id: odmId });
delete lineOdmSelections.value[selectionKey];
await loadFormalTaskDetail();
const canRegenerate = formalTaskActions.value.some(
(action) => action.enabled && String(action.code || '').trim() === 'regenerate_excel_artifact',
);
if (canRegenerate) await submitFormalGateAction('regenerate_excel_artifact');
} catch (error) {
msg.error(resolveReviewErrorMessage(error));
} finally {
lineOdmBusy.value = false;
}
}
function formalPreparationLineAllows(
line: { snapshot_line_id?: number | null },
action: 'retry_inventory_preparation' | 'retry_inventory_matching' | 'close_unfulfillable' | 'release_inventory_shortage',
@@ -4397,7 +4430,14 @@ watch(
);
watch(
[lifecycleActiveStageCode, hasFormalOt, intakeParseContextAuthorized],
[
lifecycleActiveStageCode,
hasFormalOt,
intakeParseContextAuthorized,
// 接收解析文件互切时 stage/授权通常不变;必须以 Case 变化触发新附件/邮件上下文重载,
// 否则接收解析工作面停留上一份 PDF 的附件名且预览不再自动加载。
() => String(activeCase.value?.case_no || '').trim(),
],
([code, , intakeAuthorized]) => {
// 确认进度是当前阶段内的短暂辅助视图,不由生命周期页签覆盖。
if (workbenchMode.value === 'confirm_progress') return;
@@ -4857,12 +4897,12 @@ watch(
class="rounded-full bg-brand-50 px-2.5 py-1 text-xs font-medium text-brand-700 dark:bg-brand-950/30 dark:text-brand-300"
>{{ formalPreparationStatusLabel(formalPreparationContext?.status) }}</span>
</div>
<div v-if="formalPreparationDisplayLines.length" class="review-fulfillment-prep-workspace mt-4 rounded-lg border border-default" data-testid="review-fulfillment-prep-workspace">
<!-- 标题与选行操作条固定不参与横向滚动,仅表头/表体横向滑动。 -->
<div class="flex items-center justify-between gap-3 border-b border-default bg-surface-muted/30 px-3 py-2">
<div class="text-xs font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.prepare.matchWorkspace') }}</div>
<span class="text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineCount', { count: formalPreparationDisplayLines.length }) }}</span>
</div>
<div v-if="formalPreparationDisplayLines.length" class="review-fulfillment-prep-workspace mt-4 rounded-lg border border-default" data-testid="review-fulfillment-prep-workspace">
<!-- 标题与选行操作条固定不参与横向滚动,仅表头/表体横向滑动。 -->
<div class="flex items-center justify-between gap-3 border-b border-default bg-surface-muted/30 px-3 py-2">
<div class="text-xs font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.prepare.matchWorkspace') }}</div>
<span class="text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineCount', { count: formalPreparationDisplayLines.length }) }}</span>
</div>
<div v-if="preparationEditable && formalHeaderEditable()" class="flex flex-wrap items-center justify-between gap-2 border-b border-default bg-brand-50/50 px-3 py-2 text-xs dark:bg-brand-950/20">
<div class="flex items-center gap-3 text-secondary">
<span class="font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.selectReady') }}</span>
@@ -4872,8 +4912,8 @@ watch(
</div>
<div class="overflow-x-auto overscroll-x-contain" data-testid="review-fulfillment-prep-table-scroll">
<table class="review-fulfillment-prep-table min-w-[1060px] text-xs">
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
<tbody><tr v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`" :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary">{{ line.reservation_id || '—' }}</td><td class="max-w-[220px] truncate px-3 py-2" :title="line.part_number || '—'">{{ line.part_number || '—' }}</td><td class="whitespace-nowrap px-3 py-2">{{ line.required_qty ?? '—' }}</td><td class="max-w-[220px] px-3 py-2"><div v-if="line.source_ambiguous && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-source-ambiguous-${line.snapshot_line_id || lineIndex}`" :title="t('chat.shippingOrderReview.lifecycle.prepare.sourceAmbiguous')"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-source-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="lineSourceSelections[String(line.snapshot_line_id || lineIndex)] || line.source_code || ''" @change="lineSourceSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.lifecycle.prepare.selectSource') }}</option><option v-for="code in line.source_candidates || []" :key="code" :value="code">{{ lineSourceOptionLabel(code) }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-source-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineSourceSelections[String(line.snapshot_line_id || lineIndex)] || lineSourceBusy || !preparationEditable" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" @click="submitLineSourceSelection(line)"><Check class="h-3.5 w-3.5" /></button></div><span v-else-if="line.source_ambiguous && formalPreparationSourceLocked" class="text-xs text-secondary" :title="t('chat.shippingOrderReview.lifecycle.prepare.sourceLocked')">{{ t('chat.shippingOrderReview.lifecycle.prepare.sourceLocked') }}</span><span v-else-if="!formalPreparationSourceLocked && formSourceOptions.length" class="flex items-center gap-1" :data-testid="`review-line-source-override-${line.snapshot_line_id || lineIndex}`" :title="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-source-override-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] || line.selected_source_code || line.source_code || ''" @change="overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.lifecycle.prepare.selectSource') }}</option><option v-for="s in formSourceOptions" :key="String(s.source_code)" :value="String(s.source_code)">{{ overrideSourceOptionLabel(String(s.source_code)) }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-source-override-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] || overrideSourceBusy" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :data-line-index="lineIndex" @click="submitOverrideSource(line)"><Check class="h-3.5 w-3.5" /></button></span><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) }}</span></td><td class="whitespace-nowrap px-3 py-2">{{ line.available_qty ?? '—' }}</td><td class="whitespace-nowrap px-3 py-2 font-medium" :class=Line truncated
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.odmConflict.column') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
<tbody><tr v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`" :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary">{{ line.reservation_id || '—' }}</td><td class="max-w-[220px] truncate px-3 py-2" :title="line.part_number || '—'">{{ line.part_number || '—' }}</td><td class="whitespace-nowrap px-3 py-2">{{ line.required_qty ?? '—' }}</td><td class="max-w-[220px] px-3 py-2"><div v-if="line.source_ambiguous && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-source-ambiguous-${line.snapshot_line_id || lineIndex}`" :title="t('chat.shippingOrderReview.lifecycle.prepare.sourceAmbiguous')"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-source-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="lineSourceSelections[String(line.snapshot_line_id || lineIndex)] || line.source_code || ''" @change="lineSourceSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.lifecycle.prepare.selectSource') }}</option><option v-for="code in line.source_candidates || []" :key="code" :value="code">{{ lineSourceOptionLabel(code) }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-source-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineSourceSelections[String(line.snapshot_line_id || lineIndex)] || lineSourceBusy || !preparationEditable" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" @click="submitLineSourceSelection(line)"><Check class="h-3.5 w-3.5" /></button></div><span v-else-if="line.source_ambiguous && formalPreparationSourceLocked" class="text-xs text-secondary" :title="t('chat.shippingOrderReview.lifecycle.prepare.sourceLocked')">{{ t('chat.shippingOrderReview.lifecycle.prepare.sourceLocked') }}</span><span v-else-if="!formalPreparationSourceLocked && formSourceOptions.length" class="flex items-center gap-1" :data-testid="`review-line-source-override-${line.snapshot_line_id || lineIndex}`" :title="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-source-override-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] || line.selected_source_code || line.source_code || ''" @change="overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.lifecycle.prepare.selectSource') }}</option><option v-for="s in formSourceOptions" :key="String(s.source_code)" :value="String(s.source_code)">{{ overrideSourceOptionLabel(String(s.source_code)) }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-source-override-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!overrideSourceSelections[String(line.snapshot_line_id || lineIndex)] || overrideSourceBusy" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :data-line-index="lineIndex" @click="submitOverrideSource(line)"><Check class="h-3.5 w-3.5" /></button></span><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalLine truncated
</table>
</div>
</div>
@@ -58,16 +58,21 @@ onMounted(() => { void Promise.all([admin.loadCustomers(), admin.loadShadowRepor
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.name') }}</th>
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.shortCode') }}</th>
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.status') }}</th>
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.odmIds') }}</th>
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.identityEvidences') }}</th>
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.notices') }}</th>
<th class="px-5 py-4 text-right">{{ t('admin.shippingCustomers.headers.actions') }}</th>
</tr></thead>
<tbody>
<tr v-if="admin.customers.value.length === 0"><td colspan="6" class="admin-table-empty px-5">{{ t('admin.shippingCustomers.empty') }}</td></tr>
<tr v-if="admin.customers.value.length === 0"><td colspan="7" class="admin-table-empty px-5">{{ t('admin.shippingCustomers.empty') }}</td></tr>
<tr v-for="customer in admin.customers.value" :key="customer.id">
<td class="px-5 py-4"><div class="font-medium text-primary">{{ customer.standard_name }}</div><div v-if="customer.remark" class="text-xs text-muted truncate max-w-sm">{{ customer.remark }}</div></td>
<td class="px-5 py-4 font-mono text-sm">{{ customer.short_code }}</td>
<td class="px-5 py-4"><span class="text-sm" :class="customer.status === 'active' ? 'text-emerald-600' : 'text-muted'">{{ t(`admin.shippingCustomers.status.${customer.status}`) }}</span></td>
<td class="px-5 py-4 text-sm">
<span v-if="customer.odm_ids?.length" class="font-mono text-xs">{{ customer.odm_ids.join(', ') }}</span>
<span v-else class="text-xs text-muted">{{ t('admin.shippingCustomers.fields.odmIdsUnlimited') }}</span>
</td>
<td class="px-5 py-4 text-sm">{{ customer.identity_evidence_count || 0 }}</td>
<td class="px-5 py-4 text-sm">{{ customer.notice_count }}</td>
<td class="px-5 py-4"><div class="flex justify-end gap-1">
@@ -42,6 +42,16 @@ const { t } = useI18n();
<span class="label-field">{{ t('admin.shippingCustomers.fields.remark') }}</span>
<textarea v-model="form.remark" rows="3" class="input-field text-sm resize-y" />
</label>
<label class="block space-y-1.5">
<span class="label-field">{{ t('admin.shippingCustomers.fields.odmIds') }}</span>
<textarea
v-model="form.odm_ids_text"
rows="3"
class="input-field text-sm resize-y font-mono"
:placeholder="t('admin.shippingCustomers.fields.odmIdsHint')"
/>
<span class="text-xs text-muted">{{ t('admin.shippingCustomers.fields.odmIdsHint') }}</span>
</label>
<label v-if="form.id" class="block space-y-1.5">
<span class="label-field">{{ t('admin.shippingCustomers.fields.changeReason') }}</span>
<textarea v-model="form.reason" rows="2" class="input-field text-sm resize-y" :placeholder="t('admin.shippingCustomers.fields.changeReasonHint')" />
@@ -158,11 +158,21 @@ export function useShippingCustomersAdmin() {
}
isSaving.value = true;
try {
// ODM ID 清单:文本域逐行解析,去空去重;整体为空提交 null 表示不限定。
const odmIds = Array.from(
new Set(
form.odm_ids_text
.split(/\r?\n/)
.map((item) => item.trim())
.filter(Boolean),
),
);
const payload = {
standard_name: form.standard_name.trim(),
short_code: form.short_code.trim().toUpperCase(),
status: form.status,
remark: form.remark.trim(),
odm_ids: odmIds.length ? odmIds : null,
reason: form.reason.trim(),
};
if (form.id) await updateShippingCustomer(form.id, payload);
@@ -29,6 +29,8 @@ export interface ShippingCustomerRow {
status: ShippingCustomerStatus;
merged_into_customer_id?: number | null;
remark?: string | null;
/** 客户可用的 ODM ID 清单;null/空数组表示不限定。 */
odm_ids?: string[] | null;
notice_count: number;
identifier_count: number;
identity_evidence_count?: number;
@@ -282,6 +284,8 @@ export interface ShippingCustomerFormState {
short_code: string;
status: ShippingCustomerStatus;
remark: string;
/** 文本域原文:每行一个 ODM ID;保存时解析为 odm_ids 数组。 */
odm_ids_text: string;
reason: string;
}
@@ -309,6 +313,7 @@ export const createEmptyShippingCustomerForm = (): ShippingCustomerFormState =>
short_code: '',
status: 'active',
remark: '',
odm_ids_text: '',
reason: '',
});
@@ -319,6 +324,7 @@ export const shippingCustomerToForm = (customer: ShippingCustomerRow): ShippingC
short_code: customer.short_code,
status: customer.status,
remark: customer.remark || '',
odm_ids_text: (customer.odm_ids || []).join('\n'),
reason: '',
});
+8 -4
View File
@@ -2469,7 +2469,7 @@
"normalizer": "Text handling",
"displayName": "Rule name",
"displayNamePlaceholder": "For example: US customer sender email",
"evidenceLabel": "Evidence name in customer master data",
"evidenceLabel": "Evidence name in customer data",
"evidenceLabelPlaceholder": "For example: Customer business email",
"description": "Usage note (optional)",
"descriptionPlaceholder": "For example: Identifies Bill-to customers in the US region",
@@ -2482,8 +2482,8 @@
"addDefinition": "Add business definition",
"definitionSaved": "Identity definition saved",
"workflowTitle": "Configuration sequence",
"workflowHint": "1. Add identity definitions; 2. create, save, and publish a rule set; 3. return to customer master data to maintain customer or delivery-site evidence.",
"openCustomerMaster": "Open customer master data",
"workflowHint": "1. Add identity definitions; 2. create, save, and publish a rule set; 3. return to customer data to maintain customer or delivery-site evidence.",
"openCustomerMaster": "Open customer data",
"ruleSets": "Rule set versions",
"ruleSetHint": "Published snapshots are immutable. Replace or retire definitions before retiring a referenced order field.",
"publishedDefinitions": "Definitions actually published in this version",
@@ -2510,7 +2510,7 @@
"selectFieldHint": "Only currently published order-header fields enabled for customer identity can be selected."
},
"shippingCustomers": {
"title": "Shipping Customer Master Data",
"title": "Shipping Customer Data",
"subtitle": "Maintain stable customer identities, short codes, identifiers, and initial imports",
"add": "Add Customer",
"edit": "Edit Customer",
@@ -2595,12 +2595,16 @@
"shortCodeHint": "2-6 letters; saved in uppercase",
"status": "Status",
"remark": "Remark",
"odmIds": "ODM ID scope",
"odmIdsHint": "One ODM ID per line; leave empty for no restriction",
"odmIdsUnlimited": "Unrestricted",
"changeReason": "Change reason",
"changeReasonHint": "Required when changing short code or status"
},
"headers": {
"name": "Customer",
"shortCode": "Short code",
"odmIds": "ODM ID scope",
"status": "Status",
"identifiers": "Identifiers",
"identityEvidences": "Configured evidence",
+8
View File
@@ -2204,6 +2204,14 @@
"reservation_duplicate": "Duplicate reservation ID"
}
},
"odmConflict": {
"title": "This reservation matches multiple ODM IDs. Choose the ODM ID for this shipment",
"placeholder": "Select ODM ID",
"confirm": "Confirm & regenerate",
"saving": "Submitting...",
"hint": "Other lines on the same snapshot file use this ODM ID too; Excel generation retries automatically",
"column": "ODM ID"
},
"fulfillmentDecision": {
"title": "Line fulfillment decisions",
"subtitle": "Select inventory-ready or manually released lines to create an independent shipping notice and Excel.",
+1
View File
@@ -1,6 +1,7 @@
{
"generic": "Request failed.",
"codes": {
"SHIPPING.NOTICE_ODM_CHOICE_INVALID": "The selected ODM ID is not among the feasible candidates. Please choose again.",
"SHIPPING.FULFILLMENT_POLICY_INVALID": "The fulfillment policy or field capability binding is invalid.",
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "The fulfillment policy was not found.",
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "The fulfillment policy was changed by another administrator. Refresh and try again.",
+1 -1
View File
@@ -101,7 +101,7 @@
"scheduleRuns": "Schedule Runs",
"receiptReports": "Receipt Files",
"shippingNotice": "Shipping Notice",
"shippingCustomers": "Customer Master Data",
"shippingCustomers": "Customer Data",
"shippingTasks": "Shipping Tasks",
"shippingMyTasks": "My To-Dos",
"feedback": "Feedback",
+8 -4
View File
@@ -2338,7 +2338,7 @@
"normalizer": "วิธีจัดการข้อความ",
"displayName": "ชื่อกฎ",
"displayNamePlaceholder": "เช่น อีเมลผู้ส่งของลูกค้าสหรัฐ",
"evidenceLabel": "ชื่อหลักฐานในข้อมูลหลักลูกค้า",
"evidenceLabel": "ชื่อหลักฐานในข้อมูลลูกค้า",
"evidenceLabelPlaceholder": "เช่น อีเมลธุรกิจของลูกค้า",
"description": "คำอธิบายการใช้ (ไม่บังคับ)",
"descriptionPlaceholder": "เช่น ใช้ระบุลูกค้าผู้ชำระเงินในภูมิภาคสหรัฐ",
@@ -2351,8 +2351,8 @@
"addDefinition": "เพิ่มนิยามธุรกิจ",
"definitionSaved": "บันทึกนิยามการระบุตัวตนแล้ว",
"workflowTitle": "ลำดับการตั้งค่า",
"workflowHint": "1. เพิ่มนิยามการระบุตัวตน 2. สร้าง บันทึก และเผยแพร่ชุดกฎ 3. กลับไปที่ข้อมูลหลักลูกค้าเพื่อดูแลหลักฐานของลูกค้าหรือสถานที่จัดส่ง",
"openCustomerMaster": "ไปที่ข้อมูลหลักลูกค้า",
"workflowHint": "1. เพิ่มนิยามการระบุตัวตน 2. สร้าง บันทึก และเผยแพร่ชุดกฎ 3. กลับไปที่ข้อมูลลูกค้าเพื่อดูแลหลักฐานของลูกค้าหรือสถานที่จัดส่ง",
"openCustomerMaster": "ไปที่ข้อมูลลูกค้า",
"ruleSets": "เวอร์ชันชุดกฎ",
"ruleSetHint": "สแนปช็อตที่เผยแพร่แล้วแก้ไขไม่ได้ ต้องแทนที่หรือเลิกใช้นิยามก่อนเลิกใช้ฟิลด์คำสั่งซื้อที่ถูกอ้างอิง",
"publishedDefinitions": "คำจำกัดความที่เผยแพร่จริงในเวอร์ชันนี้",
@@ -2379,7 +2379,7 @@
"selectFieldHint": "แสดงเฉพาะฟิลด์ Header ที่เปิดใช้สำหรับการระบุตัวตนลูกค้าในเวอร์ชันปัจจุบัน"
},
"shippingCustomers": {
"title": "ข้อมูลหลักลูกค้าขนส่ง",
"title": "ข้อมูลลูกค้าขนส่ง",
"subtitle": "จัดการตัวตนลูกค้า รหัสย่อ หลักฐานระบุตัวตน และการนำเข้าข้อมูลตั้งต้น",
"add": "เพิ่มลูกค้า",
"edit": "แก้ไขลูกค้า",
@@ -2464,12 +2464,16 @@
"shortCodeHint": "ตัวอักษร 2-6 ตัว บันทึกเป็นตัวพิมพ์ใหญ่",
"status": "สถานะ",
"remark": "หมายเหตุ",
"odmIds": "ขอบเขต ODM ID",
"odmIdsHint": "หนึ่ง ODM ID ต่อบรรทัด เว้นว่างหากไม่จำกัด",
"odmIdsUnlimited": "ไม่จำกัด",
"changeReason": "เหตุผลการเปลี่ยนแปลง",
"changeReasonHint": "ต้องระบุเมื่อแก้ไขรหัสย่อหรือสถานะ"
},
"headers": {
"name": "ลูกค้า",
"shortCode": "รหัสย่อ",
"odmIds": "ขอบเขต ODM ID",
"status": "สถานะ",
"identifiers": "หลักฐานระบุตัวตน",
"identityEvidences": "หลักฐานที่กำหนดค่า",
+8
View File
@@ -2204,6 +2204,14 @@
"reservation_duplicate": "Reservation ID ซ้ำ"
}
},
"odmConflict": {
"title": "ใบจองนี้ตรงกับ ODM ID หลายรายการ โปรดเลือก ODM ID ที่ใช้สำหรับการจัดส่งครั้งนี้",
"placeholder": "เลือก ODM ID",
"confirm": "ยืนยันและสร้างใหม่",
"saving": "กำลังส่ง...",
"hint": "แถวอื่นในไฟล์สแนปชอตเดียวกันจะใช้ ODM ID เดียวกัน และสร้าง Excel ใหม่โดยอัตโนมัติ",
"column": "ODM ID"
},
"fulfillmentDecision": {
"title": "การตัดสินใจการปฏิบัติตามบรรทัด",
"subtitle": "เลือกหลายบรรทัดที่สต็อกพร้อมหรืออนุมัติด้วยมือ เพื่อสร้างใบแจ้งการจัดส่งและ Excel แยกอิสระ",
+1
View File
@@ -1,6 +1,7 @@
{
"generic": "คำขอล้มเหลว",
"codes": {
"SHIPPING.NOTICE_ODM_CHOICE_INVALID": "ODM ID ที่เลือกไม่อยู่ในตัวเลือกที่ทำได้ โปรดเลือกใหม่",
"SHIPPING.FULFILLMENT_POLICY_INVALID": "นโยบายการปฏิบัติตามหรือการผูกความสามารถของฟิลด์ไม่ถูกต้อง",
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "ไม่พบนโยบายการปฏิบัติตาม",
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "นโยบายการปฏิบัติตามถูกแก้ไขโดยผู้ดูแลรายอื่น โปรดรีเฟรชแล้วลองใหม่",
+1 -1
View File
@@ -92,7 +92,7 @@
"scheduleRuns": "บันทึกตารางงาน",
"receiptReports": "ไฟล์รับสินค้า",
"shippingNotice": "ใบแจ้งส่งสินค้า",
"shippingCustomers": "ข้อมูลหลักลูกค้า",
"shippingCustomers": "ข้อมูลลูกค้า",
"shippingTasks": "งานจัดส่ง",
"shippingMyTasks": "งานที่ต้องทำของฉัน",
"feedback": "ข้อเสนอแนะ",
+8 -4
View File
@@ -2581,7 +2581,7 @@
"normalizer": "文本处理方式",
"displayName": "规则名称",
"displayNamePlaceholder": "例如:美国客户发件人邮箱",
"evidenceLabel": "客户主数据中的证据名称",
"evidenceLabel": "客户数据中的证据名称",
"evidenceLabelPlaceholder": "例如:客户业务邮箱",
"description": "使用说明(可选)",
"descriptionPlaceholder": "例如:用于识别美国区域的账款客户",
@@ -2595,8 +2595,8 @@
"addDefinition": "新增业务定义",
"definitionSaved": "识别定义已保存",
"workflowTitle": "配置顺序",
"workflowHint": "1. 新增识别定义;2. 创建、保存并发布规则集;3. 返回客户主数据维护客户或送货站点证据。",
"openCustomerMaster": "前往客户主数据维护证据",
"workflowHint": "1. 新增识别定义;2. 创建、保存并发布规则集;3. 返回客户数据维护客户或送货站点证据。",
"openCustomerMaster": "前往客户数据维护证据",
"ruleSets": "规则集版本",
"ruleSetHint": "发布后规则快照不可修改;订单字段退役前必须先替换或退役引用它的定义。",
"publishedDefinitions": "本版本实际发布的识别定义",
@@ -2622,7 +2622,7 @@
}
},
"shippingCustomers": {
"title": "货代客户主数据",
"title": "货代客户数据",
"subtitle": "维护稳定客户身份、客户简码、识别证据与期初导入",
"add": "新增客户",
"edit": "编辑客户",
@@ -2707,12 +2707,16 @@
"shortCodeHint": "2-6 位英文字母,保存后统一转为大写",
"status": "状态",
"remark": "备注",
"odmIds": "ODM ID 范围",
"odmIdsHint": "每行一个 ODM ID;留空表示不限定",
"odmIdsUnlimited": "不限定",
"changeReason": "变更原因",
"changeReasonHint": "修改简码或状态时必须填写"
},
"headers": {
"name": "客户名称",
"shortCode": "简码",
"odmIds": "ODM ID 范围",
"status": "状态",
"identifiers": "识别证据",
"identityEvidences": "配置化证据",
+8
View File
@@ -2311,6 +2311,14 @@
"reservation_duplicate": "预约单号重复"
}
},
"odmConflict": {
"title": "该预约单命中多个 ODM ID,请选择本次发货使用的 ODM ID",
"placeholder": "请选择 ODM ID",
"confirm": "确认并重新生成",
"saving": "提交中...",
"hint": "同一快照文件的其他行会同步使用该 ODM ID,确认后自动重试生成 Excel",
"column": "ODM ID"
},
"fulfillmentDecision": {
"title": "行级履约决定",
"subtitle": "可多选库存满足或已人工放行的明细,生成独立发货通知和 Excel。",
+1
View File
@@ -1,6 +1,7 @@
{
"generic": "请求失败。",
"codes": {
"SHIPPING.NOTICE_ODM_CHOICE_INVALID": "所选 ODM ID 不在当前可行候选内,请重新选择。",
"SHIPPING.FULFILLMENT_POLICY_INVALID": "货代履约策略或字段能力绑定无效。",
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "未找到货代履约策略。",
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "货代履约策略已被其他管理员修改,请刷新后重试。",
+1 -1
View File
@@ -101,7 +101,7 @@
"scheduleRuns": "排程记录",
"receiptReports": "收料文件",
"shippingNotice": "货代发货",
"shippingCustomers": "客户主数据",
"shippingCustomers": "客户数据",
"shippingTasks": "发货任务",
"shippingMyTasks": "我的待办",
"feedback": "意见反馈",
+8 -4
View File
@@ -2343,7 +2343,7 @@
"normalizer": "文字處理方式",
"displayName": "規則名稱",
"displayNamePlaceholder": "例如:美國客戶寄件者電子郵件",
"evidenceLabel": "客戶主資料中的證據名稱",
"evidenceLabel": "客戶資料中的證據名稱",
"evidenceLabelPlaceholder": "例如:客戶業務電子郵件",
"description": "使用說明(可選)",
"descriptionPlaceholder": "例如:用於識別美國區域的帳款客戶",
@@ -2356,8 +2356,8 @@
"addDefinition": "新增業務定義",
"definitionSaved": "識別定義已儲存",
"workflowTitle": "設定順序",
"workflowHint": "1. 新增識別定義;2. 建立、儲存並發布規則集;3. 返回客戶主資料維護客戶或送貨站點證據。",
"openCustomerMaster": "前往客戶主資料維護證據",
"workflowHint": "1. 新增識別定義;2. 建立、儲存並發布規則集;3. 返回客戶資料維護客戶或送貨站點證據。",
"openCustomerMaster": "前往客戶資料維護證據",
"ruleSets": "規則集版本",
"ruleSetHint": "發布後快照不可修改;退役訂單欄位前必須先替換或退役其引用定義。",
"publishedDefinitions": "本版本實際發布的識別定義",
@@ -2384,7 +2384,7 @@
"selectFieldHint": "只顯示目前版本中已啟用客戶識別的 Header 欄位"
},
"shippingCustomers": {
"title": "貨代客戶主資料",
"title": "貨代客戶資料",
"subtitle": "維護穩定客戶身份、客戶簡碼、識別證據與期初匯入",
"add": "新增客戶",
"edit": "編輯客戶",
@@ -2469,12 +2469,16 @@
"shortCodeHint": "2-6 位英文字母,儲存後統一轉為大寫",
"status": "狀態",
"remark": "備註",
"odmIds": "ODM ID 範圍",
"odmIdsHint": "每行一個 ODM ID;留空表示不限定",
"odmIdsUnlimited": "不限定",
"changeReason": "變更原因",
"changeReasonHint": "修改簡碼或狀態時必須填寫"
},
"headers": {
"name": "客戶名稱",
"shortCode": "簡碼",
"odmIds": "ODM ID 範圍",
"status": "狀態",
"identifiers": "識別證據",
"identityEvidences": "可設定證據",
+8
View File
@@ -2204,6 +2204,14 @@
"reservation_duplicate": "預約單號重複"
}
},
"odmConflict": {
"title": "該預約單命中多個 ODM ID,請選擇本次出貨使用的 ODM ID",
"placeholder": "請選擇 ODM ID",
"confirm": "確認並重新產生",
"saving": "提交中...",
"hint": "同一快照檔案的其他行會同步使用該 ODM ID,確認後自動重試產生 Excel",
"column": "ODM ID"
},
"fulfillmentDecision": {
"title": "行級履約決定",
"subtitle": "可多選庫存滿足或已人工放行的明細,產生獨立發貨通知和 Excel。",
+1
View File
@@ -1,6 +1,7 @@
{
"generic": "請求失敗。",
"codes": {
"SHIPPING.NOTICE_ODM_CHOICE_INVALID": "所選 ODM ID 不在當前可行候選內,請重新選擇。",
"SHIPPING.FULFILLMENT_POLICY_INVALID": "貨代履約策略或欄位能力綁定無效。",
"SHIPPING.FULFILLMENT_POLICY_NOT_FOUND": "找不到貨代履約策略。",
"SHIPPING.FULFILLMENT_POLICY_CONFLICT": "貨代履約策略已被其他管理員修改,請重新整理後再試。",
+1 -1
View File
@@ -101,7 +101,7 @@
"scheduleRuns": "排程記錄",
"receiptReports": "收料檔案",
"shippingNotice": "貨代發貨",
"shippingCustomers": "客戶主資料",
"shippingCustomers": "客戶資料",
"shippingTasks": "發貨任務",
"shippingMyTasks": "我的待辦",
"feedback": "意見反饋",
+36 -3
View File
@@ -4,7 +4,9 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
## 收料 RPA(独立 Worker)
收料使用 `freight_receipt_rpa_worker.py` 与 `start_receipt_rpa_worker.ps1`,仅消费 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR`,仅写 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR`,只回调 `/api/shipping-notice/rpa/receipt-batch-ready`。它可以与库存 Worker 同时运行,但四类目录(trigger、drop、browser profile、日志)绝不能共享。
收料使用 `scripts\rpa\receipt\receipt_rpa_worker.py` 与 `scripts\rpa\receipt\start_receipt_worker.ps1`,仅消费 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR`,仅写 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR`,只回调 `/api/shipping-notice/rpa/receipt-batch-ready`。它可以与库存 Worker 同时运行,但收料专用目录(trigger、drop、日志,以及启动脚本默认分开的浏览器 Profile 根)绝不能改回与库存共用。
部署手册(本地联调 + Windows RPA 主机 + Ubuntu 后端)见 `docs/features/shipping-notice/technical.md` §1.9;本节只作脚本速查。
启动示例:
@@ -160,6 +162,19 @@ Linux HXOPS 后端 Windows RPA Worker
5. `SHIPPING_NOTICE_TOOL_API_KEY` 与对应后端一致。不得把 Key、Fernet 主密钥、DSV/Crane 密码写入本 README、`.env` 提交内容、命令历史、截图或 Worker 日志。
6. 正式环境还必须确认库存站点已启用,并已绑定 published 库存文件解析方案;配置测试导出只能对停用站点发起,不能把测试文件当作正式库存快照。
### 收料 Worker 部署增量(与库存 Worker 并行)
收料 RPA(收料报表导出 + MinIO 归档 + 企微推送)使用独立 Worker,可与库存 Worker 同机并行。**部署权威手册见 `docs/features/shipping-notice/technical.md` §1.9**,这里只列与库存部署的增量:
1. 目录:每个 WorkerRoot 追加 `data\freight_receipt_rpa\receipt_triggers`、`receipt_drop`、`logs`;不得指向任何库存目录。
2. 程序:整目录复制 `scripts\rpa` 时已包含 `receipt\`;`receipt_rpa_worker.py` 要求同级存在 `connectors/`、`common/`、`inventory/`、`receipt/` 四个子目录,不能单拷 `receipt\`。
3. 依赖:在库存 Worker 依赖之上补 `cryptography`:`python -m pip install playwright openpyxl pyyaml cryptography`。
4. Secret:与库存共用 `new_rpa_worker_secret.ps1` 生成的 `C:\HxopsRpaSecrets\test.xml` / `prod.xml`,无需新建。
5. 启动:`scripts\rpa\receipt\start_receipt_worker.ps1`,参数与库存启动脚本一致(`-Environment`、`-ApiBase`、`-WorkerRoot`、`-SecretFile`,可选 `-Mock` / `-Headless`);成功输出 `[freight_receipt_rpa_worker] started trigger_dir=... drop_dir=...`。
6. 心跳/哨兵:收料 Worker **不发心跳、不写哨兵**,不参与「RPA Worker 在线」检查;收料触发前无 fail-fast,Worker 停止只会让单元等到 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 900 秒)超时回收。
7. 日志:收料 Worker 只输出到控制台;计划任务用 `cmd.exe` 包装 `>>` 重定向到 `data\freight_receipt_rpa\logs\receipt_worker.log`(完整任务计划示例见 technical.md §1.9.2)。
8. 后端:`.env` 追加 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR` / `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR` 两个共享子路径(漏配会写容器本地默认路径,Windows 看不到);容器 bind mount 无需新增。收料文件回调后原样归档 MinIO 保留三年,到期清理由平台任务「货代收料归档到期清理」负责。
## 小白部署指南:一台 Windows 主机同时运行 test/prod
@@ -267,8 +282,12 @@ Get-ChildItem C:\HxopsRpaProd\data
Test-Path C:\HxopsRpaTest\scripts\rpa\inventory\inventory_rpa_worker.py
Test-Path C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1
Test-Path C:\HxopsRpaTest\scripts\rpa\common\new_rpa_worker_secret.ps1
Test-Path C:\HxopsRpaTest\scripts\rpa\receipt\receipt_rpa_worker.py
Test-Path C:\HxopsRpaTest\scripts\rpa\receipt\start_receipt_worker.ps1
Test-Path C:\HxopsRpaProd\scripts\rpa\inventory\inventory_rpa_worker.py
Test-Path C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1
Test-Path C:\HxopsRpaProd\scripts\rpa\receipt\receipt_rpa_worker.py
Test-Path C:\HxopsRpaProd\scripts\rpa\receipt\start_receipt_worker.ps1
```
每一行都应返回 `True`。不要复制 `.env*`、旧 trigger、旧 `processed/failed`、旧浏览器 profile 和真实密钥文件。
@@ -282,8 +301,10 @@ $utf8Bom = New-Object System.Text.UTF8Encoding($true)
foreach ($path in @(
"C:\HxopsRpaTest\scripts\rpa\common\new_rpa_worker_secret.ps1",
"C:\HxopsRpaTest\scripts\rpa\inventory\start_inventory_worker.ps1",
"C:\HxopsRpaTest\scripts\rpa\receipt\start_receipt_worker.ps1",
"C:\HxopsRpaProd\scripts\rpa\common\new_rpa_worker_secret.ps1",
"C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1"
"C:\HxopsRpaProd\scripts\rpa\inventory\start_inventory_worker.ps1",
"C:\HxopsRpaProd\scripts\rpa\receipt\start_receipt_worker.ps1"
)) {
$text = [System.IO.File]::ReadAllText($path, [System.Text.UTF8Encoding]::new($false))
[System.IO.File]::WriteAllText($path, $text, $utf8Bom)
@@ -840,7 +861,7 @@ Ubuntu 访问地址:
python --version
python -m pip --version
python -m pip install --upgrade pip
python -m pip install playwright openpyxl pyyaml
python -m pip install playwright openpyxl pyyaml cryptography
python -m playwright install chromium
```
@@ -1582,6 +1603,18 @@ python scripts/rpa/inventory/inventory_rpa_worker.py
1. 在 Chat 中走 `ensure_inventory` / `upload_to_freight`,worker 会自动回调 `/api/shipping-notice/rpa/*`。
收料 Worker 本地联调(`MOCK=true` 时生成模拟 xlsx,走完整 trigger 消费 → 回调 → MinIO 归档 → 企微投递链路;详见 `docs/features/shipping-notice/technical.md` §1.9.6):
```powershell
$env:HXOPS_API_BASE = "http://127.0.0.1:5052"
$env:SHIPPING_NOTICE_TOOL_API_KEY = "<与 backend 一致>"
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "true"
$receiptRoot = Join-Path (Get-Location).Path "backend\data\shipping_notice\freight_receipt_rpa"
$env:SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $receiptRoot "receipt_triggers"
$env:SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $receiptRoot "receipt_drop"
python scripts/rpa/receipt/receipt_rpa_worker.py
```
## 四、Driver 与业务参考
+1 -1
View File
@@ -1,4 +1,4 @@
<#
<#
.SYNOPSIS
在当前 PowerShell 进程树启动独立货代收料 RPA Worker。