Merge branch 'dev' into runny827

feat(training): 新增精益培训视频与周任务管理

# Conflicts:
#	backend/app/models/__init__.py
This commit is contained in:
runny committed 2026-09-08 18:30:09 +08:00
1 parent 85d27e9ffa
commit 91b7233872
812 files changed
+73763 -18908

No files matched your search

@@ -0,0 +1,84 @@
"""
用途:验证正式客户识别结果是客户确认与流程 Gate 的唯一真相源。
依赖:内存数据库、客户识别结果服务、ShippingOrderTask/Candidate。
逻辑:覆盖非 bill_to 证据可确认,以及仅有旧 Bill-to Match 时不得放行两条边界。
"""
from __future__ import annotations
from app import db
from app.models import (
ShippingCustomer,
ShippingCustomerShadowResolution,
ShippingOrderCandidate,
ShippingOrderIntake,
ShippingOrderTask,
User,
)
from app.services.shipping_notice.customer_resolution_service import (
confirm_customer_resolution,
customer_resolution_facts,
)
def _task_with_resolution(*, status: str = 'unique_candidate') -> tuple[ShippingOrderTask, ShippingCustomerShadowResolution, ShippingCustomer]:
"""构造 OT、Candidate 和规则证据快照;不构造 bill_to 字段或 CustomerMatch。"""
user = User(username='resolution-user', email='resolution@example.com', role='user')
customer = ShippingCustomer(standard_name='规则识别客户', short_code='RID', status='active')
db.session.add_all([user, customer])
db.session.flush()
intake = ShippingOrderIntake(
intake_no='INT-RESOLUTION', asset_id=1, user_id=user.id, parser_version='test',
)
db.session.add(intake)
db.session.flush()
candidate = ShippingOrderCandidate(
candidate_no='CAND-RESOLUTION', intake_id=intake.id, primary_document_id=1,
candidate_key='resolution-test', candidate_status='accepted',
)
db.session.add(candidate)
db.session.flush()
task = ShippingOrderTask(task_no='OT-RESOLUTION', user_id=user.id, candidate_id=candidate.id)
resolution = ShippingCustomerShadowResolution(
candidate_id=candidate.id,
intake_id=intake.id,
resolution_version='shadow-v2',
status=status,
evidence_json=[{'definition_id': 'customer-code', 'normalized_value': 'C-100'}],
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
resolution_context_json={'rule_set': {'checksum': 'a' * 64}},
identity_rule_set_checksum='a' * 64,
top_customer_id=customer.id,
top_score=100,
)
db.session.add_all([task, resolution])
db.session.commit()
return task, resolution, customer
def test_non_bill_to_evidence_can_confirm_customer(app):
"""关键断言:客户代码证据可确认客户,流程不要求 bill_to 字段或旧匹配行。"""
with app.app_context():
task, resolution, customer = _task_with_resolution()
confirm_customer_resolution(task, customer_id=customer.id, actor_id=None, method='manual')
db.session.commit()
facts = customer_resolution_facts(task)
assert facts['status'] == 'confirmed'
assert facts['customer_id'] == customer.id
assert resolution.confirmed_customer_id == customer.id
# 关键断言:确认不篡改规则证据及其 checksum。
assert resolution.evidence_json == [{'definition_id': 'customer-code', 'normalized_value': 'C-100'}]
assert resolution.identity_rule_set_checksum == 'a' * 64
def test_unconfirmed_resolution_fails_closed_without_old_bill_to_fallback(app):
"""关键断言:未确认的统一识别结果不得从旧字段或旧匹配路径获得客户身份。"""
with app.app_context():
task, _resolution, _customer = _task_with_resolution(status='unique_candidate')
facts = customer_resolution_facts(task)
assert facts['status'] == 'unique_candidate'
assert facts['customer_id'] is None
@@ -13,7 +13,9 @@ from app.models import (
ShippingInventoryCandidateLine,
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingNotice,
ShippingOrderTask,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingNoticeLineInventoryMatch,
ShippingInventoryFile,
)
@@ -23,17 +25,18 @@ from app.services.shipping_notice.inventory_candidate_projection import (
from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines
def _task(task_no: str) -> ShippingNotice:
task = ShippingNotice(
def _task(task_no: str) -> ShippingOrderTask:
task = ShippingOrderTask(
task_no=task_no,
source_type='manual',
source_type='direct_pdf',
user_id=1,
)
db.session.add(task)
db.session.flush()
return task
def _candidate_set(task: ShippingNotice, version: int = 1) -> ShippingInventoryCandidateSet:
def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInventoryCandidateSet:
row = ShippingInventoryCandidateSet(
task_id=int(task.id),
set_version=version,
@@ -120,9 +123,19 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
)
db.session.add(new_line)
db.session.flush()
snapshot = ShippingOrderSnapshot(
task_id=int(task.id), extraction_id=1, schema_version_id=1,
order_data_version=1, source_manifest_json={}, header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0)
db.session.add(snapshot_line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=int(task.id),
line_key='line-1',
snapshot_line_id=int(snapshot_line.id),
line_no=1,
line_index=0,
candidate_set_id=int(old_set.id),
candidate_set_version=1,
@@ -152,16 +165,26 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app
candidate_set_id=int(candidate_set.id), line_no=1, source_codes_json=['DBS_DUB'],
))
db.session.flush()
snapshot = ShippingInventoryFile(
inventory_file = ShippingInventoryFile(
inventory_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx',
source_code='DBS_DUB', snapshot_status='ready', file_sha256='b' * 64,
)
db.session.add(inventory_file)
db.session.flush()
snapshot = ShippingOrderSnapshot(
task_id=int(task.id), extraction_id=1, schema_version_id=1,
order_data_version=1, source_manifest_json={}, header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0)
db.session.add(snapshot_line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=int(task.id), line_key='line-1', candidate_set_id=int(candidate_set.id),
candidate_set_version=1, inventory_snapshot_id=int(snapshot.id), match_result='matched',
inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=snapshot.inventory_file_no,
task_id=int(task.id), snapshot_line_id=int(snapshot_line.id), line_no=1,
candidate_set_id=int(candidate_set.id),
candidate_set_version=1, inventory_snapshot_id=int(inventory_file.id), match_result='matched',
inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=inventory_file.inventory_file_no,
matched_row_index=9, is_current=True, detail_json={},
))
db.session.commit()
@@ -81,12 +81,12 @@ def _fake_job(job_id=928, status='failed', domain='shipping_notice', job_type='s
('failed', False, 'failed', '业务阻断失败 → failed'),
('manual_fallback', True, 'retryable', 'manual_fallback retryable → retryable'),
('failed', True, 'retryable', '技术失败 retryable → retryable'),
('idle', False, 'idle', 'Idle → idle(默认)'),
('idle', False, 'waiting_human', 'Idle automation → waiting_human(禁止再发 idle)'),
],
ids=lambda t: t[3] if isinstance(t, tuple) else '',
)
def test_p3_t3_user_status_seven_value_matrix(automation_status, retryable_flag, expected_user_status, label):
"""[P3 T3] project_case_user_status 七值归一化与 Q12 invariants 一致。"""
def test_p3_t3_user_status_f2_six_value_matrix(automation_status, retryable_flag, expected_user_status, label):
"""[P3 T3] project_case_user_status F2 六值;默认人工等待 waiting_human。"""
from app.services.shipping_notice.reconciliation_projector import project_case_user_status
case = _fake_case(status='draft')
@@ -199,7 +199,8 @@ def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch):
"""正式 field_completeness 阻断必须覆盖 Case draft 的 idle/order_review_build 推导。"""
from app.services.shipping_notice import reconciliation_projector
case = _fake_case(status='draft', candidate_id=None)
# 正式门禁事实只在 Case 已确认(confirmed)时覆盖;未确认 draft 保持 order_review_build(见结算设计)。
case = _fake_case(status='confirmed', candidate_id=None)
monkeypatch.setattr(
reconciliation_projector,
'_project_case_formal_gate_summary',
@@ -25,9 +25,11 @@ from app.models import (
ShippingOrderLine,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingOrderCustomerMatch,
ShippingCustomerShadowResolution,
ShippingOrderCandidate,
ShippingOrderIntake,
ShippingCustomer,
ShippingNotice,
ShippingOrderTask,
User,
)
from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness
@@ -43,7 +45,7 @@ from app.services.shipping_notice.order_freeze_service import (
def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension: bool = False, suffix: str = '001'):
"""创建一份含预置核心字段的已接受解析;可加入扩展字段验证配置化履约。"""
user = User(username=f'snapshot-user-{suffix}', email=f'snapshot-user-{suffix}@example.test', password_hash='x')
task = ShippingNotice(task_no=f'SN-SNAPSHOT-{suffix}', source_type='test', order_data_version=7)
task = ShippingOrderTask(task_no=f'OT-SNAPSHOT-{suffix}', source_type='direct_pdf', user_id=1, order_data_version=7)
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Frozen order')
db.session.add_all([user, task, schema])
db.session.flush()
@@ -82,7 +84,7 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension:
)
db.session.add(extraction)
db.session.flush()
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
db.session.add(line)
db.session.flush()
values = {
@@ -119,13 +121,26 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension:
customer = ShippingCustomer(standard_name='Snapshot Customer', short_code='CUS')
db.session.add(customer)
db.session.flush()
db.session.add(ShippingOrderCustomerMatch(
extraction_id=extraction.id, role='bill_to', raw_name='Snapshot Customer',
normalized_name='SNAPSHOT CUSTOMER', status='confirmed', customer_id=customer.id,
customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code,
identity_fingerprint='f' * 64, identity_rule_version='order-customer-fingerprint.v1',
identity_components_json={'role': 'bill_to'}, resolution_method='manual',
confirmation_reason='测试确认', confirmed_by_id=user.id, confirmed_at=datetime.utcnow(),
intake = ShippingOrderIntake(
intake_no=f'INT-SNAPSHOT-{suffix}', asset_id=1, user_id=user.id, parser_version='test',
)
db.session.add(intake)
db.session.flush()
candidate = ShippingOrderCandidate(
candidate_no=f'CAND-SNAPSHOT-{suffix}', intake_id=intake.id, primary_document_id=1,
candidate_key=f'snapshot-{suffix}', order_extraction_id=extraction.id, candidate_status='accepted',
)
db.session.add(candidate)
db.session.flush()
task.candidate_id = candidate.id
db.session.add(ShippingCustomerShadowResolution(
candidate_id=candidate.id, intake_id=intake.id, resolution_version='test.v1', status='confirmed',
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}],
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
resolution_context_json={'rule_set': {'checksum': 'f' * 64}},
identity_rule_set_checksum='f' * 64, top_customer_id=customer.id, top_score=100,
confirmed_customer_id=customer.id, confirmation_method='manual', confirmed_by_id=user.id,
confirmed_at=datetime.utcnow(),
))
db.session.commit()
return task, user
@@ -141,7 +156,7 @@ def test_freeze_creates_strong_snapshot_and_preserves_identifiers(app):
assert task.order_snapshot_id == snapshot.id
assert snapshot.customer_short_code_snapshot == 'CUS'
assert snapshot.customer_id is not None
assert snapshot.rule_versions_json['ordering_customer']['identity_rule_version'] == 'order-customer-fingerprint.v1'
assert snapshot.rule_versions_json['ordering_customer']['identity_rule_set_checksum'] == 'f' * 64
assert snapshot.lines[0].part_number == '000123'
assert snapshot.lines[0].reservation_id == '0012345678'
assert snapshot.lines[0].qty == Decimal('12.50000000')
@@ -225,10 +240,9 @@ def test_freeze_rejects_unconfirmed_or_caller_supplied_customer(app):
"""冻结只能采纳已确认订购客户,调用者传 customer_id 不能绕过该链路。"""
with app.app_context():
task, user = _build_accepted_order()
match = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=task.current_order_extraction_id, role='bill_to',
).one()
match.status = 'unique_candidate'
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
resolution.status = 'unique_candidate'
resolution.confirmed_customer_id = None
with pytest.raises(ValidationError) as error:
freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
assert error.value.code == 'SHIPPING.ORDER_CUSTOMER_CONFIRMATION_REQUIRED'