Merge branch 'hugo-shipping-notice' into test
This commit is contained in:
commit
933ac8ebcc
18 files changed
+1050
-73
No files matched your search
@@ -2,7 +2,8 @@
|
||||
|
||||
依赖:受控 HTML 网格解析、冻结订单 Schema 表头契约、PO/Reservation 标准化。
|
||||
逻辑:订单字段表头只复用 Run/当前发布 Schema 的显式别名;邮件专属的分配事实
|
||||
仍使用受控固定列。表格歧义或缺 PO 保留原因,不将正文直接转成订单。
|
||||
仍使用受控固定列。表格歧义保留原因,不将正文直接转成订单。
|
||||
无 PO 表头时,若已映射料号或预约号仍解析行(供 merge mpn_fallback);二者皆无才整表跳过。
|
||||
非法非 PO 字段跳过本列并记 issue,避免可选列拖垮 Reservation/库存源线索。
|
||||
reservation_id 通过安全抽取后写入归一本体(含短数字行序后缀)。
|
||||
多表按文档顺序叠行:靠前为新,同行身份键先到为准;旧表仅补全新表未覆盖的行。
|
||||
@@ -58,14 +59,24 @@ def _supplement_row_identity(row: dict[str, Any]) -> tuple[str, str, str] | None
|
||||
return None
|
||||
|
||||
|
||||
_IDENTITY_FIELD_CODES = frozenset({
|
||||
'part_number', 'customer_part_number', 'reservation_id',
|
||||
})
|
||||
_PO_FIELD_CODES = frozenset({'customer_po_number', 'po_number'})
|
||||
|
||||
|
||||
def _mapping_has_identity(mapped_fields: set[str]) -> bool:
|
||||
"""表头或行是否具备可与 PDF 关联的身份列(料号或预约号)。"""
|
||||
return bool(mapped_fields & _IDENTITY_FIELD_CODES)
|
||||
|
||||
|
||||
def _normalize_schema_row(
|
||||
values: dict[str, str], *, schema_definition: dict[str, Any], issues: list[str],
|
||||
) -> dict[str, Any] | None:
|
||||
"""按冻结 Schema 规范化并校验 EML 单元格;非法非 PO 字段跳过,不拖垮整行。
|
||||
|
||||
核心逻辑:PO 仍是行身份门槛;其余字段解析/校验失败只记
|
||||
``email_supplement_field_invalid`` 并省略该字段,避免可选列(如 PO Date)
|
||||
非法时把 Reservation / 库存源线索一并丢掉。
|
||||
核心逻辑:有 PO 则写入 PO;无 PO 时须具备料号或合法预约号才成行,供 merge 兜底。
|
||||
其余字段解析/校验失败只记 ``email_supplement_field_invalid`` 并省略该字段。
|
||||
|
||||
Args:
|
||||
values: 表头映射后的 field_code → 原始单元格文本。
|
||||
@@ -73,7 +84,7 @@ def _normalize_schema_row(
|
||||
issues: 可追加的问题码列表(调用方持有,本函数原地写入)。
|
||||
|
||||
Returns:
|
||||
规范化后的补充行;缺有效 PO 时返回 None。
|
||||
规范化后的补充行;无 PO 且无料号/预约号时返回 None。
|
||||
"""
|
||||
configs = _schema_configs(schema_definition)
|
||||
normalized: dict[str, Any] = {}
|
||||
@@ -82,7 +93,7 @@ def _normalize_schema_row(
|
||||
if config is None:
|
||||
normalized[field_code] = raw_value
|
||||
continue
|
||||
# [STEP] 非 PO 字段失败只跳过本列;PO 失败则稍后由 po 门槛统一拒行。
|
||||
# [STEP] 非 PO 字段失败只跳过本列;PO 失败则稍后统一处理。
|
||||
try:
|
||||
value = normalize_order_field_value(raw_value, config)
|
||||
except Exception:
|
||||
@@ -101,11 +112,16 @@ def _normalize_schema_row(
|
||||
normalized[field_code] = value
|
||||
po_code = 'customer_po_number' if 'customer_po_number' in normalized else 'po_number'
|
||||
po_number = normalize_po_number(normalized.get(po_code))
|
||||
if not po_number:
|
||||
issues.append('email_supplement_row_po_missing')
|
||||
return None
|
||||
normalized[po_code] = po_number
|
||||
return normalized
|
||||
if po_number:
|
||||
normalized[po_code] = po_number
|
||||
return normalized
|
||||
# [STEP] 无 PO:有料号或合法预约号仍成行;否则丢弃。
|
||||
has_part = any(str(normalized.get(code) or '').strip() for code in ('part_number', 'customer_part_number'))
|
||||
has_reservation = bool(validated_reservation_id(normalized.get('reservation_id')))
|
||||
if has_part or has_reservation:
|
||||
return normalized
|
||||
issues.append('email_supplement_row_po_missing')
|
||||
return None
|
||||
|
||||
|
||||
def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[int, str], list[str]]:
|
||||
@@ -136,11 +152,25 @@ def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[in
|
||||
selected_by_field[field_code] = (priority, column)
|
||||
elif len(hits) > 1:
|
||||
issues.append('email_supplement_header_ambiguous')
|
||||
if not ({'customer_po_number', 'po_number'} & set(mapped.values())):
|
||||
mapped_fields = set(mapped.values())
|
||||
if not (mapped_fields & _PO_FIELD_CODES):
|
||||
# 无 PO:有料号/预约号时仅作可观测标记(不阻断解析);否则硬失败。
|
||||
issues.append('email_supplement_po_header_missing')
|
||||
return mapped, sorted(set(issues))
|
||||
|
||||
|
||||
def _blocking_table_issues(table_issues: list[str], *, mapped_fields: set[str]) -> list[str]:
|
||||
"""返回会跳过整表的 issue;无 PO 但已有身份列时,po_header_missing 不阻断。"""
|
||||
soft_po_missing = (
|
||||
'email_supplement_po_header_missing' in table_issues
|
||||
and _mapping_has_identity(mapped_fields)
|
||||
)
|
||||
return [
|
||||
code for code in table_issues
|
||||
if not (soft_po_missing and code == 'email_supplement_po_header_missing')
|
||||
]
|
||||
|
||||
|
||||
def _schema_header_priority(schema_definition: dict[str, Any], field_code: str, normalized_header: str) -> int:
|
||||
"""返回字段表头的 Schema 声明顺序,供同字段多别名确定性裁决。"""
|
||||
priorities: list[int] = []
|
||||
@@ -201,7 +231,7 @@ def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str,
|
||||
continue
|
||||
mapping, table_issues = _field_map(grid, schema_definition=schema_definition)
|
||||
issues.extend(table_issues)
|
||||
if table_issues:
|
||||
if _blocking_table_issues(table_issues, mapped_fields=set(mapping.values())):
|
||||
continue
|
||||
for row_index in range(1, grid.row_count):
|
||||
values: dict[str, str] = {}
|
||||
@@ -259,7 +289,9 @@ def parse_email_allocation_text(*, body_text: str, content_hash: str, schema_def
|
||||
break
|
||||
expected.append(field)
|
||||
if not ({'customer_po_number', 'po_number'} & set(expected)):
|
||||
return result
|
||||
# 与 HTML 路径一致:无 PO 时须已识别料号或预约号表头,否则安全返回空。
|
||||
if not _mapping_has_identity(set(expected)):
|
||||
return result
|
||||
column_count = len(expected)
|
||||
rows: list[dict[str, Any]] = []
|
||||
seen_rows: set[tuple[str, ...]] = set()
|
||||
|
||||
@@ -10,6 +10,7 @@ services/shipping_notice/order_review_draft_service.py
|
||||
逻辑:只修改独立 Draft JSON;每次写入锁定 Case/Draft、校验草稿版本与 WorkflowItem 可写状态,
|
||||
追加 CaseEvent + ShippingAuditEvent,并镜像 review_field_changed 到订单抽取进度流;
|
||||
Item 已关闭/重识别中的冲突经 `_reject_draft_operation` 落 rejected 审计;
|
||||
STP 等待入队/排队/执行期间拒绝草稿内容写入(显式 validate 仍放行供自动协调器);
|
||||
整单校验汇总客户确认、有效 Reservation、行级库存源候选与自动建单资格;
|
||||
行级必填 reservation_id 空值时先回退表头(与建单资格 / Schema Runtime 一致),再报缺失;
|
||||
确认建单摘要同样回填行级 reservation_id,供物化 FieldValue / 冻结门禁消费;
|
||||
@@ -225,7 +226,7 @@ def _locked_case(*, user_id: int, case_no: str, action: str) -> ShippingOrderRev
|
||||
按 owner 分别锁定 Case 和当前 Draft;不可编辑时写拒绝审计。
|
||||
|
||||
核心逻辑:两段 FOR UPDATE 避免 joinedload+nullable 侧锁问题;Case 可识别后
|
||||
若状态不在可编辑集合,先落 rejected 审计再抛错。
|
||||
若状态不在可编辑集合,先落 rejected 审计再抛错;STP 已接手时拒绝内容写入。
|
||||
"""
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
@@ -248,9 +249,92 @@ def _locked_case(*, user_id: int, case_no: str, action: str) -> ShippingOrderRev
|
||||
action=action,
|
||||
error=ConflictError('Order review case is not editable', code='SHIPPING.REVIEW_CASE_NOT_EDITABLE'),
|
||||
)
|
||||
# draft_validated 放行:自动协调器在入队前仍需显式校验;内容写入一律拦截。
|
||||
if str(action or '').strip() != 'draft_validated' and _stp_automation_holds_draft(case):
|
||||
_reject_draft_operation(
|
||||
case,
|
||||
actor_id=int(user_id),
|
||||
action=action,
|
||||
error=ConflictError(
|
||||
'Draft is locked while system auto-create is in progress',
|
||||
code='SHIPPING.REVIEW_DRAFT_LOCKED_BY_AUTOMATION',
|
||||
),
|
||||
)
|
||||
return case
|
||||
|
||||
|
||||
def _stp_waiting_timeout_seconds() -> int:
|
||||
"""与 order_review_projection 同源的 STP waiting_to_start 超时秒数。"""
|
||||
try:
|
||||
from flask import current_app
|
||||
|
||||
return max(int(current_app.config.get('SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS', 120) or 120), 15)
|
||||
except Exception: # noqa: BLE001
|
||||
return 120
|
||||
|
||||
|
||||
def _stp_automation_holds_draft(case: ShippingOrderReviewCase) -> bool:
|
||||
"""
|
||||
判断 STP 是否已接手草稿(等待入队 / 排队 / 执行),期间禁止人工改草稿。
|
||||
|
||||
核心逻辑:有活跃 Job → 锁定;无 Job 但 can_auto_create+can_build 且未超时 → 锁定。
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import build_stp_idempotency_key
|
||||
|
||||
if case.confirmed_task_id is not None:
|
||||
return False
|
||||
draft = case.current_draft
|
||||
if draft is None or case.document_id is None:
|
||||
return False
|
||||
run = case.run
|
||||
run_no = str(getattr(run, 'run_no', '') or '').strip()
|
||||
if run_no:
|
||||
business_ref = build_stp_idempotency_key(
|
||||
run_no=run_no,
|
||||
document_id=int(case.document_id),
|
||||
draft_version=int(draft.draft_version),
|
||||
)
|
||||
active = (
|
||||
Job.query.filter(
|
||||
Job.domain == 'shipping_notice',
|
||||
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
|
||||
Job.business_ref == business_ref,
|
||||
Job.status.in_(('queued', 'running')),
|
||||
)
|
||||
.order_by(Job.id.desc())
|
||||
.first()
|
||||
)
|
||||
if active is not None:
|
||||
return True
|
||||
|
||||
validation = draft.validation_result_json if isinstance(draft.validation_result_json, dict) else {}
|
||||
if not (bool(validation.get('can_auto_create')) and bool(validation.get('can_build'))):
|
||||
return False
|
||||
if str(case.status or '') in {'confirmed', 'non_order', 'quality_issue'}:
|
||||
return False
|
||||
|
||||
validated_at = None
|
||||
raw_validated = str(validation.get('validated_at') or '').strip()
|
||||
if raw_validated:
|
||||
try:
|
||||
text = raw_validated[:-1] + '+00:00' if raw_validated.endswith('Z') else raw_validated
|
||||
validated_at = datetime.fromisoformat(text)
|
||||
except ValueError:
|
||||
validated_at = None
|
||||
anchor = validated_at or getattr(case, 'updated_at', None) or getattr(draft, 'updated_at', None)
|
||||
if anchor is not None:
|
||||
if getattr(anchor, 'tzinfo', None) is None:
|
||||
anchor = anchor.replace(tzinfo=timezone.utc)
|
||||
age = (datetime.now(timezone.utc) - anchor).total_seconds()
|
||||
if age >= _stp_waiting_timeout_seconds():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _expected_version(value: Any) -> int:
|
||||
"""写入接口必须明确带版本号,避免缺省值退化为最后写入者获胜。"""
|
||||
if isinstance(value, bool):
|
||||
|
||||
@@ -16,6 +16,7 @@ backend/app/services/shipping_notice/reconciliation_projector.py
|
||||
② project_case_allowed_actions(case, automation, is_admin)
|
||||
完整复刻 order_review_projection._allowed_actions 核心路径,
|
||||
注入 reconcile_and_progress 作为统一对账恢复入口;
|
||||
STP waiting_to_start/queued/running 时剥离 edit_draft/validate;
|
||||
REMOVE_SET 白名单剔除 retry_stp_auto_create 等;
|
||||
裁决动作 derive_blocking_next_actions 一致注入。
|
||||
③ project_case_current_gate(case, automation, available_actions)
|
||||
@@ -420,6 +421,12 @@ def project_case_allowed_actions(
|
||||
actions.append('edit_draft')
|
||||
|
||||
auto_status = str((automation or {}).get('status') or '').strip().lower()
|
||||
# STP 已接手(等待入队/排队/执行)期间禁止草稿编辑与显式校验,避免误改后仍自动建单。
|
||||
if auto_status in {'waiting_to_start', 'queued', 'running'}:
|
||||
actions = [
|
||||
action for action in actions
|
||||
if action not in {'edit_draft', 'create_draft', 'validate', 'request_llm_suggestion'}
|
||||
]
|
||||
if isinstance(automation, dict) and auto_status in {
|
||||
'failed', 'manual_fallback',
|
||||
} and not case.confirmed_task_id:
|
||||
@@ -839,7 +846,7 @@ def project_case_primary_action(
|
||||
return {'code': 'edit_draft', 'variant': 'primary',
|
||||
'label_key': 'shipping.actions.edit_draft'}
|
||||
|
||||
# 1g: running/queued → 次优先 view(但 edit_draft 仍然允许)
|
||||
# 1g: running → 不展示草稿主 CTA(STP 活跃时 edit_draft 已从 available_actions 剥离)。
|
||||
if user_status == 'running' and 'edit_draft' in actions:
|
||||
return None
|
||||
|
||||
|
||||
@@ -17,6 +17,8 @@ services/shipping_notice/shipping_processing_projection.py
|
||||
已建 Notice 时填 shipping_notice_no;work_items 构建后由
|
||||
_conversation_processing_from_work_items 构建正式 conversation_processing;
|
||||
首屏摘要在订单抽取失败且无 Case 时下发 reparse + 最新 run_no;
|
||||
摘要对开放 Case 批量预取活跃 STP Job,queued/running 映射为 running,
|
||||
禁止把建单队列中误判为待人工;
|
||||
不投影会话级批量恢复动作;失败必须由用户在当前 Gate 选择具体动作。
|
||||
"""
|
||||
|
||||
@@ -63,6 +65,7 @@ from app.services.shipping_notice.processing_ownership import (
|
||||
)
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_case_primary_action,
|
||||
project_case_user_status,
|
||||
)
|
||||
from app.services.shipping_notice.lifecycle_projection import (
|
||||
LIFECYCLE_STAGE_CODES,
|
||||
@@ -4022,6 +4025,10 @@ def project_conversation_processing_summary(
|
||||
建单前五阶段权威与 order-review-queue 对齐:开放 Case 只认 Case.candidate_id
|
||||
绑定的可复核 Candidate;不得用「Case 存在」或「文档上另有未绑定 Candidate」
|
||||
抬升 candidate_count / waiting_review→order_review。
|
||||
|
||||
开放 Case 的用户态须先认活跃 STP Job(queued/running → running),再认草稿
|
||||
can_auto_create+can_build 未超时(waiting_to_start → running),与工作台
|
||||
project_case_user_status 同源;不得仅因 Case 未确认就判 waiting_human。
|
||||
"""
|
||||
del agent_id
|
||||
normalized = str(conversation_id or '').strip()
|
||||
@@ -4209,6 +4216,7 @@ def project_conversation_processing_summary(
|
||||
ShippingOrderReviewCase.current_draft_id,
|
||||
ShippingOrderReviewCase.confirmed_task_id,
|
||||
ShippingOrderReviewCase.candidate_id,
|
||||
ShippingOrderReviewCase.updated_at,
|
||||
)).filter(
|
||||
ShippingOrderReviewStream.document_id.in_(document_ids) if document_ids else False,
|
||||
).all()
|
||||
@@ -4267,6 +4275,121 @@ def project_conversation_processing_summary(
|
||||
)
|
||||
}
|
||||
|
||||
# [STEP] 开放 Case 批量预取活跃 STP Job(与 full 会话投影同构前缀),
|
||||
# 供摘要 _status 在判 waiting_human 前与工作台同源认「系统仍在建单」。
|
||||
_OPEN_CASE_STATUSES_FOR_STP = {
|
||||
'unreviewed', 'draft', 'ready', 'quality_issue', 'reparse_pending',
|
||||
}
|
||||
active_stp_status_by_document_id: dict[int, str] = {}
|
||||
open_case_stp_prefixes: dict[str, int] = {}
|
||||
for case in current_case_by_document_id.values():
|
||||
if case.confirmed_task_id is not None or case.document_id is None or case.run_id is None:
|
||||
continue
|
||||
if str(case.status or '').strip().lower() not in _OPEN_CASE_STATUSES_FOR_STP:
|
||||
continue
|
||||
run = runs_by_id.get(int(case.run_id))
|
||||
run_no = str(getattr(run, 'run_no', '') or '').strip()
|
||||
if not run_no:
|
||||
continue
|
||||
prefix = f'stp-auto:{run_no}:doc-{int(case.document_id)}:'
|
||||
open_case_stp_prefixes[prefix] = int(case.document_id)
|
||||
if open_case_stp_prefixes:
|
||||
from app.jobs.types import JobType
|
||||
|
||||
for job in (
|
||||
Job.query.filter(
|
||||
Job.domain == 'shipping_notice',
|
||||
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
|
||||
Job.status.in_(('queued', 'running')),
|
||||
or_(*(Job.business_ref.like(f'{prefix}%') for prefix in open_case_stp_prefixes)),
|
||||
)
|
||||
.order_by(Job.id.desc())
|
||||
.all()
|
||||
):
|
||||
ref = str(job.business_ref or '').strip()
|
||||
status = str(job.status or '').strip().lower()
|
||||
if status not in {'queued', 'running'}:
|
||||
continue
|
||||
for prefix, document_id in open_case_stp_prefixes.items():
|
||||
if not ref.startswith(prefix):
|
||||
continue
|
||||
# 同前缀取最新 Job(已按 id desc);已写入则跳过更旧记录。
|
||||
active_stp_status_by_document_id.setdefault(document_id, status)
|
||||
break
|
||||
|
||||
# [STEP] Phase 2:无活跃 Job 的开放 Case,批量读草稿 can_auto_create/can_build,
|
||||
# 未超时则视为 waiting_to_start(系统已接手),与工作台 F2 对齐。
|
||||
waiting_to_start_document_ids: set[int] = set()
|
||||
open_draft_ids = [
|
||||
int(case.current_draft_id)
|
||||
for case in current_case_by_document_id.values()
|
||||
if (
|
||||
case.confirmed_task_id is None
|
||||
and case.current_draft_id is not None
|
||||
and case.document_id is not None
|
||||
and str(case.status or '').strip().lower() in _OPEN_CASE_STATUSES_FOR_STP
|
||||
and int(case.document_id) not in active_stp_status_by_document_id
|
||||
)
|
||||
]
|
||||
drafts_by_id: dict[int, ShippingOrderReviewDraft] = {}
|
||||
if open_draft_ids:
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.services.shipping_notice.order_review_projection import (
|
||||
_stp_waiting_timeout_seconds as _summary_stp_waiting_timeout_seconds,
|
||||
)
|
||||
|
||||
for draft in ShippingOrderReviewDraft.query.options(load_only(
|
||||
ShippingOrderReviewDraft.id,
|
||||
ShippingOrderReviewDraft.validation_result_json,
|
||||
ShippingOrderReviewDraft.updated_at,
|
||||
)).filter(ShippingOrderReviewDraft.id.in_(open_draft_ids)).all():
|
||||
drafts_by_id[int(draft.id)] = draft
|
||||
|
||||
def _parse_validated_at(raw: Any):
|
||||
text = str(raw or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
if text.endswith('Z'):
|
||||
text = text[:-1] + '+00:00'
|
||||
return datetime.fromisoformat(text)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
timeout_sec = _summary_stp_waiting_timeout_seconds()
|
||||
for case in current_case_by_document_id.values():
|
||||
if case.confirmed_task_id is not None or case.document_id is None:
|
||||
continue
|
||||
doc_id = int(case.document_id)
|
||||
if doc_id in active_stp_status_by_document_id:
|
||||
continue
|
||||
if str(case.status or '').strip().lower() not in _OPEN_CASE_STATUSES_FOR_STP:
|
||||
continue
|
||||
draft = (
|
||||
drafts_by_id.get(int(case.current_draft_id))
|
||||
if case.current_draft_id is not None else None
|
||||
)
|
||||
if draft is None:
|
||||
continue
|
||||
validation = (
|
||||
draft.validation_result_json
|
||||
if isinstance(draft.validation_result_json, dict) else {}
|
||||
)
|
||||
if not (bool(validation.get('can_auto_create')) and bool(validation.get('can_build'))):
|
||||
continue
|
||||
anchor = (
|
||||
_parse_validated_at(validation.get('validated_at'))
|
||||
or getattr(case, 'updated_at', None)
|
||||
or getattr(draft, 'updated_at', None)
|
||||
)
|
||||
if anchor is not None:
|
||||
if getattr(anchor, 'tzinfo', None) is None:
|
||||
anchor = anchor.replace(tzinfo=timezone.utc)
|
||||
if (datetime.now(timezone.utc) - anchor).total_seconds() >= timeout_sec:
|
||||
continue
|
||||
waiting_to_start_document_ids.add(doc_id)
|
||||
|
||||
def _status(
|
||||
document: ShippingOrderDocument,
|
||||
task: ShippingOrderTask | None,
|
||||
@@ -4285,9 +4408,16 @@ def project_conversation_processing_summary(
|
||||
if gate_status == 'cancelled':
|
||||
return 'cancelled', gate_code, gate_reason
|
||||
case_status = str(getattr(case, 'status', None) or '').strip().lower()
|
||||
if case is not None and case.confirmed_task_id is None and case_status in {
|
||||
'unreviewed', 'draft', 'ready', 'quality_issue', 'reparse_pending',
|
||||
}:
|
||||
if case is not None and case.confirmed_task_id is None and case_status in _OPEN_CASE_STATUSES_FOR_STP:
|
||||
# 活跃 STP 或 waiting_to_start = 系统仍在建单;与 project_case_user_status 对齐。
|
||||
doc_id = int(case.document_id) if case.document_id is not None else int(document.id)
|
||||
stp_status = active_stp_status_by_document_id.get(doc_id)
|
||||
if stp_status in {'queued', 'running'}:
|
||||
mapped = project_case_user_status(case, {'status': stp_status})
|
||||
return mapped, 'waiting_review', None
|
||||
if doc_id in waiting_to_start_document_ids:
|
||||
mapped = project_case_user_status(case, {'status': 'waiting_to_start'})
|
||||
return mapped, 'waiting_review', None
|
||||
return 'waiting_human', 'waiting_review', f'review_case_{case_status}'
|
||||
raw = str(task.status if task is not None else document.order_extraction_status or '').strip().lower()
|
||||
stage = str(task.stage if task is not None else '').strip().lower() or (
|
||||
@@ -4378,13 +4508,18 @@ def project_conversation_processing_summary(
|
||||
if has_current_candidate:
|
||||
# Case 已绑定可复核 Candidate 后进入订单复核;仅用已批量读取的
|
||||
# current_draft_id 恢复权威业务动作,避免摘要路径逐文件加载 Case 详情。
|
||||
available_actions = ['edit_draft' if case.current_draft_id else 'create_draft']
|
||||
primary_action = project_case_primary_action(
|
||||
user_status,
|
||||
{'code': reason, 'i18n_key': None, 'details': None},
|
||||
available_actions,
|
||||
user_stage='order_review',
|
||||
)
|
||||
# STP 系统处理中禁止暴露 edit/create_draft,与 Case bundle 动作白名单一致。
|
||||
if user_status == 'running':
|
||||
available_actions = []
|
||||
primary_action = None
|
||||
else:
|
||||
available_actions = ['edit_draft' if case.current_draft_id else 'create_draft']
|
||||
primary_action = project_case_primary_action(
|
||||
user_status,
|
||||
{'code': reason, 'i18n_key': None, 'details': None},
|
||||
available_actions,
|
||||
user_stage='order_review',
|
||||
)
|
||||
else:
|
||||
# 无有效 Candidate 的 Case 仍在接收解析处置;阶段按钮只负责导航,
|
||||
# 文件主动作必须是服务端已经授权的重解析命令。
|
||||
|
||||
@@ -620,6 +620,43 @@ def test_email_supplement_requires_frozen_schema_alias_for_order_headers():
|
||||
assert result == {'version': 'email-supplement.v1', 'rows': [], 'issues': ['email_supplement_po_header_missing']}
|
||||
|
||||
|
||||
def test_email_supplement_parses_without_po_when_mpn_and_reservation_present():
|
||||
"""无 PO 表头但有 MPN + External reservation ID 时仍须产出补充行(本单回归)。"""
|
||||
html = '''<table><tr>
|
||||
<th>MPN</th><th>Source type</th><th>External reservation ID</th>
|
||||
</tr><tr>
|
||||
<td>D4-A08AR12000002</td><td>VMI-SIN</td><td>3000092917</td>
|
||||
</tr></table>'''
|
||||
supplement = parse_email_allocation_tables(
|
||||
content_hash='j' * 64, html_tables=[html], schema_definition=SCHEMA,
|
||||
)
|
||||
assert len(supplement['rows']) == 1
|
||||
assert supplement['rows'][0]['part_number'] == 'D4-A08AR12000002'
|
||||
assert supplement['rows'][0]['reservation_id'] == '3000092917'
|
||||
assert supplement['rows'][0]['inventory_source_hint'] == 'VMI-SIN'
|
||||
assert 'email_supplement_po_header_missing' in supplement['issues']
|
||||
merged = merge_email_supplements(
|
||||
orders=[_order()],
|
||||
supplements_by_intake={1: {**supplement, 'document_id': 44}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert _value(merged['lines'][0]['fields'], 'reservation') == '3000092917'
|
||||
assert _value(merged['lines'][0]['fields'], 'source') == 'VMI-SIN'
|
||||
assert merged['_hxops_email_supplement_relation'] == 'mpn_fallback'
|
||||
|
||||
|
||||
def test_email_supplement_still_skips_table_without_po_or_part_or_reservation():
|
||||
"""无 PO 且无料号/预约号可映射列时仍整表跳过,避免无身份噪声行。"""
|
||||
result = parse_email_allocation_tables(
|
||||
content_hash='k' * 64,
|
||||
schema_definition=SCHEMA,
|
||||
html_tables=['''<table><tr><th>Location ID</th><th>Supplier code</th></tr>
|
||||
<tr><td>941.76</td><td>0000000100</td></tr></table>'''],
|
||||
)
|
||||
assert result['rows'] == []
|
||||
assert 'email_supplement_po_header_missing' in result['issues']
|
||||
|
||||
|
||||
def test_email_supplement_inventec_po_date_two_digit_year_keeps_source_location():
|
||||
"""Inventec 分配表 PO Date=12-Jun-26 时仍须保留 Source Location / 预约号。
|
||||
|
||||
|
||||
@@ -1791,6 +1791,190 @@ def test_fill_dsv_username_reuses_detected_email_locator(monkeypatch):
|
||||
assert locator.value == "user@example.com"
|
||||
|
||||
|
||||
def test_maybe_switch_dsv_locale_to_zh_cn_skips_when_already_zh(monkeypatch):
|
||||
"""已是中文简体时不重复点语言下拉。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
auth_globals = worker._maybe_switch_dsv_locale_to_zh_cn.__globals__
|
||||
clicks = {"value": 0}
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, text: str = "") -> None:
|
||||
self.first = self
|
||||
self._text = text
|
||||
|
||||
def wait_for(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
def inner_text(self, *args, **kwargs) -> str:
|
||||
return self._text
|
||||
|
||||
def click(self, *args, **kwargs) -> None:
|
||||
clicks["value"] += 1
|
||||
|
||||
class _FakeFrame:
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
if selector == "#lanNavSel":
|
||||
return _FakeLocator("中文简体")
|
||||
return _FakeLocator("")
|
||||
|
||||
class _FakePage:
|
||||
frames = [_FakeFrame()]
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeFrame().locator(selector)
|
||||
|
||||
monkeypatch.setitem(auth_globals, "_dsv_switch_zh_cn_enabled", lambda: True)
|
||||
assert worker._maybe_switch_dsv_locale_to_zh_cn(_FakePage()) is True
|
||||
assert clicks["value"] == 0
|
||||
|
||||
|
||||
def test_maybe_switch_dsv_locale_to_zh_cn_clicks_english_to_simplified(monkeypatch):
|
||||
"""English 时点 #kc_locale 再选中文简体,并在标签变为中文后返回 True。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
auth_globals = worker._maybe_switch_dsv_locale_to_zh_cn.__globals__
|
||||
state = {"label": "English", "opened": False, "clicks": []}
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, kind: str) -> None:
|
||||
self.first = self
|
||||
self._kind = kind
|
||||
|
||||
def wait_for(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
def inner_text(self, *args, **kwargs) -> str:
|
||||
return state["label"]
|
||||
|
||||
def click(self, *args, **kwargs) -> None:
|
||||
state["clicks"].append(self._kind)
|
||||
if self._kind == "toggle":
|
||||
state["opened"] = True
|
||||
if self._kind == "zh":
|
||||
state["label"] = "中文简体"
|
||||
|
||||
class _FakeFrame:
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
if selector == "#lanNavSel":
|
||||
return _FakeLocator("label")
|
||||
if selector == "#kc_locale":
|
||||
return _FakeLocator("toggle")
|
||||
if "中文简体" in selector:
|
||||
if not state["opened"]:
|
||||
raise RuntimeError("menu closed")
|
||||
return _FakeLocator("zh")
|
||||
raise RuntimeError(f"unexpected selector {selector}")
|
||||
|
||||
class _FakePage:
|
||||
frames = [_FakeFrame()]
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeFrame().locator(selector)
|
||||
|
||||
monkeypatch.setitem(auth_globals, "_dsv_switch_zh_cn_enabled", lambda: True)
|
||||
monkeypatch.setattr(auth_globals["time"], "sleep", lambda seconds: None)
|
||||
ticks = {"value": 0.0}
|
||||
|
||||
def fake_monotonic() -> float:
|
||||
current = ticks["value"]
|
||||
ticks["value"] += 0.5
|
||||
return current
|
||||
|
||||
monkeypatch.setattr(auth_globals["time"], "monotonic", fake_monotonic)
|
||||
|
||||
assert worker._maybe_switch_dsv_locale_to_zh_cn(_FakePage()) is True
|
||||
assert state["clicks"] == ["toggle", "zh"]
|
||||
assert state["label"] == "中文简体"
|
||||
|
||||
|
||||
def test_maybe_switch_dsv_locale_to_zh_cn_disabled_by_env(monkeypatch):
|
||||
"""环境变量关闭时不尝试切语言。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
auth_globals = worker._maybe_switch_dsv_locale_to_zh_cn.__globals__
|
||||
monkeypatch.setitem(auth_globals, "_dsv_switch_zh_cn_enabled", lambda: False)
|
||||
assert worker._maybe_switch_dsv_locale_to_zh_cn(object()) is False
|
||||
|
||||
|
||||
def test_is_dsv_password_method_label_matches_english_subtitle_row():
|
||||
"""
|
||||
英文 MFA 页「Password + Enter your password to sign in.」整行须识别为密码方式;
|
||||
Passkey / Mobile App / E-Mail Code 不得误判(对应 2026-09-16 worker 失败页)。
|
||||
"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
assert worker._is_dsv_password_method_label("Password") is True
|
||||
assert worker._is_dsv_password_method_label("Password\nEnter your password to sign in.") is True
|
||||
assert worker._is_dsv_password_method_label("密码") is True
|
||||
assert worker._is_dsv_password_method_label("Passkey\nUse this device to sign in.") is False
|
||||
assert worker._is_dsv_password_method_label("Mobile App (iPhone 11)\nUse your PingID app to sign in.") is False
|
||||
assert worker._is_dsv_password_method_label("E-Mail Code\nEnter a 6-digit code sent to your inbox.") is False
|
||||
assert worker._is_dsv_password_method_label("Forgot password") is False
|
||||
|
||||
|
||||
def test_click_dsv_password_method_clicks_english_choose_sign_in_row(monkeypatch):
|
||||
"""
|
||||
当页面只有带副标题的 Password 行(无旧 mfaForm 精确标题)时,仍应点击并确认过渡。
|
||||
"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
auth_globals = worker._click_dsv_password_method.__globals__
|
||||
clicked = {"value": False}
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, text: str = "") -> None:
|
||||
self.first = self
|
||||
self._text = text
|
||||
|
||||
def all(self):
|
||||
return [self] if self._text else []
|
||||
|
||||
def inner_text(self, *args, **kwargs) -> str:
|
||||
return self._text
|
||||
|
||||
def wait_for(self, *args, **kwargs) -> None:
|
||||
if not self._text:
|
||||
raise RuntimeError("not visible")
|
||||
|
||||
def scroll_into_view_if_needed(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
def click(self, *args, **kwargs) -> None:
|
||||
clicked["value"] = True
|
||||
|
||||
def evaluate(self, *args, **kwargs) -> None:
|
||||
clicked["value"] = True
|
||||
|
||||
class _FakeFrame:
|
||||
def evaluate(self, script: str, *args, **kwargs):
|
||||
# 脚本路径故意失败,迫使走 Playwright 行点击兜底
|
||||
return False
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
if "listitem" in selector or "mb-2" in selector or "device-list" in selector:
|
||||
return _FakeLocator("Password\nEnter your password to sign in.")
|
||||
return _FakeLocator("")
|
||||
|
||||
class _FakePage:
|
||||
frames = [_FakeFrame()]
|
||||
url = "https://auth.dbschenker.com/as/mock/resume/as/authorization.ping"
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeFrame().locator(selector)
|
||||
|
||||
monkeypatch.setattr(auth_globals["time"], "sleep", lambda seconds: None)
|
||||
ticks = {"value": 0.0}
|
||||
|
||||
def fake_monotonic() -> float:
|
||||
current = ticks["value"]
|
||||
ticks["value"] += 0.1
|
||||
return current
|
||||
|
||||
monkeypatch.setattr(auth_globals["time"], "monotonic", fake_monotonic)
|
||||
monkeypatch.setitem(auth_globals, "_find_dsv_password_locator", lambda *args, **kwargs: object())
|
||||
monkeypatch.setitem(auth_globals, "_wait_for_visible_selector", lambda *args, **kwargs: object())
|
||||
monkeypatch.setitem(auth_globals, "_looks_like_dsv_login_method_page", lambda page: False)
|
||||
|
||||
assert worker._click_dsv_password_method(_FakePage()) is True
|
||||
assert clicked["value"] is True
|
||||
|
||||
|
||||
def test_click_dsv_password_method_ignores_forgot_password_link(monkeypatch):
|
||||
"""密码页的“忘记密码/Forgot password”链接不能被当成密码登录方式点击。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
@@ -4,7 +4,8 @@ backend/tests/test_shipping_processing_projection_stage4.py
|
||||
用途:验收多 EML / 直接 PDF 阶段 4 — 统一 ShippingProcessingProjection 适配器。
|
||||
依赖:pytest、app fixture、User/FileAsset/upload mock、ShippingOrderIntake、projection helpers。
|
||||
逻辑:断言 status/stage 映射(direct_pdf 永不 email_adjudicating);
|
||||
project_intake_work_item 填充 current_gate / 失败恢复摘要;会话投影含 work_items。
|
||||
project_intake_work_item 填充 current_gate / 失败恢复摘要;会话投影含 work_items;
|
||||
摘要开放 Case + queued STP 不得误判 waiting_human。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -1875,6 +1876,152 @@ def test_summary_leaf_preserves_edit_draft_for_current_candidate_case(app) -> No
|
||||
assert summary_leaf['intake_parse_authorized'] is False
|
||||
|
||||
|
||||
def test_summary_leaf_open_case_with_queued_stp_is_running_not_waiting_human(app) -> None:
|
||||
"""开放 Case 若已有 queued STP Job,摘要必须进系统处理中,不得误报待人工。
|
||||
|
||||
回归:批次进度中心曾见 open Case 即 waiting_human,忽略 jobs 表中
|
||||
shipping_stp_auto_create 排队态;工作台已按 Job 投影为 running。
|
||||
"""
|
||||
with app.app_context():
|
||||
from app.models import Job
|
||||
from app.jobs.types import JobType
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
build_stp_idempotency_key,
|
||||
)
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(
|
||||
suffix='SUMMARY-STP-QUEUED',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-SUMMARY-STP-QUEUED',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='summary-stp-queued',
|
||||
order_extraction_run_id=run.id,
|
||||
is_current_version=True,
|
||||
candidate_status='accepted',
|
||||
po_number='PO-SUMMARY-STP-QUEUED',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
review_case = ensure_run_review_cases(run=run)[0]
|
||||
review_case.status = 'draft'
|
||||
draft = review_case.current_draft
|
||||
assert draft is not None
|
||||
assert review_case.confirmed_task_id is None
|
||||
business_ref = build_stp_idempotency_key(
|
||||
run_no=str(run.run_no),
|
||||
document_id=int(document.id),
|
||||
draft_version=int(draft.draft_version),
|
||||
)
|
||||
db.session.add(Job(
|
||||
domain='shipping_notice',
|
||||
job_type=JobType.SHIPPING_STP_AUTO_CREATE.value,
|
||||
status='queued',
|
||||
business_ref=business_ref,
|
||||
payload_json={
|
||||
'case_no': review_case.case_no,
|
||||
'run_no': run.run_no,
|
||||
'document_id': int(document.id),
|
||||
'draft_version': int(draft.draft_version),
|
||||
},
|
||||
attempts=0,
|
||||
max_attempts=3,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
payload = project_conversation_processing_summary(
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
)
|
||||
groups = payload['conversation_processing']['status_groups']
|
||||
# 关键断言:queued STP 时叶子必须在 processing,不得进 waiting_human。
|
||||
waiting_ids = {
|
||||
child['source_summary']['document_id']
|
||||
for row in groups.get('waiting_human') or []
|
||||
for child in row.get('aggregate_children') or []
|
||||
}
|
||||
processing_leaf = next(
|
||||
child
|
||||
for row in groups.get('processing') or []
|
||||
for child in row.get('aggregate_children') or []
|
||||
if child['source_summary']['document_id'] == document.id
|
||||
)
|
||||
assert document.id not in waiting_ids
|
||||
assert processing_leaf['user_status'] == 'running'
|
||||
assert processing_leaf['user_group'] == 'processing'
|
||||
assert processing_leaf['case_no'] == review_case.case_no
|
||||
assert processing_leaf.get('blocking_reason') is None
|
||||
assert (processing_leaf.get('ui_state') or {}).get('status') == 'running'
|
||||
assert 'edit_draft' not in (processing_leaf.get('available_actions') or [])
|
||||
assert processing_leaf.get('primary_action') is None
|
||||
|
||||
|
||||
def test_summary_leaf_waiting_to_start_without_job_is_running_and_hides_edit(app) -> None:
|
||||
"""can_auto_create 且无活跃 STP Job 时,摘要须为 running,且不得暴露 edit_draft。"""
|
||||
with app.app_context():
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(
|
||||
suffix='SUMMARY-STP-WAITING',
|
||||
)
|
||||
intake.source_type = 'eml'
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-SUMMARY-STP-WAITING',
|
||||
intake_id=intake.id,
|
||||
primary_document_id=document.id,
|
||||
candidate_key='summary-stp-waiting',
|
||||
order_extraction_run_id=run.id,
|
||||
is_current_version=True,
|
||||
candidate_status='accepted',
|
||||
po_number='PO-SUMMARY-STP-WAITING',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
review_case = ensure_run_review_cases(run=run)[0]
|
||||
review_case.status = 'draft'
|
||||
draft = review_case.current_draft
|
||||
assert draft is not None
|
||||
draft.validation_result_json = {
|
||||
'status': 'ready',
|
||||
'can_build': True,
|
||||
'can_auto_create': True,
|
||||
'validated_at': datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
db.session.commit()
|
||||
|
||||
payload = project_conversation_processing_summary(
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
)
|
||||
groups = payload['conversation_processing']['status_groups']
|
||||
waiting_ids = {
|
||||
child['source_summary']['document_id']
|
||||
for row in groups.get('waiting_human') or []
|
||||
for child in row.get('aggregate_children') or []
|
||||
}
|
||||
processing_leaf = next(
|
||||
child
|
||||
for row in groups.get('processing') or []
|
||||
for child in row.get('aggregate_children') or []
|
||||
if child['source_summary']['document_id'] == document.id
|
||||
)
|
||||
assert document.id not in waiting_ids
|
||||
assert processing_leaf['user_status'] == 'running'
|
||||
assert 'edit_draft' not in (processing_leaf.get('available_actions') or [])
|
||||
assert processing_leaf.get('primary_action') is None
|
||||
|
||||
|
||||
def test_summary_leaf_uses_current_review_case_run_for_intake_parse_navigation(app) -> None:
|
||||
"""摘要投影的接收解析深链必须把同一 Case 的 Run 一并下发。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
tests/test_shipping_review_workbench_state_isolation.py
|
||||
|
||||
用途:锁定复核工作台状态隔离契约——profile_match 管理员裁剪、automation 资格分层、
|
||||
Validation Snapshot 身份字段、用户 Gate 不把客户确认/技术 pending 当优先处理。
|
||||
Validation Snapshot 身份字段、用户 Gate 不把客户确认/技术 pending 当优先处理;
|
||||
STP 接手期间剥离草稿编辑动作并拒绝内容写入。
|
||||
依赖:pytest、order_review_projection、process_gate_projection、types.SimpleNamespace。
|
||||
逻辑:纯单元/轻量投影测试;不启 Flask 全应用。
|
||||
逻辑:纯单元/轻量投影测试;含 app fixture 的草稿写锁回归。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,6 +13,7 @@ from __future__ import annotations
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.order_review_projection import (
|
||||
_inventory_rpa_is_running,
|
||||
_project_case_automation_status,
|
||||
@@ -160,6 +162,100 @@ def test_stp_failure_stays_on_order_creation_node_and_hides_review_entry():
|
||||
assert 'open_order_review' not in actions
|
||||
|
||||
|
||||
def test_stp_holding_statuses_strip_draft_edit_actions():
|
||||
"""waiting_to_start/queued/running 必须剥离 edit_draft/validate,禁止误改草稿。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_case_allowed_actions,
|
||||
)
|
||||
|
||||
case = SimpleNamespace(
|
||||
id=11,
|
||||
status='draft',
|
||||
candidate_id=90,
|
||||
disposition=None,
|
||||
confirmed_task_id=None,
|
||||
confirmed_task_no=None,
|
||||
)
|
||||
for status in ('waiting_to_start', 'queued', 'running'):
|
||||
with patch(
|
||||
'app.services.shipping_notice.workflow_ledger_service.find_item_by_current_case',
|
||||
return_value=None,
|
||||
), patch(
|
||||
'app.services.shipping_notice.tool_common.llm_review_enabled',
|
||||
return_value=True,
|
||||
):
|
||||
actions = project_case_allowed_actions(case, automation={'status': status})
|
||||
assert 'edit_draft' not in actions
|
||||
assert 'create_draft' not in actions
|
||||
assert 'validate' not in actions
|
||||
assert 'request_llm_suggestion' not in actions
|
||||
assert 'view' in actions
|
||||
|
||||
|
||||
def test_draft_mutation_rejects_when_stp_automation_holds(app, monkeypatch):
|
||||
"""STP 接手期间 patch 草稿必须 Conflict;显式 validate 仍放行给自动协调器。"""
|
||||
from app.core.errors import ConflictError
|
||||
from app.services.shipping_notice import order_review_draft_service as draft_svc
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
patch_header_field,
|
||||
validate_draft,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='DRAFT-STP-LOCK')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
snapshot = dict(run.input_snapshot_json or {})
|
||||
schema = dict(snapshot.get('schema') or {})
|
||||
definition = dict(schema.get('definition') or {})
|
||||
definition['fields'] = [
|
||||
{
|
||||
'field_id': 'po-id', 'field_code': 'po_number', 'scope': 'header',
|
||||
'value_type': 'string', 'required': False, 'normalizer_key': 'trim',
|
||||
'validator_keys': [], 'enabled': True,
|
||||
},
|
||||
]
|
||||
schema['definition'] = definition
|
||||
snapshot['schema'] = schema
|
||||
run.input_snapshot_json = snapshot
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {
|
||||
'orders': [{
|
||||
'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-1'}]}],
|
||||
'lines': [],
|
||||
}],
|
||||
}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
draft = case.current_draft
|
||||
assert draft is not None
|
||||
version = int(draft.draft_version)
|
||||
monkeypatch.setattr(draft_svc, '_stp_automation_holds_draft', lambda _case: True)
|
||||
|
||||
try:
|
||||
patch_header_field(
|
||||
user_id=user.id,
|
||||
case_no=case.case_no,
|
||||
field_id='po-id',
|
||||
value='PO-LOCKED',
|
||||
expected_draft_version=version,
|
||||
)
|
||||
except ConflictError as exc:
|
||||
assert exc.code == 'SHIPPING.REVIEW_DRAFT_LOCKED_BY_AUTOMATION'
|
||||
else:
|
||||
raise AssertionError('STP hold must block draft patch')
|
||||
|
||||
# 关键断言:自动协调仍可显式 validate(action=draft_validated 放行)。
|
||||
validated = validate_draft(
|
||||
user_id=user.id,
|
||||
case_no=case.case_no,
|
||||
expected_draft_version=version,
|
||||
)
|
||||
assert validated is not None
|
||||
|
||||
|
||||
def test_stale_running_stp_job_becomes_user_actionable_failure():
|
||||
"""超时的 running Job 必须停止,并投影当前 Gate 的明确用户动作。"""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
@@ -399,7 +399,7 @@ L1 字段级:目标单元格 + 表头 + 相邻单元格
|
||||
|
||||
**版面签名证据一致性(2026-08-04)**:表头签名不再扫描整页顶部或按表高固定比例猜测,而是直接冻结模板既有 `header_layout.region`;运行时对每个候选在同一区域独立取证。新旧 PDF 坐标证据统一按视觉行和纯几何词间距恢复表头词组,避免 `boundary_before` 有无造成同文件签名漂移;列中心和列宽由表头词组边界产生,不再使用全表单字符连续聚类。只有同时达到模板最低分和证据覆盖率的候选才参与唯一性与 Margin 决胜。
|
||||
|
||||
**邮件补充重建规则(2026-07-31)**:邮件表头只能按当前 Run 冻结 Schema 的显式别名映射;行级 `reservation_id` 包含真实业务表头 `External reservation ID`。只要 Intake 保留原始 `body_html_tables`,Run 冻结时必须按自己的 Schema 重新解析完整补充表,不能复用上传阶段缺字段但已有部分行的旧结果;没有 HTML 时才复用已有完整结果或安全回退纵向纯文本解析。**关联收紧(2026-09-15)**:`mpn_fallback` 仅适用于补充行 PO 缺失且料号唯一命中;有 PO 且与 PDF 不一致不得补充。预约号允许短数字行序后缀归一(如 `35354-1` → `35354`)。
|
||||
**邮件补充重建规则(2026-07-31)**:邮件表头只能按当前 Run 冻结 Schema 的显式别名映射;行级 `reservation_id` 包含真实业务表头 `External reservation ID`。只要 Intake 保留原始 `body_html_tables`,Run 冻结时必须按自己的 Schema 重新解析完整补充表,不能复用上传阶段缺字段但已有部分行的旧结果;没有 HTML 时才复用已有完整结果或安全回退纵向纯文本解析。**关联收紧(2026-09-15)**:`mpn_fallback` 仅适用于补充行 PO 缺失且料号唯一命中;有 PO 且与 PDF 不一致不得补充。预约号允许短数字行序后缀归一(如 `35354-1` → `35354`)。**无 PO 表头(2026-09-16)**:分配表缺 PO 列但已映射料号或预约号时仍解析补充行(`po_header_missing` 仅作可观测标记);无身份列时仍整表跳过。
|
||||
|
||||
**`llm_extraction` 回退语义(2026-08-01)**:订单字段标记为 `llm_extraction` 表示“确定性解析无法取值时允许 LLM 补充”,不表示必须使用 LLM。通用解析门禁应依据字段是否已有完整、无冲突的确定性证据裁决;已取得必填 Header/Line 值时可直通,缺失时由 `required_field_missing` 转入 LLM/人工复核。
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
逻辑:建单前订单检查为主卡;正式 OT 后保持 standard,不自动切 formal_task 空壳;
|
||||
当前 Case 的明确恢复动作优先右栏 CurrentProcessingCard,
|
||||
不回落至底栏;库存动作仅明细行浮层;表单保存校验仅底栏;
|
||||
STP waiting_to_start/queued/running 时 automating=true 且后端剥离 edit_draft;
|
||||
货代上传确认成功后须 refreshReviewQueue,左侧本批阶段与五阶段对齐。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
@@ -2163,11 +2164,11 @@ const customerResolutionWideRef = ref<{ openSelectDialog: () => Promise<void> }
|
||||
const fieldConflictPanelRef = ref<{ focusFirstConflict: () => void } | null>(null);
|
||||
const duplicatePanelRef = ref<{ focusAdjudication: () => void } | null>(null);
|
||||
|
||||
/** 系统自动推进中:仅当存在确认 Job 时隐藏主写按钮;资格达标不算 automating。 */
|
||||
/** 系统自动推进中:STP 等待入队/排队/执行时隐藏主写按钮。 */
|
||||
const isProcessingAutomating = computed(() => {
|
||||
// STP 建单前没有正式 OT 投影;已入队/运行时由 Case automation 作为唯一运行事实。
|
||||
// STP 建单前没有正式 OT 投影;等待入队与已入队/运行均由 Case automation 作为唯一运行事实。
|
||||
const stpStatus = String(activeCase.value?.automation?.status || '').trim().toLowerCase();
|
||||
if (!hasFormalOt.value && ['queued', 'running'].includes(stpStatus)) return true;
|
||||
if (!hasFormalOt.value && ['waiting_to_start', 'queued', 'running'].includes(stpStatus)) return true;
|
||||
if (!hasConfirmedAutomationJob.value) return false;
|
||||
const status = String(
|
||||
shippingProcessingProjection.value?.uiState?.status
|
||||
|
||||
@@ -516,6 +516,7 @@
|
||||
"SHIPPING.REVIEW_LLM_GATE_L4_FORBIDDEN": "Page-level (L4) evidence requires explicit admin authorization. Regular users cannot request it.",
|
||||
"SHIPPING.REVIEW_LLM_L4_FORBIDDEN": "Full-PDF (L4) evidence requires explicit admin authorization; the request is blocked.",
|
||||
"SHIPPING.REVIEW_INVENTORY_SOURCE_UNRESOLVED": "Inventory source is not uniquely resolved. Complete inventory-source review before creating a formal order.",
|
||||
"SHIPPING.REVIEW_DRAFT_LOCKED_BY_AUTOMATION": "The system is auto-creating the order; the draft cannot be edited right now. Please wait or refresh and try again.",
|
||||
"VOUCHER_CHECK_CONFIG_INVALID": "Accounting voucher check configuration is invalid.",
|
||||
"VOUCHER_CHECK_INVOICE_REQUIRED": "Invoice number is required.",
|
||||
"VOUCHER_CHECK_INVOICE_NOT_IN_PERIOD": "The invoice is not in the previous-month ERP set.",
|
||||
|
||||
@@ -516,6 +516,7 @@
|
||||
"SHIPPING.REVIEW_LLM_GATE_L4_FORBIDDEN": "การใช้หลักฐานระดับหน้า (L4) ต้องมีการอนุญาตจากผู้ดูแลระบบอย่างชัดเจน ผู้ใช้ทั่วไปไม่สามารถร้องขอได้",
|
||||
"SHIPPING.REVIEW_LLM_L4_FORBIDDEN": "การใช้หลักฐาน PDF เต็ม (L4) ต้องมีการอนุญาตจากผู้ดูแลระบบอย่างชัดเจน คำขอนี้ถูกปิดกั้น",
|
||||
"SHIPPING.REVIEW_INVENTORY_SOURCE_UNRESOLVED": "ยังไม่ยืนยันแหล่งสต็อกแบบเฉพาะเจาะจง ไม่สามารถสร้างคำสั่งอย่างเป็นทางการได้ กรุณาตรวจสอบแหล่งสต็อกก่อน",
|
||||
"SHIPPING.REVIEW_DRAFT_LOCKED_BY_AUTOMATION": "ระบบกำลังสร้างคำสั่งอัตโนมัติ ยังแก้ไขฉบับร่างไม่ได้ กรุณารอหรือรีเฟรชแล้วลองใหม่",
|
||||
"VOUCHER_CHECK_CONFIG_INVALID": "การตั้งค่าการตรวจสอบเอกสารบัญชีไม่ถูกต้อง",
|
||||
"VOUCHER_CHECK_INVOICE_REQUIRED": "ต้องระบุเลขที่ใบแจ้งหนี้",
|
||||
"VOUCHER_CHECK_INVOICE_NOT_IN_PERIOD": "ใบแจ้งหนี้ไม่อยู่ในชุด ERP ของเดือนที่แล้ว",
|
||||
|
||||
@@ -516,6 +516,7 @@
|
||||
"SHIPPING.REVIEW_LLM_GATE_L4_FORBIDDEN": "整页级证据仅管理员在显式授权下可用,普通用户无法调用。",
|
||||
"SHIPPING.REVIEW_LLM_L4_FORBIDDEN": "完整 PDF 级证据仅管理员在显式授权下可用,本次请求已阻断。",
|
||||
"SHIPPING.REVIEW_INVENTORY_SOURCE_UNRESOLVED": "库存源尚未唯一确定,不能创建正式订单。请先完成库存源复核。",
|
||||
"SHIPPING.REVIEW_DRAFT_LOCKED_BY_AUTOMATION": "系统正在自动建单,暂不可编辑草稿。请稍候或刷新后再试。",
|
||||
"VOUCHER_CHECK_CONFIG_INVALID": "立账凭证检核配置无效。",
|
||||
"VOUCHER_CHECK_INVOICE_REQUIRED": "请提供发票号。",
|
||||
"VOUCHER_CHECK_INVOICE_NOT_IN_PERIOD": "指定发票不在上一个月 ERP 集合中。",
|
||||
|
||||
@@ -516,6 +516,7 @@
|
||||
"SHIPPING.REVIEW_LLM_GATE_L4_FORBIDDEN": "整頁級證據僅管理員在顯式授權下可用,一般使用者無法調用。",
|
||||
"SHIPPING.REVIEW_LLM_L4_FORBIDDEN": "完整 PDF 級證據僅管理員在顯式授權下可用,本次請求已阻斷。",
|
||||
"SHIPPING.REVIEW_INVENTORY_SOURCE_UNRESOLVED": "庫存源尚未唯一確定,不能建立正式訂單。請先完成庫存源複核。",
|
||||
"SHIPPING.REVIEW_DRAFT_LOCKED_BY_AUTOMATION": "系統正在自動建單,暫不可編輯草稿。請稍候或重新整理後再試。",
|
||||
"VOUCHER_CHECK_CONFIG_INVALID": "立帳憑證檢核設定無效。",
|
||||
"VOUCHER_CHECK_INVOICE_REQUIRED": "請提供發票號。",
|
||||
"VOUCHER_CHECK_INVOICE_NOT_IN_PERIOD": "指定發票不在上一月 ERP 集合中。",
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
scripts/rpa/dsv_auth.py
|
||||
scripts/rpa/connectors/dsv/dsv_auth.py
|
||||
|
||||
用途:DSV 360 PingID 分步登录(邮箱 → 密码方式 → 密码 → portal)。
|
||||
用途:DSV 360 PingID 分步登录(邮箱 → 可选切简体 → 密码方式 → 密码 → portal)。
|
||||
依赖:rpa_common、dsv_debug;登录主编排见 dsv_auth_login_flow。
|
||||
逻辑:由 dsv_session / dsv_report_export 在 ensure session 时调用 maybe_auto_login_dsv。
|
||||
逻辑:由 dsv_session / dsv_report_export 在 ensure session 时调用 maybe_auto_login_dsv;
|
||||
方法页点击须兼容英文 “Choose a sign in method” 标题+副标题行(2026-09-16);
|
||||
英文页可经 #kc_locale 尝试切「中文简体」(失败不阻断)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -39,7 +41,175 @@ from dsv_debug import (
|
||||
)
|
||||
|
||||
|
||||
def _is_dsv_password_method_label(text: str) -> bool:
|
||||
"""
|
||||
判断 MFA「选择登录方式」行文案是否为密码登录选项。
|
||||
|
||||
核心逻辑:兼容旧版精确标题(密码/Password)与新版英文行
|
||||
「Password + Enter your password to sign in.」整行副标题;排除 Passkey /
|
||||
Mobile App / E-Mail Code / 忘记密码等干扰行。
|
||||
|
||||
Args:
|
||||
text: 方法行可见文案(可含换行,内部会归一化空白)。
|
||||
|
||||
Returns:
|
||||
True 表示应点击该行进入密码输入页。
|
||||
"""
|
||||
normalized = " ".join(str(text or "").split()).strip()
|
||||
if not normalized:
|
||||
return False
|
||||
lowered = normalized.lower()
|
||||
exclude_needles = (
|
||||
"忘记密码",
|
||||
"forgot password",
|
||||
"通行密钥",
|
||||
"passkey",
|
||||
"电子邮件验证码",
|
||||
"e-mail code",
|
||||
"email code",
|
||||
"移动应用程序",
|
||||
"mobile app",
|
||||
"pingid",
|
||||
"取消",
|
||||
"cancel",
|
||||
"返回",
|
||||
)
|
||||
if any(needle in normalized or needle in lowered for needle in exclude_needles):
|
||||
return False
|
||||
if normalized in {"密码", "Password"}:
|
||||
return True
|
||||
if normalized.startswith("密码") or normalized.startswith("Password"):
|
||||
return True
|
||||
if "输入您的密码并登录" in normalized:
|
||||
return True
|
||||
if "enter your password to sign in" in lowered:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _dsv_switch_zh_cn_enabled() -> bool:
|
||||
"""是否启用「英文登录页尝试切中文简体」加固;默认开启,可用环境变量关闭。"""
|
||||
raw = str(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_SWITCH_ZH_CN", "true") or "true").strip().lower()
|
||||
return raw not in {"0", "false", "no", "off"}
|
||||
|
||||
|
||||
def _read_dsv_locale_nav_label(page: Any) -> str:
|
||||
"""
|
||||
读取 SIMS 语言按钮 `#lanNavSel` 当前文案。
|
||||
|
||||
Args:
|
||||
page: Playwright Page(可含 iframe)。
|
||||
|
||||
Returns:
|
||||
归一化后的语言标签;找不到时返回空串。
|
||||
"""
|
||||
roots = [page, *getattr(page, "frames", [])]
|
||||
for root in roots:
|
||||
try:
|
||||
locator = root.locator("#lanNavSel").first
|
||||
locator.wait_for(state="visible", timeout=500)
|
||||
return " ".join(str(locator.inner_text(timeout=500) or "").split()).strip()
|
||||
except Exception:
|
||||
continue
|
||||
return ""
|
||||
|
||||
|
||||
def _maybe_switch_dsv_locale_to_zh_cn(page: Any) -> bool:
|
||||
"""
|
||||
若登录页语言为 English,尝试切换为「中文简体」。
|
||||
|
||||
核心逻辑:读 `#lanNavSel`;已是中文则跳过;否则点 `#kc_locale` 打开下拉,
|
||||
再点 `a.language.dropdown-item` 文案「中文简体」。整段失败只打日志,不抛异常。
|
||||
|
||||
Args:
|
||||
page: Playwright Page(可含 iframe)。
|
||||
|
||||
Returns:
|
||||
True 表示已是中文简体或切换成功;False 表示关闭开关/未检测到/切换失败。
|
||||
"""
|
||||
if not _dsv_switch_zh_cn_enabled():
|
||||
return False
|
||||
label = _read_dsv_locale_nav_label(page)
|
||||
if not label:
|
||||
return False
|
||||
if "中文简体" in label or label in {"中文", "简体中文"}:
|
||||
return True
|
||||
if "english" not in label.lower() and "英文" not in label:
|
||||
# 其他语言也尽量切到简体,避免后续文案漂移
|
||||
print(f"[dsv-login] locale is {label!r}; trying 中文简体")
|
||||
else:
|
||||
print(f"[dsv-login] English locale detected ({label!r}); switching to 中文简体")
|
||||
|
||||
roots = [page, *getattr(page, "frames", [])]
|
||||
try:
|
||||
# [STEP 1] 打开语言下拉
|
||||
opened = False
|
||||
for root in roots:
|
||||
try:
|
||||
toggle = root.locator("#kc_locale").first
|
||||
toggle.wait_for(state="visible", timeout=1_000)
|
||||
toggle.click(timeout=2_000, force=True)
|
||||
opened = True
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if not opened:
|
||||
print("[dsv-login] locale switch skipped: #kc_locale not clickable")
|
||||
return False
|
||||
|
||||
# [STEP 2] 点击「中文简体」
|
||||
clicked = False
|
||||
zh_selectors = (
|
||||
'a.language.dropdown-item:has-text("中文简体")',
|
||||
'a.dropdown-item:has-text("中文简体")',
|
||||
'text="中文简体"',
|
||||
)
|
||||
for root in roots:
|
||||
for selector in zh_selectors:
|
||||
try:
|
||||
item = root.locator(selector).first
|
||||
item.wait_for(state="visible", timeout=2_000)
|
||||
item.click(timeout=2_000, force=True)
|
||||
clicked = True
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if clicked:
|
||||
break
|
||||
if not clicked:
|
||||
print("[dsv-login] locale switch skipped: 中文简体 item not found")
|
||||
return False
|
||||
|
||||
# [STEP 3] 确认标签变为中文简体(页面可能短暂重绘)
|
||||
deadline = time.monotonic() + 8
|
||||
while time.monotonic() < deadline:
|
||||
current = _read_dsv_locale_nav_label(page)
|
||||
if "中文简体" in current or current in {"中文", "简体中文"}:
|
||||
print("[dsv-login] locale switched to 中文简体")
|
||||
return True
|
||||
time.sleep(0.3)
|
||||
print(f"[dsv-login] locale switch unverified; label={_read_dsv_locale_nav_label(page)!r}")
|
||||
return False
|
||||
except Exception as exc:
|
||||
print(f"[dsv-login] locale switch failed (non-blocking): {exc}")
|
||||
return False
|
||||
|
||||
|
||||
def _click_dsv_password_method(page: Any) -> bool:
|
||||
"""
|
||||
在 PingID「选择登录方式」页点击「密码」选项并确认进入密码框。
|
||||
|
||||
核心逻辑:先用 DOM 脚本按方法行点击(兼容 mfaForm / device-list / 泛化 listitem);
|
||||
失败再按 Playwright 行选择器与精确文案 `Password`/`密码` 点击;任一路经须
|
||||
`transition_confirmed`(密码框出现或离开方法页)才算成功。
|
||||
|
||||
Args:
|
||||
page: Playwright Page(可含 iframe)。
|
||||
|
||||
Returns:
|
||||
是否已确认进入密码阶段。
|
||||
"""
|
||||
|
||||
def password_ready() -> bool:
|
||||
"""密码输入框已出现即视为方法页切换成功;兼容轻量探测与通用等待。"""
|
||||
if _find_dsv_password_locator(page, timeout_ms=250) is not None:
|
||||
@@ -66,6 +236,8 @@ def _click_dsv_password_method(page: Any) -> bool:
|
||||
("输入您的密码" in body_text or "忘记密码" in body_text or "password" in lowered)
|
||||
and "通行密钥" not in body_text
|
||||
and "passkey" not in lowered
|
||||
and "choose a sign in method" not in lowered
|
||||
and "choose a sign-on method" not in lowered
|
||||
and "验证失败" not in body_text
|
||||
and "validation failed" not in lowered
|
||||
)
|
||||
@@ -76,6 +248,31 @@ def _click_dsv_password_method(page: Any) -> bool:
|
||||
time.sleep(0.3)
|
||||
return False
|
||||
|
||||
def try_click_locator(locator: Any) -> bool:
|
||||
try:
|
||||
locator.scroll_into_view_if_needed(timeout=3_000)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.click(timeout=3_000, force=True)
|
||||
except Exception:
|
||||
try:
|
||||
locator.evaluate(
|
||||
"""
|
||||
(node) => {
|
||||
if (typeof node.click === 'function') node.click();
|
||||
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
|
||||
node.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
|
||||
}
|
||||
}
|
||||
""",
|
||||
timeout=2_000,
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
return transition_confirmed()
|
||||
|
||||
# [STEP 1] DOM 脚本:放宽标题匹配 + 扩大方法行选择器(旧 mfaForm 与新英文 MFA 页)
|
||||
script_row_click = """
|
||||
() => {
|
||||
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
|
||||
@@ -84,20 +281,27 @@ def _click_dsv_password_method(page: Any) -> bool:
|
||||
const style = window.getComputedStyle(node);
|
||||
return !(style.display === 'none' || style.visibility === 'hidden' || rect.width <= 0 || rect.height <= 0);
|
||||
};
|
||||
const isPasswordMethod = (text) => (
|
||||
(text === '密码' || text === 'Password' || text === '输入您的密码并登录。' || text.includes('输入您的密码并登录'))
|
||||
&& !text.includes('忘记密码')
|
||||
&& !text.includes('取消')
|
||||
&& !text.includes('返回')
|
||||
&& !text.includes('通行密钥')
|
||||
&& !text.includes('电子邮件验证码')
|
||||
&& !text.includes('移动应用程序')
|
||||
&& !text.toLowerCase().includes('cancel')
|
||||
&& !text.toLowerCase().includes('back')
|
||||
&& !text.toLowerCase().includes('passkey')
|
||||
);
|
||||
const rows = Array.from(document.querySelectorAll("form[name='mfaForm'] li.mb-2, form[name='mfaForm'] .mb-2, .device-list li.mb-2, .device-list .mb-2"))
|
||||
.filter((node) => isVisible(node));
|
||||
const isPasswordMethod = (text) => {
|
||||
const lowered = (text || '').toLowerCase();
|
||||
const excluded = (
|
||||
text.includes('忘记密码') || lowered.includes('forgot password')
|
||||
|| text.includes('通行密钥') || lowered.includes('passkey')
|
||||
|| text.includes('电子邮件验证码') || lowered.includes('e-mail code') || lowered.includes('email code')
|
||||
|| text.includes('移动应用程序') || lowered.includes('mobile app') || lowered.includes('pingid')
|
||||
|| text.includes('取消') || lowered.includes('cancel')
|
||||
|| text.includes('返回')
|
||||
);
|
||||
if (excluded) return false;
|
||||
return (
|
||||
text === '密码' || text === 'Password'
|
||||
|| text.startsWith('密码') || text.startsWith('Password')
|
||||
|| text.includes('输入您的密码并登录')
|
||||
|| lowered.includes('enter your password to sign in')
|
||||
);
|
||||
};
|
||||
const rows = Array.from(document.querySelectorAll(
|
||||
"form[name='mfaForm'] li.mb-2, form[name='mfaForm'] .mb-2, .device-list li.mb-2, .device-list .mb-2, li.mb-2, [role='listitem'], .device-type, button, a, [role='button']"
|
||||
)).filter((node) => isVisible(node));
|
||||
const row = rows.find((node) => isPasswordMethod(textOf(node)));
|
||||
if (!row) return false;
|
||||
const target = row.querySelector('.device-continue, button, a, [role="button"], input[type="submit"]') || row;
|
||||
@@ -122,31 +326,53 @@ def _click_dsv_password_method(page: Any) -> bool:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# [STEP 2] Playwright:按方法行选择器 + 精确文案 Password/密码 点击
|
||||
row_selectors = (
|
||||
"form[name='mfaForm'] li.mb-2",
|
||||
"form[name='mfaForm'] .mb-2",
|
||||
".device-list li.mb-2",
|
||||
".device-list .mb-2",
|
||||
"li.mb-2",
|
||||
"[role='listitem']",
|
||||
)
|
||||
text_selectors = (
|
||||
'text="Password"',
|
||||
"text=Password",
|
||||
'text="密码"',
|
||||
"text=密码",
|
||||
'button:has-text("Password")',
|
||||
'button:has-text("密码")',
|
||||
'[role="button"]:has-text("Password")',
|
||||
'[role="button"]:has-text("密码")',
|
||||
'a:has-text("Password")',
|
||||
'a:has-text("密码")',
|
||||
)
|
||||
deadline = time.monotonic() + 10
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
rows = page.locator("form[name='mfaForm'] li.mb-2").all()
|
||||
for row in rows:
|
||||
text = row.inner_text(timeout=1_000)
|
||||
lowered = text.lower()
|
||||
if ("密码" in text or "Password" in text) and "忘记密码" not in text and "取消" not in text and "返回" not in text and "cancel" not in lowered and "back" not in lowered:
|
||||
row.scroll_into_view_if_needed(timeout=3_000)
|
||||
roots = [page, *getattr(page, "frames", [])]
|
||||
for root in roots:
|
||||
for selector in row_selectors:
|
||||
try:
|
||||
rows = root.locator(selector).all()
|
||||
except Exception:
|
||||
rows = []
|
||||
for row in rows:
|
||||
try:
|
||||
row.click(timeout=3_000, force=True)
|
||||
text = row.inner_text(timeout=1_000)
|
||||
except Exception:
|
||||
row.evaluate(
|
||||
"""
|
||||
(node) => {
|
||||
if (typeof node.click === 'function') node.click();
|
||||
node.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
|
||||
}
|
||||
""",
|
||||
timeout=2_000,
|
||||
)
|
||||
if transition_confirmed():
|
||||
continue
|
||||
if not _is_dsv_password_method_label(text):
|
||||
continue
|
||||
if try_click_locator(row):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
for selector in text_selectors:
|
||||
try:
|
||||
locator = root.locator(selector).first
|
||||
locator.wait_for(state="visible", timeout=500)
|
||||
except Exception:
|
||||
continue
|
||||
if try_click_locator(locator):
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
@@ -569,7 +795,15 @@ def _looks_like_dsv_login_method_page(page: Any) -> bool:
|
||||
# 宽泛 needle 造成误判(反复尝试点击“密码方式”而非关闭弹窗);命中升级提示时直接判非方法页。
|
||||
if _has_dsv_password_upgrade_prompt(page):
|
||||
return False
|
||||
needles = ("选择登录方法", "密码", "Password", "输入您的密码并登录", "Choose a sign-on method")
|
||||
# 含英文新版 “Choose a sign in method”(无连字符);旧版为 sign-on。
|
||||
needles = (
|
||||
"选择登录方法",
|
||||
"密码",
|
||||
"Password",
|
||||
"输入您的密码并登录",
|
||||
"Choose a sign-on method",
|
||||
"Choose a sign in method",
|
||||
)
|
||||
for frame in page.frames:
|
||||
try:
|
||||
text = frame.locator("body").inner_text(timeout=300)
|
||||
@@ -578,7 +812,7 @@ def _looks_like_dsv_login_method_page(page: Any) -> bool:
|
||||
lowered = text.lower()
|
||||
if "real person" in lowered and ("rabbit" in lowered or "scale" in lowered):
|
||||
continue
|
||||
if any(needle in text for needle in needles):
|
||||
if any(needle in text or needle.lower() in lowered for needle in needles):
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -1002,8 +1236,11 @@ has_dsv_password_upgrade_prompt = _has_dsv_password_upgrade_prompt
|
||||
is_dsv_auth_ping_url = _is_dsv_auth_ping_url
|
||||
is_dsv_blank_auth_transition = _is_dsv_blank_auth_transition
|
||||
is_dsv_oauth_handshake_url = _is_dsv_oauth_handshake_url
|
||||
is_dsv_password_method_label = _is_dsv_password_method_label
|
||||
is_dsv_username_page = _is_dsv_username_page
|
||||
looks_like_dsv_login_method_page = _looks_like_dsv_login_method_page
|
||||
maybe_switch_dsv_locale_to_zh_cn = _maybe_switch_dsv_locale_to_zh_cn
|
||||
read_dsv_locale_nav_label = _read_dsv_locale_nav_label
|
||||
submit_dsv_password_form = _submit_dsv_password_form
|
||||
submit_dsv_username_form = _submit_dsv_username_form
|
||||
try_fill_dsv_username_locator = _try_fill_dsv_username_locator
|
||||
|
||||
@@ -3,7 +3,8 @@ scripts/rpa/dsv_auth_login_flow.py
|
||||
|
||||
用途:DSV 360 PingID 自动登录主编排(maybe_auto_login_dsv)。
|
||||
依赖:rpa_common、dsv_debug、dsv_auth(表单/探测辅助)、dsv_session(登录后首页 ready)。
|
||||
逻辑:由 dsv_auth 在模块末尾 re-export;dsv_report_export ensure 时触发。
|
||||
逻辑:由 dsv_auth 在模块末尾 re-export;dsv_report_export ensure 时触发;
|
||||
账号页/方法页若为英文,先尝试切「中文简体」再继续(失败不阻断)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -58,6 +59,7 @@ _is_dsv_blank_auth_transition = dsv_auth._is_dsv_blank_auth_transition
|
||||
_is_dsv_oauth_handshake_url = dsv_auth._is_dsv_oauth_handshake_url
|
||||
_is_dsv_password_upgrade_redirect = dsv_auth._is_dsv_password_upgrade_redirect
|
||||
_is_dsv_username_page = dsv_auth._is_dsv_username_page
|
||||
_maybe_switch_dsv_locale_to_zh_cn = dsv_auth._maybe_switch_dsv_locale_to_zh_cn
|
||||
_submit_dsv_password_form = dsv_auth._submit_dsv_password_form
|
||||
_wait_for_dsv_auth_page_ready = dsv_auth._wait_for_dsv_auth_page_ready
|
||||
_wait_for_dsv_human_check_if_present = dsv_auth._wait_for_dsv_human_check_if_present
|
||||
@@ -174,6 +176,8 @@ def _maybe_auto_login_dsv(page: Any) -> None:
|
||||
return
|
||||
|
||||
_wait_for_dsv_auth_page_ready(page)
|
||||
# [STEP 1.5] 英文 SIMS 页先尝试切「中文简体」,失败不阻断;须在填账号前执行以免切语言清空表单。
|
||||
_maybe_switch_dsv_locale_to_zh_cn(page)
|
||||
login_ready_ms = _dsv_login_ready_timeout_ms()
|
||||
print("[dsv-login] waiting username field")
|
||||
username_locator = _wait_for_visible_selector(
|
||||
@@ -258,6 +262,7 @@ def _maybe_auto_login_dsv(page: Any) -> None:
|
||||
)
|
||||
password_method_clicked_at = 0.0
|
||||
username_retry_allowed_at = time.monotonic() + 6
|
||||
locale_switch_on_method_attempted = False
|
||||
while time.monotonic() < login_deadline:
|
||||
# [STEP 1] DSV 在密码阶段前(authorization.ping)也会弹出“使用密码升级登录!”
|
||||
# 引导弹窗(也许以后/立即启用),会遮挡密码表单和登录按钮;先点“也许以后”关闭再探测。
|
||||
@@ -309,6 +314,10 @@ def _maybe_auto_login_dsv(page: Any) -> None:
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
# 方法页若仍为英文,再尝试一次切简体(账号页未带上语言偏好时)。
|
||||
if not locale_switch_on_method_attempted:
|
||||
_maybe_switch_dsv_locale_to_zh_cn(page)
|
||||
locale_switch_on_method_attempted = True
|
||||
if password_method_clicked_at and time.monotonic() - password_method_clicked_at < 2:
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
@@ -494,9 +494,11 @@ from dsv_auth import ( # noqa: E402
|
||||
find_dsv_password_locator,
|
||||
has_dsv_human_check_prompt,
|
||||
has_dsv_password_upgrade_prompt,
|
||||
is_dsv_password_method_label,
|
||||
is_dsv_username_page,
|
||||
looks_like_dsv_login_method_page,
|
||||
maybe_auto_login_dsv,
|
||||
maybe_switch_dsv_locale_to_zh_cn,
|
||||
submit_dsv_password_form,
|
||||
wait_for_dsv_human_check_if_present,
|
||||
wait_for_dsv_login_method_page,
|
||||
|
||||
@@ -96,6 +96,8 @@ _maybe_auto_login_dsv = dsv_session.maybe_auto_login_dsv
|
||||
_fill_dsv_username = dsv_session.fill_dsv_username
|
||||
_click_dsv_continue = dsv_session.click_dsv_continue
|
||||
_click_dsv_password_method = dsv_session.click_dsv_password_method
|
||||
_is_dsv_password_method_label = dsv_session.is_dsv_password_method_label
|
||||
_maybe_switch_dsv_locale_to_zh_cn = dsv_session.maybe_switch_dsv_locale_to_zh_cn
|
||||
_fill_dsv_password_page_fields = dsv_session.fill_dsv_password_page_fields
|
||||
_wait_for_dsv_human_check_if_present = dsv_session.wait_for_dsv_human_check_if_present
|
||||
_wait_for_dsv_app_after_login = dsv_session.wait_for_dsv_app_after_login
|
||||
|
||||
Reference in new issue
Block a user