feat(shipping-notice): 收敛复核状态隔离、STP 重试幂等与 XFA 合成预览标注
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
84a881b554
commit
74270adc22
149 files changed
+20111
-3871
No files matched your search
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"run_no": "SNER-20260806-AB1F70EE",
|
||||
"rebuilt": false,
|
||||
"enqueue_results": [
|
||||
{
|
||||
"case_no": "SORC-BC8338CC6A964B8C",
|
||||
"status": "already_queued",
|
||||
"job_id": 882,
|
||||
"idempotency_key": "stp-auto:SNER-20260806-AB1F70EE:doc-135:v1",
|
||||
"job_status": "queued",
|
||||
"can_auto_create": true,
|
||||
"retry_of_job_id": null
|
||||
}
|
||||
],
|
||||
"jobs": [
|
||||
{
|
||||
"run_no": "SNER-20260806-AB1F70EE",
|
||||
"job_id": 882,
|
||||
"status": "queued",
|
||||
"business_ref": "stp-auto:SNER-20260806-AB1F70EE:doc-135:v1",
|
||||
"retry_of_job_id": null,
|
||||
"domain": "shipping_notice",
|
||||
"created_at": "2026-08-06T17:22:59.813262"
|
||||
},
|
||||
{
|
||||
"run_no": "SNER-20260806-AB1F70EE",
|
||||
"job_id": 877,
|
||||
"status": "queued",
|
||||
"business_ref": "stp-auto:SNER-20260806-AB1F70EE:doc-137:v2",
|
||||
"retry_of_job_id": null,
|
||||
"domain": "shipping_notice",
|
||||
"created_at": "2026-08-06T12:58:02.097753"
|
||||
},
|
||||
{
|
||||
"run_no": "SNER-20260806-AB1F70EE",
|
||||
"job_id": 876,
|
||||
"status": "queued",
|
||||
"business_ref": "stp-auto:SNER-20260806-AB1F70EE:doc-136:v2",
|
||||
"retry_of_job_id": null,
|
||||
"domain": "shipping_notice",
|
||||
"created_at": "2026-08-06T12:58:01.981031"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
"""
|
||||
backend/scripts/verify_stp_synthetic_sner_20260806.py
|
||||
|
||||
用途:为冻结验收提供 STP 真实入队证据(run_no / business_ref / job_id / status)。
|
||||
依赖:Flask create_app、order_stp_auto_create_service、Job / Review Case 模型。
|
||||
逻辑:优先使用 SNER-20260806-AB1F70EE;若不存在则复用现有 shipping_notice Agent
|
||||
重建最小 eligible Case,再 ensure 入队并打印/落盘查询结果。
|
||||
|
||||
用法(在 backend 目录、已激活 venv):
|
||||
python scripts/verify_stp_synthetic_sner_20260806.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
TARGET_RUN_NO = 'SNER-20260806-AB1F70EE'
|
||||
|
||||
|
||||
def _print_evidence(rows: list[dict]) -> None:
|
||||
"""打印验收所需字段。"""
|
||||
print('=== STP synthetic evidence ===')
|
||||
print(json.dumps(rows, ensure_ascii=False, indent=2, default=str))
|
||||
|
||||
|
||||
def _query_jobs_for_run(run_no: str) -> list[dict]:
|
||||
"""按 business_ref 前缀查询 shipping_stp_auto_create Job。"""
|
||||
from app.models import Job
|
||||
|
||||
like = f'%{run_no}%'
|
||||
jobs = (
|
||||
Job.query.filter(
|
||||
Job.job_type == 'shipping_stp_auto_create',
|
||||
Job.business_ref.ilike(like),
|
||||
)
|
||||
.order_by(Job.id.desc())
|
||||
.limit(20)
|
||||
.all()
|
||||
)
|
||||
return [
|
||||
{
|
||||
'run_no': run_no,
|
||||
'job_id': int(job.id),
|
||||
'status': str(job.status),
|
||||
'business_ref': str(job.business_ref or ''),
|
||||
'retry_of_job_id': int(job.retry_of_job_id) if job.retry_of_job_id else None,
|
||||
'domain': str(job.domain or ''),
|
||||
'created_at': job.created_at.isoformat() if job.created_at else None,
|
||||
}
|
||||
for job in jobs
|
||||
]
|
||||
|
||||
|
||||
def _find_target_run():
|
||||
from app.models import ShippingOrderProcessingRun
|
||||
|
||||
return ShippingOrderProcessingRun.query.filter_by(run_no=TARGET_RUN_NO).first()
|
||||
|
||||
|
||||
def _rebuild_minimal_eligible_case():
|
||||
"""
|
||||
重建最小可入队 Case(仅用于验收证据)。
|
||||
|
||||
核心逻辑:复用已存在的 shipping_notice Agent(避免 uq_agents_one_active_shipping_notice);
|
||||
新建隔离 User/Session/Intake/Document/Run/Case;写入 can_auto_create validation 后 ensure。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
Agent,
|
||||
ChatSession,
|
||||
FileAsset,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
ensure_stp_auto_create_for_case,
|
||||
)
|
||||
|
||||
suffix = f'SYN{uuid.uuid4().hex[:8].upper()}'
|
||||
agent = Agent.query.filter_by(agent_code='shipping_notice', is_active=True).first()
|
||||
if agent is None:
|
||||
agent = Agent.query.filter_by(agent_code='shipping_notice').first()
|
||||
if agent is None:
|
||||
raise RuntimeError('active shipping_notice agent not found; cannot rebuild synthetic case')
|
||||
|
||||
# [STEP] 真实库可能存在序列漂移;插入前对齐常用表序列,避免 users_pkey 冲突。
|
||||
for table, column in (
|
||||
('users', 'id'),
|
||||
('chat_sessions', 'id'),
|
||||
('file_assets', 'id'),
|
||||
('shipping_order_intakes', 'id'),
|
||||
('shipping_order_documents', 'id'),
|
||||
('shipping_order_schemas', 'id'),
|
||||
('shipping_order_schema_versions', 'id'),
|
||||
):
|
||||
db.session.execute(
|
||||
db.text(
|
||||
f"SELECT setval(pg_get_serial_sequence('{table}', '{column}'), "
|
||||
f"COALESCE((SELECT MAX({column}) FROM {table}), 1))"
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# [STEP] 开发库序列可能落后于 MAX(id);重建前对齐,避免 users_pkey 冲突。
|
||||
from sqlalchemy import text
|
||||
|
||||
for table in ('users', 'chat_sessions', 'file_assets', 'shipping_order_intakes', 'shipping_order_documents'):
|
||||
try:
|
||||
db.session.execute(text(
|
||||
f"SELECT setval(pg_get_serial_sequence('{table}', 'id'), "
|
||||
f"COALESCE((SELECT MAX(id) FROM {table}), 1))"
|
||||
))
|
||||
except Exception: # noqa: BLE001
|
||||
db.session.rollback()
|
||||
db.session.commit()
|
||||
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').first()
|
||||
if schema is None:
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=1,
|
||||
status='published',
|
||||
checksum='a' * 64,
|
||||
definition_json={
|
||||
'fields': [
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'enabled': True},
|
||||
{'field_id': 'po-id', 'field_code': 'po_number', 'scope': 'header', 'enabled': True},
|
||||
],
|
||||
},
|
||||
published_at=datetime.utcnow(),
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
user = User(
|
||||
username=f'stp-syn-{suffix.lower()}',
|
||||
email=f'stp-syn-{suffix.lower()}@example.com',
|
||||
password_hash='x',
|
||||
status='active',
|
||||
)
|
||||
user.agents.append(agent)
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
|
||||
session = ChatSession(
|
||||
session_id=f'stp-syn-session-{suffix}',
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
title='STP synthetic evidence',
|
||||
)
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-STP-{suffix}',
|
||||
owner_user_id=user.id,
|
||||
original_filename=f'stp-syn-{suffix}.pdf',
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key=f'temporary/{user.id}/stp-syn-{suffix}.pdf',
|
||||
content_hash=(suffix.lower() * 8)[:64],
|
||||
file_size=100,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add_all([session, asset])
|
||||
db.session.flush()
|
||||
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'SNI-STP-{suffix}',
|
||||
asset_id=asset.id,
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
extracted_text=f'synthetic stp {suffix}',
|
||||
structured_result_json={'email': {'from': f'Sales-{suffix}@Example.COM'}},
|
||||
expires_at=datetime.utcnow() + timedelta(hours=1),
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingOrderDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=asset.id,
|
||||
document_type='attachment',
|
||||
attachment_key=f'stp-syn-{suffix}.pdf',
|
||||
filename=f'stp-syn-{suffix}.pdf',
|
||||
content_hash=(suffix.upper() * 8)[:64],
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text=f'PO SYN{suffix} QTY 1 EA',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.commit()
|
||||
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
ensure_order_extraction_plan(run)
|
||||
for unit in run.extraction_plan.units:
|
||||
unit.status = 'candidate_ready'
|
||||
# [STEP] 固定 run_no 以便验收脚本可复现查询。
|
||||
run.run_no = TARGET_RUN_NO
|
||||
db.session.flush()
|
||||
transition_order_extraction_run(run, target_status='processing')
|
||||
transition_order_extraction_run(run, target_status='review_required', result={})
|
||||
cases = ensure_run_review_cases(run=run)
|
||||
if not cases:
|
||||
raise RuntimeError('failed to create review cases for synthetic run')
|
||||
|
||||
for case in cases:
|
||||
draft = case.current_draft
|
||||
if draft is None:
|
||||
raise RuntimeError(f'case {case.case_no} missing draft')
|
||||
draft.validation_result_json = {
|
||||
'status': 'ready',
|
||||
'can_build': True,
|
||||
'can_auto_create': True,
|
||||
'failed_gates': [],
|
||||
'issues': [],
|
||||
'validated_at': datetime.now(timezone.utc).isoformat(),
|
||||
'validation_checksum': 'synthetic-stp-evidence-v1',
|
||||
}
|
||||
draft.issue_summary_json = []
|
||||
case.status = 'ready'
|
||||
db.session.commit()
|
||||
|
||||
results = []
|
||||
for row in ShippingOrderReviewCase.query.filter_by(run_id=int(run.id)).all():
|
||||
result = ensure_stp_auto_create_for_case(
|
||||
case=row,
|
||||
run=run,
|
||||
commit=True,
|
||||
refresh_validation=False,
|
||||
force_retry=False,
|
||||
)
|
||||
results.append(result)
|
||||
refreshed = ShippingOrderProcessingRun.query.filter_by(run_no=TARGET_RUN_NO).first()
|
||||
return refreshed, results
|
||||
|
||||
|
||||
def main() -> int:
|
||||
from app import create_app
|
||||
from app.models import ShippingOrderReviewCase
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
ensure_stp_auto_create_for_case,
|
||||
)
|
||||
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
run = _find_target_run()
|
||||
rebuilt = False
|
||||
enqueue_results: list[dict] = []
|
||||
if run is None:
|
||||
print(f'[info] run {TARGET_RUN_NO} missing; rebuilding minimal eligible case')
|
||||
run, enqueue_results = _rebuild_minimal_eligible_case()
|
||||
rebuilt = True
|
||||
else:
|
||||
cases = ShippingOrderReviewCase.query.filter_by(run_id=int(run.id)).all()
|
||||
print(f'[info] found run id={run.id} cases={len(cases)}')
|
||||
for case in cases:
|
||||
if case.confirmed_task_id or str(case.status) == 'confirmed':
|
||||
continue
|
||||
draft = case.current_draft
|
||||
if draft is not None:
|
||||
validation = dict(draft.validation_result_json or {})
|
||||
validation.update({
|
||||
'status': 'ready',
|
||||
'can_build': True,
|
||||
'can_auto_create': True,
|
||||
})
|
||||
draft.validation_result_json = validation
|
||||
result = ensure_stp_auto_create_for_case(
|
||||
case=case,
|
||||
run=run,
|
||||
commit=True,
|
||||
refresh_validation=False,
|
||||
force_retry=False,
|
||||
)
|
||||
enqueue_results.append(result)
|
||||
|
||||
evidence = _query_jobs_for_run(TARGET_RUN_NO)
|
||||
payload = {
|
||||
'run_no': TARGET_RUN_NO,
|
||||
'rebuilt': rebuilt,
|
||||
'enqueue_results': enqueue_results,
|
||||
'jobs': evidence,
|
||||
}
|
||||
out_path = Path(__file__).resolve().parent / '_stp_synthetic_evidence_SNER-20260806.json'
|
||||
out_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2, default=str), encoding='utf-8')
|
||||
_print_evidence(evidence)
|
||||
print(f'[info] wrote {out_path}')
|
||||
if not evidence:
|
||||
print('[fail] no shipping_stp_auto_create jobs found')
|
||||
print('[debug] enqueue_results=', json.dumps(enqueue_results, ensure_ascii=False, default=str))
|
||||
return 1
|
||||
print('[ok] synthetic STP evidence ready')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user