From d396371020020202ba59f88ec20458f3a7f7a745 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Wed, 16 Sep 2026 19:50:12 +0800 Subject: [PATCH 1/6] =?UTF-8?q?feat(shipping=5Fnotice):=20=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E5=AE=A2=E6=88=B7=20ODM=20=E7=99=BD=E5=90=8D=E5=8D=95?= =?UTF-8?q?=E4=B8=8E=E6=95=B4=E5=8D=95=20ODM=20=E9=80=89=E6=8B=A9=E6=94=B6?= =?UTF-8?q?=E6=95=9B=E5=AF=BC=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 客户主数据新增 odm_ids 白名单字段(含 Alembic 迁移),表单与管理端支持维护 - 导出库存命中行按客户白名单与整单 ODM 裁决收敛,新增 notice_odm_choice_service - 工作台新增 odm-options / odm-choice 接口,投影行级候选并持久化用户选择 - 修复复核工作台跨 Run 切换时接收解析上下文残留 - 同步四语言 i18n、测试用例、funclist 与 shipping-notice 技术文档 --- .gitignore | 1 + backend/app/api/workspace/shipping_notice.py | 39 + backend/app/models/shipping_customer.py | 2 + .../shipping_notice_line_inventory_match.py | 2 + .../admin/shipping_customer_service.py | 49 ++ .../document_profile_quality_service.py | 5 + .../app/services/shipping_notice/export.py | 331 +++++++-- .../notice_odm_choice_service.py | 177 +++++ .../order_extraction_workflow.py | 35 +- .../order_review_projection.py | 78 +- .../shipping_notice/reservation_region.py | 44 ++ .../app/services/shipping_notice/ui_state.py | 26 + .../aa11bb22cc33_customer_odm_scope.py | 54 ++ .../test_order_extraction_pdf_po_split.py | 71 ++ backend/tests/test_shipping_excel_template.py | 257 +++++++ .../test_shipping_notice_reservation_id.py | 29 + .../test_shipping_order_review_service.py | 251 +++++++ docs/features/shipping-notice/technical.md | 185 ++++- docs/funclist.md | 2 + .../2026-09-16-review-queue-icon-semantics.md | 667 ++++++++++++++++++ ...9-16-review-queue-icon-semantics-design.md | 120 ++++ .../src/app/router/routes/workspace.routes.ts | 2 +- .../src/features/chat/api/shipping.api.ts | 10 + .../ReviewDocumentNavigation.spec.ts | 61 ++ .../ReviewDocumentNavigation.vue | 35 +- .../useShippingOrderReview.spec.ts | 42 ++ .../shipping-review/useShippingOrderReview.ts | 12 + .../features/chat/types/shipping.api.types.ts | 15 + .../chat/views/ShippingOrderReviewView.vue | 58 +- .../customers/ShippingCustomersPage.vue | 7 +- .../components/CustomerFormModal.vue | 10 + .../composables/useShippingCustomersAdmin.ts | 10 + .../types/customer-master.types.ts | 6 + frontend/src/locales/en/admin.json | 12 +- frontend/src/locales/en/chat.json | 8 + frontend/src/locales/en/errors.json | 1 + frontend/src/locales/en/workspace.json | 2 +- frontend/src/locales/th/admin.json | 12 +- frontend/src/locales/th/chat.json | 8 + frontend/src/locales/th/errors.json | 1 + frontend/src/locales/th/workspace.json | 2 +- frontend/src/locales/zh-CN/admin.json | 12 +- frontend/src/locales/zh-CN/chat.json | 8 + frontend/src/locales/zh-CN/errors.json | 1 + frontend/src/locales/zh-CN/workspace.json | 2 +- frontend/src/locales/zh-TW/admin.json | 12 +- frontend/src/locales/zh-TW/chat.json | 8 + frontend/src/locales/zh-TW/errors.json | 1 + frontend/src/locales/zh-TW/workspace.json | 2 +- scripts/rpa/README.md | 39 +- scripts/rpa/receipt/start_receipt_worker.ps1 | 2 +- 51 files changed, 2717 insertions(+), 109 deletions(-) create mode 100644 backend/app/services/shipping_notice/notice_odm_choice_service.py create mode 100644 backend/migrations/versions/aa11bb22cc33_customer_odm_scope.py create mode 100644 docs/superpowers/plans/2026-09-16-review-queue-icon-semantics.md create mode 100644 docs/superpowers/specs/2026-09-16-review-queue-icon-semantics-design.md 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..0b34aa0f 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -481,6 +481,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/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/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/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_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index 49802bb6..54f5f789 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, ) @@ -2090,14 +2091,18 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult ) decision['parsed_table_count'] = 1 decision['route_type'] = 'profile_deterministic' + # 模板确定性取值已成功,复核只针对业务归属(Reservation 专区/行校验)。 + # 必须以 deterministic 携带原因码交 STP 裁 needs_review,让已解析订单 + # 继续落 provisional Candidate 供复核台编辑;review_required 会被 + # Worker 当作"无可信取值"丢弃,复核草稿将退化为空白手工单。 if any(order.get('reservation_region_status') == 'needs_review' for order in orders): decision['fallback_reason_codes'] = ['reservation_region_needs_review'] return _apply_stp_route_adjudication( - decision, execution_mode='review_required', orders=orders, + decision, execution_mode='deterministic', orders=orders, ) if decision.get('fallback_reason_codes'): return _apply_stp_route_adjudication( - decision, execution_mode='review_required', orders=orders, + decision, execution_mode='deterministic', orders=orders, ) decision['fallback_reason_codes'] = [] return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders) @@ -2357,11 +2362,31 @@ def _build_approved_profile_order_result( if candidates: header_target = reservation_scope.get('header') line_target = reservation_scope.get('line') + # Reservation 注释的 L#n 引用单据印刷行号(LN 列),必须按 customer_po_line_no + # 值定位逻辑行;LN 非连续(部分行已拆单)时按位置写入会错配并误报越界。 + line_numbers: list[int | None] | None = None + if line_target: + ln_field_id = next( + (str(item.get('field_id') or '') for item in fields + if str(item.get('field_code') or '') == 'customer_po_line_no'), + None, + ) + if ln_field_id: + line_numbers = resolve_candidate_line_numbers([ + next( + (observation.get('value') for field in group.get('fields') or [] + if str(field.get('field_id') or '') == ln_field_id + for observation in field.get('observations') or []), + None, + ) + for group in line_groups + ]) applied = apply_reservation_region_candidates( candidates=candidates, header_field_id=str(header_target.get('field_id') or '') if header_target else None, line_field_id=str(line_target.get('field_id') or '') if line_target else None, line_count=len(line_groups), + line_numbers=line_numbers, ) if applied.header_value and header_target: header_evidence = next((item for item in candidates if item.get('scope') == 'header'), {}) @@ -2379,9 +2404,10 @@ def _build_approved_profile_order_result( ] if line_target: for line_no, value in applied.line_values.items(): + # line_no 已是逻辑行序号;候选里携带的是印刷行号,证据只按值回查。 line_evidence = next(( item for item in candidates - if item.get('scope') == 'line' and item.get('line_no') == line_no and item.get('value') == value + if item.get('scope') == 'line' and item.get('value') == value ), {}) line_groups[line_no - 1].setdefault('fields', []).append({'field_id': str(line_target.get('field_id') or ''), 'observations': [{ 'value': value, 'document_id': int(unit.document_id), @@ -2390,7 +2416,8 @@ def _build_approved_profile_order_result( line_id = str(line_target.get('field_id') or '') line_code = str(line_target.get('field_code') or '') for missing in source_missing_fields['lines']: - if isinstance(missing, dict) and int(missing.get('line_index') or -1) == line_no - 1: + # 不能用 `or -1` 兜底:line_index 0 是合法值,会被 falsy 判断跳过。 + if isinstance(missing, dict) and missing.get('line_index') == line_no - 1: missing['field_ids'] = [field_id for field_id in missing['field_ids'] if field_id != line_id] missing['field_codes'] = [field_code for field_code in missing['field_codes'] if field_code != line_code] source_missing_fields['lines'] = [ 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/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/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/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_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_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_review_service.py b/backend/tests/test_shipping_order_review_service.py index a7f7fcac..6f79b100 100644 --- a/backend/tests/test_shipping_order_review_service.py +++ b/backend/tests/test_shipping_order_review_service.py @@ -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/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 4117dad2..339ad09a 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -699,7 +699,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open **阶段 1 历史结论(2026-07-21)**:Run 锁定版本的完整 `definition_json` 已成为确定性订单表格解析的唯一业务配置来源。解析器只使用已启用字段的 `field_code + display_name + aliases` 编译冻结表头契约,不再维护业务别名常量,不读取当前 published 版本,也不在缺少契约时猜测表头。保存草稿和发布版本都会拒绝标准化后跨字段别名碰撞,并拒绝把 Allocation ID、Parent Allocation ID、Commodity Group ID、Supplier Code、UUID、Internal ID 配置为 Reservation ID 表头。同一字段命中多列时不静默选首列,而是记录 `deterministic_table_issues` 并进入复核。后端不再扫描任意单元格猜 Reservation ID,不把文档级 Reservation 广播到所有明细行,也不会为 Schema 未启用的 UOM、币种、金额等字段注入默认值或派生值。冻结的 retired 版本继续按自身别名解析,上传预处理若在任务边界选择当前 published Schema,也只生成提示,不替代正式 Run 的冻结真值。 -**Reservation ID 专用证据区域(2026-08-25)**:管理员在同一模板画布圈选唯一的 `reservation_id_region`(区域坐标与页码),不配置 JSON、来源映射、拆分规则或 Header/Line 归属。后端只从该区域内带 `Reservation` 语义的 5/10 位数字提取候选:无行号的值写入 `header.reservation_id`,并由既有有效值规则作为所有未覆盖明细的默认 Reservation;`Line N` / `for line N` 的值仅写入第 N 个逻辑明细并覆盖默认值。多个不同整单值、同一行不同值、越界行号或 Schema 未启用行字段时转 Review;普通数量、客户号等无 Reservation 标签数字一律忽略。区域页可不同于明细页,正式解析、画布预览和盲测共用同一解析/归属契约;XFA 拆分规则仍仅负责 datasets 结构取值,不能代替本能力。 +**Reservation ID 专用证据区域(2026-08-25)**:管理员在同一模板画布圈选唯一的 `reservation_id_region`(区域坐标与页码),不配置 JSON、来源映射、拆分规则或 Header/Line 归属。后端只从该区域内带 `Reservation` 语义的 5/10 位数字提取候选:无行号的值写入 `header.reservation_id`,并由既有有效值规则作为所有未覆盖明细的默认 Reservation;`Line N` / `for line N` / `L#N` 的值按 Customer PO 行号(`customer_po_line_no`,LN 列)定位对应逻辑明细并覆盖默认值(**2026-09-16 修订**:此前按"第 N 个逻辑明细"位置写入,LN 非连续——如部分行已拆到其他 PO——时会错配行归属并把存在的行号误报越界;解析行缺少 LN 取值时才回退位置序以兼容无 LN 字段的旧 Schema)。多个不同整单值、同一行不同值、被引用行号不存在或 Schema 未启用行字段时转 Review;普通数量、客户号等无 Reservation 标签数字一律忽略。区域页可不同于明细页,正式解析、画布预览和盲测共用同一解析/归属契约;XFA 拆分规则仍仅负责 datasets 结构取值,不能代替本能力。**带复核原因的确定性订单必须保留(2026-09-16)**:Reservation 专区/行校验触发 `needs_review` 时以 `deterministic` 携带原因码交 STP 裁决,已解析订单继续落 provisional Candidate 供复核台编辑;不得以 `review_required` 丢弃取值导致复核草稿空白。 **阶段 1 历史 Dify 配置**:此段不再适用订单抽取。当前无需为订单抽取配置画布、Prompt、Start/End 变量、Code 节点或 `execution_manifest`;Schema 别名只在 HXOPS 管理端维护。 @@ -2032,7 +2032,7 @@ pip --version cd C:\HxopsRpaTest python -m pip install --upgrade pip -python -m pip install playwright openpyxl pyyaml +python -m pip install playwright openpyxl pyyaml cryptography python -m playwright install chromium ``` @@ -2868,6 +2868,166 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui - 生产 Windows RPA 脚本 - 上传成功 / 失败回执样例 +### 1.9 收料报表 RPA 共享部署(Windows RPA + Ubuntu 后端) + +> 本节是收料报表 RPA(独立 Windows Worker)的部署手册,章节结构与 `1.5` 库存导出 RPA 对应。安全提示与 `1.5` 相同:示例中的 IP、账号、密码、API Key 均为占位符,请在各环境本地替换为实际值,**禁止将真实密码/密钥写入仓库或提交到 Git**。 +> 前置条件:已按 `1.5.2` 至 `1.5.10` 完成同一台 Windows RPA 主机、`hxops-rpa-test-data` / `hxops-rpa-prod-data` SMB 共享、Ubuntu 挂载与后端容器挂载。收料**不新建共享、不新建挂载**,只在既有共享下增加专用子目录、独立 Worker 与独立回调。 +> Worker 脚本层速查另见 [scripts/rpa/README.md](../../../scripts/rpa/README.md) 顶部「收料 RPA(独立 Worker)」;本节是部署权威来源。 + +#### 1.9.1 与库存 RPA 的边界和目录规划 + +**与库存 RPA 完全一致、直接复用(不重复执行)**: + +- Windows RPA 主机、Python 3.12、Playwright Chromium、`hxops_share` 共享账号、两个 SMB 共享与 Ubuntu 挂载(`1.5.2`–`1.5.8`)。 +- DPAPI Secret 文件(`1.5.10` 的 `new_rpa_worker_secret.ps1`,字段为 `ToolApiKey` + `CredentialKey`):收料启动脚本读取**同一格式、同一文件**,无需新建收料 Secret。 +- Worker `-ApiBase` 口径与 `1.5.10` 相同:Docker Compose 部署填前端 nginx 网关地址(如 `http://: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 +3651,7 @@ DBS 每个 Warehouse 单独导出且不填报表日期;Crane 固定 `Inbound D ### 可靠性、补偿与审计边界 - trigger 采用“同目录临时文件写完、`fsync` 后 `os.replace` 原子发布”方式;收料 Worker 只能 claim 完整的 `.json`,不得读取半写入 trigger。 -- `awaiting_receipt_rpa` 运行受 `SHIPPING_NOTICE_RPA_RECEIPT_CALLBACK_TIMEOUT_SECONDS`(默认值由部署配置决定)限制。超时回收将仍 pending/running 的单元标记为 `failed/RPA.RECEIPT_CALLBACK_TIMEOUT`,结束排程并写前后快照审计;**不自动重试、不自动重发**,后续 Cron 或管理员人工补偿可继续执行。 +- `awaiting_receipt_rpa` 运行受 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 `900`,可由部署配置覆盖)限制。超时回收将仍 pending/running 的单元标记为 `failed/RPA.RECEIPT_CALLBACK_TIMEOUT`,结束排程并写前后快照审计;**不自动重试、不自动重发**,后续 Cron 或管理员人工补偿可继续执行。 - Worker 启动及常规扫描均回收超时运行,避免服务或 Worker 重启后运行永久占用排程状态。 - 空结果、Worker 失败、归档成功、对象删除失败、企微文件/汇总投递成功或失败、管理员查看失败单元、人工重试和重发均写追加式 `ShippingAuditEvent`。审计包含操作人/时间/对象、结果、脱敏原因或错误码、变更前后状态;不得写入密码、Cookie、令牌、对象存储定位或浏览器会话。 - 管理员失败单元查询仅返回运行诊断所需的站点、Warehouse、状态、错误码/脱敏错误和时间;接收人不拥有该查询、配置、重试或重发权限。 @@ -3607,3 +3767,22 @@ inventory_preparation Gate - 一期规划中的「快照重冻结 + `order_data_version` 递增」由既有 `update_notice_*` ⇒ `_commit_notice_edit` ⇒ `_apply_notice_edit_change_effects` 链路承担(编辑落库后依赖 `change_effect` 失效下游);`order_data_version` 由乐观锁 `_assert_order_data_version` 保护,避免重复冻结引入二次状态机。 - 波次通知「按自身行重跑路由」(D8)已实现(见一期章节):不再继承首通知源,`freeze_wave_notice_routing` 按波次自身行冻结候选集;本二期不新增二次波次状态机,与一期波次路由冻结复用同一套链路。 + +## 客户数据 ODM ID 范围与整单 ODM 裁决(2026-09) + +- 「客户主数据」页面与文案统一更名为「客户数据」;`ShippingCustomer` 新增可空 `odm_ids`(JSON 字符串清单),由客户数据页维护(每行一个,留空表示不限定)。 +- 生成发货 Excel 的整单 ODM 裁决(模板 Header 消费 `odm_id` 字段时生效,`export._adjudicate_notice_odm`): + 1. 客户 `odm_ids` 非空 → 先全局过滤库存命中行,仅保留范围内的 ODM;把原有命中全部排除时报「订单行命中的库存记录 ODM ID 不在客户数据维护的 ODM ID 范围内」。 + 2. 用户选择(`shipping_notice_line_inventory_matches.chosen_odm_id`,task 全部 `is_current` 行统一值)→ 过滤为所选 ODM;在当前库存中不存在时报「已选择的 ODM ID 在当前库存中不存在」。 + 3. 无范围、无选择且各行命中 ODM 交集唯一 → 自动收敛到唯一可行值;交集多个 → 维持折叠冲突阻断,由工作台下发候选。 +- 工作台「通知准备」面板为**行内 ODM 下拉**(任一行候选多于一个且未生成 Excel 时展示列):候选为该行经客户范围过滤后的命中值(保留原大小写);确认后 `POST /shipping-tasks//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 33eb8eb3..849a23a2 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -93,6 +93,7 @@ | --- | --- | --- | | **统一 ShippingProcessingProjection(15 阶段)+ 正式任务编辑** | 阶段 0–6 已验收 | 库存源硬门禁;复核台原地 formal_task;Schema `task_edit_policy`/`change_effect`;正式编辑审计矩阵;Dify NONE。验收:`unified-progress-formal-edit-stage0~6` + `final-acceptance` + `dify-config`。 | | 订单生命周期工作台状态展示统一(v2) | 已实现 | 五阶段下方横幅移除;右栏「当前任务」卡为唯一状态宿主:状态行=user_status 短标签(Run 级 lifecycle_status 受控兑底映射)+ 状态块内嵌动态说明(`RUN_STATUS_FALLBACK_MAP`/`REDUNDANT_DETAIL_REASON_CODES` 双常量裁决,诊断信息不隐藏);无 Case 瞬态保留单行白名单轻提示;聊天页/任务中心同源接入零视觉变化。设计:[2026-08-31 状态展示统一设计](superpowers/specs/2026-08-31-shipping-review-status-display-unification-design.md) | +| 订单队列五态图标与门禁阻塞标志 | 已实现 | 队列 item 新增 `needs_attention`(复用批量 Gate 缓存零额外 SQL,blocked_manual/blocked_retryable/failed_terminal 为真);左侧文件队列图标收敛为 需人工⚠/进行中🔄/终态✓/失败✗/中性○ 五态,绿勾仅限通知完成终态;队列 summary 三桶同口径。设计:[2026-09-16 队列图标语义设计](superpowers/specs/2026-09-16-review-queue-icon-semantics-design.md) | | 发货通知技术手册 | 已文档化 | 见 [docs/features/shipping-notice/technical.md](features/shipping-notice/technical.md) | | 发货通知业务说明 | 已文档化 | 见 [docs/features/shipping-notice/business.md](features/shipping-notice/business.md) | | 业务去重与任务版本(Phase 3) | 已实现 | Intake 业务指纹/重复决策、修订版本链、强制新建权限与审计;见技术手册第三节摘要 | @@ -179,6 +180,7 @@ | **行级人工选源动作 select_line_inventory_source(一期)** | 已实现 | Gate 业务动作(属 `inventory_matching`):校验行冲突、源 ∈ 候选、源启用、通知未生成 Excel(否则 `SHIPPING.LINE_SOURCE_LOCKED`);写候选行覆写 + 仅该行重匹配 + 审计 `review_line_source_selected`。 | | **通知准备行源下拉与锁定渲染(一期)** | 已实现 | `ui_state.preparation` 下发 `source_locked` / `lines[].source_ambiguous` / `source_candidates`;前端歧义行渲染库存源下拉 + 首选高亮 + 确认,`source_locked` 行只读徽标;阶段自动跳转一次性 toast + 清理 `reparse` 死守卫;四语言文案。 | | **波次库存源按自身行重路由(D8)** | 已实现 | `post_ot_fulfillment_wave_service` 创建波次通知不再继承首通知任务级源字段(`inventory_source_*`/`routing_fingerprint`/`snapshot_id`),仅继承订单级路由上下文(目的地/仓提示);新增 `inventory_candidate_freeze_service.freeze_wave_notice_routing` 按波次自身行评估路由并冻结候选集,随后走同一套自动探测/匹配/反写。测试:`test_shipping_wave_rerouting.py`。 | +| **客户数据 ODM ID 范围与整单 ODM 裁决** | 已实现 | 客户数据(原客户主数据)维护可空 `odm_ids` 清单;生成 Excel 时按客户范围过滤库存命中行,范围后仍多值时工作台整单选择(写入行级匹配事实 `chosen_odm_id`)并自动重试;交集唯一自动收敛。 | | **确认后订单编辑窗谓词(二期 T10)** | 已实现 | `order_edit_window_service.editable_scope`(header=订单任一通知无 Excel 且无活动 Attempt;行=所属通知无 Excel 且无活动 Attempt,未入波次行不受首单 Excel 限制)+ `order_has_active_attempt`;`ui_state` 下发 `edit_window`;测试通过。设计 §3.1。 | | **Excel 前保存守卫 + 失效分类重跑(二期 T11/T12)** | 已实现 | 正式字段编辑路径(`task_workflow.update_notice_*`)新增活动 Attempt 守卫(`SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`);失效重跑沿用 Schema `change_effect`:路由字段→`rerun_inventory_source_resolution`、行字段→`rerun_inventory_matching`、导出→`regenerate_excel`、需重解析→`require_revision`;审计含 `applied_effects` 失效动作链。设计 §3.2/§3.3。 | | **编辑窗前端渲染(二期 T13)** | 已实现 | `ShippingTaskUiState.edit_window` 类型 + `formalHeaderEditable()`/`formalLineEditable(lineKey)`;头字段编辑块按 `edit_window.header` 门控、歧义行源下拉确认按行锁定;四语言 `errors.json` 补 `SHIPPING.EDIT_WINDOW_FIELD_LOCKED/SYSTEM_BUSY`;`npm run build` 通过。 | 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/workspace.json b/frontend/src/locales/en/workspace.json index 73329ca5..b32fbd4a 100644 --- a/frontend/src/locales/en/workspace.json +++ b/frontend/src/locales/en/workspace.json @@ -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/workspace.json b/frontend/src/locales/th/workspace.json index 063e7322..fd214951 100644 --- a/frontend/src/locales/th/workspace.json +++ b/frontend/src/locales/th/workspace.json @@ -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/workspace.json b/frontend/src/locales/zh-CN/workspace.json index 27c91369..3989b32f 100644 --- a/frontend/src/locales/zh-CN/workspace.json +++ b/frontend/src/locales/zh-CN/workspace.json @@ -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/workspace.json b/frontend/src/locales/zh-TW/workspace.json index 5007a463..a8e98763 100644 --- a/frontend/src/locales/zh-TW/workspace.json +++ b/frontend/src/locales/zh-TW/workspace.json @@ -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": {