test(shipping): 更新订单复核库存与通知流程测试

This commit is contained in:
hugo committed 2026-09-04 20:53:06 +08:00
1 parent 8ec028e6a3
commit 265a6e179a
168 files changed
+9420 -4613

No files matched your search

@@ -21,6 +21,8 @@ from app import db
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
from app.models import (
FileAsset,
ShippingCustomer,
ShippingCustomerShadowResolution,
ShippingDocumentLayoutVersion,
ShippingOrderCandidate,
ShippingOrderDocument,
@@ -29,6 +31,7 @@ from app.models import (
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingNotice,
ShippingOrderTask,
User,
)
from app.services.file_assets.service import upload_file_asset
@@ -201,12 +204,37 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
classification='order_notice',
parse_status='parsed',
)
existing = ShippingNotice(
# 重复目标由建单前 OT(ShippingOrderTask)及其正式 Notice、已消费同哈希 Intake
# 共同构成 exact_file 匹配链(ShippingNotice.order_task_id → OT → consumed Intake → FileAsset)。
existing_task = ShippingOrderTask(
task_no='OT-CANDIDATE-EXISTING-001', user_id=owner.id,
lifecycle_status='active',
)
db.session.add(existing_task)
existing_asset = FileAsset(
asset_no='FA-CANDIDATE-EXISTING-001', owner_user_id=owner.id,
original_filename='order-7001.pdf', storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{owner.id}/existing/order-7001.pdf',
content_hash='candidate-api-content-hash', file_size=100,
mime_type='application/pdf', upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(existing_asset)
db.session.flush()
# OT/资产主键在会话内固化,供跨 app_context 重挂 Notice 时使用(避免 DetachedInstance 刷新)。
existing_task_id = int(existing_task.id)
existing_notice = ShippingNotice(
task_no='SN-CANDIDATE-EXISTING-001',
user_id=owner.id,
source_content_hash=asset.content_hash,
order_task_id=existing_task_id,
)
db.session.add_all([document, existing])
consumed_intake = ShippingOrderIntake(
intake_no='SNI-CANDIDATE-EXISTING-CONSUMED', asset_id=existing_asset.id,
user_id=owner.id, purpose='shipping_notice', parse_status='consumed',
parser_version='v6', consumed_task_id=existing_task_id,
)
db.session.add_all([document, existing_notice, consumed_intake])
db.session.flush()
candidate = ShippingOrderCandidate(
candidate_no='SNC-CANDIDATE-API-001',
@@ -220,14 +248,10 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 1}],
},
},
validation_status='needs_review',
conflicts_json=[{'field': 'qty'}],
validation_status='ready',
conflicts_json=[],
extraction_source='dify_workflow',
selected=True,
duplicate_resolution='open_existing',
duplicate_target_task_no=existing.task_no,
duplicate_resolved_by_id=owner.id,
duplicate_resolved_at=datetime.utcnow(),
)
db.session.add(candidate)
db.session.commit()
@@ -236,13 +260,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
patch_response = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001',
json={
'selected': False,
'business_summary': {
'po_number': '7001',
'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 2}],
},
},
json={'selected': False},
headers=owner_headers,
)
assert patch_response.status_code == 200
@@ -273,13 +291,13 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
assert repeated.status_code == 200
assert repeated.get_json()['data']['candidate_status'] == 'accepted'
assert patched['conflicts'] == []
assert patched['content_fingerprint']
assert promoted['content_fingerprint']
assert patched['duplicate_resolution'] is None
with app.app_context():
db.session.add(ShippingNotice(
task_no='SN-CANDIDATE-EXISTING-001', user_id=owner.id,
source_content_hash='candidate-api-content-hash',
order_task_id=existing_task_id,
))
db.session.commit()
@@ -323,122 +341,36 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
)
assert consumed.status_code == 409
def test_candidate_review_rejects_empty_or_invalid_order_lines(app, client):
"""人工修订不得以空摘要或无效 part_number/Qty 绕过 Candidate 审核门禁。"""
from app.core.auth.jwt import issue_local_access_token
with app.app_context():
user = User(username='candidate-validation', email='candidate-validation@example.com', password_hash='x')
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no='FA-CANDIDATE-VALIDATION',
owner_user_id=user.id,
original_filename='invalid-order.pdf',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{user.id}/invalid-order.pdf',
content_hash='candidate-validation-hash',
file_size=10,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingOrderIntake(
intake_no='SNI-CANDIDATE-VALIDATION',
asset_id=asset.id,
user_id=user.id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
)
db.session.add(intake)
db.session.flush()
document = ShippingOrderDocument(
intake_id=intake.id,
asset_id=asset.id,
document_type='attachment',
attachment_key='invalid-order',
filename='invalid-order.pdf',
content_hash=asset.content_hash,
classification='order_notice',
parse_status='parsed',
)
db.session.add(document)
db.session.flush()
candidate = ShippingOrderCandidate(
candidate_no='SNC-CANDIDATE-VALIDATION',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='test:SNC-CANDIDATE-VALIDATION',
structured_result_json={'business_summary': {'lines': [{'part_number': 'SKU-1', 'qty': 1}]}},
validation_status='needs_review',
selected=True,
)
db.session.add(candidate)
db.session.commit()
headers = {'Authorization': f'Bearer {issue_local_access_token(user)}'}
empty = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={'business_summary': {}},
headers=headers,
)
assert empty.status_code == 400
assert empty.get_json()['error']['code'] == 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED'
invalid_qty = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={'business_summary': {'lines': [{'part_number': 'SKU-1', 'qty': 0}]}},
headers=headers,
)
assert invalid_qty.status_code == 400
invalid_reservation = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={
'business_summary': {
'lines': [
{
'part_number': 'SKU-1',
'qty': 1,
'reservation_id': '1f1a682dfdc446a393415dee93eb36ce',
}
]
}
},
headers=headers,
)
assert invalid_reservation.status_code == 400
assert invalid_reservation.get_json()['error']['code'] == 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED'
invalid_selected = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={'selected': 'false'},
headers=headers,
)
assert invalid_selected.status_code == 400
null_summary = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={'business_summary': None},
headers=headers,
)
assert null_summary.status_code == 400
def test_candidate_batch_gate_requires_accepted_lifecycle(app, shipping_user):
"""provisional Candidate 即使保留旧 selected 标记,也绝不能绕过履约门禁。"""
from app.services.shipping_notice.candidate_service import ensure_candidate_fulfillment_ready
with app.app_context():
# 建 Task 前客户必须已确认(ShippingCustomerShadowResolution 承载该事实)。
customer = ShippingCustomer(standard_name='Acceptance Customer', short_code='ACPT', status='active')
db.session.add(customer)
db.session.flush()
candidate = ShippingOrderCandidate(
candidate_no='SNC-ACCEPTANCE-GATE', candidate_key='acceptance-gate',
intake_id=1, primary_document_id=1, selected=True,
candidate_status='provisional', is_current_version=True,
validation_status='ready', conflicts_json=[],
validation_status='ready', conflicts_json=[], acceptance_mode='manual',
)
db.session.add(candidate)
db.session.flush()
# 客户确认事实只承载于影子识别结果;不再落 Notice/OT 列。
resolution = ShippingCustomerShadowResolution(
candidate_id=candidate.id, intake_id=candidate.intake_id,
resolution_version='test.v1', status='confirmed',
confirmed_customer_id=customer.id, confirmation_method='manual',
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': 'ACPT'}],
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
resolution_context_json={'rule_set': {'checksum': 't' * 64}},
identity_rule_set_checksum='t' * 64,
)
db.session.add(resolution)
db.session.commit()
with pytest.raises(ConflictError) as provisional:
ensure_candidate_fulfillment_ready(candidate)
assert provisional.value.code == 'SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED'
@@ -514,13 +446,20 @@ def test_create_intake_integrity_race_returns_existing(app, shipping_user, monke
def _boom_nested():
class _CM:
def __enter__(self):
raise IntegrityError('stmt', {}, Exception('uq'))
# 仅注入一次 IntegrityError:模拟 Intake 唯一约束竞争;
# 后续(如 Submission 归属)SAVEPOINT 正常通过。
if nested_calls['n'] == 0:
nested_calls['n'] += 1
raise IntegrityError('stmt', {}, Exception('uq'))
return True
def __exit__(self, *args):
return False
return _CM()
nested_calls = {'n': 0}
monkeypatch.setattr(db.session, 'begin_nested', _boom_nested)
payload = create_shipping_notice_intake(
@@ -637,7 +576,6 @@ def test_revision_conflict_when_successor_exists(app, shipping_user):
task_no='SN-REV-LOCK-BASE',
user_id=shipping_user.id,
source_type='manual',
upload_status='uploaded',
document_version=1,
)
db.session.add(base)
@@ -1062,69 +1000,3 @@ def test_intake_status_api_strips_texts_detail_returns_full(app, client):
# 避免未使用变量告警
assert other_id != owner_id
def test_cancel_intake_releases_stage2_documents_and_derived_refs(app, shipping_user, monkeypatch):
"""解析完成后取消须删除 Document/Candidate 并归零派生资产引用。"""
from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.intake_service import cancel_intake
msg = EmailMessage()
msg['Subject'] = 'cancel after parse'
msg['From'] = 'a@b.com'
msg['To'] = 'c@d.com'
msg.set_content('body')
msg.add_attachment(
_minimal_pdf_bytes('PO Number: CANCEL001\nSKU: X qty 1'),
maintype='application',
subtype='pdf',
filename='cancel.pdf',
)
eml_bytes = msg.as_bytes()
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=FileStorage(
stream=BytesIO(eml_bytes),
filename='cancel.eml',
content_type='message/rfc822',
),
)
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingOrderIntake(
intake_no='SNI-STAGE2-CANCEL',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version='v6',
)
db.session.add(intake)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
lambda _a: eml_bytes,
)
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = run_intake_parse(intake, parent)
assert result['status'] == 'parsed'
derived = (
db.session.query(FileAsset)
.filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None))
.one()
)
assert int(derived.reference_count or 0) >= 1
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=intake.id).count() >= 1
cancel_intake(user_id=shipping_user.id, intake_no='SNI-STAGE2-CANCEL')
db.session.expire_all()
cancelled = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-CANCEL').one()
assert cancelled.parse_status == 'cancelled'
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=cancelled.id).count() == 0
assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=cancelled.id).count() == 0
derived2 = db.session.get(FileAsset, derived.id)
assert int(derived2.reference_count or 0) == 0
assert derived2.lifecycle_status == 'temporary'