diff --git a/.gitignore b/.gitignore index d32cc207..7e1db443 100644 --- a/.gitignore +++ b/.gitignore @@ -63,6 +63,7 @@ frontend/package-lock.json *.swp *.swo .cursorrules +.zcode # Runtime files .run/ diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 4249ef79..507ce52e 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -199,6 +199,7 @@ def workspace_shipping_my_todos(): todo_category=str(request.args.get('todo_category') or '').strip() or None, customer=str(request.args.get('customer') or '').strip() or None, task_no=str(request.args.get('task_no') or '').strip() or None, + terminal_kind=str(request.args.get('terminal_kind') or '').strip() or None, )) @@ -212,6 +213,67 @@ def workspace_shipping_my_todos_count(): return _ok(count_my_todos(user.id, is_admin=is_admin)) +def _done_lines_report_params() -> dict[str, Any]: + """解析明细报表共用筛选参数(客户/料号/发货通知日期范围),供查询与导出复用。""" + return { + 'customer': str(request.args.get('customer') or '').strip() or None, + 'part_number': str(request.args.get('part_number') or '').strip() or None, + 'notice_date_from': str(request.args.get('notice_date_from') or '').strip() or None, + 'notice_date_to': str(request.args.get('notice_date_to') or '').strip() or None, + } + + +@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos/done-lines', methods=['GET']) +def workspace_shipping_done_lines(): + """ + 分页列出已完成(已核验上传成功)通知的平铺明细行,供「通知完成」子视图报表。 + + 核心逻辑:明细行跨 Notice 混排、不按 OT 聚合;支持 客户 / 料号 / + 发货通知日期范围 筛选;行结构为标准 12 字段 + 溯源编号(task_no/business_no)。 + """ + user = _require_user() + from app.services.shipping_notice.done_line_report import list_done_notice_lines + + is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' + try: + page = int(request.args.get('page') or 1) + page_size = int(request.args.get('page_size') or 20) + except (TypeError, ValueError) as exc: + raise ValidationError('page and page_size must be integers') from exc + return _ok(list_done_notice_lines( + user.id, + is_admin=is_admin, + page=page, + page_size=page_size, + **_done_lines_report_params(), + )) + + +@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos/done-lines/export', methods=['GET']) +def workspace_shipping_done_lines_export(): + """ + 导出当前筛选下的已完成通知明细 Excel。 + + 核心逻辑:固定 12 列标准格式(客户/客户编号/订单日期/订单项次/料号/数量/ + 约定出货日期/客户PO/已用数量/open qty/订单单号/单价),OT 编号不落列; + 已用数量 / open qty 无数据源留空。 + """ + user = _require_user() + from app.services.shipping_notice.done_line_report import build_done_lines_xlsx + + is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin' + stream, filename = build_done_lines_xlsx( + user.id, + is_admin=is_admin, + **_done_lines_report_params(), + ) + response = send_file( + stream, as_attachment=True, download_name=filename, mimetype=EXPORT_MIME_TYPE, + ) + response.call_on_close(stream.close) + return response + + def _batch_task_nos(data: dict) -> list[str]: """校验批量任务号,统一限制 100 条并去重,避免前端循环绕过服务端门禁。""" raw_task_nos = data.get('task_nos') @@ -481,6 +543,45 @@ def workspace_shipping_task_detail(task_no: str): )) +@workspace_shipping_notice_bp.route('/shipping-tasks//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//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//audit-timeline', methods=['GET']) def workspace_list_shipping_task_audit_timeline(task_no: str): """业务用户 Task 审计时间线(统一 ShippingAuditEvent,无敏感快照)。""" diff --git a/backend/app/models/shipping_customer.py b/backend/app/models/shipping_customer.py index 2828e693..f20ede82 100644 --- a/backend/app/models/shipping_customer.py +++ b/backend/app/models/shipping_customer.py @@ -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) diff --git a/backend/app/models/shipping_notice_line_inventory_match.py b/backend/app/models/shipping_notice_line_inventory_match.py index 04fa7526..6007838a 100644 --- a/backend/app/models/shipping_notice_line_inventory_match.py +++ b/backend/app/models/shipping_notice_line_inventory_match.py @@ -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) diff --git a/backend/app/services/admin/shipping_customer_service.py b/backend/app/services/admin/shipping_customer_service.py index e1e31406..feb77509 100644 --- a/backend/app/services/admin/shipping_customer_service.py +++ b/backend/app/services/admin/shipping_customer_service.py @@ -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, diff --git a/backend/app/services/shipping_notice/conversation_title.py b/backend/app/services/shipping_notice/conversation_title.py new file mode 100644 index 00000000..2983de68 --- /dev/null +++ b/backend/app/services/shipping_notice/conversation_title.py @@ -0,0 +1,59 @@ +""" +backend/app/services/shipping_notice/conversation_title.py + +用途:为订单抽取**新建**会话推导业务化标题,替代写死的「订单抽取」。 +依赖:仅标准库(datetime/pathlib/re);禁止引入 Flask/DB 依赖,保持可单测。 +逻辑:取首个非空附件文件名去扩展名 → 循环剥离邮件前缀 → 截断 24 字符 → + 多文件追加「等 N 个文件」→ 追加 MM-DD 日期消歧 → 全空回退「订单抽取」。 + 仅新建会话时调用;存量会话标题一律不改(设计决策见 2026-09-17 spec)。 +""" + +from __future__ import annotations + +import re +from datetime import datetime +from pathlib import PureWindowsPath + +_FALLBACK_TITLE = '订单抽取' +_NAME_MAX_CHARS = 24 +_TITLE_MAX_CHARS = 60 +# re:/fw:/fwd: 为半角冒号且大小写不敏感;回复/转发为全角冒号。循环剥离以支持多层嵌套。 +_MAIL_PREFIX_PATTERN = re.compile(r'^\s*(?:re|fw|fwd)\s*:|^\s*(?:回复|转发):', re.IGNORECASE) + + +def _strip_mail_prefixes(name: str) -> str: + """循环剥离单个文件名开头的邮件前缀(Re:/Fw:/Fwd:/回复:/转发:)。""" + current = name.strip() + while True: + stripped = _MAIL_PREFIX_PATTERN.sub('', current, count=1).lstrip() + if stripped == current: + return current + current = stripped + + +def derive_order_extraction_title(filenames: list[str], created_at: datetime) -> str: + """ + 按首个附件文件名推导订单抽取会话标题。 + + Args: + filenames: 本次冻结 Intake 对应的资产原始文件名,按 Intake 顺序; + 允许包含空串占位(保持计数口径)。 + created_at: 会话创建时间(服务器 UTC,不做时区换算),提供 MM-DD 消歧后缀。 + Returns: + 形如「PO#6075309 等 11 个文件 09-15」的标题;文件名全空时回退「订单抽取」; + 末尾做 60 字符防御性钳制(24 字主名约束下正常不可达)。 + """ + ordered = [str(name or '').strip() for name in filenames] + usable = [name for name in ordered if name] + if not usable: + return _FALLBACK_TITLE + # PureWindowsPath 同时把 '/' 与 '\' 视为目录分隔符,兼容两类上传来源的路径写法。 + stem = PureWindowsPath(usable[0]).stem + base = _strip_mail_prefixes(stem)[:_NAME_MAX_CHARS].strip() + if not base: + return _FALLBACK_TITLE + parts = [base] + if len(ordered) > 1: + parts.append(f'等 {len(ordered)} 个文件') + parts.append(f'{created_at.month:02d}-{created_at.day:02d}') + return ' '.join(parts)[:_TITLE_MAX_CHARS] diff --git a/backend/app/services/shipping_notice/customer_auto_resolution.py b/backend/app/services/shipping_notice/customer_auto_resolution.py index 3232cb29..ecbd1631 100644 --- a/backend/app/services/shipping_notice/customer_auto_resolution.py +++ b/backend/app/services/shipping_notice/customer_auto_resolution.py @@ -4,6 +4,9 @@ services/shipping_notice/customer_auto_resolution.py 用途:基于管理员审核的强证据受控自动确认 OT 客户。 依赖:ShippingIdentityEvidence/ShadowResolution/Task、customer_identity_gate、Flask 配置。 逻辑:Candidate 建单后只按影子快照中的已审核授权证据自动确认;不创建 Notice 或分配业务编号。 + 命中分级与复核侧共用:canonical 等值(unique_strong_match)与完整包含 + (unique_containment_match,指纹整体出现在提取值中且证据授权)可自动确认; + 截断包含(containment_weak)只供人工建议,永不进入本裁决。 """ from __future__ import annotations @@ -29,14 +32,18 @@ from app.services.shipping_notice.customer_identity_gate import ( customer_confirmation_facts, ) from app.services.shipping_notice.customer_normalization import ( + IDENTITY_MATCH_CONTAINMENT_STRONG, + IDENTITY_MATCH_EQUALITY, + canonical_identity_key, + classify_identity_containment, is_public_email_domain, - normalize_customer_name, - normalize_domain, - normalize_email, + normalize_identity_evidence_value, ) from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, task_event_task_id -AUTO_RESOLUTION_VERSION = "customer-auto-v2" +AUTO_RESOLUTION_VERSION = "customer-auto-v3" +# 允许自动确认的裁决状态;质量门禁分母与审计均以该集合为准。 +AUTO_CONFIRM_ELIGIBLE_STATUSES = frozenset({'unique_strong_match', 'unique_containment_match'}) CUSTOMER_AUDIT_EVENT_TYPES = ( "customer_auto_resolution_evaluated", "customer_auto_confirmed", @@ -65,8 +72,8 @@ def _auto_confirmation_quality_gate() -> dict[str, Any]: eligible_samples = 0 correct_samples = 0 for shadow in labeled: - decision = _resolve_auto_customer_from_shadow_resolution(shadow) - if decision['status'] != 'unique_strong_match': + decision = resolve_auto_customer_decision(shadow) + if decision['status'] not in AUTO_CONFIRM_ELIGIBLE_STATUSES: continue eligible_samples += 1 if int(decision['customer_id']) == int(shadow.manual_customer_id): @@ -229,23 +236,55 @@ def _verified_shadow_value( config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {} context_source = config.get('context_source') if isinstance(config.get('context_source'), dict) else {} try: - if context_source.get('option_key') == 'from_email': - return normalize_email(value) - if context_source.get('option_key') == 'from_domain': - return normalize_domain(value) - if config.get('normalizer_key') == 'name': - return normalize_customer_name(value) or None - return str(value or '').strip().upper() or None + # 与影子识别/证据导入共用同一归一化,保证复核键与存储键同源(含换行折叠)。 + return normalize_identity_evidence_value( + value, + option_key=context_source.get('option_key'), + normalizer_key=config.get('normalizer_key'), + ) except Exception: return None -def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadowResolution) -> dict[str, Any]: +def _classify_auto_evidence_match( + *, runtime_normalized: str, evidence_normalized: str, option_key: str, +) -> str | None: + """ + 对单个授权证据做自动确认视角的命中分级。 + + 核心逻辑:邮箱/域名只做大小写无关精确等值;文本类先比 canonical 等值 + (吸收标点/空白差异),再判「指纹完整出现在提取值中」的强包含; + 截断包含(containment_weak)返回给展示层但在此一律判不命中——剩余部分 + 未经验证,无法排除「另一个更短名的完整客户」,禁止自动确认。 + """ + if option_key in {'from_email', 'from_domain'}: + if runtime_normalized.casefold() == evidence_normalized.casefold(): + return IDENTITY_MATCH_EQUALITY + return None + if canonical_identity_key(runtime_normalized) == canonical_identity_key(evidence_normalized): + return IDENTITY_MATCH_EQUALITY + match_kind = classify_identity_containment( + runtime_normalized, evidence_normalized, option_key=option_key, + ) + return match_kind if match_kind == IDENTITY_MATCH_CONTAINMENT_STRONG else None + + +def resolve_auto_customer_decision(shadow: ShippingCustomerShadowResolution) -> dict[str, Any]: """ 按影子记录的冻结定义和当前已审核授权证据求唯一自动确认客户。 业务定义、站点证据、公共邮箱域名及快照外字段都不是自动确认依据;多个客户命中时 - 一律返回歧义,即使其中一个客户累积的证据更多。 + 一律返回歧义,即使其中一个客户累积的证据更多。等值命中存在时包含命中不参与裁决; + 仅「指纹完整出现在提取值中」(unique_containment_match)这一种包含形态在唯一且 + 授权时可自动确认,截断形态永不。 + + Args: + shadow: 已持久化的客户影子识别记录(须含规则快照与证据 JSON)。 + + Returns: + 裁决字典:status(unique_strong_match / unique_containment_match / + ambiguous / unmatched / rule_snapshot_missing 等)、customer_id、 + evidence(含 match_kind 溯源)与候选客户列表。 """ snapshot = _rule_snapshot(shadow) if snapshot is None: @@ -256,6 +295,7 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow if isinstance(item, dict) and str(item.get('id') or '') } matched: dict[int, list[dict[str, Any]]] = {} + match_tiers: dict[int, str] = {} for evidence in shadow.evidence_json or []: if not isinstance(evidence, dict): continue @@ -298,8 +338,12 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow auto_match_allowed=True, ).all() for record in records: - # 主数据中历史录入值也可能保留不同大小写;按指纹语义比较而非原始字符串比较。 - if str(record.normalized_value or '').strip().casefold() != normalized.casefold(): + match_kind = _classify_auto_evidence_match( + runtime_normalized=verified_normalized, + evidence_normalized=str(record.normalized_value or ''), + option_key=option_key, + ) + if match_kind is None: continue if record.customer_id is None: continue @@ -311,16 +355,34 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow 'definition_id': definition_id, 'definition_code': definition.get('definition_code'), 'normalized_value': normalized, + 'match_kind': match_kind, 'source': field_value_source, 'context_source': context_source, }) + if ( + customer.id not in match_tiers + or match_kind == IDENTITY_MATCH_EQUALITY + ): + match_tiers[customer.id] = match_kind + # [STEP] 等值优先:存在等值命中的客户时,包含命中客户不参与裁决; + # 截断包含已在分级阶段被排除,绝不出现在自动确认候选中。 + equality_customer_ids = {cid for cid, kind in match_tiers.items() if kind == IDENTITY_MATCH_EQUALITY} + decision_customer_ids = equality_customer_ids or set(match_tiers) + matched = {cid: matched[cid] for cid in decision_customer_ids} if len(matched) != 1: result = _decision_base(shadow, status='ambiguous' if matched else 'unmatched') result['evidence'] = [item for rows in matched.values() for item in rows] result['candidate_customer_ids'] = sorted(matched) return result customer_id = next(iter(matched)) - result = _decision_base(shadow, status='unique_strong_match') + result = _decision_base( + shadow, + status=( + 'unique_strong_match' + if match_tiers[customer_id] == IDENTITY_MATCH_EQUALITY + else 'unique_containment_match' + ), + ) result['customer_id'] = customer_id result['evidence'] = matched[customer_id] return result @@ -362,7 +424,7 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice | ShippingOrderTask) if shadow is None: return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []} - decision = _resolve_auto_customer_from_shadow_resolution(shadow) + decision = resolve_auto_customer_decision(shadow) quality_gate = _auto_confirmation_quality_gate() if not quality_gate['is_eligible']: return { diff --git a/backend/app/services/shipping_notice/customer_normalization.py b/backend/app/services/shipping_notice/customer_normalization.py index 63eec73c..aad8a128 100644 --- a/backend/app/services/shipping_notice/customer_normalization.py +++ b/backend/app/services/shipping_notice/customer_normalization.py @@ -1,9 +1,12 @@ """ services/shipping_notice/customer_normalization.py -用途:统一客户名称、简码、邮箱、域名和识别证据的标准化与基础校验。 +用途:统一客户名称、简码、邮箱、域名和识别证据的标准化与基础校验, + 并提供识别证据的 canonical 比较键与包含关系分级。 依赖:re、unicodedata 标准库。 -逻辑:管理后台导入与运行期客户裁决共用,避免同一证据在不同入口产生不同匹配键。 +逻辑:管理后台导入、运行期影子识别与自动确认复核共用同一证据归一化 + (normalize_identity_evidence_value),避免同一证据在不同入口产生不同匹配键; + canonical 键用于标点/空白无关的等值比较,包含分级支撑客户识别的三层匹配。 """ from __future__ import annotations @@ -130,3 +133,97 @@ def normalize_identifier(identifier_type: Any, value: Any) -> str: details={'field': 'identifier_value'}, ) return normalized + + +# 邮箱/域名上下文键:指纹语义为精确标识,禁止参与包含分级。 +_IDENTITY_EMAIL_DOMAIN_OPTION_KEYS = frozenset({'from_email', 'from_domain'}) +# 包含命中的最短 canonical 字符数:更短片段(如 'c/o'→'CO')不足以声明同主体, +# 且短指纹一律由 canonical 等值路径承担,不享受包含兜底。 +IDENTITY_CONTAINMENT_MIN_CHARS = 8 +# 包含关系等值性强弱标记:strong=指纹完整出现在提取值中;weak=提取值疑似指纹截断。 +IDENTITY_MATCH_EQUALITY = 'approved_identity_evidence' +IDENTITY_MATCH_CONTAINMENT_STRONG = 'containment_strong' +IDENTITY_MATCH_CONTAINMENT_WEAK = 'containment_weak' +# 等值 > 完整包含 > 截断包含;数值越小身份信号越强。 +IDENTITY_MATCH_TIER_RANK = { + IDENTITY_MATCH_EQUALITY: 0, + IDENTITY_MATCH_CONTAINMENT_STRONG: 1, + IDENTITY_MATCH_CONTAINMENT_WEAK: 2, +} + +_CANONICAL_STRIP_RE = re.compile(r'[\W_]+', re.UNICODE) + + +def normalize_identity_evidence_value( + value: Any, *, option_key: Any = None, normalizer_key: Any = None, +) -> str | None: + """ + 按识别定义冻结的字段配置生成证据匹配键;导入、影子识别与自动确认复核共用。 + + 核心逻辑:与 identity_rules._normalize_for_snapshot、resolver._normalize、 + customer_auto_resolution._verified_shadow_value 的历史分支一一对应;兜底分支统一 + 走 clean_text(折叠内部空白/换行),修复运行侧保留换行导致多行提取值永远无法 + 等值命中单行注册证据的不对称缺陷。 + + Args: + value: 已裁决 Header 字段值或管理员录入的原始证据值。 + option_key: 字段上下文来源(from_email/from_domain 时按邮箱/域名校验归一)。 + normalizer_key: 冻结 Schema 字段配置的 normalizer('name' 走客户名称词管线)。 + + Returns: + 归一化匹配键;空值返回 None(调用方按各自契约决定跳过或报错)。 + + Raises: + ValidationError: 邮箱/域名值不合法(由下游 normalize_* 抛出,调用方自行容错)。 + """ + kind = clean_text(option_key).lower() if option_key else '' + if kind == 'from_email': + return normalize_email(value) + if kind == 'from_domain': + return normalize_domain(value) + if clean_text(normalizer_key or '').lower() == 'name': + return normalize_customer_name(value) or None + return clean_text(value).upper() or None + + +def canonical_identity_key(value: Any) -> str: + """ + 生成识别证据的 canonical 比较键:NFKC + casefold + 剔除全部非字母数字。 + + 核心逻辑:中文等 Unicode 词字符保留(支持中文客户名),标点、空白、下划线 + 全部剔除,使 'QCH, INC.' 与 'QCH INC.' 这类打印差异在等值比较中不再分裂。 + 邮箱/域名指纹禁止使用本键比较('@'、'.' 属于语义字符),调用方须先分流。 + """ + return _CANONICAL_STRIP_RE.sub('', unicodedata.normalize('NFKC', str(value or '')).casefold()) + + +def classify_identity_containment( + runtime_normalized: Any, evidence_normalized: Any, *, option_key: Any = None, +) -> str | None: + """ + 对文本类识别证据做双向包含分级,供客户识别的弱命中层使用。 + + Args: + runtime_normalized: 运行时提取值(已经 normalize_identity_evidence_value 归一)。 + evidence_normalized: 库内已注册证据值(同上归一)。 + option_key: 字段上下文来源;from_email/from_domain 直接返回 None。 + + Returns: + IDENTITY_MATCH_CONTAINMENT_STRONG:注册指纹完整出现在提取值中(提取多带 + 折行尾巴),身份信号可参与受控自动确认; + IDENTITY_MATCH_CONTAINMENT_WEAK:提取值疑似指纹截断片段(剩余部分未经验 + 证,无法区分「截断」与「另一个更短名的完整客户」),只允许作为人工确认建议; + None:无包含关系,或包含侧短于 IDENTITY_CONTAINMENT_MIN_CHARS。 + """ + kind = clean_text(option_key).lower() if option_key else '' + if kind in _IDENTITY_EMAIL_DOMAIN_OPTION_KEYS: + return None + runtime_key = canonical_identity_key(runtime_normalized) + evidence_key = canonical_identity_key(evidence_normalized) + if not runtime_key or not evidence_key: + return None + if len(evidence_key) >= IDENTITY_CONTAINMENT_MIN_CHARS and evidence_key in runtime_key: + return IDENTITY_MATCH_CONTAINMENT_STRONG + if len(runtime_key) >= IDENTITY_CONTAINMENT_MIN_CHARS and runtime_key in evidence_key: + return IDENTITY_MATCH_CONTAINMENT_WEAK + return None diff --git a/backend/app/services/shipping_notice/customer_shadow_resolution.py b/backend/app/services/shipping_notice/customer_shadow_resolution.py index f20e7c0d..0587f8a9 100644 --- a/backend/app/services/shipping_notice/customer_shadow_resolution.py +++ b/backend/app/services/shipping_notice/customer_shadow_resolution.py @@ -36,9 +36,10 @@ def refresh_candidate_shadow_resolution(candidate: ShippingOrderCandidate) -> Sh resolution = resolve_candidate_identity(candidate, intake) evidence = list(resolution['evidence']) matches = list(resolution['customer_matches']) + # 状态一律以 resolver 的层级裁决为准(等值 > 完整包含 > 截断包含), + # 本地不再按分数重复判定,避免两处排序/歧义语义分叉;top_score 取排序首位的累计权重。 + status = str(resolution['status']) top_score = float(matches[0]['score']) if matches else None - tied = [item for item in matches if float(item['score']) == top_score] if top_score is not None else [] - status = 'unmatched' if not matches else 'unique_candidate' if len(tied) == 1 else 'ambiguous' row = db.session.query(ShippingCustomerShadowResolution).filter_by(candidate_id=int(candidate.id)).first() if row is None: row = ShippingCustomerShadowResolution(candidate_id=int(candidate.id), intake_id=int(candidate.intake_id)) diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py b/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py index ac85bd4b..afeffd64 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py @@ -11,6 +11,11 @@ services/shipping_notice/document_layout/order_profile_matcher.py 禁止表顶宽带兜底;多 pattern 观测结果并集与签名身份 token 口径一致; 主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表; 无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁; + 表头可经 Schema 别名表(header_to_field)把命中短语归一为 field:: 字段语义原子 + (schema_canonical_header_atoms),实现跨措辞的身份对齐,未配置时退化为词级原子; + canonical 序列(schema_canonical_header_tokens)供 signature_conflict 硬门禁的 + 二次机会评估复用同一表头打分逻辑(effective = max(原始, canonical),仅无必选 + 锚点且契约可用时生效,七维上报分数维持原始值); 单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。 """ @@ -126,6 +131,7 @@ def match_frozen_coordinate_profiles( profiles: list[dict[str, Any]], layout: dict[str, Any], customer_hint_id: int | None = None, + header_to_field: dict[str, str] | None = None, ) -> ProfileMatchResult: """ 对同一文档的冻结 Profile 做签名硬门禁、分项评分与唯一匹配。 @@ -134,6 +140,10 @@ def match_frozen_coordinate_profiles( profiles: 已发布模板快照列表;须含 matching_signature 与 definition。 layout: 冻结 layout 快照,含 tables 与 coordinate_evidence。 customer_hint_id: 可选运行期客户 ID,仅用于 trusted_business_context 维度。 + header_to_field: 可选 Schema 表头别名契约(TableHeaderContract.header_to_field, + key 为归一化表头文案、value 为 field_code);传入时无必选锚点路径的表头 + 原子互斥先经 schema_canonical_header_atoms 归一为字段语义原子再比对, + 实现跨别名身份对齐;None/空时退化为词级原子(既有行为)。 Returns: ProfileMatchResult:含 Top1/Top2/Margin、evidence_coverage 与候选分项得分。 @@ -233,6 +243,7 @@ def match_frozen_coordinate_profiles( optional_hits=optional_hits, customer_ids=raw.get('customer_ids') if isinstance(raw.get('customer_ids'), list) else None, customer_hint_id=customer_hint_id, + header_to_field=header_to_field, ) reason_codes.extend(hard_conflict_codes) if _profile_requires_unavailable_structure_evidence( @@ -894,8 +905,17 @@ def _compute_dimension_results( optional_hits: list[bool], customer_ids: list[int] | None, customer_hint_id: int | None, + header_to_field: dict[str, str] | None = None, ) -> tuple[dict[str, MatchDimensionResult], list[str]]: - """基于签名与冻结证据计算统一七维三态结果。""" + """ + 基于签名与冻结证据计算统一七维三态结果。 + + Args: + header_to_field: 可选 Schema 表头别名契约;非 None/非空时表头原子互斥 + (仅无必选锚点路径)先按别名归一为字段语义原子,None 时走词级原子; + 同时启用 signature_conflict 门禁的二次机会评估(见 [STEP 1.1]), + 七维上报分数不受其影响,维持原始值。 + """ hard_conflicts: list[str] = [] results: dict[str, MatchDimensionResult] = {} @@ -906,20 +926,36 @@ def _compute_dimension_results( signature=signature, observed=observed, required_hits=required_hits, enforce_atom_discriminator=enforce_header_atoms, ) + # 七维上报维持原始得分;canonical 二次评估得分只参与下方 signature_conflict 门禁。 results['header_semantic_position'] = header_result if ( enforce_header_atoms and header_result.state == 'mismatched' - and _header_discriminator_atoms_conflict(signature=signature, observed=observed) + and _header_discriminator_atoms_conflict( + signature=signature, observed=observed, header_to_field=header_to_field, + ) ): hard_conflicts.append('profile_header_discriminator_conflict') - elif ( - header_result.state == 'mismatched' - and signature - and signature.get('table_patterns') - and header_result.score < 0.35 - ): - hard_conflicts.append('profile_header_signature_conflict') + elif header_result.state == 'mismatched' and signature and signature.get('table_patterns'): + # [STEP 1.1] 二次机会门禁:原始软分被词级原子互斥压到 0.35 以下的候选, + # 在「无必选锚点 + 别名契约可用」前提下用 canonical token 复用同一打分 + # 逻辑重估一次(effective = max(原始, canonical)),使跨别名措辞不再被 + # 第二道表头硬门禁误杀;不满足前提时 effective 即原始分,行为零变化。 + effective_score = header_result.score + if header_result.score < 0.35 and enforce_header_atoms and header_to_field: + canonical_result = _score_header_semantic_position( + signature=signature, observed=observed, required_hits=required_hits, + enforce_atom_discriminator=False, + expected_tokens_override=schema_canonical_header_tokens( + _signature_identity_header_tokens(signature), header_to_field, + ), + observed_tokens_override=schema_canonical_header_tokens( + [str(item) for item in observed.get('header_tokens') or []], header_to_field, + ), + ) + effective_score = max(effective_score, canonical_result.score) + if effective_score < 0.35: + hard_conflicts.append('profile_header_signature_conflict') # [STEP 2] column_topology column_result = _score_column_topology(signature=signature, observed=observed, profile=profile) @@ -969,16 +1005,32 @@ def _score_header_semantic_position( observed: dict[str, Any], required_hits: list[bool], enforce_atom_discriminator: bool = True, + expected_tokens_override: list[str] | None = None, + observed_tokens_override: list[str] | None = None, ) -> MatchDimensionResult: """比对真实表头 token、横向顺序和位置。 核心逻辑:无必选锚点时先做表头原子硬互斥;有必选锚点则只走软评分。 期望侧先截断单逻辑表头的折行副标签污染。 + + Args: + expected_tokens_override: 期望侧 token 覆盖(如 Schema 别名归一后的 + canonical 序列);None 时按 `_signature_identity_header_tokens` + 既有口径取值,行为不变。提供时软评分(含词命中率与顺序比)整体 + 切换到该序列上进行,供二次机会门禁复用同一套打分逻辑。 + observed_tokens_override: 观测侧 token 覆盖(口径同上);None 时按 + `observed['header_tokens']` 既有口径取值,行为不变。 """ if signature is None: return MatchDimensionResult(state='unavailable', score=0.0) - expected_tokens = [str(item).casefold() for item in _signature_identity_header_tokens(signature)] - observed_tokens = [str(item).casefold() for item in observed.get('header_tokens') or []] + if expected_tokens_override is None: + expected_tokens = [str(item).casefold() for item in _signature_identity_header_tokens(signature)] + else: + expected_tokens = [str(item).casefold() for item in expected_tokens_override] + if observed_tokens_override is None: + observed_tokens = [str(item).casefold() for item in observed.get('header_tokens') or []] + else: + observed_tokens = [str(item).casefold() for item in observed_tokens_override] required_ratio = (sum(required_hits) / len(required_hits)) if required_hits else 1.0 if not expected_tokens: if not required_hits: @@ -997,8 +1049,16 @@ def _score_header_semantic_position( return MatchDimensionResult(state='mismatched', score=0.0) matched = sum(1 for token in expected_tokens if token in observed_tokens) token_ratio = matched / len(expected_tokens) - expected_order = [str(item).casefold() for item in _signature_identity_header_order(signature)] - observed_order = observed.get('header_tokens') or [] + expected_order = ( + expected_tokens + if expected_tokens_override is not None + else [str(item).casefold() for item in _signature_identity_header_order(signature)] + ) + observed_order = ( + observed_tokens + if observed_tokens_override is not None + else observed.get('header_tokens') or [] + ) shared = [item for item in expected_order if item in observed_order] order_ratio = 1.0 if len(shared) > 1: @@ -1018,6 +1078,21 @@ def _score_header_semantic_position( _HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with', 'by'}) _HEADER_ATOM_MIN_LEN = 3 _HEADER_PAREN_GLOSS = re.compile(r'[\((][^\))]*[\))]') +# 字段语义原子前缀:词级原子只含 [a-z0-9],不可能出现冒号,与前缀无碰撞空间。 +_HEADER_FIELD_MARKER = 'field::' + + +def _header_normalized_words(text: str) -> list[str]: + """ + 表头统一词管线:剥括号注记 → casefold → 去撇号 → 按非字母数字切分。 + + 核心逻辑:词级原子化与 Schema 别名短语匹配共用同一切词口径,保证两条路径 + 产出的身份原子完全同源;返回非空小写词序列(中文等非 [a-z0-9] 文本切词为空, + 调用方按各自的跳过策略处理)。 + """ + normalized = _HEADER_PAREN_GLOSS.sub(' ', str(text).casefold()) + normalized = re.sub(r"['’]", '', normalized) + return [part for part in re.split(r'[^a-z0-9]+', normalized) if part] def _sanitize_signature_table_identity( @@ -1081,32 +1156,209 @@ def _header_token_atoms(tokens: list[str]) -> frozenset[str]: """ 将表头 token 拆成稳定原子,供无锚点近亲模板互斥。 - 核心逻辑:先拼接 token 再去掉括号注记(通用印刷 gloss,跨 token 空格切开时 - 仍可剥除),再去撇号并按非字母数字切分;过滤过短词与虚词。签名侧与运行时共用。 + 核心逻辑:先拼接 token(让跨 token 空格切开的括号注记仍可整体剥除),再走 + _header_normalized_words 统一词管线切词;过滤过短词与虚词。签名侧与运行时共用。 """ joined = ' '.join(str(token) for token in tokens) - normalized = _HEADER_PAREN_GLOSS.sub(' ', joined.casefold()) - normalized = re.sub(r"['’]", '', normalized) atoms: set[str] = set() - for part in re.split(r'[^a-z0-9]+', normalized): + for part in _header_normalized_words(joined): if len(part) >= _HEADER_ATOM_MIN_LEN and part not in _HEADER_ATOM_STOPWORDS: atoms.add(part) return frozenset(atoms) +def schema_canonical_header_atoms( + tokens: list[str], + header_to_field: dict[str, str] | None, +) -> frozenset[str]: + """ + 将表头 token 按 Schema 别名归一为字段语义原子,供订单模板身份匹配跨别名对齐。 + + 用途:同一业务字段在不同供应商模板中的表头措辞不同(如 Ship Date / Requested + Ship Date / 出货日期),词级原子只能字面碰撞;本函数借助 Schema 别名表把命中 + 别名的表头文本升级为 field:: 标记原子,使身份比较基于字段语义而非 + 具体措辞。未配置别名时零行为变化,完全退化为词级原子。 + + 核心逻辑: + - header_to_field 为 None/空 dict 时直接返回词级原子(兼容旧签名,零风险); + - 先把每个别名 key 经与 token 完全相同的词管线(剥括号注记 → casefold → + 去撇号 → 按非字母数字切词)转为词元组;同一词元组 casefold 后指向多个 + field_code 时整体弃用该短语——身份归属不允许歧义; + - 逐 token 用同一词管线切词后做贪心最长短语匹配:命中即消费整段并产出 + field:: 原子(短语内单词不再残留);未命中的剩余单词沿用词级 + 原子的既有过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS); + - 中文别名经词管线切词后为空词元组 → 自然跳过(有意行为):词级原子本就只 + 保留 [a-z0-9],中文措辞无法构成词级身份,语义升级依赖别名表配置英文别名。 + + Args: + tokens: 表头 token 列表(可为合并格长文案,如 "Requested Ship Date Unit + Price");空串/空白 token 会被跳过(吸收 MinerU 空格占位)。 + header_to_field: TableHeaderContract.header_to_field(普通 dict[str, str], + key 为 Schema 别名的归一化表头文案,value 为 field_code);鸭子类型 + 消费,不引入 order_schema → matcher 反向依赖;None/空表示未配置。 + + Returns: + frozenset[str]:field:: 标记原子与词级原子的并集。 + """ + if not header_to_field: + return _header_token_atoms(tokens) + + # [STEP 1] 构建短语字典:别名 key → 词元组 → field_code;casefold 跨字段 + # 碰撞的短语整体弃用(身份归属不允许歧义,宁缺勿错)。 + grouped: dict[tuple[str, ...], dict[str, str]] = {} + for alias, field_code in header_to_field.items(): + words = tuple(_header_normalized_words(alias)) + if not words: + # 中文等非 [a-z0-9] 别名切词为空:无法参与词级匹配,有意跳过。 + continue + grouped.setdefault(words, {}).setdefault(str(field_code).casefold(), str(field_code)) + phrase_to_field: dict[tuple[str, ...], str] = { + words: next(iter(codes.values())) + for words, codes in grouped.items() + if len(codes) == 1 + } + + # [STEP 2] 逐 token 贪心最长短语匹配;未命中单词走既有词级原子过滤。 + atoms: set[str] = set() + for token in tokens: + if not str(token).strip(): + # 空串/纯空白 token(MinerU 空格占位)直接跳过。 + continue + words = _header_normalized_words(token) + index = 0 + while index < len(words): + match_end = 0 + match_code = '' + # 从当前起点尝试最长短语(先试整段剩余,再逐级缩短)。 + for end in range(len(words), index, -1): + code = phrase_to_field.get(tuple(words[index:end])) + if code is not None: + match_end = end + match_code = code + break + if match_end: + atoms.add(_HEADER_FIELD_MARKER + match_code) + index = match_end + continue + word = words[index] + if len(word) >= _HEADER_ATOM_MIN_LEN and word not in _HEADER_ATOM_STOPWORDS: + atoms.add(word) + index += 1 + return frozenset(atoms) + + +def schema_canonical_header_tokens( + tokens: list[str], + header_to_field: dict[str, str] | None, +) -> list[str]: + """ + 将表头 token 按 Schema 别名归一为序列语义的 canonical token 列表。 + + 用途:供 `profile_header_signature_conflict` 二次机会门禁复用 + `_score_header_semantic_position` 的既有软评分——词级互斥把跨别名措辞的 + 原始分压成 0 后,用本函数归一出的 canonical 序列重估一次,命中别名的片段 + 以统一的 field:: 标记项参与序列比较,实现跨措辞的软分 rescue。 + + 与 `schema_canonical_header_atoms` 的关系:二者共用同一词管线 + (`_header_normalized_words`)与同一贪心最长短语匹配口径、同一未命中词过滤, + 但语义不同——atoms 是集合语义(去重、无序,供硬互斥集合全等比较),本函数 + 是序列语义(保序、允许重复,供软评分按序列比较)。二者各自独立实现, + 不得互相调用/推导;同一输入下本函数结果去重即 atoms 结果(同源语义)。 + + 核心逻辑: + - header_to_field 为 None/空 dict 时原样返回输入列表(零归一、零行为变化); + - 短语字典构建与 atoms [STEP 1] 完全同源:别名 key 经同一词管线转词元组, + 同一词元组 casefold 后指向多个 field_code 时整体弃用(身份不允许歧义); + - 逐 token 贪心最长短语匹配:命中片段消费整段并在原位置产出**单个** + `field::` 列表项(短语内单词不残留);未命中词按 atoms 同一 + 过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS)原词保留; + - 空串/纯空白 token(MinerU 空格占位)跳过,与 atoms 口径一致。 + + Args: + tokens: 表头 token 列表(期望侧传 `_signature_identity_header_tokens` + 的结果、观测侧传 `observed['header_tokens']`);可为合并格长文案。 + header_to_field: TableHeaderContract.header_to_field(dict[str, str], + key 为 Schema 别名归一化表头文案、value 为 field_code); + None/空表示未配置。 + + Returns: + list[str]:canonical token 序列(保序、允许重复)。 + """ + if not header_to_field: + return tokens + + # [STEP 1] 短语字典:与 schema_canonical_header_atoms 完全同源的构建口径。 + grouped: dict[tuple[str, ...], dict[str, str]] = {} + for alias, field_code in header_to_field.items(): + words = tuple(_header_normalized_words(alias)) + if not words: + # 中文等非 [a-z0-9] 别名切词为空:无法参与词级匹配,有意跳过。 + continue + grouped.setdefault(words, {}).setdefault(str(field_code).casefold(), str(field_code)) + phrase_to_field: dict[tuple[str, ...], str] = { + words: next(iter(codes.values())) + for words, codes in grouped.items() + if len(codes) == 1 + } + + # [STEP 2] 逐 token 贪心最长短语匹配;序列语义:命中产出单个标记列表项, + # 未命中单词原样保留(沿用 atoms 过滤),整体保序、允许重复。 + canonical: list[str] = [] + for token in tokens: + if not str(token).strip(): + # 空串/纯空白 token(MinerU 空格占位)直接跳过。 + continue + words = _header_normalized_words(token) + index = 0 + while index < len(words): + match_end = 0 + match_code = '' + # 从当前起点尝试最长短语(先试整段剩余,再逐级缩短)。 + for end in range(len(words), index, -1): + code = phrase_to_field.get(tuple(words[index:end])) + if code is not None: + match_end = end + match_code = code + break + if match_end: + canonical.append(_HEADER_FIELD_MARKER + match_code) + index = match_end + continue + word = words[index] + if len(word) >= _HEADER_ATOM_MIN_LEN and word not in _HEADER_ATOM_STOPWORDS: + canonical.append(word) + index += 1 + return canonical + + def _header_discriminator_atoms_conflict( *, signature: dict[str, Any] | None, observed: dict[str, Any], + header_to_field: dict[str, str] | None = None, ) -> bool: - """签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。""" + """ + 签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。 + + Args: + header_to_field: 可选 Schema 表头别名契约;非 None/非空时签名侧与观测侧 + token 均先经 schema_canonical_header_atoms 归一为字段语义原子再比较 + 全等,使跨别名措辞(同字段不同表头文案)不再误判互斥;None/空时 + 两侧均走词级原子(既有行为,零变化)。 + """ if signature is None or not signature.get('table_patterns'): return False expected_tokens = _signature_identity_header_tokens(signature) observed_tokens = [str(item) for item in observed.get('header_tokens') or []] if not expected_tokens or not observed_tokens: return False - return _header_token_atoms(expected_tokens) != _header_token_atoms(observed_tokens) + if header_to_field: + expected_atoms = schema_canonical_header_atoms(expected_tokens, header_to_field) + observed_atoms = schema_canonical_header_atoms(observed_tokens, header_to_field) + else: + expected_atoms = _header_token_atoms(expected_tokens) + observed_atoms = _header_token_atoms(observed_tokens) + return expected_atoms != observed_atoms def _score_column_topology( diff --git a/backend/app/services/shipping_notice/document_profile_quality_service.py b/backend/app/services/shipping_notice/document_profile_quality_service.py index ebb84fc3..de3d3156 100644 --- a/backend/app/services/shipping_notice/document_profile_quality_service.py +++ b/backend/app/services/shipping_notice/document_profile_quality_service.py @@ -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'] diff --git a/backend/app/services/shipping_notice/done_line_report.py b/backend/app/services/shipping_notice/done_line_report.py new file mode 100644 index 00000000..9b07b0bf --- /dev/null +++ b/backend/app/services/shipping_notice/done_line_report.py @@ -0,0 +1,290 @@ +""" +backend/app/services/shipping_notice/done_line_report.py + +用途:「我的待办」已完成(已核验上传成功)发货通知的平铺明细行报表读模型与专用导出。 +依赖:query_service 的可见性与上传成功口径(_visible_tasks_query_for_todos / + _verified_upload_success_sql_expr);shipping_order_snapshot 冻结快照。 +逻辑:Notice(uploaded) → OT → Snapshot → SnapshotLine 展开为标准 12 字段行;页面另附 + OT/business 编号列便于溯源,导出严格 12 列不落编号。已用数量 / open_qty 当前无 + 数据源,契约占位为 None(前端与 Excel 均留空)。约定出货日期取行级 required_date + (field_values_json),缺失时回退快照表头 typed 列;订单单号取表头 + source_order_number(field_id 键)。支持 客户 / 料号 / 发货通知日期(Notice + 创建日期)筛选,按明细行分页;导出复用同一查询,行数受 DONE_LINE_EXPORT_LIMIT 防护。 +""" + +from __future__ import annotations + +from datetime import date, datetime, time +from io import BytesIO +from typing import Any +from zoneinfo import ZoneInfo + +from openpyxl import Workbook +from sqlalchemy import asc, desc + +from app import db +from app.core.errors import ValidationError +from app.models import ( + ShippingNotice, + ShippingOrderField, + ShippingOrderSnapshot, + ShippingOrderSnapshotLine, + ShippingOrderTask, +) +from app.services.shipping_notice.query_service import ( + _verified_upload_success_sql_expr, + _visible_tasks_query_for_todos, +) + +# 导出防护上限:超出即截断(明细行报表场景远低于该量级)。 +DONE_LINE_EXPORT_LIMIT = 10000 + +# 导出固定 12 列中文表头;顺序即业务标准格式,OT 编号不落列。 +DONE_REPORT_HEADERS: tuple[str, ...] = ( + "客户", "客户编号", "订单日期", "订单项次", "料号", "数量", + "约定出货日期", "客户PO", "已用数量", "open qty", "订单单号", "单价", +) + + +def _parse_notice_date(value: Any, *, label: str) -> date: + """解析 YYYY-MM-DD 日期参数;非法输入抛 ValidationError,禁止静默吞掉。""" + text = str(value or '').strip() + if not text: + raise ValidationError(f'{label} must be YYYY-MM-DD', code='SHIPPING.DONE_LINE_DATE_INVALID') + try: + return datetime.strptime(text[:10], '%Y-%m-%d').date() + except ValueError as exc: + raise ValidationError(f'{label} must be YYYY-MM-DD', code='SHIPPING.DONE_LINE_DATE_INVALID') from exc + + +def _done_lines_query( + user_id: int, + *, + is_admin: bool = False, + customer: str | None = None, + part_number: str | None = None, + notice_date_from: Any = None, + notice_date_to: Any = None, +): + """ + 构造已完成通知明细行的联表查询(Notice → OT → Snapshot → SnapshotLine)。 + + 核心逻辑:仅取已核验上传成功的正式 Notice;可见性复用待办口径(非管理员仅创建者); + 客户按快照 客户名称/客户编号 模糊、料号按 行料号/客户料号 模糊、发货通知日期按 + Notice created_at 自然日闭区间过滤。 + + Raises: + ValidationError: 日期参数非法。 + """ + q = ( + _visible_tasks_query_for_todos(user_id, is_admin=is_admin) + .filter(_verified_upload_success_sql_expr()) + .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id) + .join(ShippingOrderSnapshot, ShippingOrderSnapshot.task_id == ShippingOrderTask.id) + .join(ShippingOrderSnapshotLine, ShippingOrderSnapshotLine.snapshot_id == ShippingOrderSnapshot.id) + ) + customer_needle = str(customer or '').strip() + if customer_needle: + like = f"%{customer_needle}%" + q = q.filter( + db.or_( + ShippingOrderSnapshot.customer_name.ilike(like), + ShippingOrderSnapshot.customer_code.ilike(like), + ) + ) + part_needle = str(part_number or '').strip() + if part_needle: + like = f"%{part_needle}%" + q = q.filter( + db.or_( + ShippingOrderSnapshotLine.part_number.ilike(like), + ShippingOrderSnapshotLine.customer_part_number.ilike(like), + ) + ) + if notice_date_from: + from_day = notice_date_from if isinstance(notice_date_from, date) else _parse_notice_date(notice_date_from, label='notice_date_from') + q = q.filter(ShippingNotice.created_at >= datetime.combine(from_day, time.min)) + if notice_date_to: + to_day = notice_date_to if isinstance(notice_date_to, date) else _parse_notice_date(notice_date_to, label='notice_date_to') + q = q.filter(ShippingNotice.created_at <= datetime.combine(to_day, time.max)) + return q + + +def _report_field_ids() -> dict[tuple[str, str], str]: + """读取报表所需的标准字段资产 id(field_code+scope 唯一),供 JSON 值回源。""" + rows = ShippingOrderField.query.filter( + ShippingOrderField.field_code.in_(('required_date', 'source_order_number')), + ShippingOrderField.status == 'active', + ).all() + return {(row.field_code, row.scope): str(row.id) for row in rows} + + +def _date_text(value: Any) -> str | None: + """日期值统一为 YYYY-MM-DD 文本;date 对象取日期部分,字符串截前十位。""" + if value in (None, ''): + return None + if hasattr(value, 'isoformat'): + return str(value.isoformat())[:10] + text = str(value).strip() + return text[:10] or None + + +def _num_text(value: Any) -> float | None: + """数量/单价序列化为 JSON number;缺失返回 None(禁止 0 冒充)。""" + if value in (None, ''): + return None + return float(value) + + +def _serialize_done_line( + notice: ShippingNotice, + snapshot: ShippingOrderSnapshot, + line: ShippingOrderSnapshotLine, + field_ids: dict[tuple[str, str], str], +) -> dict[str, Any]: + """按标准 12 字段 + 溯源编号序列化一行明细;无数据源字段契约留空。""" + required_date_field_id = field_ids.get(('required_date', 'line')) + required_date = ( + (line.field_values_json or {}).get(required_date_field_id) + if required_date_field_id else None + ) + if required_date in (None, ''): + required_date = snapshot.required_date + source_order_field_id = field_ids.get(('source_order_number', 'header')) + source_order_number = ( + (snapshot.header_values_json or {}).get(source_order_field_id) + if source_order_field_id else None + ) + return { + # 溯源编号:仅页面展示,导出不落列。 + 'task_no': notice.task_no, + 'business_no': notice.business_no, + # 标准 12 字段。 + 'customer_name': snapshot.customer_name, + 'customer_code': snapshot.customer_code, + 'order_date': _date_text(snapshot.order_date), + 'line_no': line.line_no, + 'part_number': line.part_number, + 'qty': _num_text(line.qty), + 'required_date': _date_text(required_date), + 'customer_po_number': snapshot.customer_po_number, + 'used_qty': None, + 'open_qty': None, + 'source_order_number': source_order_number, + 'unit_price': _num_text(line.unit_price), + } + + +def list_done_notice_lines( + user_id: int, + *, + is_admin: bool = False, + customer: str | None = None, + part_number: str | None = None, + notice_date_from: Any = None, + notice_date_to: Any = None, + page: int = 1, + page_size: int = 20, +) -> dict[str, Any]: + """ + 分页列出已完成通知的平铺明细行(跨 Notice 混排,不按 OT 聚合)。 + + Returns: + {items, page, page_size, total};item 结构见 _serialize_done_line。 + """ + normalized_page = max(1, int(page)) + normalized_page_size = max(1, min(int(page_size), 100)) + q = _done_lines_query( + user_id, + is_admin=is_admin, + customer=customer, + part_number=part_number, + notice_date_from=notice_date_from, + notice_date_to=notice_date_to, + ) + total = int(q.count()) + field_ids = _report_field_ids() + items: list[dict[str, Any]] = [] + if total: + offset = (normalized_page - 1) * normalized_page_size + rows = ( + q.with_entities(ShippingNotice, ShippingOrderSnapshot, ShippingOrderSnapshotLine) + .order_by( + desc(ShippingNotice.created_at), desc(ShippingNotice.id), + asc(ShippingOrderSnapshotLine.position), + ) + .offset(offset) + .limit(normalized_page_size) + .all() + ) + items = [ + _serialize_done_line(notice, snapshot, line, field_ids) + for notice, snapshot, line in rows + ] + return { + 'items': items, + 'page': normalized_page, + 'page_size': normalized_page_size, + 'total': total, + } + + +def build_done_lines_xlsx( + user_id: int, + *, + is_admin: bool = False, + customer: str | None = None, + part_number: str | None = None, + notice_date_from: Any = None, + notice_date_to: Any = None, +) -> tuple[BytesIO, str]: + """ + 按当前筛选生成标准 12 列明细 Excel(不落 OT 编号列),返回流与下载文件名。 + + 核心逻辑:与列表同源查询、不分页;超过 DONE_LINE_EXPORT_LIMIT 截断并在文件名 + 带时间戳,避免同日下载互相覆盖。单元格空值写 None(留空),禁止以 0 伪装。 + """ + q = _done_lines_query( + user_id, + is_admin=is_admin, + customer=customer, + part_number=part_number, + notice_date_from=notice_date_from, + notice_date_to=notice_date_to, + ) + rows = ( + q.with_entities(ShippingNotice, ShippingOrderSnapshot, ShippingOrderSnapshotLine) + .order_by( + desc(ShippingNotice.created_at), desc(ShippingNotice.id), + asc(ShippingOrderSnapshotLine.position), + ) + .limit(DONE_LINE_EXPORT_LIMIT) + .all() + ) + field_ids = _report_field_ids() + workbook = Workbook() + sheet = workbook.active + sheet.title = '通知明细' + sheet.append(list(DONE_REPORT_HEADERS)) + for notice, snapshot, line in rows: + item = _serialize_done_line(notice, snapshot, line, field_ids) + sheet.append([ + item['customer_name'], + item['customer_code'], + item['order_date'], + item['line_no'], + item['part_number'], + item['qty'], + item['required_date'], + item['customer_po_number'], + item['used_qty'], + item['open_qty'], + item['source_order_number'], + item['unit_price'], + ]) + buffer = BytesIO() + workbook.save(buffer) + buffer.seek(0) + stamp = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d_%H%M%S') + filename = f'done-lines-{stamp}.xlsx' + return buffer, filename diff --git a/backend/app/services/shipping_notice/export.py b/backend/app/services/shipping_notice/export.py index 2e11c9b1..ecba0745 100644 --- a/backend/app/services/shipping_notice/export.py +++ b/backend/app/services/shipping_notice/export.py @@ -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, diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index e116e82c..92ace7e7 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -569,7 +569,7 @@ def _trigger_freight_upload_rpa( timeout = _rpa_upload_timeout_seconds() set_task_step_progress( task, - step_key='step7_upload_freight', + stage="freight_uploading", step_title='上传货代', status='running', message=t('workflow.fulfillment.upload_triggered_wait', lang=lang), @@ -1249,7 +1249,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str, line_result_status = str(match_payload.get('match_status') or 'unfulfillable') set_task_step_progress( task, - step_key="step5_match_inventory", + stage="inventory_matching", step_title="匹配库存", status="running", message=t("workflow.fulfillment.match_running", lang=lang), @@ -1639,7 +1639,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) set_task_step_progress( task, - step_key="step5_match_inventory", + stage="inventory_matching", step_title="匹配库存", status="running", message=t("workflow.fulfillment.match_running", lang=lang), @@ -1731,7 +1731,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) set_task_step_progress( task, - step_key="step5_match_inventory", + stage="inventory_matching", step_title="匹配库存", **_match_step_progress_fields( match_status=match_status, @@ -1810,7 +1810,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: percent = 10 if total <= 0 else min(95, max(10, int(processed * 100 / total))) set_task_step_progress( task, - step_key="step5_match_inventory", + stage="inventory_matching", step_title="匹配库存", status="running", message=t("workflow.fulfillment.match_running", lang=lang), @@ -1867,7 +1867,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: ) set_task_step_progress( task, - step_key="step5_match_inventory", + stage="inventory_matching", step_title="匹配库存", **_match_step_progress_fields( match_status=match_status, @@ -2066,7 +2066,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: ) set_task_step_progress( task, - step_key="step6_generate_file", + stage="excel_generating", step_title="生成发货文件", status="running", message=t("workflow.fulfillment.generate_running", lang=lang), @@ -2120,7 +2120,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: _clear_notice_invalidated_from_stage(task) set_task_step_progress( task, - step_key="step6_generate_file", + stage="excel_generating", step_title="生成发货文件", status="completed", message=t("workflow.fulfillment.generate_completed", lang=lang), @@ -2451,7 +2451,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]: _close_uploaded_task(task, actor_type='rpa', actor_id=None) set_task_step_progress( task, - step_key="step7_upload_freight", + stage="freight_uploading", step_title="上传货代", status="completed", message=t("workflow.fulfillment.rpa_uploaded", lang=lang), @@ -2507,7 +2507,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]: # unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。 set_task_step_progress( task, - step_key="step7_upload_freight", + stage="freight_uploading", step_title="上传货代", status="needs_human", message=t("workflow.fulfillment.upload_unknown_wait_manual", lang=lang), @@ -2527,7 +2527,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]: apply_task_transition(task, TaskTransition.WAITING_UPLOAD) set_task_step_progress( task, - step_key="step7_upload_freight", + stage="freight_uploading", step_title="上传货代", status="needs_human", message=t("workflow.fulfillment.upload_failed_wait_manual", lang=lang), diff --git a/backend/app/services/shipping_notice/identity_resolution/resolver.py b/backend/app/services/shipping_notice/identity_resolution/resolver.py index 249ace2a..633f87c8 100644 --- a/backend/app/services/shipping_notice/identity_resolution/resolver.py +++ b/backend/app/services/shipping_notice/identity_resolution/resolver.py @@ -2,6 +2,8 @@ 用途:基于已发布身份规则集产生客户主体与送货站点的可解释影子候选。 依赖:身份规则快照、受控订单字段裁决值、客户/站点证据主数据。 逻辑:只读取 Candidate 所属 Extraction 的 accepted/corroborated Header FieldValue;站点候选不反向确认客户主体。 + 客户命中分三层:canonical 等值 > 完整包含(指纹整体出现在提取值中)> 截断包含(仅人工建议); + 邮箱/域名指纹只做精确等值,禁止包含比较。 """ from __future__ import annotations @@ -23,12 +25,14 @@ from app.models import ( ShippingOrderSchemaVersion, ) from app.services.shipping_notice.customer_normalization import ( - normalize_customer_name, - normalize_domain, - normalize_email, + IDENTITY_MATCH_EQUALITY, + IDENTITY_MATCH_TIER_RANK, + canonical_identity_key, + classify_identity_containment, + normalize_identity_evidence_value, ) -RESOLUTION_VERSION = 'shadow-v2' +RESOLUTION_VERSION = 'shadow-v3' ACCEPTED_DECISION_STATUSES = frozenset({'accepted', 'corroborated'}) @@ -37,14 +41,11 @@ def _normalize(definition: dict[str, Any], value: object) -> str | None: try: field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {} source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {} - if source.get('option_key') == 'from_email': - return normalize_email(value) - if source.get('option_key') == 'from_domain': - return normalize_domain(value) - if field_config.get('normalizer_key') == 'name': - return normalize_customer_name(value) or None - normalized = str(value or '').strip().upper() - return normalized or None + return normalize_identity_evidence_value( + value, + option_key=source.get('option_key'), + normalizer_key=field_config.get('normalizer_key'), + ) except Exception: return None @@ -154,6 +155,8 @@ def _source_evidence( normalized = _normalize(definition, value) if not normalized: continue + field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {} + context_source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {} evidence.append({ 'definition_id': definition_id, 'definition_code': code, @@ -161,6 +164,8 @@ def _source_evidence( 'target_type': definition.get('target_type'), 'raw_value': value, 'normalized_value': normalized, + # 供命中分级使用:邮箱/域名指纹只做精确等值,不参与包含比较。 + 'option_key': str(context_source.get('option_key') or ''), 'weight': int(definition.get('default_weight') or 0), 'source': source, }) @@ -178,27 +183,68 @@ def _customer_match_payload(customer: ShippingCustomer, *, score: float, reasons } +def _classify_evidence_match( + *, runtime_value: str, evidence_value: str, option_key: str, +) -> str | None: + """ + 对单个已审核证据做命中分级:等值 > 完整包含 > 截断包含。 + + 核心逻辑:邮箱/域名指纹语义字符(@、.)参与构成身份,只做归一化后精确等值; + 文本类指纹先比 canonical 等值(吸收标点/空白/大小写差异),再判双向包含。 + """ + if option_key in {'from_email', 'from_domain'}: + return IDENTITY_MATCH_EQUALITY if runtime_value == evidence_value else None + if canonical_identity_key(runtime_value) == canonical_identity_key(evidence_value): + return IDENTITY_MATCH_EQUALITY + return classify_identity_containment(runtime_value, evidence_value, option_key=option_key) + + def _rank_customer_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]: - """按同定义已审核证据聚合客户候选;同分保留歧义,禁止排序取首条。""" + """ + 按同定义已审核证据聚合客户候选,附命中层级;禁止排序取首条抹平歧义。 + + 核心逻辑:每个(运行时证据, 注册证据)对先分级;同一客户取其最强命中层级, + 排序先按层级升序(等值候选始终排在包含候选前),再按累计权重降序。 + 顶层(最强层级)候选唯一时调用方才判 unique_candidate,多家并列即 ambiguous。 + """ scores: dict[int, float] = defaultdict(float) reasons: dict[int, list[dict[str, Any]]] = defaultdict(list) + tiers: dict[int, str] = {} customers = {item.id: item for item in ShippingCustomer.query.filter_by(status='active').all()} for item in evidence: if item['target_type'] != 'customer': continue records = ShippingIdentityEvidence.query.filter_by( - definition_id=item['definition_id'], normalized_value=item['normalized_value'], status='approved', + definition_id=item['definition_id'], status='approved', ).all() for record in records: customer = customers.get(record.customer_id) if record.customer_id is not None else None if customer is None: continue + match_kind = _classify_evidence_match( + runtime_value=str(item['normalized_value'] or ''), + evidence_value=str(record.normalized_value or ''), + option_key=str(item.get('option_key') or ''), + ) + if match_kind is None: + continue scores[customer.id] += item['weight'] - reasons[customer.id].append({**item, 'evidence_id': record.id, 'match_kind': 'approved_identity_evidence'}) - return sorted( - [_customer_match_payload(customers[customer_id], score=score, reasons=reasons[customer_id]) for customer_id, score in scores.items()], - key=lambda item: (-float(item['score']), int(item['customer_id'])), - ) + reasons[customer.id].append({**item, 'evidence_id': record.id, 'match_kind': match_kind}) + if customer.id not in tiers or IDENTITY_MATCH_TIER_RANK[match_kind] < IDENTITY_MATCH_TIER_RANK[tiers[customer.id]]: + tiers[customer.id] = match_kind + ranked = [ + _customer_match_payload(customers[customer_id], score=score, reasons=reasons[customer_id]) + for customer_id, score in scores.items() + ] + # 客户最强层级在聚合后补写,再按(层级, 权重, 客户 ID)排序。 + for item in ranked: + item['match_kind'] = tiers[int(item['customer_id'])] + ranked.sort(key=lambda item: ( + IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])], + -float(item['score']), + int(item['customer_id']), + )) + return ranked def _rank_site_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]: @@ -252,11 +298,20 @@ def resolve_candidate_identity(candidate: ShippingOrderCandidate, intake: Shippi evidence, extraction = _source_evidence(definitions, candidate=candidate, intake=intake) customer_matches = _rank_customer_matches(evidence) site_matches = _rank_site_matches(evidence) - top_score = float(customer_matches[0]['score']) if customer_matches else None - tied = [item for item in customer_matches if float(item['score']) == top_score] if top_score is not None else [] + # [STEP] 顶层 = 候选中的最强命中层级;仅顶层唯一才 unique_candidate, + # 强层级唯一时弱层级候选仅作展示,不参与歧义计算。 + top_tier_candidates: list[dict[str, Any]] = [] + if customer_matches: + top_tier_rank = min( + IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])] for item in customer_matches + ) + top_tier_candidates = [ + item for item in customer_matches + if IDENTITY_MATCH_TIER_RANK[str(item['match_kind'])] == top_tier_rank + ] return { 'resolution_version': RESOLUTION_VERSION, - 'status': 'unmatched' if not customer_matches else 'unique_candidate' if len(tied) == 1 else 'ambiguous', + 'status': 'unmatched' if not customer_matches else 'unique_candidate' if len(top_tier_candidates) == 1 else 'ambiguous', 'evidence': evidence, 'customer_matches': customer_matches, 'site_matches': site_matches, diff --git a/backend/app/services/shipping_notice/inventory_file_store.py b/backend/app/services/shipping_notice/inventory_file_store.py index 1a6610dd..3961be88 100644 --- a/backend/app/services/shipping_notice/inventory_file_store.py +++ b/backend/app/services/shipping_notice/inventory_file_store.py @@ -695,7 +695,7 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) -> if task.task_no in task_nos and not current_inventory_matches_for_task(task) and not has_verified_upload_success(task): set_task_step_progress( task, - step_key="step5_match_inventory", + stage="inventory_matching", step_title="匹配库存", status="running", message="本批库存快照已确认,等待匹配库存", diff --git a/backend/app/services/shipping_notice/inventory_mapping_workflow.py b/backend/app/services/shipping_notice/inventory_mapping_workflow.py index 9d7640d6..29eb6c3f 100644 --- a/backend/app/services/shipping_notice/inventory_mapping_workflow.py +++ b/backend/app/services/shipping_notice/inventory_mapping_workflow.py @@ -101,7 +101,7 @@ def inventory_loaded_response( ) set_task_step_progress( task, - step_key="step3_inventory_prepare", + stage="inventory_fetching", step_title="获取库存", status="completed", message=f"已载入库存 {len(inventory_lines)} 行", diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index 8a257feb..bbc889e9 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -1212,7 +1212,7 @@ def ensure_inventory_via_rpa( _set_workflow_error(task, None) set_task_step_progress( task, - step_key='step3_inventory_prepare', + stage="inventory_fetching", step_title='获取库存', status='running', message='已重新触发库存获取,等待各库存源回调。' if manual_retry_round else '已触发库存获取,等待各库存源回调。', @@ -1240,7 +1240,7 @@ def ensure_inventory_via_rpa( poll_read_only = not allow_auto_retry set_task_step_progress( task, - step_key='step3_inventory_prepare', + stage="inventory_fetching", step_title='获取库存', status='needs_human', message='库存 RPA 未能为全部库存源生成结果。', @@ -1353,7 +1353,7 @@ def ensure_inventory_via_rpa( ) set_task_step_progress( task, - step_key="step3_inventory_prepare", + stage="inventory_fetching", step_title="获取库存", status="running", message=progress_message, @@ -1403,7 +1403,7 @@ def ensure_inventory_via_rpa( _set_workflow_error(task, human_message[:500]) set_task_step_progress( task, - step_key="step3_inventory_prepare", + stage="inventory_fetching", step_title="获取库存", status="needs_human", message=human_message, @@ -1553,7 +1553,7 @@ def _handle_rpa_inventory_skipped( _set_workflow_error(task, None) set_task_step_progress( task, - step_key="step3_inventory_prepare", + stage="inventory_fetching", step_title="获取库存", status="needs_human", message="货代系统当前无可用库存", @@ -1600,7 +1600,7 @@ def _handle_rpa_inventory_failed( }) set_task_step_progress( task, - step_key='step3_inventory_prepare', + stage="inventory_fetching", step_title='获取库存', status='needs_human', message=_workflow_error(task), @@ -1950,7 +1950,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: } set_task_step_progress( task, - step_key="step3_inventory_prepare", + stage="inventory_fetching", step_title="获取库存", status="running", message="RPA 库存文件已返回,正在读取库存快照", diff --git a/backend/app/services/shipping_notice/inventory_workflow.py b/backend/app/services/shipping_notice/inventory_workflow.py index 43bd5f76..fe422e11 100644 --- a/backend/app/services/shipping_notice/inventory_workflow.py +++ b/backend/app/services/shipping_notice/inventory_workflow.py @@ -132,7 +132,7 @@ def _link_ready_candidate_prep_or_block( apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, - step_key='step3_inventory_prepare', + stage="inventory_fetching", step_title='获取库存', status='needs_human', message=t('workflow.inventory.unavailable', lang=lang), @@ -312,7 +312,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]: try: set_task_step_progress( task, - step_key="step3_inventory_prepare", + stage="inventory_fetching", step_title="获取库存", status="running", message=t("workflow.inventory.uploading", lang=lang), @@ -461,7 +461,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, - step_key="step3_inventory_prepare", + stage="inventory_fetching", step_title="获取库存", status="needs_human", message=t("workflow.inventory.unavailable", lang=lang), @@ -502,7 +502,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: task.error_message = None set_task_step_progress( task, - step_key="step3_inventory_prepare", + stage="inventory_fetching", step_title="获取库存", status="running", message="已触发库存获取,等待各库存源回调。", @@ -530,7 +530,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, - step_key="step3_inventory_prepare", + stage="inventory_fetching", step_title="获取库存", status="needs_human", message="库存 RPA 未能为全部库存源生成结果。", @@ -556,7 +556,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, - step_key="step3_inventory_prepare", + stage="inventory_fetching", step_title="获取库存", status="needs_human", message=t("workflow.inventory.unavailable", lang=lang), @@ -625,7 +625,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: apply_task_transition(task, TaskTransition.INV_UNAVAIL) set_task_step_progress( task, - step_key="step3_inventory_prepare", + stage="inventory_fetching", step_title="获取库存", status="needs_human", message=t("workflow.inventory.unavailable", lang=lang), diff --git a/backend/app/services/shipping_notice/lifecycle_projection.py b/backend/app/services/shipping_notice/lifecycle_projection.py index 3597cc5a..08377db7 100644 --- a/backend/app/services/shipping_notice/lifecycle_projection.py +++ b/backend/app/services/shipping_notice/lifecycle_projection.py @@ -5,7 +5,7 @@ services/shipping_notice/lifecycle_projection.py 依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。 逻辑:已核验上传成功 → 已持久化处理阶段 → 正式 Process Gate → 可解释阻断原因; [B''] 处理阶段是阶段唯一权威,正式 Gate 不再覆盖/升降阶段,仅在处理阶段缺失时 - 兜底;无正式事实时保持未分类。兼容 OT.stage 上残留的 step_key 别名。 + 兜底;无正式事实时保持未分类。 本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。 """ @@ -75,11 +75,6 @@ LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = { 'freight_uploading': 'freight_upload', 'manual_upload_handoff': 'freight_upload', 'completed': 'upload_complete', - # 历史 step_key 曾被误写入 OT.stage;投影只读别名,避免工作台掉回接收解析空白页。 - 'step5_match_inventory': 'fulfillment_prep', - 'step6_generate_file': 'fulfillment_prep', - 'step3_inventory_prepare': 'fulfillment_prep', - 'step7_upload_freight': 'freight_upload', } def lifecycle_entries( diff --git a/backend/app/services/shipping_notice/notice_odm_choice_service.py b/backend/app/services/shipping_notice/notice_odm_choice_service.py new file mode 100644 index 00000000..38eef103 --- /dev/null +++ b/backend/app/services/shipping_notice/notice_odm_choice_service.py @@ -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), + } diff --git a/backend/app/services/shipping_notice/order_document_profile_validation_service.py b/backend/app/services/shipping_notice/order_document_profile_validation_service.py index 69cffb18..5d94c7d5 100644 --- a/backend/app/services/shipping_notice/order_document_profile_validation_service.py +++ b/backend/app/services/shipping_notice/order_document_profile_validation_service.py @@ -30,6 +30,7 @@ from app.services.shipping_notice import order_document_profile_lease_service as from app.services.shipping_notice import order_document_profile_service as profile_service from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter from app.services.shipping_notice.audit_service import append_shipping_audit_event +from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract from app.services.shipping_notice.document_layout.order_profile_signature import ( LAYOUT_SIGNATURE_ID, MATCHER_POLICY_ID, @@ -1235,6 +1236,15 @@ def _build_coordinate_overlap_evidence( definition = dict(profile.definition_json or {}) thresholds = _match_thresholds(definition) schema_definition = profile.schema_version.definition_json if profile.schema_version is not None else {} + try: + header_to_field = compile_table_header_contract( + schema_definition if isinstance(schema_definition, dict) else {}, + ).header_to_field + except ValidationError: + # 冻结 Schema definition 非法(别名碰撞等)时容忍降级:None 使 overlap + # 证据的表头原子互斥退化为词级原子,不阻断模板验证;空 definition 编译 + # 出空映射,matcher 侧与 None 同口径。 + header_to_field = None published = published_rival_snapshots_for_overlap(profile) candidates = [draft_snapshot, *published] sample_role_pollution = _detect_sample_role_pollution(profile) @@ -1243,7 +1253,9 @@ def _build_coordinate_overlap_evidence( outcomes: list[dict[str, Any]] = [] for sample in samples: layout = _load_sample_layout(sample) - match = match_frozen_coordinate_profiles(profiles=candidates, layout=layout) + match = match_frozen_coordinate_profiles( + profiles=candidates, layout=layout, header_to_field=header_to_field, + ) parse_result = None if match.profile_code == profile.profile_code and int(match.version or 0) == int(profile.version): if parse_result_resolver is not None: @@ -1296,7 +1308,9 @@ def _build_coordinate_overlap_evidence( 'reason_code': 'representative_layout_unavailable', }) continue - match = match_frozen_coordinate_profiles(profiles=candidates, layout=layout) + match = match_frozen_coordinate_profiles( + profiles=candidates, layout=layout, header_to_field=header_to_field, + ) source_unique = ( match.status in {'unique_match', 'selected_by_score'} and match.profile_code == published_snapshot.get('profile_code') diff --git a/backend/app/services/shipping_notice/order_extraction_run_service.py b/backend/app/services/shipping_notice/order_extraction_run_service.py index ef32d206..10dba00f 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -56,6 +56,7 @@ from app.models import ( ShippingOrderSchemaVersion, User, ) +from app.services.shipping_notice.conversation_title import derive_order_extraction_title from app.services.shipping_notice.order_extraction_route_contract import ( PARSER_ENGINE_VERSION, PARSER_POLICY_VERSION, @@ -697,6 +698,16 @@ def _load_intakes( return rows +def _intake_filenames(intakes: list[ShippingOrderIntake]) -> list[str]: + """按 Intake 顺序取资产原始文件名;无资产或资产缺失以空串占位,保持计数口径。""" + asset_ids = [int(intake.asset_id) for intake in intakes if intake.asset_id] + if not asset_ids: + return [] + rows = db.session.query(FileAsset.id, FileAsset.original_filename).filter(FileAsset.id.in_(asset_ids)).all() + filename_by_id = {row[0]: str(row[1] or '') for row in rows} + return [filename_by_id.get(int(intake.asset_id), '') for intake in intakes if intake.asset_id] + + def _resolve_conversation( *, user_id: int, @@ -713,6 +724,7 @@ def _resolve_conversation( intakes: 已按用户锁定且通过业务资格校验的 Intake。 Returns: 已存在或本事务新建的 ChatSession;调用方负责最终提交。 + 新建会话的 title 由 conversation_title 按首个 Intake 文件名派生;已存在会话不改动标题。 Raises: ConflictError: 所选 Intake 已分属不同会话,或与显式会话不一致。 """ @@ -737,7 +749,7 @@ def _resolve_conversation( session_id=uuid.uuid4().hex, user_id=user_id, agent_id=agent_id, - title='订单抽取', + title=derive_order_extraction_title(_intake_filenames(intakes), datetime.utcnow()), status='running', created_at=datetime.utcnow(), updated_at=datetime.utcnow(), diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index 49802bb6..f1bb7815 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -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, ) @@ -1071,7 +1072,12 @@ def _profile_table_candidates( 'issues': ['order_profile_selected_identity_invalid'], 'match': profile_match, } else: - match = match_frozen_coordinate_profiles(profiles=coordinate_profiles, layout=layout) + # 主路由匹配与下游表格解析共用同一冻结 Schema 表头契约:matcher 侧 + # 表头原子互斥按别名归一为字段语义原子,跨措辞近亲模板不误杀。 + match = match_frozen_coordinate_profiles( + profiles=coordinate_profiles, layout=layout, + header_to_field=contract.header_to_field, + ) affinity_applied = False if not match_only: match = _apply_parse_validation_gate( @@ -1542,9 +1548,8 @@ def _apply_reparse_profile_affinity( ), None) if candidate is None: return match, False - verified = match_frozen_coordinate_profiles(profiles=[frozen], layout=layout) - if verified.status != 'unique_match': - return match, False + # 契约编译须先于复验:复验与解析验证消费同一份冻结 Schema definition, + # 表头原子互斥才能与正式取值走同一别名口径。 schema_snapshot = ( run.input_snapshot_json.get('schema') if isinstance(getattr(run, 'input_snapshot_json', None), dict) @@ -1555,6 +1560,18 @@ def _apply_reparse_profile_affinity( if isinstance(schema_snapshot, dict) and isinstance(schema_snapshot.get('definition'), dict) else {} ) + try: + header_to_field = compile_table_header_contract(schema_definition).header_to_field + except ValidationError: + # 冻结 definition 非法(别名碰撞等)时容忍降级:None 使匹配退化为 + # 词级原子,不阻断重识别亲和性;definition 为空时编译结果为空映射, + # matcher 侧与 None 同口径。 + header_to_field = None + verified = match_frozen_coordinate_profiles( + profiles=[frozen], layout=layout, header_to_field=header_to_field, + ) + if verified.status != 'unique_match': + return match, False parse_result = validate_profile_parse_candidate( profile_snapshot=frozen, layout=layout, @@ -2090,14 +2107,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 +2378,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 +2420,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 +2432,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'] = [ @@ -2540,7 +2583,15 @@ def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, An layout = ensure_on_demand_coordinate_evidence( document=document_model, layout=layout, page_nos=required_pages, ) - match = match_frozen_coordinate_profiles(profiles=profiles, layout=layout) + try: + header_to_field = compile_table_header_contract(definition).header_to_field + except ValidationError: + # 冻结 definition 非法(别名碰撞等)时容忍降级:None 使匹配退化为 + # 词级原子,confirmed 字段锁集返回空,不抛错。 + header_to_field = None + match = match_frozen_coordinate_profiles( + profiles=profiles, layout=layout, header_to_field=header_to_field, + ) match, _affinity_applied = _apply_reparse_profile_affinity( run=run, unit=unit, profiles=profiles, match=match, layout=layout, ) diff --git a/backend/app/services/shipping_notice/order_review_customer_service.py b/backend/app/services/shipping_notice/order_review_customer_service.py index b832f703..94dec08c 100644 --- a/backend/app/services/shipping_notice/order_review_customer_service.py +++ b/backend/app/services/shipping_notice/order_review_customer_service.py @@ -258,19 +258,26 @@ def retry_review_case_customer_resolution( case = _load_writable_case(user_id=user_id, case_no=case_no) matches: list[dict[str, Any]] = [] if case.candidate_id: + from app.services.shipping_notice.customer_auto_resolution import ( + AUTO_CONFIRM_ELIGIBLE_STATUSES, + resolve_auto_customer_decision, + ) from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if candidate is not None: shadow = refresh_candidate_shadow_resolution(candidate) - # [STEP 2] 重新识别后若客户指纹唯一命中,直接写入确认结果;投影函数保持纯读。 + # [STEP 2] 重新识别后与任务期协调器共用同一分级裁决:canonical 等值唯一或 + # 「指纹完整出现」包含唯一且证据授权才自动确认;截断建议(containment_weak) + # 只进候选展示,绝不在此确认。投影函数保持纯读。 + decision = resolve_auto_customer_decision(shadow) if ( - shadow.status == 'unique_candidate' - and shadow.top_customer_id + str(decision.get('status') or '') in AUTO_CONFIRM_ELIGIBLE_STATUSES + and decision.get('customer_id') is not None and not resolve_review_case_customer_resolved(case=case, candidate=candidate) ): confirm_customer_resolution( candidate, - customer_id=int(shadow.top_customer_id), + customer_id=int(decision['customer_id']), actor_id=None, method='auto_rule', reason='客户识别指纹唯一命中自动确认', diff --git a/backend/app/services/shipping_notice/order_review_projection.py b/backend/app/services/shipping_notice/order_review_projection.py index f7000fb3..c4a330df 100644 --- a/backend/app/services/shipping_notice/order_review_projection.py +++ b/backend/app/services/shipping_notice/order_review_projection.py @@ -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} diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index c99030a2..d7cdf65e 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -260,25 +260,27 @@ def map_notice_to_processing_status_stage(notice: Any) -> tuple[str, str]: return ('completed', 'completed') if ps in {'waiting_upload', 'upload_failed', 'uploading'} or projected_upload == 'uploading': return ('automating', 'freight_uploading') - if 'upload' in step or step.startswith('step7'): + # [契约唯一] current_step 只存 15 阶契约码(CheckPoint stepN_* 遗留键已清除), + # 阶段信号按契约码精确匹配,不再做子串/前缀启发式。 + if step == 'freight_uploading': return ('automating', 'freight_uploading') - if ps in {'export', 'excel', 'generating_excel'} or 'generate' in step or step.startswith('step6'): + if ps in {'export', 'excel', 'generating_excel'} or step == 'excel_generating': return ('automating', 'excel_generating') if ps == 'matched' and export_path: return ('automating', 'excel_generating') - if ps in {'matching', 'inventory_ready', 'matched'} or 'match' in step: + if ps in {'matching', 'inventory_ready', 'matched'} or step == 'inventory_matching': return ('automating', 'inventory_matching') # 正式建单后的库存获取:waiting_inventory / parsed → 获取库存(禁止仍映射到 matching)。 - if ps in {'waiting_inventory', 'parsed'} or 'fetch' in step or step.startswith('step4'): + if ps in {'waiting_inventory', 'parsed'} or step == 'inventory_fetching': return ('automating', 'inventory_fetching') if ps == 'pending_review': return ('waiting_review', 'waiting_review') - if ps in {'creating', 'order_creating', 'confirming'} or 'create' in step or step.startswith('step3'): + if ps in {'creating', 'order_creating', 'confirming'} or step == 'order_creating': return ('automating', 'order_creating') if ps in {'fetching_inventory', 'inventory_fetching'}: return ('automating', 'inventory_fetching') @@ -687,13 +689,8 @@ _USER_STAGE_TO_CODE: dict[str, str] = { 'waiting_review': 'waiting_human_review', 'inventory_fetching': 'inventory_fetch', 'inventory_matching': 'inventory_match', - # step_key 误写入 OT.stage 时的只读别名(与 lifecycle_projection 同源)。 - 'step5_match_inventory': 'inventory_match', - 'step3_inventory_prepare': 'inventory_fetch', - 'step6_generate_file': 'excel_generate', 'excel_generating': 'excel_generate', 'freight_uploading': 'freight_upload', - 'step7_upload_freight': 'freight_upload', 'completed': 'completed', 'failed': 'failed_terminal', 'cancelled': 'cancelled', diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index 3bb53c84..ec2f17b0 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -88,6 +88,13 @@ from app.services.shipping_notice.constants import ( RS_SHORTAGE_REVIEW, ) from app.services.shipping_notice.upload_attempt_service import latest_export_artifact +from app.services.shipping_notice.lifecycle_projection import ( + LIFECYCLE_STAGE_BY_GATE, + LIFECYCLE_STAGE_BY_PROCESSING_STAGE, +) +from app.services.shipping_notice.process_gate_contract import ( + PROCESS_GATE_REASON_OWNING_GATE, +) from app.services.shipping_notice.state_machine import ( UserMode, resolve_task_ui_state, @@ -132,6 +139,17 @@ _TODO_BUCKET_CATEGORIES: dict[str, frozenset[str]] = { "done": frozenset({"done"}), } +# 阶段筛选 tab 仅覆盖四个可动作阶段;「通知完成」属 done 桶终态,不做筛选维度。 +_ACTIONABLE_TODO_STAGES: tuple[str, ...] = ( + "intake_parse", "order_review", "fulfillment_prep", "freight_upload", +) +# 无 processing_stage 且人工原因不可映射时的 todo_category 粗兜底(与 Gate 映射语义对齐)。 +_TODO_STAGE_BY_CATEGORY_FALLBACK: dict[str, str] = { + "review": "order_review", + "exception": "fulfillment_prep", + "manual_upload": "freight_upload", +} + # 尚未挂 OT、仍需用户/系统关注的 Intake 解析状态(进入我的待办)。 _ORPHAN_INTAKE_TODO_PARSE_STATUSES = frozenset({ "created", @@ -2762,12 +2780,14 @@ def _todo_tasks_base_query( customer_needle: str, customer_like: str, task_no: str | None, + terminal_kind: str | None = None, ): """ 构造带精确 category CASE 过滤的 Task 待办查询。 核心逻辑:可见性 / 客户过滤后,用 _task_todo_category_sql_expr().in_(allowed); - done 桶另加终态粗筛。pending/processing 不再用领域标量粗筛,避免与 COUNT 分叉。 + done 桶另加终态粗筛;terminal_kind 进一步拆分 done 子视图(通知完成 / 驳回作废)。 + pending/processing 不再用领域标量粗筛,避免与 COUNT 分叉。 """ q = _visible_tasks_query_for_todos(user_id, is_admin=is_admin) workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() @@ -2817,6 +2837,17 @@ def _todo_tasks_base_query( ), ) ) + # [STEP] 终态子视图过滤:前端「通知完成 / 复核驳回·已作废」子 tab 各取所需; + # 口径与分类 CASE 的 done 分支保持一致(上传成功优先,二者互斥)。 + if terminal_kind == "upload_complete": + q = q.filter(upload_success) + elif terminal_kind == "reject_void": + q = q.filter( + db.or_( + workflow_review_status == RS_REJECTED, + ShippingNotice.lifecycle_status.in_(("voided", "archived", "deleted")), + ) + ) return q.filter(_task_todo_category_sql_expr().in_(tuple(sorted(allowed)))) @@ -2825,6 +2856,108 @@ def _active_todo_tasks_scope(user_id: int, *, is_admin: bool = False): return _visible_tasks_query_for_todos(user_id, is_admin=is_admin) +def _classify_todo_lifecycle_stage( + category: str, + *, + pending_human_reason: Any = None, + processing_stage: Any = None, +) -> str | None: + """ + 按统一生命周期口径归类待办条目的阶段 tab(仅供计数,不替代 ui_state)。 + + 核心逻辑:与 ``project_lifecycle`` 同优先级——processing_stage 权威 → 人工原因 + 归属 Gate 兜底 → todo_category 粗兜底;结果若不是四个可动作阶段(如 completed + 映射出的 upload_complete)则返回 None,由调用方跳过,避免污染阶段 tab 计数。 + + Args: + category: 待办分类 CASE 结果(review/exception/manual_upload/in_progress)。 + pending_human_reason: OT ``pending_human_reason`` 人工原因码(可空)。 + processing_stage: OT ``stage`` 已持久化处理阶段(可空)。 + + Returns: + 四个可动作阶段码之一;不可归入时 None。 + """ + stage_key = str(processing_stage or '').strip().lower() + if stage_key in LIFECYCLE_STAGE_BY_PROCESSING_STAGE: + stage = LIFECYCLE_STAGE_BY_PROCESSING_STAGE[stage_key] + else: + gate = PROCESS_GATE_REASON_OWNING_GATE.get(str(pending_human_reason or '').strip()) + if gate in LIFECYCLE_STAGE_BY_GATE: + stage = LIFECYCLE_STAGE_BY_GATE[gate] + else: + stage = _TODO_STAGE_BY_CATEGORY_FALLBACK.get(str(category or ''), 'fulfillment_prep') + return stage if stage in _ACTIONABLE_TODO_STAGES else None + + +def _my_todo_stage_counts(user_id: int, *, is_admin: bool) -> dict[str, int]: + """ + 统计待处理桶在四个可动作阶段的分布,供前端阶段筛选 tab 展示全量计数。 + + 核心逻辑:Review Case 走统一生命周期投影(候选有效性裁决 接收解析 vs 订单复核); + 孤儿 Intake 恒为接收解析;Notice / OT 分支一次取回「分类 CASE + OT stage + + 人工原因」后在 Python 侧归类,避免为计数复制一份 SQL 阶段状态机。 + + Returns: + {intake_parse, order_review, fulfillment_prep, freight_upload}(含 0 值键)。 + """ + counts: dict[str, int] = {code: 0 for code in _ACTIONABLE_TODO_STAGES} + + def _bump(stage: str | None) -> None: + if stage in counts: + counts[str(stage)] += 1 + + # [STEP 1] 开放 Review Case:复用统一投影,禁止另写候选有效性判断。 + for case_row in _visible_open_review_cases_query(user_id, is_admin=is_admin).all(): + projection = _review_case_lifecycle_projection(case_row) + _bump(str(projection.get('lifecycle_stage') or '').strip() or None) + + # [STEP 2] 孤儿 Intake(未建 OT 的解析待办)恒为接收解析。 + counts["intake_parse"] += int( + _visible_orphan_intakes_query(user_id, is_admin=is_admin).count() + ) + + # [STEP 3] Notice 分支:分类 CASE 直接作为列取回,连同 OT stage / 人工原因归类。 + category_expr = _task_todo_category_sql_expr() + ot_stage_subquery = select(ShippingOrderTask.stage).where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ).scalar_subquery() + ot_reason_subquery = select(ShippingOrderTask.pending_human_reason).where( + ShippingOrderTask.id == ShippingNotice.order_task_id, + ).scalar_subquery() + notice_rows = ( + _active_todo_tasks_scope(user_id, is_admin=is_admin) + .filter(category_expr.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"})))) + .with_entities( + category_expr.label("category"), + ot_stage_subquery.label("ot_stage"), + ot_reason_subquery.label("ot_reason"), + ) + .all() + ) + for category, ot_stage, ot_reason in notice_rows: + _bump(_classify_todo_lifecycle_stage( + category, pending_human_reason=ot_reason, processing_stage=ot_stage, + )) + + # [STEP 4] OT 分支(库存准备尚未建正式 Notice)同理。 + ot_category_expr = _order_task_todo_category_sql_expr() + ot_rows = ( + _visible_order_tasks_query_for_todos(user_id, is_admin=is_admin) + .filter(ot_category_expr.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"})))) + .with_entities( + ot_category_expr.label("category"), + ShippingOrderTask.stage.label("ot_stage"), + ShippingOrderTask.pending_human_reason.label("ot_reason"), + ) + .all() + ) + for category, ot_stage, ot_reason in ot_rows: + _bump(_classify_todo_lifecycle_stage( + category, pending_human_reason=ot_reason, processing_stage=ot_stage, + )) + return counts + + def list_my_todos( user_id: int, *, @@ -2835,6 +2968,7 @@ def list_my_todos( todo_category: str | None = None, customer: str | None = None, task_no: str | None = None, + terminal_kind: str | None = None, ) -> dict[str, Any]: """ 分页列出「我的待办」:建单前 Review Case + 未建 OT Intake + 建单后 Task。 @@ -2851,6 +2985,7 @@ def list_my_todos( todo_category: 可选细分类覆盖 bucket。 customer: 客户名/代码/来源文件名/Case 号/PO/Intake 号模糊过滤。 task_no: 精确任务号过滤(仅 Task 项;复核/Intake 项忽略)。 + terminal_kind: done 桶终态子视图过滤(upload_complete | reject_void);其余 bucket 忽略。 Returns: {items, page, page_size, total} @@ -2869,6 +3004,7 @@ def list_my_todos( customer_like = f"%{customer_needle}%" if customer_needle else "" include_review_cases = "review" in allowed and not task_no include_orphan_intakes = "intake_parse" in allowed and not task_no + normalized_terminal_kind = str(terminal_kind or "").strip().lower() or None # [STEP 1] 多端投影为统一列:kind / entity_id / sort_at / sort_ref。 branches = [] @@ -2915,6 +3051,7 @@ def list_my_todos( customer_needle=customer_needle, customer_like=customer_like, task_no=task_no, + terminal_kind=normalized_terminal_kind, ) branches.append( tasks_q.with_entities( @@ -3053,14 +3190,17 @@ def list_my_todos( } -def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]: +def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, Any]: """ - 统计「我的待办」各 bucket 数量,供导航徽标使用。 + 统计「我的待办」各 bucket 数量,供导航徽标与阶段筛选 tab 使用。 - 核心逻辑:开放 Review Case + 未建 OT Intake 计入 pending;Task 用 SQL CASE COUNT。 + 核心逻辑:开放 Review Case + 未建 OT Intake 计入 pending;Task 用 SQL CASE COUNT; + 阶段 tab 计数与 done 终态拆分见 _my_todo_stage_counts / done_counts 组装。 Returns: - {pending, processing, done, total_pending_badge} + {pending, processing, done, total_pending_badge, + stage_counts: {intake_parse, order_review, fulfillment_prep, freight_upload}, + done_counts: {upload_complete, reject_void}} """ workflow_review_status = select(ShippingOrderTask.review_status).where(ShippingOrderTask.id == ShippingNotice.order_task_id).scalar_subquery() artifact_exists = exists(select(1).select_from(ShippingExportArtifact).where(ShippingExportArtifact.task_id == ShippingNotice.id, ShippingExportArtifact.status.in_(('ready', 'uploading', 'uploaded')))) @@ -3077,7 +3217,7 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]: pending += ot_active.filter(ot_category.in_(tuple(sorted(_PENDING_TODO_CATEGORIES - {"intake_parse"})))).count() processing = active.filter(category_expr == "in_progress").count() processing += ot_active.filter(ot_category == "in_progress").count() - done = ( + done_base = ( _visible_tasks_query_for_todos(user_id, is_admin=is_admin) .filter( db.or_( @@ -3091,11 +3231,19 @@ def count_my_todos(user_id: int, *, is_admin: bool = False) -> dict[str, int]: ) ) .filter(category_expr == "done") - .count() ) + done = done_base.count() + # done 拆分:已核验上传成功 vs 复核驳回/作废归档;分类 CASE 中上传成功优先, + # 故二者互斥,reject_void 用差值即无重叠计数。 + done_upload = done_base.filter(upload_success).count() return { "pending": pending, "processing": processing, "done": done, "total_pending_badge": pending, + "stage_counts": _my_todo_stage_counts(user_id, is_admin=is_admin), + "done_counts": { + "upload_complete": done_upload, + "reject_void": max(0, done - done_upload), + }, } diff --git a/backend/app/services/shipping_notice/reconciliation_projector.py b/backend/app/services/shipping_notice/reconciliation_projector.py index 79954e23..2b4aaeeb 100644 --- a/backend/app/services/shipping_notice/reconciliation_projector.py +++ b/backend/app/services/shipping_notice/reconciliation_projector.py @@ -44,6 +44,9 @@ from app.models import ( ShippingOrderReviewCase, User, ) +from app.services.shipping_notice.error_explainability_contract import ( + UNKNOWN_BUSINESS_FAILURE_REASON_CODE, +) # ============================================================ @@ -60,6 +63,11 @@ class BlockingReason(TypedDict, total=False): code: str | None i18n_key: str | None details: dict[str, Any] | None + # 建单前资格快照回退透传字段(来自冻结 explainability 契约, + # 见 error_explainability_contract.build_explainability_reason; + # message 为中文兜底文案,前端优先按 i18n 命名空间解析)。 + message: str | None + next_action: str | None class CurrentGate(TypedDict, total=False): @@ -723,11 +731,67 @@ def project_case_blocking_reason(automation: dict[str, Any] | None) -> BlockingR return BlockingReason(code=None, i18n_key=None, details=details) i18n_key = _REASON_TO_I18N_KEY.get(raw_code) if i18n_key is None: - # fail-closed:给一个通用兜底 key - i18n_key = 'shipping.review.blocked_generic' + # fail-closed:兜底键必须指向前端真实存在的键;此前指向不存在的 + # shipping.review.blocked_generic,任何未映射码都会在前端双重落空成 + # 「当前步骤需要人工处理」。 + i18n_key = 'chat.shippingProcessing.reasonCode.unknown' return BlockingReason(code=raw_code, i18n_key=i18n_key, details=details) +def _blocking_reason_is_generic(reason: BlockingReason) -> bool: + """ + 判断 blocking_reason 是否未携带具体原因(无码或仅落通用兜底键)。 + 仅此情形才允许回退到资格快照,避免覆盖 automation 侧更精确的裁决。 + """ + if not isinstance(reason, dict): + return True + code = str(reason.get('code') or '').strip() + if not code: + return True + return str(reason.get('i18n_key') or '').strip() == 'chat.shippingProcessing.reasonCode.unknown' + + +def _primary_validation_blocking_reason(validation: dict[str, Any] | None) -> BlockingReason | None: + """ + 【AI 触发时机】:automation 无具体原因码,需要从草稿校验快照取首要阻断原因时。 + 核心逻辑:只认 severity=blocking 且 explainability 未降级(非 + unknown_business_failure)的 issue;透传冻结契约的 message / next_action, + 本模块不新造文案或映射。无可用 issue 返回 None,由调用方保持既有兜底。 + """ + if not isinstance(validation, dict): + return None + issues = validation.get('issues') + if not isinstance(issues, list): + return None + for issue in issues: + if not isinstance(issue, dict): + continue + if str(issue.get('severity') or '').strip().lower() != 'blocking': + continue + explainability = issue.get('explainability') if isinstance(issue.get('explainability'), dict) else {} + code = str( + explainability.get('reason_code') + or issue.get('reason_code') + or issue.get('code') + or '' + ).strip() + if not code or code == UNKNOWN_BUSINESS_FAILURE_REASON_CODE: + continue + details = { + key: value for key, value in issue.items() + if key in {'field_code', 'field_id', 'line_index', 'owning_gate_code'} + and value is not None + } + return BlockingReason( + code=code, + i18n_key=_REASON_TO_I18N_KEY.get(code), + details=details or None, + message=str(explainability.get('message') or issue.get('message') or '').strip() or None, + next_action=str(explainability.get('next_action') or '').strip() or None, + ) + return None + + # ============================================================ # [5] user_status(F2 六值;默认人工等待 = waiting_human,禁止 idle) # ============================================================ @@ -1218,6 +1282,13 @@ def project_review_case_projection_bundle( current_gate = project_case_current_gate(case, automation, available_actions) # [STEP 4] blocking_reason blocking_reason = project_case_blocking_reason(automation) + # [STEP 4.1] automation 未携带具体原因时,回退到草稿校验快照的首要 blocking + # issue:资格评估落库时已按冻结 explainability 契约附带原因文案与下一步动作, + # 此处仅透传,让批次中心/工作台展示「客户尚未确认」等具体原因而非通用兜底。 + if _blocking_reason_is_generic(blocking_reason): + fallback_reason = _primary_validation_blocking_reason(validation) + if fallback_reason is not None: + blocking_reason = fallback_reason # [STEP 5] user_status user_status = project_case_user_status(case, automation) # [STEP 5.1] 已持久化的正式 Gate 是实时状态唯一裁决源。此前这里用 Case diff --git a/backend/app/services/shipping_notice/reservation_region.py b/backend/app/services/shipping_notice/reservation_region.py index 4d897f78..80c645c0 100644 --- a/backend/app/services/shipping_notice/reservation_region.py +++ b/backend/app/services/shipping_notice/reservation_region.py @@ -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 diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index 4d9d9ddf..bf5cf5c8 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -4003,6 +4003,33 @@ def _conversation_processing_from_work_items( } +def _review_case_blocking_reason( + case: ShippingOrderReviewCase | None, + drafts_by_id: dict[int, Any], +) -> dict[str, Any] | None: + """ + 建单前 Case 摘要叶子的具体阻断原因:回退到草稿校验快照的首要 blocking issue。 + + 核心逻辑:资格评估落库时已按冻结 explainability 契约附带 code/message/next_action + (见 reconciliation_projector._primary_validation_blocking_reason);摘要路径的 + drafts_by_id 已批量加载,透传零额外查询。无 Draft / 无可用 issue 返回 None, + 调用方保持 review_case_{status} 状态码兜底。 + """ + if case is None: + return None + draft_id = getattr(case, 'current_draft_id', None) + if draft_id is None: + return None + draft = drafts_by_id.get(int(draft_id)) + validation = getattr(draft, 'validation_result_json', None) + if not isinstance(validation, dict): + return None + from app.services.shipping_notice.reconciliation_projector import ( + _primary_validation_blocking_reason, + ) + return _primary_validation_blocking_reason(validation) + + def project_conversation_processing_summary( *, user_id: int, @@ -4585,7 +4612,13 @@ def project_conversation_processing_summary( 'po_number': candidate_po or None, }, 'current_gate': current_gate, - 'blocking_reason': {'code': reason} if reason else None, + # v4:建单前 Case 的 review_case_{status} 状态码先回退到资格快照的 + # 首要阻断 issue(客户尚未确认等具体原因),无可用 issue 才落状态码。 + 'blocking_reason': ( + _review_case_blocking_reason(case, drafts_by_id) + if str(reason or '').startswith('review_case_') + else ({'code': reason} if reason else None) + ), 'primary_action': primary_action, 'available_actions': available_actions, 'intake_parse_authorized': intake_parse_authorized, diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index b4a2f40e..824b784c 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -703,7 +703,7 @@ def replace_task_notice( intake.parse_warnings_json = cleaned_warnings set_task_step_progress( task, - step_key="step2_parse_confirm", + stage="waiting_review", step_title="确认解析", status="needs_human", message="发货通知文本抽取失败", @@ -732,7 +732,7 @@ def replace_task_notice( _reset_notice_edit_downstream(task) set_task_step_progress( task, - step_key="step1_notice_submit", + stage="order_creating", step_title="提交通知", status="completed", message="已重新上传发货通知并覆盖当前任务", diff --git a/backend/app/services/shipping_notice/tool_common.py b/backend/app/services/shipping_notice/tool_common.py index fd3f4002..a5e811f2 100644 --- a/backend/app/services/shipping_notice/tool_common.py +++ b/backend/app/services/shipping_notice/tool_common.py @@ -2,7 +2,7 @@ services/shipping_notice/tool_common.py 用途:发货通知 Tool 链共享配置、payload 合并、消息拼接与任务事件写入(无阶段业务编排)。 -依赖:constants、models.ShippingTaskEvent、fulfillment_audit、stp_progress_contract。 +依赖:constants、models.ShippingTaskEvent、fulfillment_audit、stp_progress_contract、progress_audit_contract。 逻辑:task_workflow / inventory_workflow / fulfillment_workflow / decision_workflow 共用; log_task_event 对 inventory_rpa_/inventory_source_/export_/notice_replace/ freight_cancellation_/STP 事件同步投影到 ShippingAuditEvent; @@ -20,6 +20,10 @@ from flask import current_app from app import db from app.models import ShippingNotice, ShippingOrderTask, ShippingTaskEvent from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK +from app.services.shipping_notice.progress_audit_contract import ( + SHIPPING_PROCESSING_STAGES, + shipping_processing_stage_index, +) def cfg_bool(key: str, default: bool = False) -> bool: @@ -211,7 +215,7 @@ def prepend_tool_message(result: dict[str, Any], prefix: str) -> dict[str, Any]: def set_task_step_progress( task: ShippingNotice, *, - step_key: str, + stage: str, step_title: str, status: str, message: str, @@ -221,13 +225,38 @@ def set_task_step_progress( detail: str | None = None, extra: dict[str, Any] | None = None, ) -> None: - """写入任务当前步骤与步骤内细粒度进度,统一落到 OT 的流程字段。""" + """写入任务当前步骤与步骤内细粒度进度,统一落到 OT 的流程字段。 + + 【AI 触发时机】履约工作流(库存准备/匹配/Excel/上传/通知重解析)报告阶段内 + 细粒度进度或失败等待人工时调用。 + + 核心逻辑:``stage`` 必须是冻结 15 阶契约码(SHIPPING_PROCESSING_STAGES 成员), + 写入 ``current_step`` 与 ``step_payload_json.current_step_progress`` 供投影展示; + ``OT.stage`` 仅按 15 阶序列【只进不退】推进——空缺时直接写入,已有值仅当新 + stage 序号不小于旧值才覆盖,保证进度上报永远不会把订单拉回早期阶段。 + + Args: + stage: 15 阶契约码(如 inventory_fetching / inventory_matching / + excel_generating / freight_uploading);禁止传入 CheckPoint 时代 + stepN_* 遗留键(已全部清除)。 + step_title: 展示用步骤名。 + status: 步骤执行态(running/completed/needs_human/failed 等调用方语义)。 + message: 用户可读进度说明。 + + Raises: + ValueError: ``stage`` 不是 15 阶契约成员时立即失败(写错阶段码属于代码缺陷)。 + """ + code = str(stage or '').strip() + if code not in SHIPPING_PROCESSING_STAGES: + raise ValueError( + f'set_task_step_progress: stage must be a SHIPPING_PROCESSING_STAGES member, got {stage!r}' + ) owner = task if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None): owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task payload = dict(getattr(owner, 'step_payload_json', None) or {}) progress: dict[str, Any] = { - "step_key": step_key, + "stage": code, "step_title": step_title, "status": status, "message": str(message or "").strip(), @@ -244,9 +273,19 @@ def set_task_step_progress( progress["extra"] = extra payload["current_step_progress"] = progress if hasattr(owner, 'current_step'): - owner.current_step = step_key + owner.current_step = code if hasattr(owner, 'stage'): - owner.stage = step_key + current_stage = str(getattr(owner, 'stage', None) or '').strip().lower() + current_idx = shipping_processing_stage_index(current_stage) + target_idx = shipping_processing_stage_index(code) + # 只进不退:进度上报只允许推进或停留在既有序列位置,禁止回退 + # (历史缺陷:进度上报曾把 order_creating 踩回早期码,工作台掉回接收解析)。 + if ( + not current_stage + or current_idx is None + or (target_idx is not None and target_idx >= current_idx) + ): + owner.stage = code if hasattr(owner, 'step_payload_json'): owner.step_payload_json = payload diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index aa9ace77..7c9fe2fa 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -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, diff --git a/backend/migrations/versions/aa11bb22cc33_customer_odm_scope.py b/backend/migrations/versions/aa11bb22cc33_customer_odm_scope.py new file mode 100644 index 00000000..eefe24ba --- /dev/null +++ b/backend/migrations/versions/aa11bb22cc33_customer_odm_scope.py @@ -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") diff --git a/backend/migrations/versions/dd22ee33ff44_merge_migration_heads.py b/backend/migrations/versions/dd22ee33ff44_merge_migration_heads.py new file mode 100644 index 00000000..47d74188 --- /dev/null +++ b/backend/migrations/versions/dd22ee33ff44_merge_migration_heads.py @@ -0,0 +1,25 @@ +"""merge migration heads + +用途:合并平行迁移分支,恢复 Alembic 单 head 链。 +依赖:无表结构操作,仅声明多父级(aa11bb22cc33 客户 ODM 字段 × vc6a7b8c9d0e 凭证检核通知配置)。 +逻辑:hugo-shipping-notice 与 dev 两侧各自新增迁移产生分叉;本 Revision 只做图合并, + upgrade/downgrade 均为空操作,实际 DDL 由两个父迁移各自负责。 + +Revision ID: dd22ee33ff44 +Revises: aa11bb22cc33, vc6a7b8c9d0e +Create Date: 2026-09-17 00:00:00.000000 + +""" + +revision = "dd22ee33ff44" +down_revision = ("aa11bb22cc33", "vc6a7b8c9d0e") +branch_labels = None +depends_on = None + + +def upgrade(): + pass + + +def downgrade(): + pass diff --git a/backend/tests/services/shipping_notice/test_customer_identity_tier_matching.py b/backend/tests/services/shipping_notice/test_customer_identity_tier_matching.py new file mode 100644 index 00000000..4e1f0780 --- /dev/null +++ b/backend/tests/services/shipping_notice/test_customer_identity_tier_matching.py @@ -0,0 +1,384 @@ +""" +backend/tests/services/shipping_notice/test_customer_identity_tier_matching.py + +用途:验证客户识别三级命中(canonical 等值 > 完整包含 > 截断包含)与受控自动确认边界。 +依赖:内存数据库、customer_normalization、identity_resolution.resolver、 + customer_auto_resolution、customer_shadow_resolution。 +逻辑:以 QCH/Quanta 真实差异形态(标点变体、c/o 截断、折行块整段提取、家族前缀、 + 跨行 vs 单行证据)构造分支,断言影子候选层级、状态语义,以及自动确认只放行 + 「等值唯一」与「完整包含唯一且证据授权」,截断建议永不自动确认。 +""" + +from __future__ import annotations + +from datetime import datetime + +import pytest + +from app import db +from app.models import ( + ShippingCustomer, + ShippingIdentityDefinition, + ShippingIdentityEvidence, + ShippingIdentityRuleSet, + ShippingOrderCandidate, + ShippingOrderExtraction, + ShippingOrderFieldDecision, + ShippingOrderFieldValue, + ShippingOrderIntake, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + User, +) +from app.services.shipping_notice.customer_auto_resolution import resolve_auto_customer_decision +from app.services.shipping_notice.customer_normalization import ( + IDENTITY_MATCH_CONTAINMENT_STRONG, + IDENTITY_MATCH_CONTAINMENT_WEAK, + IDENTITY_MATCH_EQUALITY, + canonical_identity_key, + classify_identity_containment, + normalize_identity_evidence_value, +) +from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution +from app.services.shipping_notice.identity_resolution import resolve_candidate_identity + +FIELD_ID = 'fid-ship-to-customer' +RULE_SET_DEF_ID = 'def-ship-to-customer' + + +@pytest.mark.pure_unit +class TestCanonicalIdentityKey: + """canonical 键:标点/空白/大小写不敏感,中文保留。""" + + def test_punctuation_whitespace_case_insensitive(self): + # 关键断言:QCH 注册值与 PDF 打印值的标点/空格差异不再分裂等值命中。 + assert canonical_identity_key('QCH, INC., A NEVADA CORPORATION') == canonical_identity_key( + 'qch inc a nevada corporation', + ) + + def test_keeps_cjk_word_chars(self): + # 关键断言:中文客户名不被剔除,仍可参与等值比较。 + assert canonical_identity_key('英業達股份有限公司桃科廠') == '英業達股份有限公司桃科廠' + assert canonical_identity_key('Inventec 英業達') == 'inventec英業達' + + +@pytest.mark.pure_unit +class TestNormalizeIdentityEvidenceValue: + """识别证据统一归一化:三处调用点同源,兜底分支折叠内部空白。""" + + def test_fallback_collapses_newlines(self): + # 关键断言:多行提取值折叠换行后可与单行注册证据等值(修复换行不对称缺陷)。 + assert normalize_identity_evidence_value('QUANTA MFG,\n1 WALDENBOOKS DR.') == 'QUANTA MFG, 1 WALDENBOOKS DR.' + + def test_name_normalizer_strips_punctuation(self): + assert normalize_identity_evidence_value('Hyve, Solutions', normalizer_key='name') == 'HYVESOLUTIONS' + + def test_email_branch_keeps_semantic_chars(self): + assert normalize_identity_evidence_value('A@B.COM', option_key='from_email') == 'a@b.com' + + def test_blank_returns_none(self): + assert normalize_identity_evidence_value(' ') is None + + +@pytest.mark.pure_unit +class TestClassifyIdentityContainment: + """双向包含分级:强=指纹完整出现;弱=提取值疑似截断;邮箱/域名不参与。""" + + EVIDENCE = 'QCH INC., A NEVADA CORPORATION C/O QUANTA' + + def test_strong_when_fingerprint_fully_inside_runtime(self): + # 关键断言:折行块整段进入字段值时,完整指纹命中判强包含(可受控自动确认)。 + assert classify_identity_containment( + 'QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC', self.EVIDENCE, + ) == IDENTITY_MATCH_CONTAINMENT_STRONG + + def test_weak_when_runtime_is_truncation(self): + # 关键断言:截断方向只判弱命中——剩余部分未经验证,禁止自动确认。 + assert classify_identity_containment( + 'QCH, INC., A NEVADA CORPORATION c/o', self.EVIDENCE, + ) == IDENTITY_MATCH_CONTAINMENT_WEAK + + def test_fragment_below_minimum_chars_rejected(self): + # 关键断言:'c/o'→'CO' 这类短碎片不得产生包含噪声。 + assert classify_identity_containment('c/o', self.EVIDENCE) is None + + def test_email_domain_never_contained(self): + assert classify_identity_containment('ops@corp.com', 'ops@corp', option_key='from_email') is None + + def test_unrelated_values_rejected(self): + assert classify_identity_containment('HYVE SOLUTIONS CORPORATION', self.EVIDENCE) is None + + +def _build_identity_world(*, runtime_value: str, evidences: list[dict]): + """ + 构建最小识别世界:发布规则集 + 单 Header 字段抽取链 + 客户/证据主数据。 + + Args: + runtime_value: 已裁决 Header 字段值(模拟 PDF 提取结果)。 + evidences: 注册证据列表,每项含 customer_name/short_code/normalized_value, + 可选 auto(默认 True,对应 auto_match_allowed)。 + Returns: + (candidate, intake) 供 resolve_candidate_identity / 影子刷新使用。 + """ + user = User(username='tier-user', email='tier@example.com', role='user') + db.session.add(user) + db.session.flush() + schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none() + if schema is None: + schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单') + db.session.add(schema) + db.session.flush() + version = ShippingOrderSchemaVersion( + schema_id=schema.id, version=1, status='published', lock_version=1, checksum='1' * 64, + definition_json={'fields': [{ + 'field_id': FIELD_ID, 'field_code': 'ship_to_customer', 'display_name': 'Ship To Customer', + 'scope': 'header', 'value_type': 'string', 'enabled': True, + 'available_for_customer_identity': True, 'normalizer_key': 'trim', + }]}, + ) + db.session.add(version) + db.session.flush() + definition_json = { + 'order_schema': {'id': version.id, 'version': version.version, 'checksum': version.checksum}, + 'definitions': [{ + 'id': RULE_SET_DEF_ID, 'definition_code': 'ship_to_customer_rule', + 'display_name': 'Ship To Customer', 'evidence_label': 'Ship To', + 'target_type': 'customer', 'context_field_id': FIELD_ID, + 'default_weight': 100, 'max_automation': 'conditional', 'status': 'active', + 'field_config': { + 'field_id': FIELD_ID, 'field_code': 'ship_to_customer', 'scope': 'header', + 'value_type': 'string', 'normalizer_key': 'trim', + 'context_source': {'provider': 'order_field', 'option_key': None}, + 'available_for_customer_identity': True, + }, + }], + } + db.session.add(ShippingIdentityRuleSet(version=1, status='published', definition_json=definition_json, checksum='c' * 64)) + db.session.add(ShippingIdentityDefinition( + id=RULE_SET_DEF_ID, definition_code='ship_to_customer_rule', target_type='customer', + context_field_id=FIELD_ID, default_weight=100, max_automation='conditional', status='active', + )) + intake = ShippingOrderIntake(intake_no='INT-TIER', asset_id=1, user_id=user.id, parser_version='test') + db.session.add(intake) + db.session.flush() + extraction = ShippingOrderExtraction( + intake_id=intake.id, schema_version_id=version.id, input_snapshot_hash='h' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + decision = ShippingOrderFieldDecision( + extraction_id=extraction.id, field_id=FIELD_ID, decision_status='accepted', decided_at=datetime.utcnow(), + ) + db.session.add(decision) + db.session.flush() + db.session.add(ShippingOrderFieldValue( + extraction_id=extraction.id, field_id=FIELD_ID, decision_id=decision.id, value_text=runtime_value, + )) + candidate = ShippingOrderCandidate( + candidate_no='CAND-TIER', intake_id=intake.id, primary_document_id=1, + candidate_key='tier-test', candidate_status='accepted', order_extraction_id=extraction.id, + ) + db.session.add(candidate) + for index, spec in enumerate(evidences, start=1): + customer = ShippingCustomer( + standard_name=spec['customer_name'], short_code=spec['short_code'], status='active', + ) + db.session.add(customer) + db.session.flush() + db.session.add(ShippingIdentityEvidence( + definition_id=RULE_SET_DEF_ID, customer_id=customer.id, + raw_value=spec['normalized_value'], normalized_value=spec['normalized_value'], + status='approved', auto_match_allowed=spec.get('auto', True), + )) + db.session.commit() + return candidate, intake + + +class TestResolverTierMatching: + """影子识别三级命中与状态语义(resolve_candidate_identity)。""" + + def test_punctuation_variant_hits_equality_tier(self, app): + with app.app_context(): + # 关键断言:'QCH,' vs 'QCH' 标点差异经 canonical 等值命中,不再是 unmatched。 + candidate, intake = _build_identity_world( + runtime_value='QCH, INC., A NEVADA CORPORATION', + evidences=[{ + 'customer_name': 'QUANTA QMN', 'short_code': 'QMN', + 'normalized_value': 'QCH INC., A NEVADA CORPORATION', + }], + ) + result = resolve_candidate_identity(candidate, intake) + assert result['status'] == 'unique_candidate' + assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_EQUALITY + + def test_truncated_runtime_becomes_weak_suggestion(self, app): + with app.app_context(): + # 关键断言:c/o 截断形态产出唯一弱命中候选(unique_candidate 仅表示展示层唯一), + # match_kind=containment_weak,交由人工确认。 + candidate, intake = _build_identity_world( + runtime_value='QCH, INC., A NEVADA CORPORATION c/o', + evidences=[{ + 'customer_name': 'QUANTA QMN', 'short_code': 'QMN', + 'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA', + }], + ) + result = resolve_candidate_identity(candidate, intake) + assert result['status'] == 'unique_candidate' + assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_WEAK + + def test_wrapped_block_hits_strong_containment(self, app): + with app.app_context(): + # 关键断言:折行块整段提取时完整指纹出现,判强包含。 + candidate, intake = _build_identity_world( + runtime_value='QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC', + evidences=[{ + 'customer_name': 'QUANTA QMN', 'short_code': 'QMN', + 'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA', + }], + ) + result = resolve_candidate_identity(candidate, intake) + assert result['status'] == 'unique_candidate' + assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG + + def test_family_prefix_stays_ambiguous(self, app): + with app.app_context(): + # 关键断言:家族共享前缀同时包含命中 QCG/TW 两个站点客户 → ambiguous,不取首条。 + candidate, intake = _build_identity_world( + runtime_value='Quanta Computer Inc.', + evidences=[ + { + 'customer_name': 'QUANTA QCG', 'short_code': 'QCG', + 'normalized_value': 'QUANTA COMPUTER INC. DE 2470.58.340', + }, + { + 'customer_name': 'QUANTA TW', 'short_code': 'TWQ', + 'normalized_value': 'QUANTA COMPUTER INC. HQ PLANT', + }, + ], + ) + result = resolve_candidate_identity(candidate, intake) + assert result['status'] == 'ambiguous' + assert {item['match_kind'] for item in result['customer_matches']} == {IDENTITY_MATCH_CONTAINMENT_WEAK} + + def test_equality_beats_containment_in_order(self, app): + with app.app_context(): + # 关键断言:等值候选排在包含候选之前,且顶层唯一时状态为 unique_candidate。 + candidate, intake = _build_identity_world( + runtime_value='WISTRON CORPORATION C/O WIWYNN CZECH', + evidences=[ + { + 'customer_name': 'WIWYNN CZ', 'short_code': 'WYC', + 'normalized_value': 'WISTRON CORPORATION', + }, + { + 'customer_name': 'WIWYNN CZ BRNO', 'short_code': 'WCB', + 'normalized_value': 'WISTRON CORPORATION C/O WIWYNN CZECH', + }, + ], + ) + result = resolve_candidate_identity(candidate, intake) + assert result['status'] == 'unique_candidate' + names = {item['standard_name']: item for item in result['customer_matches']} + # 关键断言:等值候选排第一,强包含候选次之;强层级唯一 → unique_candidate。 + assert result['customer_matches'][0]['standard_name'] == 'WIWYNN CZ BRNO' + assert names['WIWYNN CZ BRNO']['match_kind'] == IDENTITY_MATCH_EQUALITY + assert names['WIWYNN CZ']['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG + + def test_multiline_runtime_matches_single_line_evidence(self, app): + with app.app_context(): + # 关键断言:运行侧换行折叠修复后,跨行提取值可与单行注册证据等值命中。 + candidate, intake = _build_identity_world( + runtime_value='Quanta Manufacturing Nashville, LLC,\n1 Waldenbooks Dr.', + evidences=[{ + 'customer_name': 'QUANTA QMN', 'short_code': 'QMN', + 'normalized_value': 'QUANTA MANUFACTURING NASHVILLE, LLC, 1 WALDENBOOKS DR.', + }], + ) + result = resolve_candidate_identity(candidate, intake) + assert result['status'] == 'unique_candidate' + assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_EQUALITY + + +class TestAutoConfirmDecision: + """自动确认分级裁决(resolve_auto_customer_decision)。""" + + def _shadow(self, candidate): + return refresh_candidate_shadow_resolution(candidate) + + def test_equality_unique_confirms_strong(self, app): + with app.app_context(): + candidate, _intake = _build_identity_world( + runtime_value='QCH, INC., A NEVADA CORPORATION', + evidences=[{ + 'customer_name': 'QUANTA QMN', 'short_code': 'QMN', + 'normalized_value': 'QCH INC., A NEVADA CORPORATION', + }], + ) + decision = resolve_auto_customer_decision(self._shadow(candidate)) + assert decision['status'] == 'unique_strong_match' + assert decision['customer_id'] is not None + + def test_containment_strong_unique_confirms_with_match_kind(self, app): + with app.app_context(): + # 关键断言:指纹完整出现的唯一包含命中且证据授权 → unique_containment_match, + # 审计证据带 match_kind=containment_strong 溯源。 + candidate, _intake = _build_identity_world( + runtime_value='QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC', + evidences=[{ + 'customer_name': 'QUANTA QMN', 'short_code': 'QMN', + 'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA', + }], + ) + decision = resolve_auto_customer_decision(self._shadow(candidate)) + assert decision['status'] == 'unique_containment_match' + assert decision['customer_id'] is not None + assert decision['evidence'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG + + def test_truncation_only_never_confirms(self, app): + with app.app_context(): + # 关键断言:截断形态(本单 7911678818.PDF)永不自动确认,保持 unmatched 交人工。 + candidate, _intake = _build_identity_world( + runtime_value='QCH, INC., A NEVADA CORPORATION c/o', + evidences=[{ + 'customer_name': 'QUANTA QMN', 'short_code': 'QMN', + 'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA', + }], + ) + decision = resolve_auto_customer_decision(self._shadow(candidate)) + assert decision['status'] == 'unmatched' + assert decision['customer_id'] is None + + def test_unauthorized_evidence_never_confirms(self, app): + with app.app_context(): + # 关键断言:auto_match_allowed=False 的证据即使等值唯一也不自动确认。 + candidate, _intake = _build_identity_world( + runtime_value='QCH, INC., A NEVADA CORPORATION', + evidences=[{ + 'customer_name': 'QUANTA QMN', 'short_code': 'QMN', + 'normalized_value': 'QCH INC., A NEVADA CORPORATION', 'auto': False, + }], + ) + decision = resolve_auto_customer_decision(self._shadow(candidate)) + assert decision['status'] == 'unmatched' + assert decision['customer_id'] is None + + def test_equality_precedes_containment(self, app): + with app.app_context(): + # 关键断言:等值命中存在时包含命中不参与裁决,等值客户唯一即确认。 + candidate, _intake = _build_identity_world( + runtime_value='WISTRON CORPORATION C/O WIWYNN CZECH', + evidences=[ + { + 'customer_name': 'WIWYNN CZ', 'short_code': 'WYC', + 'normalized_value': 'WISTRON CORPORATION', + }, + { + 'customer_name': 'WIWYNN CZ BRNO', 'short_code': 'WCB', + 'normalized_value': 'WISTRON CORPORATION C/O WIWYNN CZECH', + }, + ], + ) + decision = resolve_auto_customer_decision(self._shadow(candidate)) + assert decision['status'] == 'unique_strong_match' + customers = {c.id: c.standard_name for c in ShippingCustomer.query.all()} + assert customers[decision['customer_id']] == 'WIWYNN CZ BRNO' diff --git a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py index 1ca8a885..6c92183f 100644 --- a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py +++ b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py @@ -235,6 +235,180 @@ def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch): assert bundle['user_status'] == 'waiting_human' +# ============================================================ +# [BR] blocking_reason 资格快照回退: +# automation 无具体原因码时,回退到草稿校验快照(validation_result_json) +# 中首要 blocking issue 的冻结 explainability 透传(code/message/next_action), +# 让批次中心与工作台展示具体原因,而非「当前步骤需要人工处理」兜底。 +# ============================================================ + +def _validation_snapshot_with_issues(issues: list[dict]) -> dict: + """构造与 order_build_eligibility 持久化结构一致的 validation 快照。""" + return {'can_build': False, 'can_auto_create': False, 'issues': issues} + + +@pytest.mark.pure_unit +def test_bundle_falls_back_to_primary_validation_issue_when_automation_lacks_reason(): + """[BR-1] automation 无具体原因码时,blocking_reason 必须回退到首要 blocking issue。""" + from app.services.shipping_notice.reconciliation_projector import ( + project_review_case_projection_bundle, + ) + + case = _fake_case(status='draft', candidate_id=None) + bundle = project_review_case_projection_bundle( + case, + validation=_validation_snapshot_with_issues([ + { + 'code': 'customer_unresolved', + 'severity': 'blocking', + 'owning_gate_code': 'customer_resolution', + 'message': '客户尚未确认', + 'explainability': { + 'reason_code': 'customer_unresolved', + 'message': '客户尚未确认', + 'next_action': 'confirm_customer', + }, + }, + ]), + post_confirm=None, + is_admin=False, + ) + + reason = bundle['blocking_reason'] + # 断言意图:透传冻结契约的事实三元组,前端据此展示「客户尚未确认 / 确认客户」 + assert reason['code'] == 'customer_unresolved' + assert reason['message'] == '客户尚未确认' + assert reason['next_action'] == 'confirm_customer' + + +@pytest.mark.pure_unit +def test_validation_fallback_skips_degraded_and_non_blocking_issues(): + """[BR-2] 降级码(unknown_business_failure)与非 blocking issue 不进入回退。""" + from app.services.shipping_notice.reconciliation_projector import ( + project_review_case_projection_bundle, + ) + + case = _fake_case(status='draft', candidate_id=None) + bundle = project_review_case_projection_bundle( + case, + validation=_validation_snapshot_with_issues([ + # 仅阻断自动建单,不属用户阻断 + { + 'code': 'candidate_qualification_blocked', + 'severity': 'auto_create_blocking', + 'explainability': { + 'reason_code': 'llm_path_cannot_auto_freeze', + 'message': '智能识别结果尚未通过自动建单资格检查', + 'next_action': 'open_order_review', + }, + }, + # 契约降级码:不透传给用户 + { + 'code': 'weird_new_issue', + 'severity': 'blocking', + 'explainability': { + 'reason_code': 'unknown_business_failure', + 'message': '业务处理失败,请凭请求编号联系管理员', + 'next_action': '', + }, + }, + # 首个可用 blocking issue + { + 'code': 'required_field_missing', + 'severity': 'blocking', + 'field_code': 'reservation_id', + 'explainability': { + 'reason_code': 'required_field_missing', + 'message': '缺少创建订单所需字段', + 'next_action': 'open_order_review', + }, + }, + ]), + post_confirm=None, + is_admin=False, + ) + + reason = bundle['blocking_reason'] + assert reason['code'] == 'required_field_missing' + assert reason['next_action'] == 'open_order_review' + assert reason['details'].get('field_code') == 'reservation_id' + + +@pytest.mark.pure_unit +def test_bundle_keeps_mapped_automation_reason_over_validation_fallback(monkeypatch): + """[BR-3] automation 已有映射的具体原因码时不回退,避免覆盖更精确的裁决。""" + from app.services.shipping_notice import reconciliation_projector + + case = _fake_case(status='draft', candidate_id=None) + monkeypatch.setattr( + reconciliation_projector, + 'project_case_automation_status', + lambda case, *, validation, post_confirm: { + 'status': 'manual_fallback', + 'retryable': False, + 'reason_code': 'duplicate_decision_required', + }, + ) + bundle = reconciliation_projector.project_review_case_projection_bundle( + case, + validation=_validation_snapshot_with_issues([ + { + 'code': 'customer_unresolved', + 'severity': 'blocking', + 'explainability': { + 'reason_code': 'customer_unresolved', + 'message': '客户尚未确认', + 'next_action': 'confirm_customer', + }, + }, + ]), + post_confirm=None, + is_admin=False, + ) + + reason = bundle['blocking_reason'] + assert reason['code'] == 'duplicate_decision_required' + assert reason.get('message') is None + + +@pytest.mark.pure_unit +def test_bundle_without_usable_issues_keeps_legacy_blocking_reason(): + """[BR-4] 快照无可用 issue 时保持既有兜底行为(不得抛错、不得造原因)。""" + from app.services.shipping_notice.reconciliation_projector import ( + project_review_case_projection_bundle, + ) + + case = _fake_case(status='draft', candidate_id=None) + bundle = project_review_case_projection_bundle( + case, + validation={'can_build': True, 'can_auto_create': True, 'issues': []}, + post_confirm=None, + is_admin=False, + ) + + reason = bundle['blocking_reason'] + assert isinstance(reason, dict) + assert reason.get('message') is None + assert reason.get('next_action') is None + + +@pytest.mark.pure_unit +def test_unmapped_automation_reason_uses_existing_generic_i18n_key(): + """[BR-5] 未映射原因码的 fail-closed 兜底必须指向前端真实存在的键。""" + from app.services.shipping_notice.reconciliation_projector import ( + project_case_blocking_reason, + ) + + reason = project_case_blocking_reason({ + 'status': 'manual_fallback', + 'reason_code': 'totally_new_unmapped_code', + }) + + assert reason['code'] == 'totally_new_unmapped_code' + # 此前指向不存在的 shipping.review.blocked_generic,任何未映射码都会双重落空 + assert reason['i18n_key'] == 'chat.shippingProcessing.reasonCode.unknown' + + @pytest.mark.pure_unit def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_task(): """字段冲突 Gate 已通过后,下游 pending 只能表示系统推进,不能回退旧 STP 冲突。""" diff --git a/backend/tests/test_gate_derivation.py b/backend/tests/test_gate_derivation.py index 3184d0ef..7621d0e9 100644 --- a/backend/tests/test_gate_derivation.py +++ b/backend/tests/test_gate_derivation.py @@ -91,7 +91,7 @@ def test_fetch_gate_positions_batched(app): user_id=user.id, conversation_id=session.session_id, status='waiting_review', - stage='step5_match_inventory', + stage='inventory_matching', progress_version=1, ) ot_b = ShippingOrderTask( @@ -345,7 +345,7 @@ def test_sql_todo_category_prefers_gate_inventory_sufficiency(app): user_id=user.id, conversation_id=session.session_id, status='waiting_review', - stage='step5_match_inventory', + stage='inventory_matching', progress_version=1, ) db.session.add(ot) diff --git a/backend/tests/test_order_extraction_pdf_po_split.py b/backend/tests/test_order_extraction_pdf_po_split.py index cbf8c50a..0f8e1f5a 100644 --- a/backend/tests/test_order_extraction_pdf_po_split.py +++ b/backend/tests/test_order_extraction_pdf_po_split.py @@ -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( diff --git a/backend/tests/test_order_profile_header_identity.py b/backend/tests/test_order_profile_header_identity.py new file mode 100644 index 00000000..b9ffaa49 --- /dev/null +++ b/backend/tests/test_order_profile_header_identity.py @@ -0,0 +1,298 @@ +""" +tests/test_order_profile_header_identity.py + +用途:锁定 schema_canonical_header_atoms / schema_canonical_header_tokens 的表头 + 别名语义归一行为,及其在表头原子硬互斥(_header_discriminator_atoms_conflict) + 与 signature_conflict 二次机会门禁中的防回归契约;含真实故障单 PO_6075316 + (日期换词 + 相邻列并格 + 空串 token)的形状回归。 +依赖:order_profile_matcher.schema_canonical_header_atoms / + schema_canonical_header_tokens / _header_token_atoms / + _header_discriminator_atoms_conflict。 +逻辑:pure_unit;别名命中产出 field:: 标记原子(atoms 为集合语义、 + tokens 为序列语义且同源——去重即 atoms),未命中词沿用既有词级原子过滤; + None/空 dict 零行为变化;歧义短语整体弃用;PO_6075316 形状仅在含 Ship Date + 别名的契约下跨措辞对齐,异义词不归并。 +""" + +from __future__ import annotations + +import pytest + +from app.services.shipping_notice.document_layout.order_profile_matcher import ( + _header_discriminator_atoms_conflict, + _header_token_atoms, + schema_canonical_header_atoms, + schema_canonical_header_tokens, +) + +pytestmark = pytest.mark.pure_unit + + +def test_none_or_empty_mapping_degrades_to_word_atoms(): + """未配置别名表时必须与既有词级原子化完全一致(零行为变化)。""" + tokens = ['Requested Ship Date (ETD)', 'Qty', 'Unit Price'] + # 关键断言:None 与空 dict 均退化为 _header_token_atoms,结果与直接调用逐项相等 + assert schema_canonical_header_atoms(tokens, None) == _header_token_atoms(tokens) + assert schema_canonical_header_atoms(tokens, {}) == _header_token_atoms(tokens) + # 关键断言:退化路径下不得混入任何 field:: 标记原子 + assert not any( + atom.startswith('field::') + for atom in schema_canonical_header_atoms(tokens, None) + ) + + +def test_exact_phrase_hit_emits_field_marker(): + """别名精确命中时短语整体替换为 field::,不残留短语内单词。""" + atoms = schema_canonical_header_atoms( + ['Requested Ship Date'], + {'requested ship date': 'requested_receipt_date'}, + ) + # 关键断言:命中段落被消费,仅剩语义标记原子,词级原子 requested/ship/date 不再出现 + assert atoms == frozenset({'field::requested_receipt_date'}) + + +def test_merged_cell_greedy_decomposition(): + """合并格长文案按贪心最长短语分解为多个 field 标记原子。""" + atoms = schema_canonical_header_atoms( + ['Requested Ship Date Unit Price'], + { + 'requested ship date': 'requested_receipt_date', + 'unit price': 'unit_price', + }, + ) + # 关键断言:两个别名短语各自命中并消费整段,互不残留单词原子 + assert atoms == frozenset({'field::requested_receipt_date', 'field::unit_price'}) + + +def test_greedy_prefers_longest_phrase(): + """同一位置长短短语重叠时必须取最长短语(贪心最长匹配)。""" + atoms = schema_canonical_header_atoms( + ['Requested Ship Date'], + { + 'ship date': 'ship_date', + 'requested ship date': 'requested_receipt_date', + }, + ) + # 关键断言:最长短语胜出且整段消费,短短语不产生任何残留 field/词级原子 + assert atoms == frozenset({'field::requested_receipt_date'}) + + +def test_case_insensitive_matching(): + """表头与别名 key 大小写不同仍命中(casefold 同源词管线)。""" + atoms = schema_canonical_header_atoms( + ['UNIT PRICE'], + {'Unit Price': 'unit_price'}, + ) + # 关键断言:大小写差异不阻断短语命中,field_code 保留别名表原样 + assert atoms == frozenset({'field::unit_price'}) + + +def test_unmatched_words_kept_and_short_words_filtered(): + """未命中别名的词沿用既有过滤:长度 >=3 且非虚词才保留为词级原子。""" + atoms = schema_canonical_header_atoms( + ['Total Amount ok the ab'], + {'unit price': 'unit_price'}, + ) + # 关键断言:total/amount 保留;'ok'/'ab' 过短被滤;'the' 为虚词被滤 + assert atoms == frozenset({'total', 'amount'}) + + mixed = schema_canonical_header_atoms( + ['Unit Price Remarks ok'], + {'unit price': 'unit_price'}, + ) + # 关键断言:同一 token 内 field 标记原子与词级原子可共存 + assert mixed == frozenset({'field::unit_price', 'remarks'}) + + +def test_empty_tokens_skipped(): + """空串/纯空白 token(MinerU 空格占位)直接跳过且不影响其余 token。""" + atoms = schema_canonical_header_atoms( + ['', ' ', 'Unit Price'], + {'unit price': 'unit_price'}, + ) + # 关键断言:空白 token 不产生原子也不中断匹配,后续 token 照常命中 + assert atoms == frozenset({'field::unit_price'}) + + +def test_chinese_alias_yields_no_field_atom(): + """中文别名切词为空 → 自然跳过(有意行为:词级原子只保留 [a-z0-9])。""" + atoms = schema_canonical_header_atoms( + ['数量', 'Qty'], + {'数量': 'quantity'}, + ) + # 关键断言:中文别名不产生 field:: 原子;词级原子口径不变(qty 长度 >=3 保留) + assert atoms == frozenset({'qty'}) + + +def test_casefold_collision_phrase_discarded(): + """同一短语 casefold 后映射到多个 field_code → 整体弃用,回退词级原子。""" + atoms = schema_canonical_header_atoms( + ['Ship Date'], + { + 'Ship Date': 'ship_date', + 'ship date': 'requested_ship_date', + }, + ) + # 关键断言:歧义短语不得产出任何 field:: 原子;未命中单词走既有过滤保留 + assert atoms == frozenset({'ship', 'date'}) + + +def test_casefold_equal_duplicate_alias_kept(): + """同短语重复别名但 field_code 仅大小写不同 → 不视为歧义,短语保留。""" + atoms = schema_canonical_header_atoms( + ['Ship Date'], + {'Ship Date': 'ship_date', 'SHIP DATE': 'SHIP_DATE'}, + ) + # 关键断言:casefold 视角同码不构成身份歧义,短语照常产出标记原子 + assert atoms == frozenset({'field::ship_date'}) + + +# --- PO_6075316 真实故障形状回归:别名契约 vs 表头原子硬互斥 --- + +_SIGNATURE_TRAINING_TOKENS = [ + 'LN', 'Quantity', 'Part Number Vendor Item#', 'Description', + 'Requested Arrival Date', 'Unit Price', 'Extension', +] +_PO6075316_OBSERVED_TOKENS = [ + 'LN', 'Quantity', 'Part Number Vendor Item#', 'Description', + 'Requested Ship Date Unit Price', '', 'Extension', +] +_SCHEMA_V4_HEADER_TO_FIELD = { + 'Requested Receipt Date': 'requested_receipt_date', + 'Requested Arrival Date': 'requested_receipt_date', + 'Requested Ship Date': 'requested_receipt_date', + 'Unit Price': 'unit_price', + 'Extension': 'line_amount_with_tax', + 'Part Number': 'customer_part_number', + 'Vendor Item': 'part_number', + 'Quantity': 'qty', + 'LN': 'customer_po_line_no', +} + + +def _po6075316_signature() -> dict: + """训练签名(命中模板 HYVE)的明细表 header_tokens 形状。""" + return {'table_patterns': [{'header_tokens': list(_SIGNATURE_TRAINING_TOKENS)}]} + + +def test_po6075316_fault_shape_passes_with_ship_date_alias_contract(): + """PO_6075316 形状(日期换词+并格+空串)在含 Ship Date 别名契约下不再互斥。""" + observed = {'header_tokens': list(_PO6075316_OBSERVED_TOKENS)} + # 关键断言:两侧经 Schema 别名归一后字段语义原子全等,硬互斥判定为不冲突 + assert _header_discriminator_atoms_conflict( + signature=_po6075316_signature(), + observed=observed, + header_to_field=_SCHEMA_V4_HEADER_TO_FIELD, + ) is False + # 佐证:'Requested Ship Date' 与 'Requested Arrival Date' 归一为同一标记原子; + # 并格长文案贪心分解出日期+单价两个标记原子;空串 token(MinerU 占位)零原子。 + assert schema_canonical_header_atoms( + observed['header_tokens'], _SCHEMA_V4_HEADER_TO_FIELD, + ) == schema_canonical_header_atoms( + _SIGNATURE_TRAINING_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD, + ) + + +def test_po6075316_fault_shape_still_conflicts_without_alias_contract(): + """同形状不传契约(或契约缺 Ship Date 别名)时互斥仍在——豁免效果来自别名。""" + observed = {'header_tokens': list(_PO6075316_OBSERVED_TOKENS)} + # 关键断言:不传 header_to_field 时两侧退化词级原子,arrival≠ship,既有互斥零变化 + assert _header_discriminator_atoms_conflict( + signature=_po6075316_signature(), observed=observed, + ) is True + contract_without_ship_alias = { + key: value + for key, value in _SCHEMA_V4_HEADER_TO_FIELD.items() + if key != 'Requested Ship Date' + } + # 关键断言:契约缺 Ship Date 别名时观测侧 ship 退回词级原子,互斥依旧成立 + assert _header_discriminator_atoms_conflict( + signature=_po6075316_signature(), + observed=observed, + header_to_field=contract_without_ship_alias, + ) is True + + +def test_po6075316_foreign_date_word_not_merged_by_alias(): + """日期列换成未配别名的真正异义词(Customer PO Date)时不得归并,互斥仍触发。""" + observed = {'header_tokens': [ + 'LN', 'Quantity', 'Part Number Vendor Item#', 'Description', + 'Customer PO Date Unit Price', '', 'Extension', + ]} + # 关键断言:别名契约只归并已治理措辞,不同语义字段(客户 PO 日期)保持互斥 + assert _header_discriminator_atoms_conflict( + signature=_po6075316_signature(), + observed=observed, + header_to_field=_SCHEMA_V4_HEADER_TO_FIELD, + ) is True + + +# --- schema_canonical_header_tokens:序列语义 canonical 归一(二次机会门禁供料) --- + +def test_tokens_none_or_empty_mapping_returns_input_list_unchanged(): + """None/空 dict 时原样返回输入列表(零归一,与 atoms 的退化口径一致)。""" + tokens = ['Requested Ship Date (ETD)', 'Qty', ''] + # 关键断言:None 与空 dict 均不做任何归一,列表内容原样返回 + assert schema_canonical_header_tokens(tokens, None) == tokens + assert schema_canonical_header_tokens(tokens, {}) == tokens + # 关键断言:退化路径下不得混入任何 field:: 标记项 + assert not any(item.startswith('field::') for item in schema_canonical_header_tokens(tokens, None)) + + +def test_tokens_hit_phrase_collapses_to_single_item_and_keeps_order(): + """命中片段坍缩为单个 field 标记列表项,且保持在原 token 的序列位置。""" + canonical = schema_canonical_header_tokens( + ['Requested Ship Date', 'Remarks', 'Unit Price'], + { + 'requested ship date': 'requested_receipt_date', + 'unit price': 'unit_price', + }, + ) + # 关键断言:命中短语各坍缩为单列表项并按原顺序交错排列,短语内单词不残留 + assert canonical == [ + 'field::requested_receipt_date', 'remarks', 'field::unit_price', + ] + + +def test_tokens_sequence_semantics_keeps_duplicates_and_unmatched_words(): + """序列语义:允许重复、未命中词原样保留——与 atoms 的集合语义形成对照。""" + canonical = schema_canonical_header_tokens( + ['Unit Price', 'Total Amount ok the ab', 'Unit Price'], + {'unit price': 'unit_price'}, + ) + # 关键断言:重复 token 各自产出标记项(不去重);total/amount 原词保序保留; + # 'ok'/'ab' 过短、'the' 为虚词被滤(与 atoms 同一过滤口径) + assert canonical == [ + 'field::unit_price', 'total', 'amount', 'field::unit_price', + ] + + +def test_tokens_dedup_equals_atoms_same_source_semantics(): + """同源语义:同一输入下 tokens 版去重即 atoms 版结果(同管线同短语匹配)。""" + tokens = ['', ' ', 'Requested Ship Date Unit Price', 'Vendor Item#', 'ok the ab'] + mapping = { + 'requested ship date': 'requested_receipt_date', + 'unit price': 'unit_price', + 'vendor item': 'part_number', + } + canonical = schema_canonical_header_tokens(tokens, mapping) + atoms = schema_canonical_header_atoms(tokens, mapping) + # 关键断言:序列版去重后与集合版逐项相等——两条路径完全同源,不得漂移 + assert set(canonical) == set(atoms) + # 关键断言:空白 token 不产出列表项(与 atoms 跳过口径一致) + assert len(canonical) == len([item for item in canonical if item]) + + +def test_po6075316_tokens_canonical_sequences_identical_with_ship_date_alias(): + """PO_6075316 形状在含 Ship Date 别名下两侧 canonical 序列逐项相等(保序)。""" + canonical_expected = schema_canonical_header_tokens( + _SIGNATURE_TRAINING_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD, + ) + canonical_observed = schema_canonical_header_tokens( + _PO6075316_OBSERVED_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD, + ) + # 关键断言:并格长文案贪心分解出的标记原子序列与训练侧完全一致(含顺序), + # 供二次机会门禁按序列比较得出满配额软分 + assert canonical_expected == canonical_observed + # 关键断言:LN 别名命中产出标记项(词级过滤会丢掉 2 字母 ln,别名先行兜住) + assert canonical_expected[0] == 'field::customer_po_line_no' diff --git a/backend/tests/test_shipping_conversation_title.py b/backend/tests/test_shipping_conversation_title.py new file mode 100644 index 00000000..78c4f057 --- /dev/null +++ b/backend/tests/test_shipping_conversation_title.py @@ -0,0 +1,37 @@ +""" +backend/tests/test_shipping_conversation_title.py + +用途:验证订单抽取会话标题纯函数的派生规则(前缀剥离/截断/计数后缀/日期/回退)。 +依赖:纯函数,无 Flask/DB 夹具。 +逻辑:命名是内容派生的确定性函数,用逐条断言锁定规则,防止后续误改口径。 +""" + +from __future__ import annotations + +from datetime import datetime + +from app.services.shipping_notice.conversation_title import derive_order_extraction_title + + +def test_strips_leading_mail_prefixes_and_appends_date(): + """首个文件名循环剥离 Re/Fw/Fwd/回复/转发 前缀,末尾追加 MM-DD。""" + title = derive_order_extraction_title(['回复:转发:FWD: PO#6075309.eml'], datetime(2026, 9, 15)) + assert title == 'PO#6075309 09-15' + + +def test_multi_files_appends_count_suffix(): + """文件总数大于 1 时追加「等 N 个文件」,N 按传入文件名总数计。""" + title = derive_order_extraction_title(['PO#6075309.eml', 'invoice.pdf', 'list.pdf'], datetime(2026, 9, 15)) + assert title == 'PO#6075309 等 3 个文件 09-15' + + +def test_truncates_long_name_to_24_chars(): + """主名超过 24 字符截断,且不吞掉日期后缀。""" + title = derive_order_extraction_title(['A' * 30 + '.pdf'], datetime(2026, 12, 31)) + assert title == 'A' * 24 + ' 12-31' + + +def test_blank_filenames_fall_back_to_default(): + """文件名全空(含空列表与纯空白项)回退写死标题「订单抽取」。""" + assert derive_order_extraction_title([], datetime(2026, 9, 15)) == '订单抽取' + assert derive_order_extraction_title(['', ' '], datetime(2026, 9, 15)) == '订单抽取' diff --git a/backend/tests/test_shipping_done_line_report.py b/backend/tests/test_shipping_done_line_report.py new file mode 100644 index 00000000..439ef298 --- /dev/null +++ b/backend/tests/test_shipping_done_line_report.py @@ -0,0 +1,227 @@ +""" +backend/tests/test_shipping_done_line_report.py + +用途:已完成通知明细行报表(done-lines)查询与专用导出的单测。 +依赖:pytest、openpyxl、ShippingNotice/OT/Snapshot/Artifact 夹具、done_line_report。 +逻辑:覆盖 12 字段映射(typed 列 + field_values_json 回源与回退)、可见性(非本人不可见、 + 未上传成功不进报表)、客户/料号/发货通知日期筛选、分页、导出表头与留空行为。 +""" + +from datetime import date, datetime, timedelta + +import pytest +from openpyxl import load_workbook + +from app.models import ( + ShippingNotice, + ShippingOrderExtraction, + ShippingOrderField, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + ShippingOrderSnapshot, + ShippingOrderSnapshotLine, + ShippingOrderTask, + ShippingExportArtifact, + ShippingExcelTemplate, + ShippingInventoryParsingProfile, +) +from app.services.shipping_notice.done_line_report import ( + DONE_REPORT_HEADERS, + build_done_lines_xlsx, + list_done_notice_lines, +) + + +def _seed_report_fixture(db, *, owner: int): + """最小报表夹具:一张已完成双行通知 + 一张仅 ready 未上传的通知(应被排除)。""" + order = ShippingOrderTask(task_no="OT-DONE-LINE", source_type="direct_pdf", user_id=owner) + pending_order = ShippingOrderTask(task_no="OT-DONE-LINE-PENDING", source_type="direct_pdf", user_id=owner) + notice = ShippingNotice(task_no="SN-DONE-LINE", source_type="manual", user_id=owner) + pending_notice = ShippingNotice(task_no="SN-DONE-LINE-PENDING", source_type="manual", user_id=owner) + db.session.add_all([order, pending_order, notice, pending_notice]) + template = ShippingExcelTemplate( + template_code='DONELINE', display_name='DoneLine', version=1, status='published', + storage_bucket='test', storage_key='done.xlsx', original_filename='done.xlsx', + file_checksum='a' * 64, definition_json={}, + ) + profile = ShippingInventoryParsingProfile( + profile_code='DONELINE', display_name='DoneLine', version=1, status='published', + file_format='xlsx', definition_json={}, + ) + schema = ShippingOrderSchema(schema_code='DONELINE', display_name='DoneLine') + db.session.add_all([template, profile, schema]) + db.session.flush() + version = ShippingOrderSchemaVersion( + schema_id=schema.id, version=1, status='published', definition_json={'fields': []}, + ) + db.session.add(version) + db.session.flush() + extraction = ShippingOrderExtraction( + schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + + # 标准字段资产:约定出货日期(行级)与来源单号(表头级),值为 field_id 键 JSON。 + db.session.add(ShippingOrderField( + id='f-req-date', field_code='required_date', scope='line', value_type='date', + field_category='order_line', collection_mode='deterministic_context', + asset_kind='system_standard', storage_mode='typed_column', storage_column='required_date', + )) + db.session.add(ShippingOrderField( + id='f-source-order', field_code='source_order_number', scope='header', value_type='string', + field_category='order_header', collection_mode='deterministic_context', + asset_kind='system_standard', storage_mode='json_only', + )) + db.session.flush() + + snapshot = ShippingOrderSnapshot( + task_id=order.id, extraction_id=extraction.id, schema_version_id=version.id, + order_data_version=1, + customer_name='HYVE CS', customer_code='HC001', customer_po_number='306085', + order_date=date(2026, 6, 1), required_date=date(2026, 6, 15), + header_values_json={'f-source-order': '8301-2606010052'}, + ) + db.session.add(snapshot) + db.session.flush() + db.session.add_all([ + ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, position=1, line_no=1, + part_number='B3-A08AR10000017-A6', qty=80, unit_price=1525.08, + field_values_json={'f-req-date': '2026-06-15'}, + ), + ShippingOrderSnapshotLine( + snapshot_id=snapshot.id, position=2, line_no=2, + part_number='D4-A08AR12000001', qty=1000, unit_price=898.72, + field_values_json={}, + ), + ]) + order.order_snapshot_id = snapshot.id + notice.order_task_id = order.id + + extraction_two = ShippingOrderExtraction( + schema_version_id=version.id, input_snapshot_hash='e' * 64, status='accepted', + ) + db.session.add(extraction_two) + db.session.flush() + pending_snapshot = ShippingOrderSnapshot( + task_id=pending_order.id, extraction_id=extraction_two.id, schema_version_id=version.id, + order_data_version=1, + customer_name='PENDING CS', customer_code='PC001', + ) + db.session.add(pending_snapshot) + db.session.flush() + db.session.add(ShippingOrderSnapshotLine( + snapshot_id=pending_snapshot.id, position=1, line_no=1, part_number='X-1', qty=1, + )) + pending_order.order_snapshot_id = pending_snapshot.id + pending_notice.order_task_id = pending_order.id + + def add_artifact(target, *, artifact_no: str, status: str) -> None: + """为 Notice 建立报表口径所需的最小 Artifact。""" + db.session.add(ShippingExportArtifact( + artifact_no=artifact_no, task_id=target.id, template_id=template.id, + order_schema_version_id=version.id, order_extraction_id=extraction.id, + inventory_parsing_profile_id=profile.id, input_checksum='c' * 64, + file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx', + file_checksum='d' * 64, file_size=1, status=status, + )) + + add_artifact(notice, artifact_no='ART-DONE-LINE', status='uploaded') + add_artifact(pending_notice, artifact_no='ART-DONE-LINE-PENDING', status='ready') + db.session.commit() + return notice + + +def test_list_done_notice_lines_maps_standard_fields(app): + """明细行平铺不按 OT 聚合;12 字段含 JSON 回源与表头回退,无数据源字段留空。""" + with app.app_context(): + from app import db + + owner = 88 + _seed_report_fixture(db, owner=owner) + + result = list_done_notice_lines(owner, page=1, page_size=20) + # 断言:仅 uploaded 通知进入报表;两行明细平铺,OT 不聚合。 + assert result["total"] == 2 + assert {item["line_no"] for item in result["items"]} == {1, 2} + first = next(item for item in result["items"] if item["line_no"] == 1) + # 断言:溯源编号 + 标准 12 字段映射。 + assert first["task_no"] == "SN-DONE-LINE" + assert first["customer_name"] == "HYVE CS" + assert first["customer_code"] == "HC001" + assert first["order_date"] == "2026-06-01" + assert first["part_number"] == "B3-A08AR10000017-A6" + assert first["qty"] == 80.0 + # 行级 field_values_json 有值时优先于快照表头 typed 列。 + assert first["required_date"] == "2026-06-15" + assert first["customer_po_number"] == "306085" + assert first["source_order_number"] == "8301-2606010052" + assert first["unit_price"] == 1525.08 + # 已用数量 / open qty 当前无数据源,契约留空。 + assert first["used_qty"] is None + assert first["open_qty"] is None + second = next(item for item in result["items"] if item["line_no"] == 2) + # 断言:行级无 required_date 时回退快照表头 typed 列。 + assert second["required_date"] == "2026-06-15" + assert second["source_order_number"] == "8301-2606010052" + + # 断言:其他用户不可见(非管理员仅创建者)。 + assert list_done_notice_lines(999)["total"] == 0 + + +def test_list_done_notice_lines_filters_and_pagination(app): + """客户/料号/发货通知日期筛选与按明细行分页生效。""" + with app.app_context(): + from app import db + + owner = 89 + _seed_report_fixture(db, owner=owner) + + # 客户模糊(大小写不敏感)。 + assert list_done_notice_lines(owner, customer="hyve")["total"] == 2 + assert list_done_notice_lines(owner, customer="不存在")["total"] == 0 + # 料号模糊(命中单行)。 + part_page = list_done_notice_lines(owner, part_number="B3-") + assert part_page["total"] == 1 + assert part_page["items"][0]["part_number"] == "B3-A08AR10000017-A6" + # 发货通知日期范围:今天闭区间命中;未来区间为空。 + today = datetime.utcnow().date() + assert list_done_notice_lines( + owner, notice_date_from=today.isoformat(), notice_date_to=today.isoformat(), + )["total"] == 2 + tomorrow = (today + timedelta(days=1)).isoformat() + assert list_done_notice_lines(owner, notice_date_from=tomorrow)["total"] == 0 + # 按明细行分页。 + page_one = list_done_notice_lines(owner, page=1, page_size=1) + page_two = list_done_notice_lines(owner, page=2, page_size=1) + assert page_one["total"] == 2 + assert {page_one["items"][0]["line_no"], page_two["items"][0]["line_no"]} == {1, 2} + + +def test_build_done_lines_xlsx_writes_fixed_twelve_columns(app): + """导出严格 12 列标准格式:OT 编号不落列,无数据源列留空。""" + with app.app_context(): + from app import db + + owner = 90 + _seed_report_fixture(db, owner=owner) + + stream, filename = build_done_lines_xlsx(owner) + assert filename.startswith("done-lines-") and filename.endswith(".xlsx") + workbook = load_workbook(stream) + sheet = workbook.active + rows = list(sheet.iter_rows(values_only=True)) + # 断言:表头为固定 12 列中文标准格式。 + assert tuple(rows[0]) == DONE_REPORT_HEADERS + # 断言:两行明细,且不含 OT 编号列;数量/单价写数值,无数据源列留空。 + assert len(rows) == 3 + first_data = rows[1] + assert first_data[0] == "HYVE CS" + assert first_data[3] == 1 + assert first_data[4] == "B3-A08AR10000017-A6" + assert first_data[5] == 80.0 + assert first_data[8] is None + assert first_data[9] is None + assert first_data[10] == "8301-2606010052" + assert first_data[11] == 1525.08 diff --git a/backend/tests/test_shipping_excel_template.py b/backend/tests/test_shipping_excel_template.py index 75f25409..ca93620d 100644 --- a/backend/tests/test_shipping_excel_template.py +++ b/backend/tests/test_shipping_excel_template.py @@ -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'] diff --git a/backend/tests/test_shipping_my_todo_stage_counts.py b/backend/tests/test_shipping_my_todo_stage_counts.py new file mode 100644 index 00000000..7eddbc73 --- /dev/null +++ b/backend/tests/test_shipping_my_todo_stage_counts.py @@ -0,0 +1,125 @@ +""" +backend/tests/test_shipping_my_todo_stage_counts.py + +用途:「我的待办」count 聚合扩展单测(阶段 tab 计数 + 已完成子终态拆分)。 +依赖:pytest、ShippingNotice / ShippingOrderTask / Artifact 夹具、query_service.count_my_todos。 +逻辑:覆盖 processing_stage 权威 / 人工原因归属 Gate / todo_category 兜底三路阶段归类; + done 桶拆分为已核验上传成功与 复核驳回/作废 两类终态计数。 +""" + +import pytest + +from app.models import ( + ShippingNotice, + ShippingOrderTask, + ShippingExportArtifact, + ShippingExcelTemplate, + ShippingInventoryParsingProfile, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + ShippingOrderExtraction, +) +from app.services.shipping_notice.constants import RS_REJECTED +from app.services.shipping_notice.query_service import count_my_todos, list_my_todos + + +def test_count_my_todos_reports_stage_counts_and_done_breakdown(app): + """阶段 tab 计数按权威口径归类;done 拆分为上传成功与驳回作废两类。""" + with app.app_context(): + from app import db + + owner = 77 + # [STEP] 四个待处理条目分别覆盖三路归类路径: + # OT.stage 权威(waiting_review→订单复核)、原因映射(upload_rpa_failed→货代上传、 + # inventory_source_unresolved→通知准备)、类别兜底(artifact ready 人工上传→货代上传)。 + review_task = ShippingOrderTask( + task_no="OT-STAGE-REVIEW", stage="waiting_review", + source_type="direct_pdf", user_id=owner, + ) + upload_rpa_task = ShippingOrderTask( + task_no="OT-STAGE-UPLOAD-RPA", pending_human_reason="upload_rpa_failed", + source_type="direct_pdf", user_id=owner, + ) + inventory_task = ShippingOrderTask( + task_no="OT-STAGE-INVENTORY", pending_human_reason="inventory_source_unresolved", + source_type="direct_pdf", user_id=owner, + ) + rejected_task = ShippingOrderTask( + task_no="OT-STAGE-REJECTED", review_status=RS_REJECTED, + source_type="direct_pdf", user_id=owner, + ) + manual_task = ShippingOrderTask( + task_no="OT-STAGE-MANUAL", source_type="direct_pdf", user_id=owner, + ) + manual_notice = ShippingNotice(task_no="SN-STAGE-MANUAL", source_type="manual", user_id=owner) + done_notice = ShippingNotice(task_no="SN-STAGE-DONE", source_type="manual", user_id=owner) + rejected_notice = ShippingNotice(task_no="SN-STAGE-REJECTED", source_type="manual", user_id=owner) + db.session.add_all([ + review_task, upload_rpa_task, inventory_task, rejected_task, manual_task, + manual_notice, done_notice, rejected_notice, + ]) + template = ShippingExcelTemplate( + template_code='STAGE', display_name='Stage', version=1, status='published', + storage_bucket='test', storage_key='stage.xlsx', original_filename='stage.xlsx', + file_checksum='a' * 64, definition_json={}, + ) + profile = ShippingInventoryParsingProfile( + profile_code='STAGE', display_name='Stage', version=1, status='published', + file_format='xlsx', definition_json={}, + ) + schema = ShippingOrderSchema(schema_code='STAGE', display_name='Stage') + db.session.add_all([template, profile, schema]) + db.session.flush() + version = ShippingOrderSchemaVersion( + schema_id=schema.id, version=1, status='published', definition_json={}, + ) + db.session.add(version) + db.session.flush() + extraction = ShippingOrderExtraction( + schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + manual_notice.order_task_id = manual_task.id + rejected_notice.order_task_id = rejected_task.id + + def add_artifact(notice, *, artifact_no: str, status: str) -> ShippingExportArtifact: + """为 Notice 建立待办分类所需的最小正式 Excel Artifact。""" + artifact = ShippingExportArtifact( + artifact_no=artifact_no, task_id=notice.id, template_id=template.id, + order_schema_version_id=version.id, order_extraction_id=extraction.id, + inventory_parsing_profile_id=profile.id, input_checksum='c' * 64, + file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx', + file_checksum='d' * 64, file_size=1, status=status, + ) + db.session.add(artifact) + return artifact + + # 人工上传待登记(ready→manual_upload);已完成(uploaded→done/upload_complete); + # 驳回终态(ready 但 OT 复核驳回→done/reject_void)。 + add_artifact(manual_notice, artifact_no='ART-STAGE-MANUAL', status='ready') + add_artifact(done_notice, artifact_no='ART-STAGE-DONE-UP', status='uploaded') + add_artifact(rejected_notice, artifact_no='ART-STAGE-REJ', status='ready') + db.session.commit() + + counts = count_my_todos(owner) + + # 断言:四个待处理条目按权威口径落入正确阶段 tab。 + assert counts["pending"] == 4 + assert counts["stage_counts"] == { + "intake_parse": 0, + "order_review": 1, + "fulfillment_prep": 1, + "freight_upload": 2, + } + # 断言:done 拆分——uploaded Artifact 计上传成功,OT 复核驳回计驳回作废。 + assert counts["done"] == 2 + assert counts["done_counts"] == {"upload_complete": 1, "reject_void": 1} + + # 断言:terminal_kind 子视图过滤——两个终态子 tab 各自只取对应集合,互不重叠。 + upload_page = list_my_todos(owner, bucket="done", terminal_kind="upload_complete") + assert {item["task_no"] for item in upload_page["items"]} == {"SN-STAGE-DONE"} + reject_page = list_my_todos(owner, bucket="done", terminal_kind="reject_void") + assert {item["task_no"] for item in reject_page["items"]} == {"SN-STAGE-REJECTED"} + # 无过滤参数时保持既有行为:done 全量。 + assert list_my_todos(owner, bucket="done")["total"] == 2 diff --git a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py index 07610593..4cb10a37 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py @@ -538,7 +538,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev db.session.refresh(task) assert result['status'] == 'ok', result - assert result['data']['stage'] == 'step5_match_inventory' + assert result['data']['stage'] == 'inventory_matching' link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).one() snapshot = db.session.get(ShippingInventoryFile, link.inventory_file_id) assert snapshot is not None diff --git a/backend/tests/test_shipping_notice_reservation_id.py b/backend/tests/test_shipping_notice_reservation_id.py index 63671232..83612644 100644 --- a/backend/tests/test_shipping_notice_reservation_id.py +++ b/backend/tests/test_shipping_notice_reservation_id.py @@ -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 diff --git a/backend/tests/test_shipping_order_extraction_conversation_title.py b/backend/tests/test_shipping_order_extraction_conversation_title.py new file mode 100644 index 00000000..8f75fb39 --- /dev/null +++ b/backend/tests/test_shipping_order_extraction_conversation_title.py @@ -0,0 +1,87 @@ +""" +backend/tests/test_shipping_order_extraction_conversation_title.py + +用途:验证订单抽取新建会话按 Intake 资产文件名派生标题,且已存在会话标题一律不动。 +依赖:全局 Flask/SQLite 测试夹具(app)、Run service 的会话解析内部函数。 +逻辑:新建分支走 conversation_title 派生;追加归属等存量路径保持原标题(含「订单抽取」)。 +""" + +from __future__ import annotations + +from app import db +from app.models import Agent, ChatSession, FileAsset, ShippingOrderIntake, User +from app.services.shipping_notice.order_extraction_run_service import _resolve_conversation + + +def _seed_user_agent(suffix: str) -> tuple[User, Agent]: + """构造用户与货代 Agent;suffix 保证同文件内多用例数据隔离。""" + user = User(username=f'title-user-{suffix}', email=f'title-{suffix}@example.com', password_hash='x') + agent = Agent( + name=f'Title Agent {suffix}', + agent_code='shipping_notice', + runtime_provider='hybrid', + dify_app_id=f'title-agent-{suffix}', + dify_api_key='test-key', + is_active=True, + ) + user.agents.append(agent) + db.session.add_all([user, agent]) + db.session.flush() + return user, agent + + +def _seed_intake(suffix: str, user: User, filename: str, conversation_id: str | None = None) -> ShippingOrderIntake: + """构造带资产文件名的已解析 Intake。""" + asset = FileAsset( + asset_no=f'FA-TITLE-{suffix}', + owner_user_id=user.id, + original_filename=filename, + storage_provider='minio', + storage_bucket='test', + storage_key=f'temporary/{user.id}/{filename}', + content_hash=(suffix.lower() * 64)[:64], + file_size=10, + mime_type='application/pdf', + upload_status='ready', + lifecycle_status='temporary', + ) + db.session.add(asset) + db.session.flush() + intake = ShippingOrderIntake( + intake_no=f'SNI-TITLE-{suffix}', + asset_id=asset.id, + user_id=user.id, + conversation_id=conversation_id, + purpose='shipping_notice', + parse_status='parsed', + parser_version='test', + ) + db.session.add(intake) + db.session.flush() + return intake + + +def test_new_session_title_derives_from_intake_filenames(app): + """新建会话:标题 = 首个文件名(剥离邮件前缀)+ 等 N 个文件 + 日期后缀。""" + user, agent = _seed_user_agent('NEW') + first = _seed_intake('NEW1', user, 'RE: PO#6075309 for HOXIN.eml') + second = _seed_intake('NEW2', user, 'invoice.pdf') + + session = _resolve_conversation(user_id=user.id, agent_id=agent.id, conversation_id='', intakes=[first, second]) + + # 日期后缀来自 utcnow,断言前缀避免对当天日期产生脆弱依赖。 + assert session.title.startswith('PO#6075309 for HOXIN 等 2 个文件 ') + + +def test_existing_session_title_stays_untouched(app): + """已存在会话:即便标题仍是写死的「订单抽取」,Intake 归属也不改标题。""" + user, agent = _seed_user_agent('KEEP') + session = ChatSession(session_id='title-session-keep', user_id=user.id, agent_id=agent.id, title='订单抽取') + db.session.add(session) + db.session.flush() + intake = _seed_intake('KEEP1', user, 'RE: PO#6075309.eml', conversation_id=session.session_id) + + resolved = _resolve_conversation(user_id=user.id, agent_id=agent.id, conversation_id='', intakes=[intake]) + + assert resolved.session_id == session.session_id + assert resolved.title == '订单抽取' diff --git a/backend/tests/test_shipping_order_profile_matcher.py b/backend/tests/test_shipping_order_profile_matcher.py index 20c1acbc..2e716317 100644 --- a/backend/tests/test_shipping_order_profile_matcher.py +++ b/backend/tests/test_shipping_order_profile_matcher.py @@ -5,6 +5,7 @@ from app.services.shipping_notice.document_layout.order_profile_matcher import ( _extract_matching_signature, _observe_layout_features, _resolve_coordinate_transform, + _signature_identity_header_tokens, match_frozen_coordinate_profiles, ) from app.services.shipping_notice.document_layout.order_profile_signature import ( @@ -1386,3 +1387,125 @@ def test_observe_layout_features_applies_business_row_clip(): assert bbox is not None assert bbox[3] < 0.62 assert bbox[3] > 0.50 + + +# --- PO_6075316 路由级合成回归:别名契约经二次机会门禁清空两道表头硬门禁 --- + +# 训练签名(命中模板 HYVE)的明细表 header_tokens 形状。 +_PO6075316_TRAINING_TOKENS = [ + 'LN', 'Quantity', 'Part Number Vendor Item#', 'Description', + 'Requested Arrival Date', 'Unit Price', 'Extension', +] +# 故障 PDF(PO_6075316)观测形状:日期词变更 + 相邻列并格 + 一个 MinerU 空串占位。 +_PO6075316_FAULT_TOKENS = [ + 'LN', 'Quantity', 'Part Number Vendor Item#', 'Description', + 'Requested Ship Date Unit Price', '', 'Extension', +] +# Schema v4 相关别名(归一化 key → field_code),含治理后的 Requested Ship Date。 +_PO6075316_HEADER_TO_FIELD = { + 'Requested Receipt Date': 'requested_receipt_date', + 'Requested Arrival Date': 'requested_receipt_date', + 'Requested Ship Date': 'requested_receipt_date', + 'Unit Price': 'unit_price', + 'Extension': 'line_amount_with_tax', + 'Part Number': 'customer_part_number', + 'Vendor Item': 'part_number', + 'Quantity': 'qty', + 'LN': 'customer_po_line_no', +} + + +def _column_header_glyphs(tokens: list[str], *, x_start: float = 40.0, y0: float = 76.0, y1: float = 88.0, column_gap: float = 12.0) -> list[dict]: + """按列生成表头字符证据。 + + 列内空格不额外步进(合并格文案保持为单一 span,空格由 boundary 恢复); + 列间留大间隔强制 positioned_token_spans 切分;空串列不产出字符。 + """ + glyphs: list[dict] = [] + cursor = x_start + for token in tokens: + first_of_column = True + for index, char in enumerate(token): + if char == ' ': + continue + glyphs.append({ + 'text': char, + 'bbox': {'x0': cursor, 'y0': y0, 'x1': cursor + 3, 'y1': y1}, + 'boundary_before': 'none' if first_of_column else ('space' if index and token[index - 1] == ' ' else 'none'), + }) + first_of_column = False + cursor += 4.0 + cursor += column_gap + return glyphs + + +def _layout_with_column_header(tokens: list[str], *, page_width: float = 640) -> dict: + """以指定列 token 形状构造坐标 layout(沿用 _layout 骨架,整体替换表头字符)。""" + layout = _layout() + layout['coordinate_evidence']['pages']['1']['width'] = page_width + header = _column_header_glyphs(tokens) + layout['coordinate_evidence']['tables']['table-1'] = header + layout['coordinate_evidence']['page_glyphs']['1'] = [ + *layout['coordinate_evidence']['page_glyphs']['1'][: len('PLANT NAME: FACTORY A')], + *header, + ] + return layout + + +def test_header_alias_contract_clears_all_po6075316_header_hard_gates(): + """路由重放 PO_6075316:含 Ship Date 别名的契约清空 discriminator 与 + signature_conflict 两道表头硬门禁(二次机会:canonical 序列复评达标)。""" + training = _layout_with_column_header(_PO6075316_TRAINING_TOKENS) + fault = _layout_with_column_header(_PO6075316_FAULT_TOKENS) + profile = _profile_without_required_anchors('PO_HYVE_6075316', training) + + # 构造守卫:冻结签名 token 必须与训练形状逐字一致,防止证据管线漂移使断言空转。 + signature_body, _ = _extract_matching_signature(profile) + assert _signature_identity_header_tokens(signature_body) == _PO6075316_TRAINING_TOKENS + + with_contract = match_frozen_coordinate_profiles( + profiles=[profile], layout=fault, + header_to_field=_PO6075316_HEADER_TO_FIELD, + ) + without_contract = match_frozen_coordinate_profiles(profiles=[profile], layout=fault) + + contract_candidate = with_contract.candidates[0] + plain_candidate = without_contract.candidates[0] + # 关键断言:别名契约下第一道 discriminator 互斥被 canonical 原子全等豁免。 + assert 'profile_header_discriminator_conflict' not in contract_candidate.reason_codes + # 关键断言:第二道 signature_conflict 门禁被二次机会清空——原始分被词级互斥 + # 压成 0 后,canonical 序列复用同一打分逻辑重估,effective >= 0.35 不再硬拒。 + assert 'profile_header_signature_conflict' not in contract_candidate.reason_codes + # 关键断言:两道表头硬门禁全清后候选成为硬匹配(表头类原因码不为拦路面)。 + assert contract_candidate.hard_match is True + # 关键断言:不传契约时同形状仍被词级原子互斥拒绝——互斥机制本身未被别名破坏。 + assert 'profile_header_discriminator_conflict' in plain_candidate.reason_codes + + +def test_header_alias_contract_without_ship_date_alias_keeps_hard_rejection(): + """反向用例:契约缺 Ship Date 别名时二次机会不生效,候选仍被表头硬门禁拒绝。 + + 证明二次机会来自别名本身而非门禁放水。缺 Ship Date 别名时两侧 canonical + 原子不再全等,先触发 discriminator 分支——if/elif 结构下 signature_conflict + 分支被前置分支吸收(不得并列上报同根因),故拦路码为 discriminator; + 断言落点是「仍被硬拒」:hard_match False 且综合分归零。 + """ + training = _layout_with_column_header(_PO6075316_TRAINING_TOKENS) + fault = _layout_with_column_header(_PO6075316_FAULT_TOKENS) + profile = _profile_without_required_anchors('PO_HYVE_6075316', training) + contract_without_ship_alias = { + key: value + for key, value in _PO6075316_HEADER_TO_FIELD.items() + if key != 'Requested Ship Date' + } + + partial = match_frozen_coordinate_profiles( + profiles=[profile], layout=fault, + header_to_field=contract_without_ship_alias, + ) + candidate = partial.candidates[0] + # 关键断言:缺 Ship Date 别名 → 跨措辞(ship vs arrival)无法归一 → 硬互斥仍在。 + assert 'profile_header_discriminator_conflict' in candidate.reason_codes + # 关键断言:候选仍被硬拒(综合分归零、非硬匹配)——别名缺失绝不放行。 + assert candidate.hard_match is False + assert candidate.score == 0.0 diff --git a/backend/tests/test_shipping_order_review_service.py b/backend/tests/test_shipping_order_review_service.py index a7f7fcac..ac7ddd9c 100644 --- a/backend/tests/test_shipping_order_review_service.py +++ b/backend/tests/test_shipping_order_review_service.py @@ -372,7 +372,7 @@ def test_review_queue_falls_back_to_process_gate_when_ot_stage_is_legacy_step(ap conversation_id=session.session_id, extraction_run_id=run.id, status='waiting_review', - stage='step5_match_inventory', + stage='inventory_matching', ) db.session.add(task) db.session.flush() @@ -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 diff --git a/backend/tests/test_shipping_processing_projection_invariants.py b/backend/tests/test_shipping_processing_projection_invariants.py index 807d7a2e..71b0c886 100644 --- a/backend/tests/test_shipping_processing_projection_invariants.py +++ b/backend/tests/test_shipping_processing_projection_invariants.py @@ -230,18 +230,18 @@ def test_map_notice_to_processing_status_stage_domain_mapping(): # 与无 Artifact 时,停留在上传工作面只能由 current_step 提示导出(与 Step 7 上传阶段一致)。 uploaded = SimpleNamespace( id=None, - current_step='step7_upload', upload_status='uploaded', export_file_path=None, + current_step='freight_uploading', upload_status='uploaded', export_file_path=None, ) # 历史聚合字段没有预约单与成功 Attempt,不得直接进入完成。 assert map_notice_to_processing_status_stage(uploaded) == ('automating', 'freight_uploading') waiting = SimpleNamespace( - current_step='step7_upload', upload_status='pending', export_file_path='/x.xlsx', + current_step='freight_uploading', upload_status='pending', export_file_path='/x.xlsx', ) assert map_notice_to_processing_status_stage(waiting) == ('automating', 'freight_uploading') matching = SimpleNamespace( - current_step='step5_match', upload_status='', match_status='matching', export_file_path=None, + current_step='inventory_matching', upload_status='', match_status='matching', export_file_path=None, ) assert map_notice_to_processing_status_stage(matching) == ('automating', 'inventory_matching') diff --git a/backend/tests/test_shipping_processing_projection_stage4.py b/backend/tests/test_shipping_processing_projection_stage4.py index 7affccc5..2f9c362d 100644 --- a/backend/tests/test_shipping_processing_projection_stage4.py +++ b/backend/tests/test_shipping_processing_projection_stage4.py @@ -540,7 +540,7 @@ def test_order_task_work_item_uses_ot_execution_when_notice_missing(app) -> None owner_agent_id=int(agent.id), candidate_id=None, status='waiting_review', - stage='step5_match_inventory', + stage='inventory_matching', progress_version=3, ) db.session.add(task) @@ -1660,7 +1660,7 @@ def test_summary_loads_process_execution_by_order_task_id_not_candidate_id(app) intake_id=intake.id, candidate_id=candidate.id, status='waiting_review', - stage='step3_inventory_prepare', + stage='inventory_fetching', ) db.session.add(order_task) db.session.flush() @@ -1876,6 +1876,73 @@ def test_summary_leaf_preserves_edit_draft_for_current_candidate_case(app) -> No assert summary_leaf['intake_parse_authorized'] is False +def test_summary_leaf_surfaces_primary_validation_issue_for_open_case(app) -> None: + """摘要叶子对建单前 Case 必须透传首要资格 issue,而非 review_case_{status} 状态码。 + + 回归:批次进度中心对"客户尚未确认"等具体阻断只显示「订单草稿待处理」状态文案, + 原因是叶子摘要用 Case 状态拼 blocking_reason.code;资格评估已把冻结 + explainability(code/message/next_action)持久化进 draft.validation_result_json, + 摘要路径应透传该裁决(drafts_by_id 已批量加载,零额外查询)。 + """ + with app.app_context(): + from app.services.shipping_notice.order_review_service import ensure_run_review_cases + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + + user, agent, session, intake, document = _seed_run_input( + suffix='SUMMARY-LEAF-ISSUE-REASON', + ) + intake.source_type = 'eml' + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + candidate = ShippingOrderCandidate( + candidate_no='CAND-SUMMARY-ISSUE-REASON', intake_id=intake.id, + primary_document_id=document.id, candidate_key='summary-issue-reason', + order_extraction_run_id=run.id, is_current_version=True, + candidate_status='accepted', po_number='PO-SUMMARY-ISSUE-REASON', + ) + db.session.add(candidate) + db.session.flush() + review_case = ensure_run_review_cases(run=run)[0] + review_case.status = 'draft' + draft = review_case.current_draft + assert draft is not None + # 模拟资格评估落库的首要阻断 issue(与 order_build_eligibility 持久化结构一致) + draft.validation_result_json = { + 'can_build': False, + 'can_auto_create': False, + 'issues': [{ + 'code': 'customer_unresolved', + 'severity': 'blocking', + 'owning_gate_code': 'customer_resolution', + 'message': '客户尚未确认', + 'explainability': { + 'reason_code': 'customer_unresolved', + 'message': '客户尚未确认', + 'next_action': 'confirm_customer', + }, + }], + } + db.session.commit() + + payload = project_conversation_processing_summary( + user_id=user.id, + conversation_id=session.session_id, + ) + summary_leaf = next( + child + for rows in payload['conversation_processing']['status_groups'].values() + for row in rows + for child in row.get('aggregate_children', []) + if child['source_summary']['document_id'] == document.id + ) + + reason = summary_leaf['ui_state']['blocking_reason'] + # 关键断言:透传契约三元组;不得再是 review_case_draft 状态码 + assert reason['code'] == 'customer_unresolved' + assert reason['message'] == '客户尚未确认' + assert reason['next_action'] == 'confirm_customer' + + def test_summary_leaf_open_case_with_queued_stp_is_running_not_waiting_human(app) -> None: """开放 Case 若已有 queued STP Job,摘要必须进系统处理中,不得误报待人工。 @@ -2860,7 +2927,7 @@ def test_single_order_task_work_item_includes_authoritative_lifecycle_ui_state(a conversation_id=session.session_id, intake_id=int(intake.id), extraction_run_id=int(run.id), - current_step='step7_upload_freight', + current_step='freight_uploading', status='automating', stage='freight_uploading', progress_version=1, @@ -3139,7 +3206,7 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u user_id=user.id, conversation_id=session.session_id, extraction_run_id=int(run.id), - current_step='step7_upload_freight', + current_step='freight_uploading', status='processing', stage='candidate_creating', progress_version=1, diff --git a/backend/tests/test_shipping_projection_cross_surface.py b/backend/tests/test_shipping_projection_cross_surface.py index 4f0909f6..0c645f24 100644 --- a/backend/tests/test_shipping_projection_cross_surface.py +++ b/backend/tests/test_shipping_projection_cross_surface.py @@ -36,21 +36,39 @@ def test_fifteen_processing_stages_all_map_to_a_lifecycle_stage(): ) -def test_legacy_step_key_stage_maps_to_fulfillment_prep(): - """OT.stage 若残留 step5_match_inventory,生命周期必须进通知准备而非接收解析。""" +def test_stage_mapping_rejects_checkpoint_legacy_keys(): + """CheckPoint stepN_* 遗留键已全部清除:阶段映射只认 15 阶契约码。 + + 历史缺陷:step_key 被写进 OT.stage,靠投影别名兜底;现写路径只产出契约码 + (set_task_step_progress 校验 + 存量迁移清洗),别名不得再存在。 + """ + legacy_keys = [ + 'step1_notice_submit', + 'step2_parse_confirm', + 'step3_inventory_prepare', + 'step5_match_inventory', + 'step6_generate_file', + 'step7_upload_freight', + ] + for key in legacy_keys: + assert key not in LIFECYCLE_STAGE_BY_PROCESSING_STAGE, ( + f"CheckPoint 遗留键 {key!r} 不得再进入阶段映射" + ) + for stage_code in LIFECYCLE_STAGE_BY_PROCESSING_STAGE: + assert not str(stage_code).startswith('step'), ( + f"阶段映射出现非契约键 {stage_code!r}" + ) + # 契约码本身仍能正常映射:库存匹配属通知准备,processing_stage 权威生效。 from app.services.shipping_notice.lifecycle_projection import project_lifecycle result = project_lifecycle( current_gate={'gate_code': 'task_creation', 'status': 'invalidated'}, blocking_reason={'code': 'gate_invalidated'}, has_candidate_context=True, - processing_stage='step5_match_inventory', + processing_stage='inventory_matching', ) - # processing_stage 权威高于错误的 task_creation 门禁。 assert result['lifecycle_stage'] == 'fulfillment_prep' assert result['lifecycle_authority'] == 'processing_stage' - current = next(e for e in result['lifecycle_entries'] if e['state'] == 'current') - assert current['code'] == 'fulfillment_prep' def test_fifteen_stages_inventory_source_before_review(): diff --git a/backend/tests/test_shipping_review_workbench_stage_layering.py b/backend/tests/test_shipping_review_workbench_stage_layering.py index fa500f51..edf5f6b4 100644 --- a/backend/tests/test_shipping_review_workbench_stage_layering.py +++ b/backend/tests/test_shipping_review_workbench_stage_layering.py @@ -283,7 +283,7 @@ def test_project_stage_for_task_legacy_uploaded_notice_stays_in_freight_upload(m id=1, order_task_id=9, upload_status='uploaded', - current_step='step6_generate_file', + current_step='excel_generating', stage_nodes_json=None, step_payload_json=None, ) diff --git a/backend/tests/test_shipping_task_center_review_run_deep_link.py b/backend/tests/test_shipping_task_center_review_run_deep_link.py index be8b999d..1ef37d60 100644 --- a/backend/tests/test_shipping_task_center_review_run_deep_link.py +++ b/backend/tests/test_shipping_task_center_review_run_deep_link.py @@ -76,7 +76,7 @@ def test_serialize_order_task_keeps_self_order_task_no_after_enrich(app): extraction_run_id=int(run.id), owner_agent_id=int(agent.id), status='waiting_review', - stage='step5_match_inventory', + stage='inventory_matching', progress_version=3, ) db.session.add(order_task) diff --git a/backend/tests/test_shipping_workbench_service_chains.py b/backend/tests/test_shipping_workbench_service_chains.py index ecd8b47b..babbb95c 100644 --- a/backend/tests/test_shipping_workbench_service_chains.py +++ b/backend/tests/test_shipping_workbench_service_chains.py @@ -91,7 +91,7 @@ def test_service_chain_customer_confirm_projection(app, workbench_chain_ids): with app.app_context(): run, notice, order_task = _load_chain(workbench_chain_ids) notice.review_status = 'pending_confirm' - notice.current_step = 'step4_match_inventory' + notice.current_step = 'inventory_matching' notice.customer_id = 1 db.session.commit() @@ -112,7 +112,7 @@ def test_service_chain_inventory_match_projection(app, workbench_chain_ids): with app.app_context(): run, notice, order_task = _load_chain(workbench_chain_ids) notice.match_status = 'matched' - notice.current_step = 'step4_match_inventory' + notice.current_step = 'inventory_matching' db.session.commit() before, projection = _project_after_sync(notice, order_task, run) @@ -130,7 +130,7 @@ def test_service_chain_excel_generate_projection(app, workbench_chain_ids): with app.app_context(): run, notice, order_task = _load_chain(workbench_chain_ids) notice.upload_status = 'pending' - notice.current_step = 'step7_upload_freight' + notice.current_step = 'freight_uploading' notice.export_file_path = '/tmp/fake-shipping.xlsx' db.session.commit() @@ -148,7 +148,7 @@ def test_service_chain_freight_upload_retry_projection(app, workbench_chain_ids) """ with app.app_context(): run, notice, order_task = _load_chain(workbench_chain_ids) - notice.current_step = 'step7_upload_freight' + notice.current_step = 'freight_uploading' notice.upload_status = 'failed' notice.export_file_path = '/tmp/fake-shipping.xlsx' db.session.commit() diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 4117dad2..ad7c83d1 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -5,6 +5,41 @@ > **同步维护**:流程、字段规则、人工确认节点等变更时,**须同时更新本文件与** **`business.md`**。\ > **Dify 文档维护原则**:Dify 编排仅在本文件维护,且以**节点级配置**为准;重点维护各节点的职责、输入、输出、条件、Tool 绑定与连线关系,不再额外维护独立 DSL 解读文档。\ +## 我的待办改版:列表优先 + 按需抽屉 + 已完成明细报表(2026-09-16) + +任务中心「我的待办」(`/workspace/shipping-notice/my-tasks`)布局与数据契约改版,设计稿见 [`docs/superpowers/prototypes/2026-09-16-my-tasks-redesign.html`](../../superpowers/prototypes/2026-09-16-my-tasks-redesign.html),实施计划见 [`docs/superpowers/plans/2026-09-16-my-tasks-redesign.md`](../../superpowers/plans/2026-09-16-my-tasks-redesign.md)。 + +**布局**:移除右侧常驻详情面板,改为紧凑表格行 + 点击行弹出右侧抽屉(`ShippingTaskDrawer`,分诊决策面板:头部阶段/阻断、逐行明细 `notice_line_summary` 全量列、文件区、底部深链操作;Esc/遮罩关闭)。组件拆分:`ShippingStageTabs`(阶段筛选 tab)、`ShippingTaskTable`(表格 + 批量浮动条)、`ShippingTaskDrawer`、`ShippingDoneLineReport`(通知完成明细报表),共享口径在 `shippingTaskCenterShared.ts`。 + +**阶段与桶**:阶段筛选 tab 收敛为四个可动作阶段(`intake_parse/order_review/fulfillment_prep/freight_upload`),计数来自后端 `my-todos/count` 聚合扩展字段 `stage_counts`(Review Case 走统一生命周期投影、Intake 恒为接收解析、Notice/OT 以 processing_stage 权威 → 人工原因归属 Gate → 类别兜底归类);「通知完成」不再是筛选维度,done 桶拆子视图 tab(`done_counts`:`upload_complete` / `reject_void`)。 + +**已完成桶**:默认子视图「通知完成」为跨 OT 平铺的明细行报表(`GET /shipping-tasks/my-todos/done-lines`),行 = 标准 12 字段(客户/客户编号/订单日期/订单项次/料号/数量/约定出货日期/客户PO/已用数量/open qty/订单单号/单价)+ 页面溯源列(`business_no||task_no`);筛选支持 客户 / 料号 / 发货通知日期(Notice created_at)范围,按明细行分页;导出 `GET .../done-lines/export` 严格 12 列中文表头(OT 不落列,openpyxl 直写,不注册模板)。已用数量/open qty 后端暂无数据源,契约留空;约定出货日期取行级 `required_date`(缺失回退快照表头列)、订单单号取表头 `source_order_number`(field_id 键)、单价取行 `unit_price`。「复核驳回 / 已作废」子视图走既有任务表 + 抽屉,`my-todos` 新增 `terminal_kind` 参数(`upload_complete|reject_void`)服务端过滤。 + +**批量操作**:仅「货代上传」阶段的正式 Notice 行有复选框(`isFreightUploadRow`),勾选 ≥1 后浮出深色操作条(下载 ZIP / 确认已上传 / 发起 RPA / 清除),无常驻工具栏;修复批量按钮 i18n 裸 key(`workspace.shippingNotice.batch.*` 此前误挂 `schedule.batch`,已在四语言归位补齐)。新增页面文案(表格/终态角标/子视图/抽屉/报表列头等)已同步 zh-CN / zh-TW / en / th。 + +## 阻塞原因具体化:资格快照回退 + 原因/动作语义分离(2026-09-17) + +**背景**:批次中心与工作台「当前任务」对建单前 Review Case 一律显示兜底文案「当前步骤需要人工处理」(同卡重复两遍),而具体原因(如 `customer_unresolved`「客户尚未确认」)早已随资格评估持久化在 `draft.validation_result_json.issues[].explainability`,只是从未进入 `blocking_reason` 通道。 + +**后端**(`reconciliation_projector.py`,单一裁决点):`project_review_case_projection_bundle` 在 automation 未携带具体原因码时,回退到 validation 快照的首要 blocking issue(跳过降级为 `unknown_business_failure` 的条目),透传冻结 explainability 契约的 `code / message / next_action / details(field_code, line_index, owning_gate_code)`——不新造任何文案映射;`project_case_blocking_reason` 的 fail-closed 兜底键从不存在的 `shipping.review.blocked_generic` 修正为前端真实存在的 `chat.shippingProcessing.reasonCode.unknown`。`BlockingReason` TypedDict 新增 `message` / `next_action` 可选字段(加法变更,向后兼容)。 + +**前端**:①`shippingProcessingLabels.isGenericBlockingReason` 升级判定(Gate 三命名空间任一命中或契约 `message` 非空即具体原因),新增 `resolveBlockingReasonText`(i18n_key → reasonCode → Gate 命名空间 → message,通用兜底返回空串);②批次中心卡(`ShippingConversationProcessingCard`)原因行改用该解析链,未知码不再渲染「当前步骤需要人工处理」空话,workbench 模式下任务卡头原因行由文件行页脚独家承载(去重);③工作台「当前任务」卡(`ReviewCurrentProcessingCard`)「下一步」优先消费 `blocking_reason.next_action` 渲染 `processGate.actionCodes.*` 建议动作(语义=做什么,而非为什么),且具体阻断原因在场时隐藏泛化的 Run 级 statusDetail。原因(客户尚未确认)与动作(确认客户)全链路文案均复用既有契约与四语言目录,未新增文案键。 + +**补充收口(同日)**:联调发现两处断点——①批次中心叶子摘要路径(`shipping_processing_projection._leaf`)对建单前 Case 直接下发 `{'code': f'review_case_{status}'}`(前端解析为「订单草稿待处理」状态文案);现新增 `_review_case_blocking_reason` 回退:`reason` 为 `review_case_*` 时从闭包内已批量加载的 `drafts_by_id` 取当前 Draft 校验快照,透传首要资格 issue(零额外查询),无可用 issue 保持状态码兜底。②API 归一化层(`normalizeShippingProcessing.normalizeBlockingReason`)白名单剥离了 `message`/`next_action`,致工作台「下一步」退化为原因文案;现保留两个透传字段(camel/snake 兼容)。 + +## CheckPoint 遗留 step_key 彻底清除(2026-09-17) + +**背景缺陷**:`set_task_step_progress`(`tool_common.py`)历史上把 CheckPoint 时代 step_key(`step1_notice_submit` / `step2_parse_confirm` / `step3_inventory_prepare` / `step5_match_inventory` / `step6_generate_file` / `step7_upload_freight`)直接写入 `OT.stage` 与 `OT.current_step`。库存 RPA 失败上报曾把已建单 OT 的 `stage=order_creating` 踩回 `step3_inventory_prepare`;该值不在冻结 15 阶契约(`SHIPPING_PROCESSING_STAGES`)内,工作台投影回退到 Run 的识别期阶段 `candidate_creating`,五阶段步进器因此把已建单订单拉回「接收解析」(`project_lifecycle` 的 processing_stage 权威高于 Gate)。 + +**彻底清除(不留兼容层)**: + +- **写路径**:`set_task_step_progress` 入参 `step_key` 改名 `stage`,必须传 15 阶契约码(非法值 `ValueError` 立即失败);`current_step` 与 `current_step_progress` 载荷字段同步改存/改名 `stage`;`OT.stage` 写入带**只进不退守卫**(按 `shipping_processing_stage_index`,仅允许推进或平齐,禁止回退),进度上报永远无法再拉低阶段。 +- **29 个调用点**全部改传契约码:库存准备/映射/RPA → `inventory_fetching`;库存匹配/文件入库 → `inventory_matching`;Excel 生成 → `excel_generating`;货代上传 → `freight_uploading`;通知重提交/解析确认 → `order_creating` / `waiting_review`。 +- **读路径别名全部删除**:`lifecycle_projection.LIFECYCLE_STAGE_BY_PROCESSING_STAGE` 与 `processing_projection_invariants._USER_STAGE_TO_CODE` 中的 4 个 stepN_* 别名条目移除,映射表只认契约码;`map_notice_to_processing_status_stage` 对 `current_step` 的子串/前缀启发式(`'upload' in step` / `startswith('step7')` 等)改为契约码精确匹配。 +- **存量数据**:不落数据迁移——各环境确认无需要清洗的 stepN_* 存量,写路径切换后不再产生新遗留值。 +- **前端**:`ShippingCurrentStepProgress.step_key` 字段改名 `stage`(无组件消费该字段,仅类型同步)。 +- **测试**:跨面一致性新增守护用例 `test_stage_mapping_rejects_checkpoint_legacy_keys`(阶段映射禁止任何 stepN_* 键);各测试夹具的遗留字面量已替换为契约码。 + ## 五阶段 UI 状态契约(2026-08) 业务人员只看到五个阶段:`intake_parse`(接收解析)→ `order_review`(订单复核)→ `fulfillment_prep`(通知准备)→ `freight_upload`(货代上传)→ `upload_complete`(通知完成)。`ui_state` 是唯一前端读模型;Gate/Execution 是业务门禁真相。正式 Task 的操作使用 `ui_state.actions.primary/secondary`,批次 / 生命周期投影的操作使用 `ui_state.primary_action/secondary_actions`;两者均由后端下发,前端不得根据领域字段自行推导阶段或按钮;`process_status` 已删除。 @@ -399,6 +434,8 @@ L1 字段级:目标单元格 + 表头 + 相邻单元格 **版面签名证据一致性(2026-08-04)**:表头签名不再扫描整页顶部或按表高固定比例猜测,而是直接冻结模板既有 `header_layout.region`;运行时对每个候选在同一区域独立取证。新旧 PDF 坐标证据统一按视觉行和纯几何词间距恢复表头词组,避免 `boundary_before` 有无造成同文件签名漂移;列中心和列宽由表头词组边界产生,不再使用全表单字符连续聚类。只有同时达到模板最低分和证据覆盖率的候选才参与唯一性与 Margin 决胜。 +**表头身份原子按 Schema 别名归一(2026-09-16)**:无必选锚点模板的两道表头硬门禁——原子集全等互斥(`profile_header_discriminator_conflict`)与软评分硬门槛(`profile_header_signature_conflict`,score<0.35)——在传入 Run 冻结 Schema 编译的表头契约(`compile_table_header_contract().header_to_field`)后,签名侧与观测侧 token 均先按别名归一为字段语义类(`schema_canonical_header_atoms` / `schema_canonical_header_tokens`:贪心最长别名短语匹配,命中归并为 `field::`,未命中词保留词级原子;casefold 后跨字段碰撞的别名短语弃用)再比较/评分。**同字段同义列名不再误杀**(如 `Requested Arrival Date` ≡ `Requested Ship Date`,含 provider 单元格粘连与空格噪声),原子全等互斥的互斥强度与 0.35 硬门槛本身不变;二次机会仅在无锚点前提、契约非空且原始分<0.35 时参与门槛(`effective=max(原始,canonical)`),七维上报的 `header_semantic_position` 维持原始分。别名的同义词治理唯一入口是 Schema 字段 `aliases`(发布碰撞校验沿用);`header_to_field=None` 的调用路径行为不变,已发布模板签名无需重冻结。背景:PO_6075316 因日期列名变体全模板 0 分转人工空单;测试环境 Schema v1(行 id=4)已原位补 `Requested Ship Date` 别名(checksum 同步重算)。 + **邮件补充重建规则(2026-07-31)**:邮件表头只能按当前 Run 冻结 Schema 的显式别名映射;行级 `reservation_id` 包含真实业务表头 `External reservation ID`。只要 Intake 保留原始 `body_html_tables`,Run 冻结时必须按自己的 Schema 重新解析完整补充表,不能复用上传阶段缺字段但已有部分行的旧结果;没有 HTML 时才复用已有完整结果或安全回退纵向纯文本解析。**关联收紧(2026-09-15)**:`mpn_fallback` 仅适用于补充行 PO 缺失且料号唯一命中;有 PO 且与 PDF 不一致不得补充。预约号允许短数字行序后缀归一(如 `35354-1` → `35354`)。**无 PO 表头(2026-09-16)**:分配表缺 PO 列但已映射料号或预约号时仍解析补充行(`po_header_missing` 仅作可观测标记);无身份列时仍整表跳过。 **`llm_extraction` 回退语义(2026-08-01)**:订单字段标记为 `llm_extraction` 表示“确定性解析无法取值时允许 LLM 补充”,不表示必须使用 LLM。通用解析门禁应依据字段是否已有完整、无冲突的确定性证据裁决;已取得必填 Header/Line 值时可直通,缺失时由 `required_field_missing` 转入 LLM/人工复核。 @@ -699,7 +736,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 管理端维护。 @@ -1366,6 +1403,8 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工 - 管理端只列出当前 published Schema 中 `enabled=true`、Header 文本类型且 `available_for_customer_identity=true` 的字段。规则集发布时重新校验字段仍可用,不能仅依赖草稿创建时状态。 - Resolver 只读取 Candidate 所属 Extraction 中 accepted/corroborated Header FieldValue。EML From、模板指纹、原始 LLM 输出和 Candidate 摘要均不能作为旁路证据。 - 规则快照冻结 `context_field_id` 与完整 `field_config`;字段退役、删除或新 Schema 移除引用字段时由定义和草稿/发布规则快照共同阻断。 +- 客户命中分三级(2026-09-17 起,`shadow-v3`):① canonical 等值(NFKC+casefold+剔除非字母数字,中文保留;吸收标点/空白/大小写打印差异);② 完整包含(注册指纹整体出现在提取值中,指纹 canonical 长度 ≥8);③ 截断包含(提取值疑似指纹截断片段,同 8 字符下限)。证据归一化在导入、影子识别与自动确认复核三处共用 `normalize_identity_evidence_value`(兜底分支折叠内部空白/换行)。邮箱/域名指纹只做精确等值,禁止包含比较;短于 8 字符的指纹由等值路径承担,不享受包含兜底。 +- 自动确认边界:①级唯一命中且证据 `auto_match_allowed` → `unique_strong_match`;②级唯一且授权 → `unique_containment_match`(审计证据带 `match_kind=containment_strong`);③级与未授权证据永不自动确认,只进入复核面板候选建议。等值命中存在时包含命中不参与裁决;任务期协调器与复核「重新识别」按钮共用 `resolve_auto_customer_decision` 同一裁决,质量门禁分母包含两类唯一命中。 - 本阶段为不兼容升级:迁移清空旧定义、规则集、证据、影子匹配及其审计快照,然后物理删除旧适配器列;不提供运行时兼容映射。 ### 阶段 4 可靠性、监控与故障注入 @@ -2032,7 +2071,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 ``` @@ -2590,6 +2629,21 @@ Task 工作台 = 非主界面,仅保留备用深链 - **自动建单安全**:分类置信度与 LLM 字段置信度缺失 fail-closed;阈值来源写入 `confidence_policy`(schema / key_field / default_fallback)。 - **货代上传**:`SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED` 默认 `false`(须显式开启);开启时启动/触发前校验 Worker(`freight_upload`)、凭据、共享目录与环境隔离。RPA 进行中投影 `display_lifecycle_status=upload_rpa_pending` 且 `is_waiting_manual_upload=false`,不得仅凭 lifecycle 显示为待人工上传。 +### 会话主区域与批次进度中心(2026-09 方案 A) + +- 货代发货智能体主区域规则:`isShippingNoticeAgent && conversation_id 非空` → 全屏渲染批次进度中心 + (`ShippingWorkflowTimeline`,常驻无关闭按钮);否则渲染欢迎页 + 输入框(唯一附件提交入口)。 + 判定纯函数:`frontend/src/features/chat/shipping/shippingWorkbenchLayout.ts`。 +- 提交链路不变:`startRun` 成功 → 路由写回 `conversation_id` → 中心出现;对话流不再出现 + 「本次订单文件处理」卡片入口,`open-batch-workbench` / `compact-shipping-progress` 链路已移除; + `ShippingOrderExtractionCard` 保留为历史消息兜底渲染。 +- 中心头部复用会话标题(父级从侧栏 `displayHistory` 按 conversation_id 匹配传入 `conversation-title`)。 +- 新建抽取会话命名:`backend/app/services/shipping_notice/conversation_title.py` + `derive_order_extraction_title(filenames, created_at)` —— 首个非空文件名去扩展名、剥离 + Re:/Fw:/Fwd:/回复:/转发:前缀、截 24 字、多文件追加「等 N 个文件」、追加 MM-DD; + 全空回退「订单抽取」。仅在 `_resolve_conversation` 新建分支调用;存量会话标题一律不改。 +- 同批次追加附件:中心不提供入口,通过「新建对话」重新提交(后端 append/create 裁决逻辑不变)。 + #### 1.6.0a Gate 统一用户动作裁决(2026-08-19) 为避免“页面按 checkpoint、状态或 action code 猜按钮位置”导致展示与执行漂移,正式履约任务采用以下职责边界: @@ -2868,6 +2922,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://: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`(收料启动脚本默认指向 `\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://:<端口>" ` + -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://:<端口>" +$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 +3705,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 +3821,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//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` 驱动。 diff --git a/docs/funclist.md b/docs/funclist.md index bfe53a56..704f9d84 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -22,8 +22,12 @@ - 订单复核:核对订单并确认正式建单。 - 通知准备:库存处理、匹配和生成发货通知 Excel;一个 `shipping_notice` 对应一张发货通知单、一个单号和一个 Excel,可包含多条订单明细;RPA 超时优先重新读取已产生的库存结果,用户可再明确选择重新获取库存(RPA)。 - 货代上传:下载 Excel、RPA 上传、按发货通知单号人工确认已上传、失败恢复和未知结果核对;未知结果禁止自动重试。 +- 我的待办改版(2026-09-16):紧凑表格 + 按需详情抽屉;阶段筛选 tab 计数后端全量聚合(仅四个可动作阶段);批量操作仅货代上传阶段可勾选、勾选后浮动操作条;已完成桶拆子视图——「通知完成」为跨单平铺明细报表(客户/料号/发货通知日期筛选,按明细行分页,导出严格 12 列标准 Excel),「复核驳回/已作废」为任务表 + 抽屉。 +- 阻塞原因具体化(2026-09-17):批次中心/工作台对建单前 Case 回退消费草稿校验快照的首要阻断 issue(冻结 explainability 契约透传 code/message/next_action),展示「客户尚未确认」等具体原因;「下一步」渲染建议动作文案;通用兜底码不再渲染,同卡重复原因行去重。 - 通知完成:只读展示已核验的上传成功证据;仅 Task 聚合、全部预约单与成功 Upload Attempt 同时满足时显示并计入完成。 - 通知完成:上传通知或登记上传回执;仅服务端确认的上传 Attempt 成功后显示完成结果。 +- 货代发货会话主区域为批次进度中心:有会话即全屏常驻展示(不可关闭),无会话显示欢迎页与附件提交入口;历史会话点击直达中心 +- 新建订单抽取会话自动按首个附件文件名命名(剥离邮件前缀 + 等 N 个文件 + 日期后缀);存量会话名不变 - 平台把文本提交给 Dify 后,会继续确认 Dify 的 `indexing_status`;只有 `completed` 才展示“同步:已完成”。 - Dify 返回 `error/failed` 或 60 秒内未完成索引时,同步任务、同步记录和文档卡片会显示失败原因;再次同步会重新提交失败文档。 - 管理端“知识库配置 → Dify 设置”支持配置新建 Dataset 的默认检索模型(检索方式、重排序、Top K、相似度阈值开关及阈值),以及文档同步的自定义分段参数(最大 Token 数、重叠 Token 数);保存仅更新 HXOPS 运行时配置,不自动回写已创建的 Dify Dataset。 @@ -93,6 +97,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 业务指纹/重复决策、修订版本链、强制新建权限与审计;见技术手册第三节摘要 | @@ -114,7 +119,7 @@ | EML 正文补充表合并(阶段 2) | 已实现 | 正文 HTML 表解析为带 DOM 单元格证据的 PO 级补充事实,不创建独立订单或执行 Unit;按 `PO + MPN`、受限 PO 降级补 Reservation/Allocation/库存来源提示,支持 `External reservation ID` 等冻结 Schema 显式别名;每个 Run 从原始 HTML 重建,避免旧的部分解析结果遮蔽新规则;PDF 数量保持权威,歧义统一进入人工复核 | | PDF 模板 PO 拆分与严格拒识(阶段 3) | 已实现 | 已批准模板中每条明细均有唯一 PO 证据时,单 PDF 自动拆为多个独立订单;表级多 PO 未能归属明细、模板歧义、漂移和证据不足统一转人工复核,Route Decision 分别审计四类表计数 | | 订单模板版本中心(阶段 0-7) | 已实现 | 订单文档模板按 `profile_code` 聚合版本族;已落地独立版本详情、历史只读样本画布、服务端语义差异、审计记录页签、实际使用页签,以及阶段 7 的 blind test 隔离与发布治理;只读画布完整展示必需锚点及各受控标签区域的冻结识别值,必需锚点可对照配置值、识别值和匹配状态;标注取字、运行匹配与版本诊断统一按视觉行恢复字符阅读顺序;标注 Reservation ID 专区的模板跨页以 `Vendor Comments` 至首次 `Terms and Condition(s)` 作为语义边界读取预约单号,未标注模板保持原解析路径 | -| **订单模板版面签名 Matcher** | 代码已落地(待真实样本灰度) | 版面签名存 ValidationRun;Profile 轻量引用;Matcher 三态证据 + Top-N 解析验证;表头签名直接消费既有 `header_layout.region`,签名生成与运行时统一视觉词组和坐标口径;跨模板发布门禁与发布检查页;重识别亲和性校验签名;`SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED` 控制全量切换。说明:[order-profile-layout-signature.md](features/shipping-notice/order-profile-layout-signature.md) | +| **订单模板版面签名 Matcher** | 代码已落地(待真实样本灰度) | 版面签名存 ValidationRun;Profile 轻量引用;Matcher 三态证据 + Top-N 解析验证;表头签名直接消费既有 `header_layout.region`,签名生成与运行时统一视觉词组和坐标口径;跨模板发布门禁与发布检查页;重识别亲和性校验签名;表头身份原子按 Run 冻结 Schema 别名归一,同字段同义列名(如 Requested Arrival/Ship Date)不再触发表头硬互斥;`SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED` 控制全量切换。说明:[order-profile-layout-signature.md](features/shipping-notice/order-profile-layout-signature.md) | | **XFA 数据路径 Profile(统一回退)** | 代码收口(2026-08-18) | datasets + 拆分规则为首选;失败进入普通 PDF 共用 PDFium/Widget/OCR 证据链,保留 `fallback_from`、原因码与 `value_source`,回退候选固定 Review、禁止 STP;Dify 主链:**NONE**。 | | **XFA 统一视觉标注 + 字段拆分** | 统一入口已收口 | 普通 PDF/XFA 共用 Editor、`/pdf-automark` Job、保存、验证和发布 DTO;`value_binding` + `visual_binding`、RE2、统一 CQ/STP;XFA 仅在首选 datasets 取值与拆分规则上保留适配器差异。 | | **XFA 可见值回读补偿** | 已实现(2026-08-25) | 编辑器在原生坐标、服务端 OCR 与唯一 Widget 无值后,OCR 同一 PDF.js XFA 画布的受控裁剪图(`xfa_rendered_ocr`);仍无值保留值框并提示诊断,可继续绑定 datasets。裁剪图不持久化,datasets 仍为唯一正式值源。 | @@ -179,6 +184,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` 通过。 | diff --git a/docs/superpowers/plans/2026-09-16-my-tasks-redesign.md b/docs/superpowers/plans/2026-09-16-my-tasks-redesign.md new file mode 100644 index 00000000..74e89397 --- /dev/null +++ b/docs/superpowers/plans/2026-09-16-my-tasks-redesign.md @@ -0,0 +1,89 @@ +# 实施计划:我的待办改版(列表优先 + 按需抽屉 + 已完成明细报表) + +日期:2026-09-16 分支:`hugo-shipping-notice` 设计稿:`docs/superpowers/prototypes/2026-09-16-my-tasks-redesign.html` + +## 背景与目标 + +货代发货通知「我的待办」页(`/workspace/shipping-notice/my-tasks`)当前为「卡片列表 + 常驻右侧详情」布局,存在:列表卡片过重、详情面板信息重复低价值、阶段卡片只统计当前页失真、批量工具栏常驻且 i18n key 缺失显示原始 key 等问题。本次改版目标: + +1. 列表改为紧凑表格 + 按需抽屉(待处理/处理中/驳回作废); +2. 阶段筛选收敛为 4 个可动作阶段,计数后端全量聚合; +3. 「已完成」桶拆子视图:通知完成 = 明细平铺报表(可筛选、按明细行分页、导出 Excel);复核驳回/已作废 = OT 级列表 + 抽屉; +4. 批量操作改为情境式浮动条(仅货代上传阶段、勾选后出现); +5. 顺带修复 batch i18n key 错位。 + +## 已确认的设计决策 + +- 待处理列表:紧凑表格行 = [复选框(仅货代上传)] 编号+类别角标+副行(客户·PO·文件) / 阶段徽章 / 状态摘要(阻断红色) / 项次·缺口 / 货代状态;点行开抽屉。 +- 阶段 tab:`全部 | 接收解析 | 订单复核 | 通知准备 | 货代上传`,计数来自后端聚合(待处理桶),点击即筛选。 +- 抽屉:头部(编号/客户/PO/阶段/阻断) + 逐行明细(notice_line_summary 全量列) + 文件区 + 底部操作(沿用 ui_state 权限裁决;review/intake 分支迁入)。 +- 已完成桶子视图 tab:`通知完成(N) | 复核驳回/已作废(M)`。 +- 通知完成报表:明细行平铺不按 OT 聚合;页面首列 OT 编号;列 = OT编号 + 标准12字段(客户/客户编号/订单日期/订单项次/料号/数量/约定出货日期/客户PO/已用数量/open qty/订单单号/单价);筛选 = 客户 + 料号 + 发货通知日期范围;按明细行分页。 +- 导出 Excel:**严格 12 列**(不带 OT 列),专用平铺导出器(不注册模板、不走 per-Notice 模板机制);已用数量/open qty 暂留空。 +- 字段映射:约定出货日期→`required_date`;订单单号→`source_order_number`;单价→`unit_price`(Schema 未启用则为空);料号→`part_number`。 +- 批量:无常驻工具栏;货代上传行有复选框,勾选≥1 浮出深色操作条(下载 Excel/确认上传/发起 RPA),全选仅作用当前筛选结果。 +- 无数据库结构变更、无迁移、无新增依赖。 + +## 任务清单(TDD,顺序执行) + +### T1 后端:count 接口扩展(阶段聚合 + 已完成子计数) +- `query_service.count_my_todos` 返回结构增加: + - `stage_counts: {intake_parse, order_review, fulfillment_prep, freight_upload}`(待处理桶按生命周期阶段聚合,复用既有 lifecycle stage SQL/投影口径); + - `done_counts: {upload_complete, reject_or_void}`(done 桶:已核验上传成功 vs 复核驳回∪作废/归档)。 +- API `GET /shipping-tasks/my-todos/count`(`api/workspace/shipping_notice.py`)透传新字段;保持既有 key(pending/processing/done/total_pending_badge)不变。 +- 测试:`backend/tests/` 新增/扩展 count 聚合用例(覆盖四阶段计数与 done 两种终态归类)。 +- 验证:`pytest` 相关用例绿。 + +### T2 后端:my-todos 列表支持终态过滤参数 +- `list_my_todos` 增加可选参数 `terminal_kind`(仅 bucket=done 时生效):`upload_complete` → 仅已核验上传成功;`reject_void` → 仅 复核驳回 ∪ 作废/归档。 +- 测试:参数过滤用例。 +- 验证:`pytest` 绿。 + +### T3 后端:已完成明细行级查询接口 +- 新增 service 查询(query_service 或独立模块):跨已完成 Notice 平铺行明细,join 冻结 ShippingOrderSnapshot 行字段。 +- 返回行字段:`task_no(OT编号), customer_name, customer_code, order_date, line_no, part_number, qty, required_date, customer_po_number, used_qty(None), open_qty(None), source_order_number, unit_price`。 +- 筛选:`customer`(名称/简码模糊)、`part_number`(模糊)、`notice_date_from/to`(发货通知日期=Notice 创建日期范围);`page/page_size`(默认 20,上限 100)+ `total`。 +- API:`GET /api/workspace/shipping-tasks/my-todos/done-lines`。 +- 测试:行字段映射(含字段缺失留空)、筛选、分页用例。 +- 验证:`pytest` 绿。 + +### T4 后端:专用平铺导出器(12 列 xlsx) +- 新增导出函数:同 T3 查询(不分页,行数上限 10000 防护),固定写 12 列中文表头,OT 不落列;openpyxl 沿用项目内既有用法。 +- API:`GET /api/workspace/shipping-tasks/my-todos/done-lines/export`(同筛选参数,流式返回 xlsx)。 +- 测试:生成的 workbook 表头/行值/空值断言。 +- 验证:`pytest` 绿。 + +### T5 前端:API 层与类型 +- `features/workspace/api/shipping-tasks.api.ts`:count 返回类型扩展 + done-lines 查询 + 导出下载(复用既有下载工具)。 +- `features/chat/types/shipping.api.types.ts`:新增行明细类型 `ShippingDoneLineItem` 等。 +- 验证:`npm run build` 通过(类型层面)。 + +### T6 前端:主页面拆分重构(列表态/抽屉态/批量浮动条) +- 新组件(`features/workspace/shipping-task-center/`): + - `ShippingStageTabs.vue`:阶段 tab(后端计数、点击筛选); + - `ShippingTaskTable.vue`:紧凑表格行 + 复选框列(仅货代上传)+ 批量浮动条插槽; + - `ShippingTaskDrawer.vue`:抽屉(task/review/intake 三分支 + 文件区 + 操作区,迁移自现页面 1086-1273 行逻辑)。 +- `ShippingTaskCenterPage.vue`:移除右侧常驻详情与五张阶段卡片;接入新组件;保留桶切换、筛选、分页、轮询(`shippingTaskCenterPolling` 不动)。 +- 测试:更新 `ShippingTaskCenterPage.notice-batch.spec.ts`(浮动条出现条件、仅货代上传可勾选)+ 新增抽屉渲染测试。 +- 验证:`npm run test` 相关用例绿;`npm run build` 通过。 + +### T7 前端:已完成桶子视图与明细报表 +- 新组件 `ShippingDoneLineReport.vue`:子视图 tab(通知完成/复核驳回·已作废,计数来自 T1); + - 通知完成:13 列表格(OT编号+12字段,横向滚动)+ 客户/料号/发货通知日期筛选 + 按行分页 + 导出按钮(T4 接口); + - 复核驳回/已作废:走既有任务列表(T2 参数)+ 抽屉。 +- 验证:`npm run test` + `npm run build`。 + +### T8 i18n 四语言 +- 修复:`schedule.batch.*` 12 个 key 复制/迁移到各语言 `workspace.json` 的 `shippingNotice.batch`(zh-TW/th 当前整块缺失,按 zh-CN 补齐翻译)。 +- 新增:阶段 tab、抽屉、报表列头、筛选、终态角标、导出等文案,zh-CN/zh-TW/en/th 四语言同步。 +- 验证:脚本断言四语言 key 集合一致;页面无裸 key。 + +### T9 回归与收尾 +- 后端:`pytest backend/tests` 全量相关目录通过。 +- 前端:`npm run test`、`npm run build` 通过。 +- 文档:`docs/features/shipping-notice/technical.md` 增补改版说明;`funclist.md` 若涉及功能条目变化则同步。 +- 提交拆分:后端(T1-T4)、前端(T5-T7)、i18n(T8)、文档(T9) 分开提交,遵循 Conventional Commits。 + +## 明确不做 + +- 虚拟滚动 / 服务端排序 / 保存视图 / 列自定义 / 看板;数据库迁移;新增第三方依赖;通知完成报表行点击行为(后续增量);已用数量、open qty 数据源接入。 diff --git a/docs/superpowers/plans/2026-09-16-order-profile-header-alias-canonicalization.md b/docs/superpowers/plans/2026-09-16-order-profile-header-alias-canonicalization.md new file mode 100644 index 00000000..c56b7ba6 --- /dev/null +++ b/docs/superpowers/plans/2026-09-16-order-profile-header-alias-canonicalization.md @@ -0,0 +1,69 @@ +# 计划:订单模板表头身份原子按 Schema 别名归一(契约层) + +> 状态:已确认(2026-09-16,会话内评审)。执行方式:subagent-driven-development。 +> 背景:PO_6075316.pdf 因日期列名 `Requested Ship Date`(训练样本为 `Requested Arrival Date`) +> 触发 `profile_header_discriminator_conflict`,11 模板全 0 分,layout_drift 转人工空单。 +> 契约层方案:表头身份原子比较前按冻结 Schema 的字段别名归一为字段语义类; +> 原子集全等硬门禁与近亲模板互斥语义**不变**;复用现有别名机制,不新造轮子。 + +## Global Constraints(全局约束,评审时的注意力透镜) + +1. 硬门禁不弱化:归一后仍要求原子集**全等**;不同字段类、Schema 外新词照样冲突。 +2. `header_to_field=None` 的所有路径行为与现状完全一致(向后兼容,已发布签名不重冻结)。 +3. 同义词唯一治理来源 = Schema `fields[].aliases`;matcher 不新增同义词表/配置面。 +4. 纯后端改动;不引入新第三方依赖;新函数/文件须满足 AGENTS §5 三层注释。 +5. 全程不 commit(用户规则);测试环境 Schema v4 **原位**补别名、不升版(用户确认)。 +6. 已确认:`Requested Ship Date` 归 `requested_receipt_date`。 + +## Task 1:核心纯函数 + 单测(文件 `backend/app/services/shipping_notice/document_layout/order_profile_matcher.py`) + +- 新增模块级常量 `_HEADER_FIELD_MARKER = 'field::'`(标记原子前缀;词级原子不可能含冒号,无碰撞)。 +- 新增 `schema_canonical_header_atoms(tokens: list[str], header_to_field: dict[str, str] | None) -> frozenset[str]`: + - `header_to_field` 为 `TableHeaderContract.header_to_field`(普通 dict,鸭子类型,不引入 order_schema→matcher 反向依赖); + - **None 时直接返回 `_header_token_atoms(tokens)`**(零行为变化); + - 短语字典:对每个 alias key 先 `_HEADER_PAREN_GLOSS` 剥注记 → casefold → 按 `[^a-z0-9]+` 切词元组;**casefold 后跨字段碰撞的短语弃用**(身份归属不允许歧义); + - 每个 token:空串跳过(吸收 MinerU 空格);同一词管线(剥注记/casefold/切词)后,**贪心最长短语匹配**(命中 → `_HEADER_FIELD_MARKER + field_code` 原子);未命中的剩余词沿用既有规则(≥`_HEADER_ATOM_MIN_LEN`、非 `_HEADER_ATOM_STOPWORDS`); + - 中文别名经 `[^a-z0-9]+` 切词后为空 → 自然跳过(与词级原子只保留 `[a-z0-9]` 的现状一致),docstring 注明。 +- 单测(新文件 `backend/tests/test_order_profile_header_identity.py`,pure_unit): + 精确命中 / 合并格贪心分解(`requested ship date unit price` → 两个 field 标记)/ 大小写不敏感 / + 未命中词保留原词(含过短词过滤)/ 空串跳过 / casefold 碰撞短语弃用 / None 兼容。 +- Verify:`pytest tests/test_order_profile_header_identity.py -q` 全绿。 + +## Task 2:matcher 接线(同文件三层透传) + +- `_header_discriminator_atoms_conflict(..., header_to_field: dict[str, str] | None = None)`:非 None 时两侧均用 Task 1 函数归一后比较;None 走现行为。 +- `_compute_dimension_results(..., header_to_field=None)` 透传(唯一调用点在 `match_frozen_coordinate_profiles` 主循环)。 +- `match_frozen_coordinate_profiles(..., header_to_field=None)` 透传 + docstring 同步。 +- Verify:matcher 既有测试套件全绿(执行时 `grep -rl match_frozen_coordinate_profiles tests/` 定位)。 + +## Task 3:调用点传入契约(5 处,与 Task 2 同一派发批次) + +- `order_extraction_workflow.py` 主路由匹配处(约 :1075):传 `contract.header_to_field`(contract 已在作用域)。 +- `order_extraction_workflow.py` `_apply_reparse_profile_affinity` 内复验调用(约 :1546):先由 `run.input_snapshot_json` 冻结 definition 编译 `compile_table_header_contract` 再传入。 +- `order_extraction_workflow.py` `_confirmed_profile_order_fields`(约 :2570):同上,definition 已在作用域。 +- `order_document_profile_validation_service.py` 两处(约 :1246、:1299):从 `profile.schema_version.definition_json`(已在作用域)编译传入——满足"正式/验证/盲测同契约"。 +- Verify:`test_shipping_xfa_formal_extraction_route / test_shipping_order_extraction_worker / test_shipping_order_extraction_runs / test_shipping_document_profile_quality / test_order_document_profile_preview_service / test_order_extraction_pdf_po_split / test_shipping_notice_reservation_id` 全绿。 + +## Task 4:回归测试(新) + +- matcher 级(放入 Task 1 测试文件):PO_6075316 形状观测 `['LN','Quantity','Part Number Vendor Item#','Description','Requested Ship Date Unit Price','','Extension']` vs 签名 token(`Requested Arrival Date` 版)——传契约不冲突;不传冲突;换真正异义词(如 `Customer PO Date` 未配别名)仍冲突。 +- 路由级合成用例:最小 frozen profile + layout 重放 `match_frozen_coordinate_profiles`,断言不再因 discriminator 拒绝(参考 tests/ 内既有 matcher 测试的构造方式)。 +- Verify:新旧用例全绿。 + +## Task 5:真实数据回归矩阵(离线重放,测试库 192.168.100.192/hxops_testing) + +- T5.1 run 317(`SNER-20260916-C2AF1BF3`)冻结快照 + doc 879(PO_6075316)layout:向冻结 definition 注入 `Requested Ship Date` 别名(模拟治理后)→ 期望 HYVE 不再 `profile_header_discriminator_conflict`、score>0(理想 unique_match)。 +- T5.2 对照:不注入别名(=当前线上态)→ 仍 conflict(证明效果来自别名契约而非代码放水)。 +- T5.3 **全文档×全模板无翻转**:对 run 317 快照内全部文档,三种配置重放 `(i) 旧行为(header_to_field=None)`、`(ii) 新逻辑+现网 v4 别名`、`(iii) 新逻辑+注入别名`;断言 (ii)≡(i) 全部一致、(iii) 仅 879 变化其余全部一致。 +- T5.4 **模板自样本回归**:对每个已发布模板的 training/annotation 样本(layout_version_id 从 `shipping_order_document_profile_samples` 取,含坐标证据资产回填),新逻辑下各模板仍唯一自匹配。 +- Verify:输出留档 `.zcode/header_alias_replay/`。 + +## Task 6:Schema v4 原位补别名(测试库,用户已授权)+ 文档 + +- 控制器亲自执行:UPDATE `shipping_order_schema_versions`(version id=4)`definition_json` 中 `requested_receipt_date`(field_id `dfa4544a-b789-478e-ba1a-d19725817ac2`)的 aliases 追加 `'Requested Ship Date'`;改前备份原 JSON 到工作区,改后回读验证;同事务检查有无 checksum 列需同步(执行时核实)。 +- `docs/features/shipping-notice/technical.md`:补 2026-09-16 契约注记(身份原子按冻结 Schema 别名归一;别名是同义词唯一治理入口;硬互斥不变;v4 原位修订记录)。 +- `docs/funclist.md`:若存在模板匹配相关条目则补一句(执行时检查)。 + +## Task 7:收尾 + +全量相关测试套件;汇总验证输出;不 commit。 diff --git a/docs/superpowers/plans/2026-09-16-review-queue-icon-semantics.md b/docs/superpowers/plans/2026-09-16-review-queue-icon-semantics.md new file mode 100644 index 00000000..c6fa3019 --- /dev/null +++ b/docs/superpowers/plans/2026-09-16-review-queue-icon-semantics.md @@ -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 ` + + diff --git a/frontend/src/features/workspace/shipping-task-center/ShippingStageTabs.vue b/frontend/src/features/workspace/shipping-task-center/ShippingStageTabs.vue new file mode 100644 index 00000000..f8d48170 --- /dev/null +++ b/frontend/src/features/workspace/shipping-task-center/ShippingStageTabs.vue @@ -0,0 +1,63 @@ + + + + diff --git a/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts b/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts index 683a0f9d..2ed380fd 100644 --- a/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts +++ b/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts @@ -1,8 +1,10 @@ /** * features/workspace/shipping-task-center/ShippingTaskCenterPage.notice-batch.spec.ts - * 用途:验收任务中心只按发货通知单 business_no 展示与执行货代批量操作。 + * 用途:验收任务中心改版——紧凑表格、货代上传阶段限定批量、阶段 tab 后端计数、 + * done 桶子视图(通知完成明细报表 / 驳回作废任务表)与详情抽屉。 * 依赖:ShippingTaskCenterPage、货代 API、我的待办 API、Vue Test Utils。 - * 逻辑:正式 Notice 可选择并传 business_nos;Review/Intake 不能进入选择集;列表行只显示服务端投影的通知明细。 + * 逻辑:批量仅正式 Notice 且货代上传阶段可选;明细行详情进抽屉(Teleport 到 body); + * 通知完成子视图消费 done-lines 平铺报表;驳回作废子视图带 terminal_kind 过滤。 */ import { afterEach, describe, expect, it, vi } from 'vitest'; import { flushPromises, mount } from '@vue/test-utils'; @@ -14,6 +16,11 @@ const batchConfirm = vi.fn(async () => ({ results: [{ status: 'confirmed' }] })) const batchRpa = vi.fn(async () => ({ results: [{ status: 'accepted' }] })); const downloadArchive = vi.fn(async () => undefined); const listTodos = vi.fn(async () => ({ items: [], page: 1, page_size: 20, total: 0 })); +const listDoneLines = vi.fn(async () => ({ items: [], page: 1, page_size: 50, total: 0 })); +const downloadDoneLinesExcel = vi.fn(async () => undefined); +const countTodos = vi.fn(async () => ({ + pending: 0, processing: 0, done: 0, total_pending_badge: 0, +})); vi.mock('@/features/chat/api/shipping.api', () => ({ SHIPPING_NOTICE_AGENT_CODE: 'shipping_notice', @@ -26,7 +33,9 @@ vi.mock('@/features/chat/api/shipping.api', () => ({ vi.mock('@/features/workspace/api/shipping-tasks.api', () => ({ listWorkspaceShippingMyTodos: (...args: unknown[]) => listTodos(...args), - countWorkspaceShippingMyTodos: vi.fn(async () => ({ pending: 0, processing: 0, done: 0, total_pending_badge: 0 })), + countWorkspaceShippingMyTodos: (...args: unknown[]) => countTodos(...args), + listWorkspaceShippingDoneLines: (...args: unknown[]) => listDoneLines(...args), + downloadWorkspaceShippingDoneLinesExcel: (...args: unknown[]) => downloadDoneLinesExcel(...args), })); vi.mock('@/features/workspace/composables/useShippingTodoBadge', () => ({ @@ -53,6 +62,7 @@ const i18n = createI18n({ subtitle: '按文件查看进度', lifecycleStages: { filterLabel: '阶段', + viewStage: '查看阶段', intake_parse: '接收解析', order_review: '订单复核', fulfillment_prep: '通知准备', @@ -60,6 +70,12 @@ const i18n = createI18n({ upload_complete: '通知完成', }, buckets: { pending: '待处理', processing: '处理中', done: '已完成' }, + subTabs: { uploadComplete: '通知完成', rejectVoid: '复核驳回 / 已作废' }, + table: { + no: '编号', stage: '阶段', summary: '状态摘要', lines: '项次', + lineUnit: '项', shortage: '缺 {count}', freightStatus: '货代状态', + }, + terminal: { uploadComplete: '上传完成', rejectVoid: '复核驳回' }, filters: { todoCategory: '待办类型', all: '全部', review: '待复核', exception: '异常', manualUpload: '人工上传', intakeParse: '接收解析', customer: '客户', @@ -75,9 +91,44 @@ const i18n = createI18n({ intakeParseBadge: '材料解析', progressSummary: '当前阶段:{stage}', progressBlocker: '当前阻断:{reason}', - viewStage: '查看阶段', + drawer: { + details: '逐行明细', + files: '文件', + close: '关闭', + exportExcel: '导出 Excel', + lineTable: { + lineNo: '行', partNumber: '料号', customerPartNumber: '客户料号', + reservationId: '预约号', shipmentQty: '本次发货', availableQty: '可用库存', + shortageQty: '缺口', status: '状态', + }, + }, + doneReport: { + export: '导出 Excel(当前筛选)', + exportStarted: '已开始下载', + filters: { customer: '客户', partNumber: '料号', dateFrom: '通知日期起', dateTo: '通知日期止' }, + columns: { + taskNo: 'OT 编号', customer: '客户', customerCode: '客户编号', orderDate: '订单日期', + lineNo: '订单项次', partNumber: '料号', qty: '数量', requiredDate: '约定出货日期', + customerPo: '客户PO', usedQty: '已用数量', openQty: 'open qty', + sourceOrderNo: '订单单号', unitPrice: '单价', + }, + }, }, openChat: '打开对话', + batch: { + selectAll: '全选当前页通知单', + selected: '已选 {count} 张', + download: '批量下载 Excel', + confirm: '批量确认已上传', + rpa: '批量发起 RPA', + clearSelection: '清除选择', + downloadStarted: '已开始下载', + success: '成功 {count} 张', + partialResult: '部分成功 {accepted}/{accepted}/{blocked}', + }, + todo: { adminViewOnlyShort: '只读' }, + actions: { failed: '操作失败' }, + pagination: { previous: '上一页', next: '下一页' }, }, }, }, @@ -90,12 +141,17 @@ const routes = [{ component: ShippingTaskCenterPage, }]; +/** 待处理货代上传阶段 Notice:批量可选 + 列表投影。 */ function notice(businessNo: string, poNumber: string, partNumber: string) { return { id: Number(businessNo.slice(-2)), task_no: `SN-${businessNo}`, business_no: businessNo, item_kind: 'task', todo_ref: `SN-${businessNo}`, source_type: 'post_ot_fulfillment_wave', po_number: poNumber, customer_name: 'Customer', upload_status: 'pending', - notice_line_summary: [{ line_no: '10', part_number: partNumber, shipment_qty: '4', available_qty: '9' }], + ui_state: { stage: { code: 'freight_upload', label: '货代上传' }, lifecycle_entries: [] }, + notice_line_summary: [ + { line_no: '10', part_number: partNumber, shipment_qty: '4', available_qty: '9' }, + { line_no: '20', part_number: `${partNumber}-B`, shipment_qty: '2', available_qty: '9', shortage_qty: 1 }, + ], artifact_summary: { export_file_name: `${businessNo}.xlsx` }, }; } @@ -115,12 +171,17 @@ async function mountPage() { }); } +function drawerText(): string { + return document.body.querySelector('[data-testid="my-todos-drawer"]')?.textContent || ''; +} + describe('ShippingTaskCenterPage notice batch operations', () => { afterEach(() => { vi.clearAllMocks(); + document.body.innerHTML = ''; }); - it('only makes formal Notices selectable and displays each Notice projection', async () => { + it('only makes freight-upload Notices selectable and shows line details in drawer', async () => { listTodos.mockResolvedValueOnce({ items: [ notice('WYC26082301', 'PO-100', 'PART-A'), @@ -132,13 +193,20 @@ describe('ShippingTaskCenterPage notice batch operations', () => { const wrapper = await mountPage(); await flushPromises(); + // 断言:货代上传阶段 Notice 可勾选;Review/Intake 行无复选框。 expect(wrapper.get('[aria-label="WYC26082301"]').exists()).toBe(true); expect(wrapper.get('[aria-label="WYC26082302"]').exists()).toBe(true); expect(wrapper.find('[aria-label="SNRC-30"]').exists()).toBe(false); + // 断言:表格副行展示 客户 · PO · 文件。 expect(wrapper.text()).toContain('PO-100'); - expect(wrapper.text()).toContain('PART-A'); - expect(wrapper.text()).toContain('PART-B'); expect(wrapper.text()).toContain('WYC26082301.xlsx'); + // 断言:点行打开抽屉,逐行明细承载料号(列表不再堆明细)。 + await wrapper.get('[data-testid="my-todos-row-WYC26082301"]').trigger('click'); + await flushPromises(); + expect(document.body.querySelector('[data-testid="my-todos-drawer"]')).not.toBeNull(); + const drawer = drawerText(); + expect(drawer).toContain('PART-A'); + expect(drawer).toContain('PART-A-B'); wrapper.unmount(); }); @@ -152,53 +220,106 @@ describe('ShippingTaskCenterPage notice batch operations', () => { await wrapper.get('[aria-label="WYC26082301"]').setValue(true); await wrapper.get('[aria-label="WYC26082302"]').setValue(true); - const toolbar = wrapper.get('[data-testid="shipping-notice-batch-toolbar"]'); - const buttons = toolbar.findAll('button'); + // 断言:勾选后浮出操作条,三个动作按序对应 download/confirm/rpa。 + // 每次 action 后列表会静默重载(表格重挂载),因此逐次重新查询按钮。 + const toolbarButtons = () => wrapper + .get('[data-testid="shipping-notice-batch-toolbar"]') + .findAll('button'); + const buttons = toolbarButtons(); + expect(buttons.length).toBeGreaterThanOrEqual(3); await buttons[0].trigger('click'); expect(downloadArchive).toHaveBeenCalledWith(['WYC26082301', 'WYC26082302']); - await buttons[1].trigger('click'); + await flushPromises(); + await toolbarButtons()[1].trigger('click'); await flushPromises(); expect(batchConfirm).toHaveBeenCalledWith(['WYC26082301', 'WYC26082302']); - await buttons[2].trigger('click'); + await toolbarButtons()[2].trigger('click'); await flushPromises(); expect(batchRpa).toHaveBeenCalledWith(['WYC26082301', 'WYC26082302']); wrapper.unmount(); }); - it('keeps all five lifecycle stage filters on one wide-screen row', async () => { + it('renders one row of stage tabs covering all plus four actionable stages', async () => { const wrapper = await mountPage(); await flushPromises(); const track = wrapper.get('[data-testid="my-todos-lifecycle-stage-filter"]'); - expect(track.classes()).toContain('xl:grid-cols-5'); + // 断言:全部 + 四个可动作阶段;「通知完成」不再是筛选维度。 expect(track.findAll('button')).toHaveLength(5); expect(track.text()).toContain('货代上传'); + expect(track.text()).not.toContain('通知完成'); expect(track.text()).not.toContain('workspace.shippingNotice.myTodos.lifecycleStages.freight_upload'); wrapper.unmount(); }); - it('counts a pending review item from its backend stage even without an enterable lifecycle entry', async () => { - listTodos.mockResolvedValueOnce({ - items: [{ - item_kind: 'review_case', - task_no: '', - review_run_no: 'RUN-1', - review_case_no: 'CASE-1', - ui_state: { - stage: { code: 'order_review', label: '订单复核', index: 2, total: 5 }, - lifecycle_entries: [], - }, - }], - page: 1, - page_size: 20, - total: 1, + it('shows backend aggregated stage counts instead of current-page counting', async () => { + countTodos.mockResolvedValueOnce({ + pending: 13, processing: 0, done: 0, total_pending_badge: 13, + stage_counts: { intake_parse: 2, order_review: 4, fulfillment_prep: 3, freight_upload: 4 }, + done_counts: { upload_complete: 0, reject_void: 0 }, }); + listTodos.mockResolvedValueOnce({ items: [], page: 1, page_size: 20, total: 0 }); const wrapper = await mountPage(); await flushPromises(); - expect(wrapper.get('[data-testid="my-todos-stage-filter-order_review"]').text()).toContain('1'); + // 断言:阶段计数来自后端聚合(当前页为空列表也显示全量计数)。 + expect(wrapper.get('[data-testid="my-todos-stage-filter-order_review"]').text()).toContain('4'); + expect(wrapper.get('[data-testid="my-todos-stage-filter-fulfillment_prep"]').text()).toContain('3'); + wrapper.unmount(); + }); + + it('defaults done bucket to the flat done-lines report and exports current filters', async () => { + listDoneLines.mockResolvedValue({ + items: [{ + task_no: 'SN-DONE-1', business_no: 'BIZ-1', customer_name: 'HYVE CS', customer_code: 'HC001', + order_date: '2026-06-01', line_no: 1, part_number: 'B3-A08AR1', qty: 80, + required_date: '2026-06-15', customer_po_number: '306085', used_qty: null, + open_qty: null, source_order_number: '8301-1', unit_price: 1525.08, + }], + page: 1, page_size: 50, total: 1, + }); + const wrapper = await mountPage(); + await flushPromises(); + await wrapper.get('[data-testid="my-todos-bucket-done"]').trigger('click'); + await flushPromises(); + + // 断言:done 桶默认进入通知完成明细报表,消费 done-lines 接口。 + expect(listDoneLines).toHaveBeenCalled(); + const table = wrapper.get('[data-testid="done-lines-table"]'); + expect(table.text()).toContain('B3-A08AR1'); + expect(table.text()).toContain('8301-1'); + // 断言:导出按钮把当前筛选交给受控下载。 + await wrapper.get('[data-testid="done-lines-export"]').trigger('click'); + await flushPromises(); + expect(downloadDoneLinesExcel).toHaveBeenCalled(); + wrapper.unmount(); + }); + + it('loads reject_void sub tab with terminal_kind filter and badges rows', async () => { + listTodos.mockResolvedValue({ + items: [{ + id: 41, task_no: 'SN-REJ-1', business_no: 'BIZ-R1', item_kind: 'task', + todo_ref: 'SN-REJ-1', todo_category: 'done', + ui_state: { stage: { code: 'upload_complete', label: '通知完成' }, lifecycle_entries: [] }, + }], + page: 1, page_size: 20, total: 1, + }); + const wrapper = await mountPage(); + await flushPromises(); + await wrapper.get('[data-testid="my-todos-bucket-done"]').trigger('click'); + await flushPromises(); + const subtabs = wrapper.findAll('[data-testid="my-todos-done-subtabs"] button'); + await subtabs[1].trigger('click'); + await flushPromises(); + + // 断言:驳回/作废子视图按 terminal_kind 拉任务表,行带终态角标。 + expect(listTodos).toHaveBeenCalledWith(expect.objectContaining({ + bucket: 'done', + terminal_kind: 'reject_void', + })); + expect(wrapper.get('[data-testid="my-todos-row-BIZ-R1"]').text()).toContain('复核驳回'); wrapper.unmount(); }); }); diff --git a/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.vue b/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.vue index 2bb66024..86ceccde 100644 --- a/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.vue +++ b/frontend/src/features/workspace/shipping-task-center/ShippingTaskCenterPage.vue @@ -1,17 +1,19 @@ -/** - * features/workspace/shipping-task-center/ShippingTaskCenterPage.vue - * 用途:发货「任务中心」壳——Pending|Processing|Done + 识别 Run 续办表;列表入口 + STP 重试。 - * 依赖:shipping-tasks.api(my-todos)、shipping.api(详情/STP retry)、ShippingRunProgressTable、 - * useShippingTodoBadge、useMessage、shippingProcessingLabels。 - * 逻辑:选中项展示入口卡 + 五阶段筛选 + 统一进度紧凑摘要;主按钮深链「订单生命周期工作台」; - * review_case 在 failed/manual_fallback 时提供「重试自动推进」(与底栏同一 API/幂等键); - * 不内嵌 ShippingTaskWorkbench;生命周期筛选、禁用与深链只消费后端 - * ui_state.lifecycle_entries;轮询只跟系统 running,silent 刷新不闪加载。 - */ + + + diff --git a/frontend/src/features/workspace/shipping-task-center/ShippingTaskTable.vue b/frontend/src/features/workspace/shipping-task-center/ShippingTaskTable.vue new file mode 100644 index 00000000..187be00c --- /dev/null +++ b/frontend/src/features/workspace/shipping-task-center/ShippingTaskTable.vue @@ -0,0 +1,240 @@ + + + + diff --git a/frontend/src/features/workspace/shipping-task-center/shippingTaskCenterShared.ts b/frontend/src/features/workspace/shipping-task-center/shippingTaskCenterShared.ts new file mode 100644 index 00000000..031931a5 --- /dev/null +++ b/frontend/src/features/workspace/shipping-task-center/shippingTaskCenterShared.ts @@ -0,0 +1,174 @@ +/** + * features/workspace/shipping-task-center/shippingTaskCenterShared.ts + * 用途:任务中心列表 / 表格 / 抽屉共用的纯函数与类型(阶段口径、编号、选择)。 + * 依赖:chat shipping.api 类型、gateReasonLabel。 + * 逻辑:阶段只消费后端 ui_state.lifecycle_entries / ui_state.stage(与页面同口径); + * 本模块不发起请求、不操作路由,供 TaskTable / Drawer / Page 复用。 + */ +import type { ShippingTaskDetail, ShippingTaskSummary } from '@/features/chat/api/shipping.api'; +import { resolveGateReasonLabel } from '@/features/shipping-progress/gateReasonLabel'; + +export type LifecycleStageCode = 'intake_parse' | 'order_review' | 'fulfillment_prep' + | 'freight_upload' | 'upload_complete'; + +/** 五阶段完整序列(抽屉阶段下拉消费后端 entries,仍需全集做过滤)。 */ +export const LIFECYCLE_STAGES: LifecycleStageCode[] = [ + 'intake_parse', + 'order_review', + 'fulfillment_prep', + 'freight_upload', + 'upload_complete', +]; + +/** 阶段筛选 tab 仅覆盖四个可动作阶段;「通知完成」归 done 桶终态。 */ +export const ACTIONABLE_TODO_STAGES: Exclude[] = [ + 'intake_parse', + 'order_review', + 'fulfillment_prep', + 'freight_upload', +]; + +export type TodoLike = ShippingTaskSummary | ShippingTaskDetail; + +/** + * 待办列表项稳定主键:复核用 case_no,Intake 用 intake_no,任务用 task_no。 + */ +export function todoItemKey(item: ShippingTaskSummary): string { + if (item.item_kind === 'review_case' || item.review_case_no) { + return String(item.todo_ref || item.review_case_no || item.review_run_no || ''); + } + if (item.item_kind === 'order_intake' || item.intake_no) { + return String(item.todo_ref || item.intake_no || ''); + } + return String(item.todo_ref || item.task_no || ''); +} + +/** + * 列表展示编号:复核显示 case_no,Intake 显示 intake_no,任务显示业务编号/SN。 + */ +export function todoDisplayNo(item: ShippingTaskSummary): string { + if (item.item_kind === 'review_case' || item.review_case_no) { + return String(item.review_case_no || item.review_run_no || item.todo_ref || '—'); + } + if (item.item_kind === 'order_intake' || item.intake_no) { + return String(item.intake_no || item.todo_ref || '—'); + } + return String(item.business_no || item.task_no || item.todo_ref || '—'); +} + +/** + * 读取后端已裁决的生命周期入口;缺失即无授权,绝不按 task/case/intake 身份补造入口。 + */ +export function lifecycleEntriesOf(item: TodoLike) { + const entries = item.ui_state?.lifecycle_entries; + if (!Array.isArray(entries)) return []; + return entries.filter((entry) => LIFECYCLE_STAGES.includes(entry.code as LifecycleStageCode)); +} + +/** 当前阶段只取后端标为 current 的入口,必要时回退 ui_state.stage(仅统计口径)。 */ +export function lifecycleStageCodeOf(item: TodoLike): LifecycleStageCode | null { + const current = lifecycleEntriesOf(item).find((entry) => entry.state === 'current'); + if (current) return current.code as LifecycleStageCode; + // [AUTHORITY] 待人工处理的 Review Case 可能没有可进入工作台的 lifecycle entry, + // 但后端仍会下发 ui_state.stage 作为当前业务阶段;统计与筛选必须保留该阶段。 + const stage = String(item.ui_state?.stage?.code || '').trim(); + return LIFECYCLE_STAGES.includes(stage as LifecycleStageCode) + ? stage as LifecycleStageCode + : null; +} + +/** 可进入工作台的业务阶段仅由后端 entry.state 授权。 */ +export function lifecycleEntryFor( + item: TodoLike, + stage: Exclude, +) { + return lifecycleEntriesOf(item).find((entry) => entry.code === stage) || null; +} + +/** 后端仅以 current / available 表示可进入工作台;未知状态一律拒绝深链。 */ +export function lifecycleEntryIsEnterable( + entry: ReturnType, +): boolean { + return entry?.state === 'current' || entry?.state === 'available'; +} + +/** 阶段目标下拉默认值:优先 current,其次 available。 */ +export function defaultLifecycleTarget( + item: TodoLike, +): Exclude | null { + const current = lifecycleEntriesOf(item).find( + (entry) => entry.code !== 'intake_parse' && entry.state === 'current', + ); + const available = lifecycleEntriesOf(item).find( + (entry) => entry.code !== 'intake_parse' && entry.state === 'available', + ); + return (current || available)?.code as Exclude | undefined || null; +} + +/** 接收解析入口只消费后端独立授权 + run/agent 前提,不从阶段名称推导可写权限。 */ +export function canOpenIntakeParse(item: TodoLike | null, chatAgentId: number | null): boolean { + if (!item) return false; + const runNo = String(item.review_run_no || '').trim(); + const agentId = Number(item.owner_agent_id || chatAgentId || 0); + return Boolean( + runNo + && agentId + && item.ui_state?.intake_parse_authorized === true, + ); +} + +/** + * 行状态摘要标题:后端待办标题优先,逐级回退到阶段标签。 + */ +export function todoTitleText(item: ShippingTaskSummary): string { + return String( + item.ui_state?.todo?.title + || item.ui_state?.summary?.current_todo + || item.ui_state?.summary?.title + || item.ui_state?.stage?.label + || '—', + ); +} + +/** + * 行阻断原因文本:优先后端 reason.message,其次 Gate 原因码的本地化标签。 + * 空串表示当前无阻断(调用方据此决定红色高亮)。 + */ +export function todoBlockerText( + item: TodoLike, + t: (key: string, named?: Record) => string, + te: (key: string) => boolean, +): string { + const reason = item.ui_state?.reason; + const text = String(reason?.message || '').trim(); + if (text) return text; + const code = String(reason?.code || '').trim(); + if (!code) return ''; + return resolveGateReasonLabel(code, { t, te }); +} + +/** 表格副行:客户 · PO · 源文件/导出文件,缺省段自动跳过。 */ +export function todoSubTitleText(item: ShippingTaskSummary): string { + const segments = [ + String(item.customer_name || '').trim(), + String(item.po_number || '').trim() ? `PO ${String(item.po_number).trim()}` : '', + String(item.source_file_name || '').trim() + || String(item.artifact_summary?.export_file_name || '').trim(), + ].filter(Boolean); + return segments.join(' · '); +} + +/** 项次/缺口摘要:total 项 + 缺 n(缺口>0 的行数)。 */ +export function todoLineBrief(item: ShippingTaskSummary): { total: number; shortage: number } { + const lines = Array.isArray(item.notice_line_summary) ? item.notice_line_summary : []; + const shortage = lines.filter((line) => Number(line.shortage_qty || 0) > 0).length; + return { total: lines.length, shortage }; +} + +/** + * 批量可选行:正式 Notice 且处于货代上传阶段(业务约束:批量操作仅该阶段可用)。 + */ +export function isFreightUploadRow(item: ShippingTaskSummary): boolean { + return Boolean(String(item.business_no || '').trim()) + && lifecycleStageCodeOf(item) === 'freight_upload'; +} diff --git a/frontend/src/locales/en/admin.json b/frontend/src/locales/en/admin.json index 5be46577..6eec9a14 100644 --- a/frontend/src/locales/en/admin.json +++ b/frontend/src/locales/en/admin.json @@ -2473,7 +2473,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", @@ -2486,8 +2486,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", @@ -2514,7 +2514,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", @@ -2599,12 +2599,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", diff --git a/frontend/src/locales/en/chat.json b/frontend/src/locales/en/chat.json index 2843b196..63351664 100644 --- a/frontend/src/locales/en/chat.json +++ b/frontend/src/locales/en/chat.json @@ -2211,6 +2211,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.", @@ -3076,8 +3084,6 @@ "primaryFile": "Primary file: {name}", "continueProcessing": "Continue", "fileCountUnavailable": "File count unavailable", - "panelPinnedHint": "Active tasks keep this panel open; you can still collapse file details", - "panelPinnedLabel": "Action needed", "groupHistory": "History · {count}", "groupHistoryRecords": "Past versions · {count} files", "groupCancelled": "Cancelled · {count} files", diff --git a/frontend/src/locales/en/errors.json b/frontend/src/locales/en/errors.json index 7857691b..290105b3 100644 --- a/frontend/src/locales/en/errors.json +++ b/frontend/src/locales/en/errors.json @@ -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.", diff --git a/frontend/src/locales/en/workspace.json b/frontend/src/locales/en/workspace.json index f493cb1f..2cab7882 100644 --- a/frontend/src/locales/en/workspace.json +++ b/frontend/src/locales/en/workspace.json @@ -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", @@ -280,8 +280,8 @@ "customerTaskMissing": "Task number missing — cannot open customer confirm. Refresh and try again.", "genericBlocking": "This step needs manual attention", "unknownStep": "Current step", - "continueAction": "Continue", - "recoveryTargets": "Prerequisite recovery", + "continueAction": "Continue", + "recoveryTargets": "Prerequisite recovery", "actionSubmitted": "Action submitted", "submitting": "Submitting…", "readOnlyUseFooter": "Use the footer action bar to proceed", @@ -522,6 +522,75 @@ "taskNoPlaceholder": "SN number", "apply": "Apply filters", "reset": "Reset" + }, + "batch": { + "selectAll": "Select all filtered notices", + "selected": "{count} selected", + "download": "Batch download Excel", + "confirm": "Batch confirm uploaded", + "rpa": "Batch start RPA", + "clearSelection": "Clear selection", + "downloadStarted": "Export download started", + "success": "{action}: {count} succeeded", + "partialResult": "{action}: {accepted} succeeded, {blocked} not accepted" + }, + "table": { + "no": "No.", + "stage": "Stage", + "summary": "Status summary", + "lines": "Lines", + "lineUnit": "lines", + "shortage": "{count} short", + "freightStatus": "Freight status" + }, + "terminal": { + "uploadComplete": "Uploaded", + "rejectVoid": "Rejected" + }, + "subTabs": { + "uploadComplete": "Completed", + "rejectVoid": "Rejected / Voided" + }, + "drawer": { + "details": "Line details", + "files": "Files", + "close": "Close", + "exportExcel": "Export Excel", + "lineTable": { + "lineNo": "Line", + "partNumber": "Part No.", + "customerPartNumber": "Customer part", + "reservationId": "Reservation", + "shipmentQty": "Ship qty", + "availableQty": "Available", + "shortageQty": "Shortage", + "status": "Status" + } + }, + "doneReport": { + "export": "Export Excel (current filters)", + "exportStarted": "Detail Excel download started", + "filters": { + "customer": "Customer", + "partNumber": "Part No.", + "dateFrom": "Notice date from", + "dateTo": "Notice date to" + }, + "columns": { + "taskNo": "OT No.", + "customer": "Customer", + "customerCode": "Customer code", + "orderDate": "Order date", + "lineNo": "Order line", + "partNumber": "Part No.", + "qty": "Qty", + "requiredDate": "Agreed ship date", + "customerPo": "Customer PO", + "usedQty": "Used qty", + "openQty": "Open qty", + "sourceOrderNo": "Source order no.", + "unitPrice": "Unit price" + } } }, "risk": { @@ -765,6 +834,17 @@ "total": "{count} total", "previous": "Previous", "next": "Next" + }, + "batch": { + "selectAll": "Select all filtered notices", + "selected": "{count} selected", + "download": "Batch download Excel", + "confirm": "Batch confirm uploaded", + "rpa": "Batch start RPA", + "clearSelection": "Clear selection", + "downloadStarted": "Export download started", + "success": "{action}: {count} succeeded", + "partialResult": "{action}: {accepted} succeeded, {blocked} not accepted" } }, "profile": { diff --git a/frontend/src/locales/th/admin.json b/frontend/src/locales/th/admin.json index 56e6c1b2..57d59a99 100644 --- a/frontend/src/locales/th/admin.json +++ b/frontend/src/locales/th/admin.json @@ -2342,7 +2342,7 @@ "normalizer": "วิธีจัดการข้อความ", "displayName": "ชื่อกฎ", "displayNamePlaceholder": "เช่น อีเมลผู้ส่งของลูกค้าสหรัฐ", - "evidenceLabel": "ชื่อหลักฐานในข้อมูลหลักลูกค้า", + "evidenceLabel": "ชื่อหลักฐานในข้อมูลลูกค้า", "evidenceLabelPlaceholder": "เช่น อีเมลธุรกิจของลูกค้า", "description": "คำอธิบายการใช้ (ไม่บังคับ)", "descriptionPlaceholder": "เช่น ใช้ระบุลูกค้าผู้ชำระเงินในภูมิภาคสหรัฐ", @@ -2355,8 +2355,8 @@ "addDefinition": "เพิ่มนิยามธุรกิจ", "definitionSaved": "บันทึกนิยามการระบุตัวตนแล้ว", "workflowTitle": "ลำดับการตั้งค่า", - "workflowHint": "1. เพิ่มนิยามการระบุตัวตน 2. สร้าง บันทึก และเผยแพร่ชุดกฎ 3. กลับไปที่ข้อมูลหลักลูกค้าเพื่อดูแลหลักฐานของลูกค้าหรือสถานที่จัดส่ง", - "openCustomerMaster": "ไปที่ข้อมูลหลักลูกค้า", + "workflowHint": "1. เพิ่มนิยามการระบุตัวตน 2. สร้าง บันทึก และเผยแพร่ชุดกฎ 3. กลับไปที่ข้อมูลลูกค้าเพื่อดูแลหลักฐานของลูกค้าหรือสถานที่จัดส่ง", + "openCustomerMaster": "ไปที่ข้อมูลลูกค้า", "ruleSets": "เวอร์ชันชุดกฎ", "ruleSetHint": "สแนปช็อตที่เผยแพร่แล้วแก้ไขไม่ได้ ต้องแทนที่หรือเลิกใช้นิยามก่อนเลิกใช้ฟิลด์คำสั่งซื้อที่ถูกอ้างอิง", "publishedDefinitions": "คำจำกัดความที่เผยแพร่จริงในเวอร์ชันนี้", @@ -2383,7 +2383,7 @@ "selectFieldHint": "แสดงเฉพาะฟิลด์ Header ที่เปิดใช้สำหรับการระบุตัวตนลูกค้าในเวอร์ชันปัจจุบัน" }, "shippingCustomers": { - "title": "ข้อมูลหลักลูกค้าขนส่ง", + "title": "ข้อมูลลูกค้าขนส่ง", "subtitle": "จัดการตัวตนลูกค้า รหัสย่อ หลักฐานระบุตัวตน และการนำเข้าข้อมูลตั้งต้น", "add": "เพิ่มลูกค้า", "edit": "แก้ไขลูกค้า", @@ -2468,12 +2468,16 @@ "shortCodeHint": "ตัวอักษร 2-6 ตัว บันทึกเป็นตัวพิมพ์ใหญ่", "status": "สถานะ", "remark": "หมายเหตุ", + "odmIds": "ขอบเขต ODM ID", + "odmIdsHint": "หนึ่ง ODM ID ต่อบรรทัด เว้นว่างหากไม่จำกัด", + "odmIdsUnlimited": "ไม่จำกัด", "changeReason": "เหตุผลการเปลี่ยนแปลง", "changeReasonHint": "ต้องระบุเมื่อแก้ไขรหัสย่อหรือสถานะ" }, "headers": { "name": "ลูกค้า", "shortCode": "รหัสย่อ", + "odmIds": "ขอบเขต ODM ID", "status": "สถานะ", "identifiers": "หลักฐานระบุตัวตน", "identityEvidences": "หลักฐานที่กำหนดค่า", diff --git a/frontend/src/locales/th/chat.json b/frontend/src/locales/th/chat.json index cff49455..ef630932 100644 --- a/frontend/src/locales/th/chat.json +++ b/frontend/src/locales/th/chat.json @@ -2211,6 +2211,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 แยกอิสระ", @@ -3202,8 +3210,6 @@ "primaryFile": "ไฟล์หลัก: {name}", "continueProcessing": "ดำเนินการต่อ", "fileCountUnavailable": "ยังไม่มีจำนวนไฟล์", - "panelPinnedHint": "มีงานที่กำลังทำหรือต้องดำเนินการ แผงนี้จะเปิดค้างไว้ คุณยังยุบรายละเอียดไฟล์ได้", - "panelPinnedLabel": "ต้องดำเนินการ", "groupHistory": "ประวัติ · {count}", "groupHistoryRecords": "เวอร์ชันก่อนหน้า · {count} ไฟล์", "groupCancelled": "ยกเลิกแล้ว · {count} ไฟล์", diff --git a/frontend/src/locales/th/errors.json b/frontend/src/locales/th/errors.json index a38afd31..b324781a 100644 --- a/frontend/src/locales/th/errors.json +++ b/frontend/src/locales/th/errors.json @@ -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": "นโยบายการปฏิบัติตามถูกแก้ไขโดยผู้ดูแลรายอื่น โปรดรีเฟรชแล้วลองใหม่", diff --git a/frontend/src/locales/th/workspace.json b/frontend/src/locales/th/workspace.json index da2579c9..91a5f699 100644 --- a/frontend/src/locales/th/workspace.json +++ b/frontend/src/locales/th/workspace.json @@ -92,7 +92,7 @@ "scheduleRuns": "บันทึกตารางงาน", "receiptReports": "ไฟล์รับสินค้า", "shippingNotice": "ใบแจ้งส่งสินค้า", - "shippingCustomers": "ข้อมูลหลักลูกค้า", + "shippingCustomers": "ข้อมูลลูกค้า", "shippingTasks": "งานจัดส่ง", "shippingMyTasks": "งานที่ต้องทำของฉัน", "feedback": "ข้อเสนอแนะ", @@ -456,6 +456,75 @@ "taskNoPlaceholder": "หมายเลข SN", "apply": "ใช้ตัวกรอง", "reset": "รีเซ็ต" + }, + "batch": { + "selectAll": "เลือกทั้งหมดตามตัวกรอง", + "selected": "เลือกแล้ว {count} รายการ", + "download": "ดาวน์โหลด Excel เป็นชุด", + "confirm": "ยืนยันการอัปโหลดเป็นชุด", + "rpa": "เริ่ม RPA เป็นชุด", + "clearSelection": "ล้างการเลือก", + "downloadStarted": "เริ่มดาวน์โหลดไฟล์ส่งออกแล้ว", + "success": "{action}: สำเร็จ {count} รายการ", + "partialResult": "{action}: สำเร็จ {accepted} รายการ ไม่ได้รับ {blocked} รายการ" + }, + "table": { + "no": "หมายเลข", + "stage": "ขั้นตอน", + "summary": "สรุปสถานะ", + "lines": "รายการ", + "lineUnit": "รายการ", + "shortage": "ขาด {count}", + "freightStatus": "สถานะขนส่ง" + }, + "terminal": { + "uploadComplete": "อัปโหลดสำเร็จ", + "rejectVoid": "ถูกปฏิเสธ" + }, + "subTabs": { + "uploadComplete": "แจ้งฝากส่งเสร็จ", + "rejectVoid": "ปฏิเสธ / ยกเลิก" + }, + "drawer": { + "details": "รายละเอียดรายการ", + "files": "ไฟล์", + "close": "ปิด", + "exportExcel": "ส่งออก Excel", + "lineTable": { + "lineNo": "ลำดับ", + "partNumber": "รหัสสินค้า", + "customerPartNumber": "รหัสสินค้าลูกค้า", + "reservationId": "เลขจอง", + "shipmentQty": "จำนวนส่ง", + "availableQty": "คงเหลือ", + "shortageQty": "ขาด", + "status": "สถานะ" + } + }, + "doneReport": { + "export": "ส่งออก Excel (ตามตัวกรอง)", + "exportStarted": "เริ่มดาวน์โหลด Excel รายละเอียดแล้ว", + "filters": { + "customer": "ลูกค้า", + "partNumber": "รหัสสินค้า", + "dateFrom": "วันที่แจ้งฝากส่งจาก", + "dateTo": "ถึง" + }, + "columns": { + "taskNo": "เลข OT", + "customer": "ลูกค้า", + "customerCode": "รหัสลูกค้า", + "orderDate": "วันที่สั่งซื้อ", + "lineNo": "ลำดับรายการ", + "partNumber": "รหัสสินค้า", + "qty": "จำนวน", + "requiredDate": "วันส่งมอบตกลง", + "customerPo": "PO ลูกค้า", + "usedQty": "จำนวนที่ใช้", + "openQty": "open qty", + "sourceOrderNo": "เลขที่ออเดอร์ต้นทาง", + "unitPrice": "ราคาต่อหน่วย" + } } }, "risk": { @@ -699,6 +768,17 @@ "total": "ทั้งหมด {count}", "previous": "ก่อนหน้า", "next": "ถัดไป" + }, + "batch": { + "selectAll": "เลือกทั้งหมดตามตัวกรอง", + "selected": "เลือกแล้ว {count} รายการ", + "download": "ดาวน์โหลด Excel เป็นชุด", + "confirm": "ยืนยันการอัปโหลดเป็นชุด", + "rpa": "เริ่ม RPA เป็นชุด", + "clearSelection": "ล้างการเลือก", + "downloadStarted": "เริ่มดาวน์โหลดไฟล์ส่งออกแล้ว", + "success": "{action}: สำเร็จ {count} รายการ", + "partialResult": "{action}: สำเร็จ {accepted} รายการ ไม่ได้รับ {blocked} รายการ" } }, "mobileTabs": { diff --git a/frontend/src/locales/zh-CN/admin.json b/frontend/src/locales/zh-CN/admin.json index 8d2ba95d..41b2874b 100644 --- a/frontend/src/locales/zh-CN/admin.json +++ b/frontend/src/locales/zh-CN/admin.json @@ -2585,7 +2585,7 @@ "normalizer": "文本处理方式", "displayName": "规则名称", "displayNamePlaceholder": "例如:美国客户发件人邮箱", - "evidenceLabel": "客户主数据中的证据名称", + "evidenceLabel": "客户数据中的证据名称", "evidenceLabelPlaceholder": "例如:客户业务邮箱", "description": "使用说明(可选)", "descriptionPlaceholder": "例如:用于识别美国区域的账款客户", @@ -2599,8 +2599,8 @@ "addDefinition": "新增业务定义", "definitionSaved": "识别定义已保存", "workflowTitle": "配置顺序", - "workflowHint": "1. 新增识别定义;2. 创建、保存并发布规则集;3. 返回客户主数据维护客户或送货站点证据。", - "openCustomerMaster": "前往客户主数据维护证据", + "workflowHint": "1. 新增识别定义;2. 创建、保存并发布规则集;3. 返回客户数据维护客户或送货站点证据。", + "openCustomerMaster": "前往客户数据维护证据", "ruleSets": "规则集版本", "ruleSetHint": "发布后规则快照不可修改;订单字段退役前必须先替换或退役引用它的定义。", "publishedDefinitions": "本版本实际发布的识别定义", @@ -2626,7 +2626,7 @@ } }, "shippingCustomers": { - "title": "货代客户主数据", + "title": "货代客户数据", "subtitle": "维护稳定客户身份、客户简码、识别证据与期初导入", "add": "新增客户", "edit": "编辑客户", @@ -2711,12 +2711,16 @@ "shortCodeHint": "2-6 位英文字母,保存后统一转为大写", "status": "状态", "remark": "备注", + "odmIds": "ODM ID 范围", + "odmIdsHint": "每行一个 ODM ID;留空表示不限定", + "odmIdsUnlimited": "不限定", "changeReason": "变更原因", "changeReasonHint": "修改简码或状态时必须填写" }, "headers": { "name": "客户名称", "shortCode": "简码", + "odmIds": "ODM ID 范围", "status": "状态", "identifiers": "识别证据", "identityEvidences": "配置化证据", diff --git a/frontend/src/locales/zh-CN/chat.json b/frontend/src/locales/zh-CN/chat.json index dece0724..74164e04 100644 --- a/frontend/src/locales/zh-CN/chat.json +++ b/frontend/src/locales/zh-CN/chat.json @@ -2318,6 +2318,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。", @@ -3150,8 +3158,6 @@ "primaryFile": "主文件:{name}", "continueProcessing": "继续处理", "fileCountUnavailable": "文件数暂不可用", - "panelPinnedHint": "仍有处理中或待处理任务,侧栏保持展开;可收起文件详情", - "panelPinnedLabel": "待处理", "groupHistory": "处理记录 · {count}", "groupHistoryRecords": "历史版本 · {count} 个文件", "groupCancelled": "已取消 · {count} 个文件", diff --git a/frontend/src/locales/zh-CN/errors.json b/frontend/src/locales/zh-CN/errors.json index a2377992..c47b3ff4 100644 --- a/frontend/src/locales/zh-CN/errors.json +++ b/frontend/src/locales/zh-CN/errors.json @@ -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": "货代履约策略已被其他管理员修改,请刷新后重试。", diff --git a/frontend/src/locales/zh-CN/workspace.json b/frontend/src/locales/zh-CN/workspace.json index 716f74ab..87272a62 100644 --- a/frontend/src/locales/zh-CN/workspace.json +++ b/frontend/src/locales/zh-CN/workspace.json @@ -101,7 +101,7 @@ "scheduleRuns": "排程记录", "receiptReports": "收料文件", "shippingNotice": "货代发货", - "shippingCustomers": "客户主数据", + "shippingCustomers": "客户数据", "shippingTasks": "发货任务", "shippingMyTasks": "我的待办", "feedback": "意见反馈", @@ -280,8 +280,8 @@ "customerTaskMissing": "缺少任务编号,无法打开客户确认,请刷新后重试", "genericBlocking": "当前步骤需要人工处理", "unknownStep": "当前步骤", - "continueAction": "继续处理", - "recoveryTargets": "前置恢复", + "continueAction": "继续处理", + "recoveryTargets": "前置恢复", "actionSubmitted": "操作已提交", "submitting": "提交中…", "readOnlyUseFooter": "请使用底部操作栏继续处理", @@ -522,6 +522,75 @@ "taskNoPlaceholder": "SN 编号", "apply": "应用筛选", "reset": "重置" + }, + "batch": { + "selectAll": "全选当前筛选通知单", + "selected": "已选 {count} 张", + "download": "批量下载 Excel", + "confirm": "批量确认已上传", + "rpa": "批量发起 RPA", + "clearSelection": "清除选择", + "downloadStarted": "已开始下载导出包", + "success": "{action}:成功 {count} 张", + "partialResult": "{action}:成功 {accepted} 张,未受理 {blocked} 张" + }, + "table": { + "no": "编号", + "stage": "阶段", + "summary": "状态摘要", + "lines": "项次", + "lineUnit": "项", + "shortage": "缺 {count}", + "freightStatus": "货代状态" + }, + "terminal": { + "uploadComplete": "上传完成", + "rejectVoid": "复核驳回" + }, + "subTabs": { + "uploadComplete": "通知完成", + "rejectVoid": "复核驳回 / 已作废" + }, + "drawer": { + "details": "逐行明细", + "files": "文件", + "close": "关闭", + "exportExcel": "导出 Excel", + "lineTable": { + "lineNo": "行", + "partNumber": "料号", + "customerPartNumber": "客户料号", + "reservationId": "预约号", + "shipmentQty": "本次发货", + "availableQty": "可用库存", + "shortageQty": "缺口", + "status": "状态" + } + }, + "doneReport": { + "export": "导出 Excel(当前筛选)", + "exportStarted": "已开始下载明细 Excel", + "filters": { + "customer": "客户", + "partNumber": "料号", + "dateFrom": "通知日期起", + "dateTo": "通知日期止" + }, + "columns": { + "taskNo": "OT 编号", + "customer": "客户", + "customerCode": "客户编号", + "orderDate": "订单日期", + "lineNo": "订单项次", + "partNumber": "料号", + "qty": "数量", + "requiredDate": "约定出货日期", + "customerPo": "客户PO", + "usedQty": "已用数量", + "openQty": "open qty", + "sourceOrderNo": "订单单号", + "unitPrice": "单价" + } } }, "risk": { @@ -765,6 +834,17 @@ "total": "共 {count} 条", "previous": "上一页", "next": "下一页" + }, + "batch": { + "selectAll": "全选当前筛选通知单", + "selected": "已选 {count} 张", + "download": "批量下载 Excel", + "confirm": "批量确认已上传", + "rpa": "批量发起 RPA", + "clearSelection": "清除选择", + "downloadStarted": "已开始下载导出包", + "success": "{action}:成功 {count} 张", + "partialResult": "{action}:成功 {accepted} 张,未受理 {blocked} 张" } }, "profile": { @@ -780,7 +860,7 @@ "casdoorNotMatchedNeedLocalUser": "Casdoor 登录成功,但未匹配到本地账号。请让管理员在本地用户表创建同名 username 或相同 email 的账号。", "localAccountDisabled": "该本地账号已被禁用,请联系管理员启用后再登录。" }, - "voucherCheck": { + "voucherCheck": { "title": "立账凭证检核任务", "subtitle": "每周二增量检核上一个自然月;扫描销售开票附件类型目录后按 invoice 归档,并汇总缺件。", "period": "资料所属期间", diff --git a/frontend/src/locales/zh-TW/admin.json b/frontend/src/locales/zh-TW/admin.json index ebe4ceee..37f54e33 100644 --- a/frontend/src/locales/zh-TW/admin.json +++ b/frontend/src/locales/zh-TW/admin.json @@ -2347,7 +2347,7 @@ "normalizer": "文字處理方式", "displayName": "規則名稱", "displayNamePlaceholder": "例如:美國客戶寄件者電子郵件", - "evidenceLabel": "客戶主資料中的證據名稱", + "evidenceLabel": "客戶資料中的證據名稱", "evidenceLabelPlaceholder": "例如:客戶業務電子郵件", "description": "使用說明(可選)", "descriptionPlaceholder": "例如:用於識別美國區域的帳款客戶", @@ -2360,8 +2360,8 @@ "addDefinition": "新增業務定義", "definitionSaved": "識別定義已儲存", "workflowTitle": "設定順序", - "workflowHint": "1. 新增識別定義;2. 建立、儲存並發布規則集;3. 返回客戶主資料維護客戶或送貨站點證據。", - "openCustomerMaster": "前往客戶主資料維護證據", + "workflowHint": "1. 新增識別定義;2. 建立、儲存並發布規則集;3. 返回客戶資料維護客戶或送貨站點證據。", + "openCustomerMaster": "前往客戶資料維護證據", "ruleSets": "規則集版本", "ruleSetHint": "發布後快照不可修改;退役訂單欄位前必須先替換或退役其引用定義。", "publishedDefinitions": "本版本實際發布的識別定義", @@ -2388,7 +2388,7 @@ "selectFieldHint": "只顯示目前版本中已啟用客戶識別的 Header 欄位" }, "shippingCustomers": { - "title": "貨代客戶主資料", + "title": "貨代客戶資料", "subtitle": "維護穩定客戶身份、客戶簡碼、識別證據與期初匯入", "add": "新增客戶", "edit": "編輯客戶", @@ -2473,12 +2473,16 @@ "shortCodeHint": "2-6 位英文字母,儲存後統一轉為大寫", "status": "狀態", "remark": "備註", + "odmIds": "ODM ID 範圍", + "odmIdsHint": "每行一個 ODM ID;留空表示不限定", + "odmIdsUnlimited": "不限定", "changeReason": "變更原因", "changeReasonHint": "修改簡碼或狀態時必須填寫" }, "headers": { "name": "客戶名稱", "shortCode": "簡碼", + "odmIds": "ODM ID 範圍", "status": "狀態", "identifiers": "識別證據", "identityEvidences": "可設定證據", diff --git a/frontend/src/locales/zh-TW/chat.json b/frontend/src/locales/zh-TW/chat.json index 2543648a..5a94b5db 100644 --- a/frontend/src/locales/zh-TW/chat.json +++ b/frontend/src/locales/zh-TW/chat.json @@ -2211,6 +2211,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。", @@ -3202,8 +3210,6 @@ "primaryFile": "主檔案:{name}", "continueProcessing": "繼續處理", "fileCountUnavailable": "檔案數暫不可用", - "panelPinnedHint": "仍有處理中或待處理任務,側欄保持展開;可收起檔案詳情", - "panelPinnedLabel": "待處理", "groupHistory": "處理記錄 · {count}", "groupHistoryRecords": "歷史版本 · {count} 個檔案", "groupCancelled": "已取消 · {count} 個檔案", diff --git a/frontend/src/locales/zh-TW/errors.json b/frontend/src/locales/zh-TW/errors.json index dc8847a7..d853e82d 100644 --- a/frontend/src/locales/zh-TW/errors.json +++ b/frontend/src/locales/zh-TW/errors.json @@ -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": "貨代履約策略已被其他管理員修改,請重新整理後再試。", diff --git a/frontend/src/locales/zh-TW/workspace.json b/frontend/src/locales/zh-TW/workspace.json index d00bfbd6..e7942a0a 100644 --- a/frontend/src/locales/zh-TW/workspace.json +++ b/frontend/src/locales/zh-TW/workspace.json @@ -101,7 +101,7 @@ "scheduleRuns": "排程記錄", "receiptReports": "收料檔案", "shippingNotice": "貨代發貨", - "shippingCustomers": "客戶主資料", + "shippingCustomers": "客戶資料", "shippingTasks": "發貨任務", "shippingMyTasks": "我的待辦", "feedback": "意見反饋", @@ -280,8 +280,8 @@ "customerTaskMissing": "缺少任務編號,無法開啟客戶確認,請重新整理後再試", "genericBlocking": "目前步驟需要人工處理", "unknownStep": "目前步驟", - "continueAction": "繼續處理", - "recoveryTargets": "前置恢復", + "continueAction": "繼續處理", + "recoveryTargets": "前置恢復", "actionSubmitted": "操作已提交", "submitting": "提交中…", "readOnlyUseFooter": "請使用底部操作列繼續處理", @@ -522,6 +522,75 @@ "taskNoPlaceholder": "SN 編號", "apply": "套用篩選", "reset": "重置" + }, + "batch": { + "selectAll": "全選當前篩選通知單", + "selected": "已選 {count} 張", + "download": "批量下載 Excel", + "confirm": "批量確認已上傳", + "rpa": "批量發起 RPA", + "clearSelection": "清除選擇", + "downloadStarted": "已開始下載導出包", + "success": "{action}:成功 {count} 張", + "partialResult": "{action}:成功 {accepted} 張,未受理 {blocked} 張" + }, + "table": { + "no": "編號", + "stage": "階段", + "summary": "狀態摘要", + "lines": "項次", + "lineUnit": "項", + "shortage": "缺 {count}", + "freightStatus": "貨代狀態" + }, + "terminal": { + "uploadComplete": "上傳完成", + "rejectVoid": "複核駁回" + }, + "subTabs": { + "uploadComplete": "通知完成", + "rejectVoid": "複核駁回 / 已作廢" + }, + "drawer": { + "details": "逐行明細", + "files": "文件", + "close": "關閉", + "exportExcel": "導出 Excel", + "lineTable": { + "lineNo": "行", + "partNumber": "料號", + "customerPartNumber": "客戶料號", + "reservationId": "預約號", + "shipmentQty": "本次發貨", + "availableQty": "可用庫存", + "shortageQty": "缺口", + "status": "狀態" + } + }, + "doneReport": { + "export": "導出 Excel(當前篩選)", + "exportStarted": "已開始下載明細 Excel", + "filters": { + "customer": "客戶", + "partNumber": "料號", + "dateFrom": "通知日期起", + "dateTo": "通知日期止" + }, + "columns": { + "taskNo": "OT 編號", + "customer": "客戶", + "customerCode": "客戶編號", + "orderDate": "訂單日期", + "lineNo": "訂單項次", + "partNumber": "料號", + "qty": "數量", + "requiredDate": "約定出貨日期", + "customerPo": "客戶PO", + "usedQty": "已用數量", + "openQty": "open qty", + "sourceOrderNo": "訂單單號", + "unitPrice": "單價" + } } }, "risk": { @@ -765,6 +834,17 @@ "total": "共 {count} 條", "previous": "上一頁", "next": "下一頁" + }, + "batch": { + "selectAll": "全選當前篩選通知單", + "selected": "已選 {count} 張", + "download": "批量下載 Excel", + "confirm": "批量確認已上傳", + "rpa": "批量發起 RPA", + "clearSelection": "清除選擇", + "downloadStarted": "已開始下載導出包", + "success": "{action}:成功 {count} 張", + "partialResult": "{action}:成功 {accepted} 張,未受理 {blocked} 張" } }, "profile": { diff --git a/scripts/rpa/README.md b/scripts/rpa/README.md index d6a4cc5f..05cace84 100644 --- a/scripts/rpa/README.md +++ b/scripts/rpa/README.md @@ -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 与业务参考 diff --git a/scripts/rpa/receipt/start_receipt_worker.ps1 b/scripts/rpa/receipt/start_receipt_worker.ps1 index e51d95db..6b051655 100644 --- a/scripts/rpa/receipt/start_receipt_worker.ps1 +++ b/scripts/rpa/receipt/start_receipt_worker.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS 在当前 PowerShell 进程树启动独立货代收料 RPA Worker。